问:
Line partially not plotted
Problem:
Plotting a closed 2D polygon works fine.
When I try plotting it 1D (by replacing the second dimension with a constant), it fails in some special cases: Then the polygon (which becomes a line) is not drawn completely.

What I tried:

Different plotting-styles like . , o -- of which only the latter one reproduces the problem while non-line-like-styles work.

Shifted/rolled the polygon-array which did not work when shifting by 1 or 2, but for 3 and 4 that solved the problem.

Asked a friend who is clueless ^^

Helped myself so far by directly plotting a line between x.min() and x.max().

For simplicity I removed the z-Data. When plotting x in combination with z, it also works - as long as z is far away from being constant. But then I get a wobbly graph instead of a straight line.

Still How can it be, that whether the data is fully plotted or not depends on its order? What did I do wrong?

I tried reducing the data for one of the special cases, but did not get very far.
Here's the working mini-example to produce the image, I'm sorry for the long dataset but could not figure out which values to remove while keeping the problem reproducable.

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

s = np.array([
       [-0.08527125,  0.08810856],
       [-0.08967261, -0.06748633],
       [-0.08772675, -0.08396971],
       [-0.08766724, -0.08440267],
       [-0.08748191, -0.08521958],
       [-0.08438602, -0.09529874],
       [-0.08385044, -0.09684308],
       [-0.08202714, -0.10180355],
       [-0.07874478, -0.1066276 ],
       [-0.07857811, -0.10686354],
       [-0.07789635, -0.10778213],
       [-0.07781094, -0.10789337],
       [-0.07710836, -0.10880646],
       [-0.07007289, -0.11655674],
       [-0.06962708, -0.11703841],
       [-0.06727917, -0.11933749],
       [-0.06584873, -0.12070607],
       [-0.06552574, -0.12100522],
       [-0.06527846, -0.12121293],
       [-0.06401669, -0.12214381],
       [-0.06349801, -0.12245992],
       [-0.06328962, -0.12258028],
       [-0.0627093 , -0.12290901],
       [-0.06225359, -0.12314782],
       [-0.06116991, -0.12368258],
       [-0.06041895, -0.12403051],
       [-0.06017477, -0.12413955],
       [-0.05992829, -0.12424804],
       [-0.04659197, -0.13006904],
       [-0.04634663, -0.13017319],
       [-0.04628731, -0.1301966 ],
       [-0.04567821, -0.13041967],
       [-0.04552972, -0.13047215],
       [-0.04521702, -0.13058213],
       [-0.00325617, -0.14513102],
       [ 0.00180445, -0.14683444],
       [ 0.00950078, -0.14923653],
       [ 0.01392647, -0.15030046],
       [ 0.01518804, -0.15045976],
       [ 0.02734024, -0.15177574],
       [ 0.02813995, -0.15177997],
       [ 0.02882764, -0.15176844],
       [ 0.02947446, -0.15171012],
       [ 0.03001744, -0.15165147],
       [ 0.0309922 , -0.15149313],
       [ 0.03121784, -0.15145567],
       [ 0.031327  , -0.15143527],
       [ 0.03142507, -0.15141573],
       [ 0.03150791, -0.15139799],
       [ 0.03222764, -0.15124224],
       [ 0.03798838, -0.14988557],
       [ 0.038991  , -0.1496481 ],
       [ 0.0391266 , -0.14961472],
       [ 0.03920601, -0.14959498],
       [ 0.03938681, -0.14954736],
       [ 0.03991586, -0.14940614],
       [ 0.05465674, -0.14538513],
       [ 0.05500815, -0.14528457],
       [ 0.05512499, -0.14524203],
       [ 0.05522656, -0.14520209],
       [ 0.05558739, -0.14504381],
       [ 0.05580602, -0.1449474 ],
       [ 0.05609256, -0.14478439],
       [ 0.05713959, -0.14412759],
       [ 0.05743526, -0.14392656],
       [ 0.05889567, -0.14277855],
       [ 0.06059875, -0.14143159],
       [ 0.06530732, -0.13766523],
       [ 0.06933674, -0.13424303],
       [ 0.0702827 , -0.13335664],
       [ 0.07036637, -0.13327235],
       [ 0.07405533, -0.12951652],
       [ 0.07810863, -0.125367  ],
       [ 0.08087981, -0.12226141],
       [ 0.08176499, -0.12123622],
       [ 0.08381519, -0.1150717 ],
       [ 0.08734418, -0.0927558 ],
       [ 0.08230393,  0.09131774],
       [ 0.08183173,  0.097691  ],
       [ 0.08169106,  0.09931977],
       [ 0.08130204,  0.10177584],
       [ 0.07914312,  0.11230088],
       [ 0.07895476,  0.11316267],
       [ 0.07514703,  0.12076318],
       [ 0.07464758,  0.12166996],
       [ 0.0733333 ,  0.12382546],
       [ 0.07297538,  0.12425848],
       [ 0.06620658,  0.13199037],
       [ 0.05294461,  0.14660768],
       [ 0.05262742,  0.14694802],
       [ 0.05097036,  0.14849098],
       [ 0.04972845,  0.14937964],
       [ 0.04815287,  0.15002114],
       [ 0.04783434,  0.15013311],
       [ 0.04757239,  0.15022502],
       [ 0.02928349,  0.15634586],
       [ 0.02842644,  0.15662035],
       [ 0.02776939,  0.15677726],
       [ 0.0270936 ,  0.15690821],
       [ 0.02666639,  0.15698384],
       [ 0.02610376,  0.15707915],
       [ 0.02601474,  0.15709266],
       [ 0.025126  ,  0.15722434],
       [ 0.02474755,  0.15727606],
       [ 0.02296123,  0.15742128],
       [ 0.02202472,  0.15744494],
       [ 0.02086636,  0.15744469],
       [ 0.01967163,  0.15742308],
       [ 0.01872141,  0.15737815],
       [ 0.01568162,  0.15718458],
       [-0.00722516,  0.15361993],
       [-0.00785781,  0.15350418],
       [-0.02865655,  0.14966376],
       [-0.02928172,  0.1495445 ],
       [-0.02970399,  0.14942282],
       [-0.03124785,  0.14896281],
       [-0.03160079,  0.14884731],
       [-0.03311488,  0.14832349],
       [-0.04643741,  0.14369722],
       [-0.04831254,  0.14301643],
       [-0.04846789,  0.14294296],
       [-0.04902343,  0.14264339],
       [-0.04980039,  0.14218488],
       [-0.05127431,  0.14122099],
       [-0.05343824,  0.13978482],
       [-0.06641953,  0.1306598 ],
       [-0.06719992,  0.13009146],
       [-0.06732267,  0.12997761],
       [-0.06842394,  0.12872382],
       [-0.06895024,  0.12808815],
       [-0.07854825,  0.11574519],
       [-0.08365013,  0.10504   ],
       [-0.0837306 ,  0.10486896],
       [-0.08384365,  0.10417084],
       [-0.08444646,  0.09768441]])

# make first and last point the same, to close the circle
s = np.concatenate([s,s[:1]])
y = s[:,0]
x = s[:,1]
# plot the polygon xy
plt.plot(x, y, 'b--', label='Polygon with x/y')
# plot only x values of the polygon (does not work)
plt.plot(x, np.zeros(len(x)), 'g-', linewidth=10, label='does not stretch over red dots')
# do the same, but with dots to show x values (does work)
plt.plot(x, np.zeros(len(x)), 'r.')
# do the same, a little bit lower, but with shifted/rolled x values.
# rolled by 1 or 2 does not help, but by 3 or 4 does.
plt.plot(np.roll(x,3), np.ones(len(x))-1.02, '-', color="lightgreen", linewidth=10, label="stretches over red dots")
# do the same again with dots to show x values
plt.plot(np.roll(x,3), np.ones(len(x))-1.02, 'r.')
plt.legend(loc='lower center').get_frame().set_alpha(1)
plt.show()
</code>```

Python 3.5 x64 via Anaconda in Windows10. Matplotlib is v2.0.0

答:
How long is a swimming pool that is 0 mm wide? In theory, it has a length of course, but in practice you couldn't measure it. The same happens here, a polygon without extention in one dimension could potentially be rendered to any length. And you would see the same effect happening to both polygons depending on the figure size, zoom level, axis range.

I think you already found a solution, by plotting a line instead of a polygon. And that would also be my recommendation.

Title: Line partially not plotted

Body:
Problem:
Plotting a closed 2D polygon works fine.
When I try plotting it 1D (by replacing the second dimension with a constant), it fails in some special cases: Then the polygon (which becomes a line) is not drawn completely.

What I tried:

Different plotting-styles like . , o -- of which only the latter one reproduces the problem while non-line-like-styles work.

Shifted/rolled the polygon-array which did not work when shifting by 1 or 2, but for 3 and 4 that solved the problem.

Asked a friend who is clueless ^^

Helped myself so far by directly plotting a line between x.min() and x.max().

For simplicity I removed the z-Data. When plotting x in combination with z, it also works - as long as z is far away from being constant. But then I get a wobbly graph instead of a straight line.

Still How can it be, that whether the data is fully plotted or not depends on its order? What did I do wrong?

I tried reducing the data for one of the special cases, but did not get very far.
Here's the working mini-example to produce the image, I'm sorry for the long dataset but could not figure out which values to remove while keeping the problem reproducable.

import numpy as np
from matplotlib import pyplot as plt

s = np.array([
       [-0.08527125,  0.08810856],
       [-0.08967261, -0.06748633],
       [-0.08772675, -0.08396971],
       [-0.08766724, -0.08440267],
       [-0.08748191, -0.08521958],
       [-0.08438602, -0.09529874],
       [-0.08385044, -0.09684308],
       [-0.08202714, -0.10180355],
       [-0.07874478, -0.1066276 ],
       [-0.07857811, -0.10686354],
       [-0.07789635, -0.10778213],
       [-0.07781094, -0.10789337],
       [-0.07710836, -0.10880646],
       [-0.07007289, -0.11655674],
       [-0.06962708, -0.11703841],
       [-0.06727917, -0.11933749],
       [-0.06584873, -0.12070607],
       [-0.06552574, -0.12100522],
       [-0.06527846, -0.12121293],
       [-0.06401669, -0.12214381],
       [-0.06349801, -0.12245992],
       [-0.06328962, -0.12258028],
       [-0.0627093 , -0.12290901],
       [-0.06225359, -0.12314782],
       [-0.06116991, -0.12368258],
       [-0.06041895, -0.12403051],
       [-0.06017477, -0.12413955],
       [-0.05992829, -0.12424804],
       [-0.04659197, -0.13006904],
       [-0.04634663, -0.13017319],
       [-0.04628731, -0.1301966 ],
       [-0.04567821, -0.13041967],
       [-0.04552972, -0.13047215],
       [-0.04521702, -0.13058213],
       [-0.00325617, -0.14513102],
       [ 0.00180445, -0.14683444],
       [ 0.00950078, -0.14923653],
       [ 0.01392647, -0.15030046],
       [ 0.01518804, -0.15045976],
       [ 0.02734024, -0.15177574],
       [ 0.02813995, -0.15177997],
       [ 0.02882764, -0.15176844],
       [ 0.02947446, -0.15171012],
       [ 0.03001744, -0.15165147],
       [ 0.0309922 , -0.15149313],
       [ 0.03121784, -0.15145567],
       [ 0.031327  , -0.15143527],
       [ 0.03142507, -0.15141573],
       [ 0.03150791, -0.15139799],
       [ 0.03222764, -0.15124224],
       [ 0.03798838, -0.14988557],
       [ 0.038991  , -0.1496481 ],
       [ 0.0391266 , -0.14961472],
       [ 0.03920601, -0.14959498],
       [ 0.03938681, -0.14954736],
       [ 0.03991586, -0.14940614],
       [ 0.05465674, -0.14538513],
       [ 0.05500815, -0.14528457],
       [ 0.05512499, -0.14524203],
       [ 0.05522656, -0.14520209],
       [ 0.05558739, -0.14504381],
       [ 0.05580602, -0.1449474 ],
       [ 0.05609256, -0.14478439],
       [ 0.05713959, -0.14412759],
       [ 0.05743526, -0.14392656],
       [ 0.05889567, -0.14277855],
       [ 0.06059875, -0.14143159],
       [ 0.06530732, -0.13766523],
       [ 0.06933674, -0.13424303],
       [ 0.0702827 , -0.13335664],
       [ 0.07036637, -0.13327235],
       [ 0.07405533, -0.12951652],
       [ 0.07810863, -0.125367  ],
       [ 0.08087981, -0.12226141],
       [ 0.08176499, -0.12123622],
       [ 0.08381519, -0.1150717 ],
       [ 0.08734418, -0.0927558 ],
       [ 0.08230393,  0.09131774],
       [ 0.08183173,  0.097691  ],
       [ 0.08169106,  0.09931977],
       [ 0.08130204,  0.10177584],
       [ 0.07914312,  0.11230088],
       [ 0.07895476,  0.11316267],
       [ 0.07514703,  0.12076318],
       [ 0.07464758,  0.12166996],
       [ 0.0733333 ,  0.12382546],
       [ 0.07297538,  0.12425848],
       [ 0.06620658,  0.13199037],
       [ 0.05294461,  0.14660768],
       [ 0.05262742,  0.14694802],
       [ 0.05097036,  0.14849098],
       [ 0.04972845,  0.14937964],
       [ 0.04815287,  0.15002114],
       [ 0.04783434,  0.15013311],
       [ 0.04757239,  0.15022502],
       [ 0.02928349,  0.15634586],
       [ 0.02842644,  0.15662035],
       [ 0.02776939,  0.15677726],
       [ 0.0270936 ,  0.15690821],
       [ 0.02666639,  0.15698384],
       [ 0.02610376,  0.15707915],
       [ 0.02601474,  0.15709266],
       [ 0.025126  ,  0.15722434],
       [ 0.02474755,  0.15727606],
       [ 0.02296123,  0.15742128],
       [ 0.02202472,  0.15744494],
       [ 0.02086636,  0.15744469],
       [ 0.01967163,  0.15742308],
       [ 0.01872141,  0.15737815],
       [ 0.01568162,  0.15718458],
       [-0.00722516,  0.15361993],
       [-0.00785781,  0.15350418],
       [-0.02865655,  0.14966376],
       [-0.02928172,  0.1495445 ],
       [-0.02970399,  0.14942282],
       [-0.03124785,  0.14896281],
       [-0.03160079,  0.14884731],
       [-0.03311488,  0.14832349],
       [-0.04643741,  0.14369722],
       [-0.04831254,  0.14301643],
       [-0.04846789,  0.14294296],
       [-0.04902343,  0.14264339],
       [-0.04980039,  0.14218488],
       [-0.05127431,  0.14122099],
       [-0.05343824,  0.13978482],
       [-0.06641953,  0.1306598 ],
       [-0.06719992,  0.13009146],
       [-0.06732267,  0.12997761],
       [-0.06842394,  0.12872382],
       [-0.06895024,  0.12808815],
       [-0.07854825,  0.11574519],
       [-0.08365013,  0.10504   ],
       [-0.0837306 ,  0.10486896],
       [-0.08384365,  0.10417084],
       [-0.08444646,  0.09768441]])

# make first and last point the same, to close the circle
s = np.concatenate([s,s[:1]])
y = s[:,0]
x = s[:,1]
# plot the polygon xy
plt.plot(x, y, 'b--', label='Polygon with x/y')
# plot only x values of the polygon (does not work)
plt.plot(x, np.zeros(len(x)), 'g-', linewidth=10, label='does not stretch over red dots')
# do the same, but with dots to show x values (does work)
plt.plot(x, np.zeros(len(x)), 'r.')
# do the same, a little bit lower, but with shifted/rolled x values.
# rolled by 1 or 2 does not help, but by 3 or 4 does.
plt.plot(np.roll(x,3), np.ones(len(x))-1.02, '-', color="lightgreen", linewidth=10, label="stretches over red dots")
# do the same again with dots to show x values
plt.plot(np.roll(x,3), np.ones(len(x))-1.02, 'r.')
plt.legend(loc='lower center').get_frame().set_alpha(1)
plt.show()

Python 3.5 x64 via Anaconda in Windows10. Matplotlib is v2.0.0


来源: stackexchange

问:
Help with linux kernel compilation script
i wrote a script to compile the kernel:

```<code>cd /usr/src/linux-2.4.18-14custom
make bzImage
make modules
make modules_install
cd arch/i386/boot
yes|cp bzImage /boot/vmlinuz-2.4.18-14custom
cd /boot
yes|mv 2.4.18-14custom.img 2.4.18-14custom.img.back
mkinitrd 2.4.18-14custom.img 2.4.18-14custom
reboot
</code>```

if i execute every line in the console it works, but when I put all of them in the script it executes only this 2 lines and ends:

```<code>    make bzImage
    make modules
</code>```

any ideas to make it work?

答:
kernel building

make -C /usr/src/linux help shows the options for building and installing a kernel.

initramfs allows for a built-in initrd equivalent that requires no post-build effort. I don't know if that's been backported to linux-2.4; but why 2.4?

Use make all install modules_install to install everything. Maybe 2.4 Makefiles require a separate "modules" target too.

After switching to initramfs, it's likely everything can be accomplished with  one make command:

```<code> make -C /usr/src/linux  all install modules_install
</code>```

Scripts

For an example install script see arch/i386/boot/install.sh.  Also, seen the Makefile in that same directory to see how it all works.  If a system-wide installkernel script exists (/sbin/installkernel in Gentoo), or a user one $HOME/bin/installkernel, that'll be used.

The script originally posted with this question will work under the right conditions. I ran it; but faked mkinitrd, and skipped reboot.

The script does not check for failure. It should stop if make fails, and not fail if the old fies for mv or cp don't exist.

cosmetic: yes|mv and yes|cp should be replaced with cp -f and mv -f.  See the man pages (or mv --help, cp --help).

ContentLicense: CC BY-SA 2.5

Body:
i wrote a script to compile the kernel:

cd /usr/src/linux-2.4.18-14custom
make bzImage
make modules
make modules_install
cd arch/i386/boot
yes|cp bzImage /boot/vmlinuz-2.4.18-14custom
cd /boot
yes|mv 2.4.18-14custom.img 2.4.18-14custom.img.back
mkinitrd 2.4.18-14custom.img 2.4.18-14custom
reboot

if i execute every line in the console it works, but when I put all of them in the script it executes only this 2 lines and ends:

    make bzImage
    make modules

any ideas to make it work?

Body:
kernel building

make -C /usr/src/linux help shows the options for building and installing a kernel.

initramfs allows for a built-in initrd equivalent that requires no post-build effort. I don't know if that's been backported to linux-2.4; but why 2.4?

Use make all install modules_install to install everything. Maybe 2.4 Makefiles require a separate "modules" target too.

After switching to initramfs, it's likely everything can be accomplished with  one make command:

 make -C /usr/src/linux  all install modules_install

Scripts

For an example install script see arch/i386/boot/install.sh.  Also, seen the Makefile in that same directory to see how it all works.  If a system-wide installkernel script exists (/sbin/installkernel in Gentoo), or a user one $HOME/bin/installkernel, that'll be used.

The script originally posted with this question will work under the right conditions. I ran it; but faked mkinitrd, and skipped reboot.

The script does not check for failure. It should stop if make fails, and not fail if the old fies for mv or cp don't exist.

cosmetic: yes|mv and yes|cp should be replaced with cp -f and mv -f.  See the man pages (or mv --help, cp --help).


问:
Fetching data to table from array
I'm new to programming and codeigniter,

I'm passing an array to view from controller and when i use print_r function i can view the array data in view
but i want them to show in a table but gives error as "Message: Undefined index: pid....."

my codes are below:

Controller:

```<code>public function bill_data()
{
    $data['data2'] = array(
        'pid' => $this->input->post('pid[]'),
        'proname' => $this->input->post('proname[]'),
        'uprice' => $this->input->post('uprice[]'),
        'qty' => $this->input->post('qty[]'),
        'total' => $this->input->post('total[]'),
        'discount' => $this->input->post('discount'),
        'subtotal' => $this->input->post('subtotal'),
    );

    foreach ($data as $entry) {

        $discount = $entry['discount'];
        $subtotal = $entry['subtotal'];
        $pid = $entry['pid'];
        $proname = $entry['proname'];
        $uprice = $entry['uprice'];
        $qty = $entry['qty'];
        $total = $entry['total'];

    }

    $subtotal = $subtotal - $discount;
    $d['final_result'] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");

    $this->load->view("invoice", $d);

}
</code>```

my view is like below:

```<code><?php foreach ($final_result as $row) { ?>
<table class="table m-t-30">
   <thead class="bg-faded">
      <tr>
         <th>#</th>
         <th>Product Name</th>
         <th>Unit Price</th>
         <th>Quantity</th>
         <th>Total</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td><?php echo $row['pid']; ?></td>
         <td>dsfdfsdf</td>
         <td>upprice</td>
         <td>qty</td>
         <td>Total</td>
      </tr>
   </tbody>
</table>
</code>```

Why it gives me an error? if i use print_r in view i can see the datas perfectly in view

Result:

答:
It is because your are using foreach. Your "pid" is a top level key. If you foreach your result array your $row will be the individual values not another arrays.

You have 2 options here:

1) remove the foreach iterator in the view

2) wrap your result in array:

```<code>$d['final_result'][] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");
</code>```

the option you need will depend on whether you will have more data sets or only one, if it's only one then just remove the foreach in your view.

Also keep in mind that <?php echo $row['pid']; ?> will not work as you 'pid' is an array.

ContentLicense: CC BY-SA 3.0

Title: Fetching data to table from array

Body:
I'm new to programming and codeigniter,

I'm passing an array to view from controller and when i use print_r function i can view the array data in view
but i want them to show in a table but gives error as "Message: Undefined index: pid....."

my codes are below:

Controller:

public function bill_data()
{
    $data['data2'] = array(
        'pid' => $this->input->post('pid[]'),
        'proname' => $this->input->post('proname[]'),
        'uprice' => $this->input->post('uprice[]'),
        'qty' => $this->input->post('qty[]'),
        'total' => $this->input->post('total[]'),
        'discount' => $this->input->post('discount'),
        'subtotal' => $this->input->post('subtotal'),
    );

    foreach ($data as $entry) {

        $discount = $entry['discount'];
        $subtotal = $entry['subtotal'];
        $pid = $entry['pid'];
        $proname = $entry['proname'];
        $uprice = $entry['uprice'];
        $qty = $entry['qty'];
        $total = $entry['total'];

    }

    $subtotal = $subtotal - $discount;
    $d['final_result'] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");

    $this->load->view("invoice", $d);

}

my view is like below:

<?php foreach ($final_result as $row) { ?>

         #
         Product Name
         Unit Price
         Quantity
         Total

         <?php echo $row['pid']; ?>
         dsfdfsdf
         upprice
         qty
         Total

Why it gives me an error? if i use print_r in view i can see the datas perfectly in view

Result:

Body:
It is because your are using foreach. Your "pid" is a top level key. If you foreach your result array your $row will be the individual values not another arrays.

You have 2 options here:

1) remove the foreach iterator in the view

2) wrap your result in array:

$d['final_result'][] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");

the option you need will depend on whether you will have more data sets or only one, if it's only one then just remove the foreach in your view.

Also keep in mind that <?php echo $row['pid']; ?> will not work as you 'pid' is an array.


问:
efficiency of a program that checks range of variable vs another that checks values one by one?
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

```<code>bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}
</code>```

f2:

```<code>bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}
</code>```

答:
The question is which one of the following functions are more efficient?

The C11 standard (read n1570) does not care about (or speak of) efficiency.

An optimizing compiler could generate the same code for both functions (and several of them do).

My GCC 7.1 compiler on Linux/x86-64 generate the same code with gcc -fverbose-asm -O2 -S:

```<code>         .text
         .p2align 4,,15
         .globl  f1
         .type   f1, @function
 f1:
 .LFB0:
         .cfi_startproc
 # abraham.c:3:     if (number >= 200 && number <= 202)
         subl    $200, %edi      #, tmp92
         cmpl    $2, %edi        #, tmp92
         setbe   %al     #, tmp93
 # abraham.c:6: }
         ret
         .cfi_endproc
 .LFE0:
         .size   f1, .-f1
         .p2align 4,,15
         .globl  f2
         .type   f2, @function
 f2:
 .LFB3:
         .cfi_startproc
         subl    $200, %edi      #, tmp92
         cmpl    $2, %edi        #, tmp92
         setbe   %al     #, tmp93
         ret
         .cfi_endproc
 .LFE3:
         .size   f2, .-f2
         .ident  "GCC: (Debian 7.1.0-2) 7.1.0"
         .section        .note.GNU-stack,"",@progbits
</code>```

BTW clang-4.0 -fverbose-asm -S -O2 generates also the same code for both functions, but a different one than gcc:

```<code>          .type   f1,@function
  f1:                                     # @f1
          .cfi_startproc
  # BB#0:
          addl    $-200, %edi
          cmpl    $3, %edi
          setb    %al
          retq
  .Lfunc_end0:
          .size   f1, .Lfunc_end0-f1
          .cfi_endproc
</code>```

And if performance matters that much to you, I recommend defining both functions as static inline in some common included header.

If you really care about performance, benchmark (after asking the compiler to optimize, e.g. with gcc -Wall -O2 with GCC). But read more about premature optimization, notably the fallacy of premature optimization. Notice that asking about performance without enabling optimization is contradictory.

Most of the time, you should choose whatever is more readable.

Body:
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}

f2:

bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}

Body:
The question is which one of the following functions are more efficient?

The C11 standard (read n1570) does not care about (or speak of) efficiency.

An optimizing compiler could generate the same code for both functions (and several of them do).

My GCC 7.1 compiler on Linux/x86-64 generate the same code with gcc -fverbose-asm -O2 -S:

         .text
         .p2align 4,,15
         .globl  f1
         .type   f1, @function
 f1:
 .LFB0:
         .cfi_startproc
 # abraham.c:3:     if (number >= 200 && number <= 202)
         subl    $200, %edi      #, tmp92
         cmpl    $2, %edi        #, tmp92
         setbe   %al     #, tmp93
 # abraham.c:6: }
         ret
         .cfi_endproc
 .LFE0:
         .size   f1, .-f1
         .p2align 4,,15
         .globl  f2
         .type   f2, @function
 f2:
 .LFB3:
         .cfi_startproc
         subl    $200, %edi      #, tmp92
         cmpl    $2, %edi        #, tmp92
         setbe   %al     #, tmp93
         ret
         .cfi_endproc
 .LFE3:
         .size   f2, .-f2
         .ident  "GCC: (Debian 7.1.0-2) 7.1.0"
         .section        .note.GNU-stack,"",@progbits

BTW clang-4.0 -fverbose-asm -S -O2 generates also the same code for both functions, but a different one than gcc:

          .type   f1,@function
  f1:                                     # @f1
          .cfi_startproc
  # BB#0:
          addl    $-200, %edi
          cmpl    $3, %edi
          setb    %al
          retq
  .Lfunc_end0:
          .size   f1, .Lfunc_end0-f1
          .cfi_endproc

And if performance matters that much to you, I recommend defining both functions as static inline in some common included header.

If you really care about performance, benchmark (after asking the compiler to optimize, e.g. with gcc -Wall -O2 with GCC). But read more about premature optimization, notably the fallacy of premature optimization. Notice that asking about performance without enabling optimization is contradictory.

Most of the time, you should choose whatever is more readable.


问:
PostgreSQL get date
I have the following query which returns the date as dd/mm/yyyy hh:mm:ss, but I would like to extract the time and date as separate columns, how can I do this please?  I am new to PostgreSQL

Thanks
Kath

```<code>select
    up.mis_id,
    up.name,
    up.surname,
    es.created as "signed in",
    es1.created as "signed out",
    bb.name as "location"

from users_person as up

join users_role as ur on ur.id = up.role_id
join events_event as ee on ee.user_id = up.id
join events_swipe as es on es.id = ee.sign_in_id
join events_swipe as es1 on es1.id = ee.sign_out_id
join buildings_building as bb on bb.id = es.location_id
</code>```

答:
use explicit casting, for time:

```<code>es.created::time
</code>```

and for date:

```<code>es.created::date
</code>```

Eg:

```<code>t=# select now()::time(0) "Time",now()::date "Date";
   Time   |    Date
----------+------------
 08:19:59 | 2017-06-06
(1 row)
</code>```

Title: PostgreSQL get date

Body:
I have the following query which returns the date as dd/mm/yyyy hh:mm:ss, but I would like to extract the time and date as separate columns, how can I do this please?  I am new to PostgreSQL

Thanks
Kath

select
    up.mis_id,
    up.name,
    up.surname,
    es.created as "signed in",
    es1.created as "signed out",
    bb.name as "location"

from users_person as up

join users_role as ur on ur.id = up.role_id
join events_event as ee on ee.user_id = up.id
join events_swipe as es on es.id = ee.sign_in_id
join events_swipe as es1 on es1.id = ee.sign_out_id
join buildings_building as bb on bb.id = es.location_id

Body:
use explicit casting, for time:

es.created::time

and for date:

es.created::date

Eg:

t=# select now()::time(0) "Time",now()::date "Date";
   Time   |    Date
----------+------------
 08:19:59 | 2017-06-06
(1 row)


问:
How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

答:
You need to set position: relative; to the parent element and position: absolute; to the shape element. Then use max min value for random where max is the parent width/height and subtract the shape width/height ...

This is snippet before update

function position() {
  var playSpace = document.querySelector('#playSpace');
  var shape = document.getElementById("shape");
  var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
  var maxWidth = playSpace.offsetWidth - shape.offsetWidth;

  var positionTop = Math.random() * (maxHeight - 0) + 0;
  var positionLeft = Math.random() * (maxWidth - 0) + 0;

  // think of this like so:
  // var positionTop = Math.random() * (max - min) + min;
  // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

  var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
  return position;
}

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin:0;
  padding-top: 30px;
}

#playSpace {
  position: relative; /* add this line */
  width: 90%;
  height: 90%;
  margin: 0 auto;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```
</div>
</div>
</p>

<p><strong>Updated after comment</strong>
Not sure how you added the <code>size()</code> function but probably the problem was with using <code>...cssText</code> that you overwrote the changes. So now I changed the code with passing the <code>element</code> to the functions and then only change the single CSS statements which need to be changed.</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-js lang-js prettyprint-override"><code>function position(element) {
  var playSpace = document.querySelector('#playSpace');
  var shape = document.getElementById("shape");
  var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
  var maxWidth = playSpace.offsetWidth - shape.offsetWidth;

  var positionTop = Math.random() * (maxHeight - 0) + 0;
  var positionLeft = Math.random() * (maxWidth - 0) + 0;

  // think of this like so:
  // var positionTop = Math.random() * (max - min) + min;
  // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

  element.style.position = 'absolute';
  element.style.top = positionTop + "px";
  element.style.left = positionLeft + "px";
}

function size(element) {
  var sizeMath = (Math.random() * 200) + 50;
  element.style.width = sizeMath + "px";
  element.style.height = sizeMath + "px";
}

document.getElementById("shape").onclick = function() {
    size(document.getElementById("shape"));
    position(document.getElementById("shape"));
}</code>```

#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}

#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}

#shape {
width: 100px;
height: 100px;
background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gameSpace">
    <div id="playSpace">
        <!-- here we put the shape -->
        <div id="shape"></div>
    </div>
</div></code>```

Body:
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

Body:
You need to set position: relative; to the parent element and position: absolute; to the shape element. Then use max min value for random where max is the parent width/height and subtract the shape width/height ...

This is snippet before update

function position() {
  var playSpace = document.querySelector('#playSpace');
  var shape = document.getElementById("shape");
  var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
  var maxWidth = playSpace.offsetWidth - shape.offsetWidth;

  var positionTop = Math.random() * (maxHeight - 0) + 0;
  var positionLeft = Math.random() * (maxWidth - 0) + 0;

  // think of this like so:
  // var positionTop = Math.random() * (max - min) + min;
  // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

  var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
  return position;
}

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin:0;
  padding-top: 30px;
}

#playSpace {
  position: relative; /* add this line */
  width: 90%;
  height: 90%;
  margin: 0 auto;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

<div id="gameSpace">
    <div id="playSpace">
        <!-- here we put the shape -->
        <div id="shape"></div>
    </div>
</div>

Updated after comment
Not sure how you added the size() function but probably the problem was with using ...cssText that you overwrote the changes. So now I changed the code with passing the element to the functions and then only change the single CSS statements which need to be changed.

function position(element) {
  var playSpace = document.querySelector('#playSpace');
  var shape = document.getElementById("shape");
  var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
  var maxWidth = playSpace.offsetWidth - shape.offsetWidth;

  var positionTop = Math.random() * (maxHeight - 0) + 0;
  var positionLeft = Math.random() * (maxWidth - 0) + 0;

  // think of this like so:
  // var positionTop = Math.random() * (max - min) + min;
  // more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

  element.style.position = 'absolute';
  element.style.top = positionTop + "px";
  element.style.left = positionLeft + "px";
}

function size(element) {
  var sizeMath = (Math.random() * 200) + 50;
  element.style.width = sizeMath + "px";
  element.style.height = sizeMath + "px";
}

document.getElementById("shape").onclick = function() {
    size(document.getElementById("shape"));
    position(document.getElementById("shape"));
}

#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}

#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}

#shape {
width: 100px;
height: 100px;
background-color: red;
}

<div id="gameSpace">
    <div id="playSpace">
        <!-- here we put the shape -->
        <div id="shape"></div>
    </div>
</div>


问:
how to calculate shortest 2D distance between a point and a line segment in all cases in C, C# / .NET 2.0 or Java?

Possible Duplicate:

  Shortest distance between a point and a line segment

i am looking for a way to calculate the minimum distance in all cases. the problems with solutions i found are:

Solutions with graphical conceptual drawings show point always on perpendicular from line segment so it's "between line segment's end points". My geometry skills are horrible so i can't verify that these solutions work in all cases.

Algorithm solutions are a: with fortran or some other language i don't fully understand,
b: are flagged as incomplete by people, c: calling methods/functions that are not described in any way (considered trivial).

Good example of 2 a, b and c is

Shortest distance between a point and a line segment

i have the 2D line segment as double-type co-ordinate pair (x1, y1), (x2,y2) and point as double type co-ordinate (x3,y3). C#/Java/C solutions are all appreciated.

Thanks for your answers & BR: Matti

答:
If you have line

L: A * x + B * y + C = 0

Then distance from this line to point (x1, y1) is  abs(A * x1 + B * y1 + C) / sqrt(A * A + B * B). in your case if you has interval, (xa, ya); (xb, yb) you should find min( distance(x1, y1, xa, ya), distance(x1, y1, xb, yb)) then see if perpendecular from (x1, y1) to line L is on the interval, then the answer is the distance is it. otherwise min of two distances.


问:
I can't connect a webpage on my ec2
I am building simple webpage.

I could run on my local host.

I made ec2 instance, I opened ports 22, 8000.

I could connect with ssh and run server for webpage,

but I get this error

this is my github address that contain the code.
enter link description herehttps://github.com/MoreNiceJay/django2

答:
In your security group rules, open port 80
This is the standard port for http traffic

Other things to check: login to the host with ssh and use netstat |grep LISTEN to see if there is a process listening on port 80

Title: I can't connect a webpage on my ec2


问:
SQL complex query- ORDER BY and GROUP BY in the same query did not work properly
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

```<code>SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn
</code>```

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.

答:
I think this is what you need</p>

```<code>SELECT TOP (1) WITH TIES
       msisdn , COUNT(is_correct) AS NumberOfCorrectAnswers,
       max(creation_time) AS LastCorrectAnswerDatetime
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1
GROUP BY msisdn
ORDER BY COUNT(is_correct) DESC, max(creation_time) ASC
</code>```

Body:
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.

Body:
I think this is what you need

SELECT TOP (1) WITH TIES
       msisdn , COUNT(is_correct) AS NumberOfCorrectAnswers,
       max(creation_time) AS LastCorrectAnswerDatetime
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1
GROUP BY msisdn
ORDER BY COUNT(is_correct) DESC, max(creation_time) ASC


问:
Invalid request URI while adding a video to playlist via youtube api
I have been unable to overcome this error while trying to add a video to my playlist using the youtube gdata python api.

gdata.service.RequestError: {'status':
  400, 'body': 'Invalid request URI',
  'reason': 'Bad Request'}

This seems to be the same error, but there are no solutions as yet. Any help guys?

```<code> import getpass
 import gdata.youtube
 import gdata.youtube.service

 yt_service = gdata.youtube.service.YouTubeService()

 # The YouTube API does not currently support HTTPS/SSL access.
 yt_service.ssl = False
 yt_service = gdata.youtube.service.YouTubeService()
 yt_service.email = #myemail
 yt_service.password = getpass.getpass()
 yt_service.developer_key = #mykey
 yt_service.source = #text
 yt_service.client_id= #text
 yt_service.ProgrammaticLogin()

 feed = yt_service.GetYouTubePlaylistFeed(username='default')
 # iterate through the feed as you would with any other
 for entry in feed.entry:
     if (entry.title.text == "test"):
         lst = entry;
         print entry.title.text, entry.id.text

 custom_video_title = 'my test video on my test playlist'
 custom_video_description = 'this is a test video on my test playlist'
 video_id = 'Ncakifd_16k'
 playlist_uri = lst.id.text

 playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist(playlist_uri, video_id, custom_video_title, custom_video_description)

 if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
 print 'Video added'
</code>```

The confounding thing is that updating the playlist works, but adding a video does not.

```<code> playlist_entry_id = lst.id.text.split('/')[-1]
 original_playlist_description = lst.description.text
 updated_playlist = yt_service.UpdatePlaylist(playlist_entry_id,'test',original_playlist_description,playlist_private=False)
</code>```

The video_id is not wrong because its the video from the sample code. What am I missing here? Somebody help!

Thanks.

答:
Gdata seems to use v1 API. So, the relevant documentation is here: http://code.google.com/apis/youtube/1.0/developers_guide_protocol.html#Retrieving_a_playlist

This means, your "playlist_uri" should not take the value of "lst.id.text", but should take the "feedLink" element's "href" attribute in order to be used with "AddPlaylistVideoEntryToPlaylist"

Even if you happen to use v2 API, you should take the URI from the "content" element's "src" attribute as explained in the documentation, you get by substituting 2.0, in the above URL! (SO doesn't allow me to put two hyperlinks because i don't have enough reputations! :))

Body:
I have been unable to overcome this error while trying to add a video to my playlist using the youtube gdata python api.

gdata.service.RequestError: {'status':
  400, 'body': 'Invalid request URI',
  'reason': 'Bad Request'}

This seems to be the same error, but there are no solutions as yet. Any help guys?

 import getpass
 import gdata.youtube
 import gdata.youtube.service

 yt_service = gdata.youtube.service.YouTubeService()

 # The YouTube API does not currently support HTTPS/SSL access.
 yt_service.ssl = False
 yt_service = gdata.youtube.service.YouTubeService()
 yt_service.email = #myemail
 yt_service.password = getpass.getpass()
 yt_service.developer_key = #mykey
 yt_service.source = #text
 yt_service.client_id= #text
 yt_service.ProgrammaticLogin()

 feed = yt_service.GetYouTubePlaylistFeed(username='default')
 # iterate through the feed as you would with any other
 for entry in feed.entry:
     if (entry.title.text == "test"):
         lst = entry;
         print entry.title.text, entry.id.text

 custom_video_title = 'my test video on my test playlist'
 custom_video_description = 'this is a test video on my test playlist'
 video_id = 'Ncakifd_16k'
 playlist_uri = lst.id.text

 playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist(playlist_uri, video_id, custom_video_title, custom_video_description)

 if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
 print 'Video added'

The confounding thing is that updating the playlist works, but adding a video does not.

 playlist_entry_id = lst.id.text.split('/')[-1]
 original_playlist_description = lst.description.text
 updated_playlist = yt_service.UpdatePlaylist(playlist_entry_id,'test',original_playlist_description,playlist_private=False)

The video_id is not wrong because its the video from the sample code. What am I missing here? Somebody help!

Thanks.


问:
How to show actual image size on tableviewcell without using custom cell?
I am showing image on cell using  cell.imageView.image = [UIImage imageNamed:@"demoImg.png"]; but in this image is not showing as its actual size.

Is there any way to show image in actual size?

Like this image is showing small but actual images are of different size and bigger but only if i click on cell it shows actual size

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"cellIdentifier";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    if (self.content.count > 0){

        NSDictionary *contentdata = self.content[indexPath.row];

        NSString *title = contentdata[@"description"];
        NSString *imageUrlString = contentdata[@"imageHref"];
       // NSString *description = contentdata[@"title"];

        cell.textLabel.text =  [title isKindOfClass:[NSNull class]] ? @"" : title;  //----- Title
        cell.imageView.image = [UIImage imageNamed:@"demoImg.png"];
       //cell.detailTextLabel.text  =  [description isKindOfClass:[NSNull class]] ? @"" : description;  //----- Description

        cell.contentView.layer.borderColor = [UIColor blackColor].CGColor;
        cell.contentView.layer.borderWidth = 1.0;
</code>```

答: No you can't do this with the default cell, you need a custom cell. Then you can set it up how you like.</p>

Body:
I am showing image on cell using  cell.imageView.image = [UIImage imageNamed:@"demoImg.png"]; but in this image is not showing as its actual size.

Is there any way to show image in actual size?

Like this image is showing small but actual images are of different size and bigger but only if i click on cell it shows actual size

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"cellIdentifier";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    if (self.content.count > 0){

        NSDictionary *contentdata = self.content[indexPath.row];

        NSString *title = contentdata[@"description"];
        NSString *imageUrlString = contentdata[@"imageHref"];
       // NSString *description = contentdata[@"title"];

        cell.textLabel.text =  [title isKindOfClass:[NSNull class]] ? @"" : title;  //----- Title
        cell.imageView.image = [UIImage imageNamed:@"demoImg.png"];
       //cell.detailTextLabel.text  =  [description isKindOfClass:[NSNull class]] ? @"" : description;  //----- Description

        cell.contentView.layer.borderColor = [UIColor blackColor].CGColor;
        cell.contentView.layer.borderWidth = 1.0;


问:
Correctly defining this data relation in Django models
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

```<code>dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)
</code>```

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

```<code>    preparation = models.???(???)
</code>```

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

```<code>preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()
</code>```

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

答:
Make sure, relations are correct otherwise you have repeating tuples in your models which is not very good practice, make your database very heavy. see relation from my perspective.</p>

```<code> class dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)

class Ingredients(models.Model):
    name = models.CharField(max_length=100)
    dish = models.ForeignKey(dish)

class preparation(models.Model):
    prep_test = models.TextField()
    last_update = models.DateTimeField()
    dish = models.OneToOneField(dish)
</code>```

Body:
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

    preparation = models.???(???)

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

Body:
Make sure, relations are correct otherwise you have repeating tuples in your models which is not very good practice, make your database very heavy. see relation from my perspective.

 class dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)

class Ingredients(models.Model):
    name = models.CharField(max_length=100)
    dish = models.ForeignKey(dish)

class preparation(models.Model):
    prep_test = models.TextField()
    last_update = models.DateTimeField()
    dish = models.OneToOneField(dish)


问:
How to create a new Microsoft Azure HybridConnection via code?
I am using HybridConnectionNamespace and create multiple HybridConnections via Azure portal. The question is quite simple. How can I create it programmatically (Azure SDK, PowerShell scripts, etc.)?

答:
According to this article, there are currently two different ways to create a relay namespace.

Azure portal and Azure Resource Manager templates

If you want to create it programmatically, I suggest you could use azure rest api to send the deployment templates by codes.

More details, you could refer to this article and codes:

Notice: If you want to use rest api to send request to azure, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.

Rest Body(json.txt):

Notice: You need change the parameters' name and location value.

```<code>{"properties":{"mode":"incremental","debugSetting":{"detailLevel":"RequestContent, ResponseContent"},"parameters":{"name":{"value":"yourrelayname"},"location":{"value":"location"}},"template":{"$schema":"http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#","contentVersion":"1.0.0.0","parameters":{"name":{"type":"string"},"location":{"type":"string"}},"resources":[{"apiVersion":"2016-07-01","name":"[parameters('name')]","location":"[parameters('location')]","type":"Microsoft.Relay/namespaces","properties":{"namespaceType":"Relay"}}]}}}
</code>```

Code:

```<code>   string body = File.ReadAllText(@"D:\json.txt");
            // Display the file contents to the console. Variable text is a string.
            string tenantId = "tenantId";
            string clientId = "clientId(applicationid)";
            string clientSecret = "applicationSecret";
            string subscription = "subscriptionId";
            string resourcegroup = "Youresourcegroup";

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientSecret);
            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Resources/deployments/Microsoft.Relay?api-version=2016-07-01", subscription, resourcegroup));
            request.Method = "PUT";
            request.Headers["Authorization"] = "Bearer " + token;
            request.ContentType = "application/json";

            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(body);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //Get the response
            var httpResponse = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(httpResponse.StatusCode);

            Console.ReadLine();
</code>```

Result:

Body:
According to this article, there are currently two different ways to create a relay namespace.

Azure portal and Azure Resource Manager templates

If you want to create it programmatically, I suggest you could use azure rest api to send the deployment templates by codes.

More details, you could refer to this article and codes:

Notice: If you want to use rest api to send request to azure, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.

Rest Body(json.txt):

Notice: You need change the parameters' name and location value.

{"properties":{"mode":"incremental","debugSetting":{"detailLevel":"RequestContent, ResponseContent"},"parameters":{"name":{"value":"yourrelayname"},"location":{"value":"location"}},"template":{"$schema":"http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#","contentVersion":"1.0.0.0","parameters":{"name":{"type":"string"},"location":{"type":"string"}},"resources":[{"apiVersion":"2016-07-01","name":"[parameters('name')]","location":"[parameters('location')]","type":"Microsoft.Relay/namespaces","properties":{"namespaceType":"Relay"}}]}}}

Code:

   string body = File.ReadAllText(@"D:\json.txt");
            // Display the file contents to the console. Variable text is a string.
            string tenantId = "tenantId";
            string clientId = "clientId(applicationid)";
            string clientSecret = "applicationSecret";
            string subscription = "subscriptionId";
            string resourcegroup = "Youresourcegroup";

            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientSecret);
            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Resources/deployments/Microsoft.Relay?api-version=2016-07-01", subscription, resourcegroup));
            request.Method = "PUT";
            request.Headers["Authorization"] = "Bearer " + token;
            request.ContentType = "application/json";

            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(body);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //Get the response
            var httpResponse = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(httpResponse.StatusCode);

            Console.ReadLine();

Result:


问:
How can I get the source code of XmlDiffPatch library?
I came across the Microsofr.XmlDiffPatch and I would like to check how the Patch algorithm works. I spent sometime searching for the source code of this library, but didn't find anything useful yet.
My questions are:

Is it possible to obtain this code from some online repository - is it open source?

If not, is there any other strategy to extract this code somehow from references in Visual Studio?

答:
You could download and install XmlDiffPatch from here:

http://download.microsoft.com/download/1/f/1/1f146f9b-2a71-4904-8b91-e2f62d7b64b3/XmlDiffPatch.exe

And then, you could find source code in Src directory.


Title: How to sort this type of complex 3d array in php

Body:
The array is like this (I am using PHP)

array(2){[0]=>
             {[0]=>"DEF"=>
                       {[0]=>"a",[1]=>"c",[2]=>"b"},
              [1]=>"ABC"=>
                      {[0]=>"f",[1]=>"d",[2]=>"e"}},
        [1]=>
            {[0]=>"DEF"=>
                      {[0]=>"h",[1]=>"i",[2]=>"g"},
             [1]=>"ABC"=>
                      {[0]=>"k",[1]=>"l",[2]=>"j"}
            }
        }

I wish to be sort it like the first entry i.e. [0] index has two entries DEF and ABC so it should be sorted ABC and DEF then in ABC also a b c should be sorted.

The final result should be this

array(2){[0]=>
             {[0]=>"ABC"=>
                       {[0]=>"d",[1]=>"e",[2]=>"f"},
              [1]=>"DEF"=>
                      {[0]=>"a",[1]=>"b",[2]=>"c"}},
        [1]=>
            {[0]=>"ABC"=>
                      {[0]=>"j",[1]=>"k",[2]=>"l"},
             [1]=>"DEF"=>
                      {[0]=>"g",[1]=>"h",[2]=>"i"}
            }
        }

Thanks in advance

Body:
Using sort will solve problem

   $a = array(
            array(
                 "ABC"=>array("d","e","f"),
                 "DEF"=>array("a","b","c")
                ),

           array(
                "ABC"=>array("j","k","l"),
                "DEF"=>array("g","h","i")
                )
           );

  sort($a);
  var_dump($a);

The result

array(2) {
  [0]=>
  array(2) {
    ["ABC"]=>
    array(3) {
      [0]=>
      string(1) "d"
      [1]=>
      string(1) "e"
      [2]=>
      string(1) "f"
    }
    ["DEF"]=>
    array(3) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
      [2]=>
      string(1) "c"
    }
  }
  [1]=>
  array(2) {
    ["ABC"]=>
    array(3) {
      [0]=>
      string(1) "j"
      [1]=>
      string(1) "k"
      [2]=>
      string(1) "l"
    }
    ["DEF"]=>
    array(3) {
      [0]=>
      string(1) "g"
      [1]=>
      string(1) "h"
      [2]=>
      string(1) "i"
    }
  }
}


问:
Is there a way to list all the rpms in an iso image?
I need a way to list all the RPMS in an iso image without booting the iso file and making a live image. Eventually I'm trying to make a very light weight cron job or Jenkins jobs to get the list of RPMS on an iso image.</p>

答:
Presumably you want the list of rpm's that were used to construct the iso.

If the ISO contains an rpmdb, you can mount the ISO, and then run

```<code>rpm -qa --dbpath /path/to/iso/mount/var/lib/rpm
</code>```

Watch out for lock creation (if run as root and/or the ISO rpmdb directory is "writable" somehow).

The simplest way to avoid rpmdb lock creation is to run the query as non-root: rpm queries will run without creating locks if the rpmdb directory is unwritable.

Body:
Presumably you want the list of rpm's that were used to construct the iso.

If the ISO contains an rpmdb, you can mount the ISO, and then run

rpm -qa --dbpath /path/to/iso/mount/var/lib/rpm

Watch out for lock creation (if run as root and/or the ISO rpmdb directory is "writable" somehow).

The simplest way to avoid rpmdb lock creation is to run the query as non-root: rpm queries will run without creating locks if the rpmdb directory is unwritable.


问:
How get FlexGrid control inside a ng-include file?
I'm building a SPA with Angularjs and Wijmo 5.

I've inserted a Wijmo FlexGrid inside a partial file, then I've included it to the parent page using ng-include. The parent page is also an partial file: it's inside the ng-view.

```<code><wj-flex-grid id="myFlexGrid"
              control="myFlexGrid"></wj-flex-grid>
</code>```

The problem is that I can't reach the FlexGrid control. When i try to declare the flex control, it throws a error: Cannot read property 'selection' of undefined.

```<code>var flex = $scope.myFlexGrid;
var myVar = flex.selection;
</code>```

How can I reach the FlexGrid control?

答:
ng-include creates a child scope so any directive used within it will be on child scope. You should create flex grid like this -

```<code><wj-flex-grid id="myFlexGrid" control="file.myFlexGrid" items-source="file.data" loaded-rows="loadedRows()">
</wj-flex-grid>
</code>```

Here is working fiddle.

Body:
I'm building a SPA with Angularjs and Wijmo 5.

I've inserted a Wijmo FlexGrid inside a partial file, then I've included it to the parent page using ng-include. The parent page is also an partial file: it's inside the ng-view.

<wj-flex-grid id="myFlexGrid"
              control="myFlexGrid"></wj-flex-grid>

The problem is that I can't reach the FlexGrid control. When i try to declare the flex control, it throws a error: Cannot read property 'selection' of undefined.

var flex = $scope.myFlexGrid;
var myVar = flex.selection;

How can I reach the FlexGrid control?

Body:
ng-include creates a child scope so any directive used within it will be on child scope. You should create flex grid like this -

<wj-flex-grid id="myFlexGrid" control="file.myFlexGrid" items-source="file.data" loaded-rows="loadedRows()">
</wj-flex-grid>

Here is working fiddle.


问:
IE bug with min-width?
I have given a div a min-width , and a percentage width . It seems to be working as expected on Chrome and FF , but in IE ( 7 & 9 ) , the min-width is not enforced . The following code illustrates the behaviour in t.</p>

```<code><div style="background-color:#fc0;min-width:500px; width:10%;">
test
</div>
</code>```

答:
The min-width attribute is supported in IE 7 and later, but only if you have a strict doctype.

Ref: min-width Attribute

Title: IE bug with min-width?

Body:
I have given a div a min-width , and a percentage width . It seems to be working as expected on Chrome and FF , but in IE ( 7 & 9 ) , the min-width is not enforced . The following code illustrates the behaviour in t.

test


问:
how to redirect `command ...` all output into a file in linux?
I'm running command xxx xxx in linux, and I want to redirect all output, including std/warn/err output into one file IN ORDER.

How to deal with this?

For example, if I run command xxx xxx 2>file, the file will only contains error message. If I run command xxx xxx 1>file, the file will only contains std message. But I want all message together, not devided message. How to deal with this?

Thank you!

答:
I think you are looking for this:</p>

```<code>command >outfile 2>&1.
</code>```

Body:
I think you are looking for this:

command >outfile 2>&1.


问:
Adding new objects to a jframe
I have seen a program and was hoping to replicate one feature of it in my program. The program is a flashcard app, and when you create a new deck it adds another section to the homescreeen. I will attach images. I would love some advice on how to do this.

答: One of possible way is to use correct layouts, here is examples. Using this you may dynamically add any components (labels, images, buttons etc.) into your JPanel (I recommend to use JPanel as main container of all components instead of JFrame that should be one and just contain your JPanel).</p>

Title: Adding new objects to a jframe


问:
how to convert String ("1-DEC-16") and ("01-DEC-16") to java Date as 01-DEC-2016
I have CSV data to import into data base where I have date column in that CSV in that some dates are like 1-DEC-16 without a leading zero (padding zero). How to make that String as 01-DEC-2016? Can it be done with  SimpleDateFormat or is there any String format method? I tried with below but it’s not happening.

```<code>String d="1-DEC-17";

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(newstring);
</code>```

答:
d vs dd

To parse a string with a leading zero on the month or day-of-month, use a pair of formatting pattern characters. That would be dd for day-of-month.

To parse a string without a leading zero, use a single character, d for day-of-month.

Unfortunately, your input has the month name abbreviation in all uppercase. That violates the norm of the English-speaking locales I know of, such as Locale.US. So by default, a DateTimeFormatter will refuse to process that improper input. To tolerate the all-uppercase, we can set the formatter to be “lenient”.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MMM-uu" , Locale.US ).withResolverStyle( ResolverStyle.LENIENT )  ;
LocalDate ld = LocalDate.parse( "1-DEC-17" , f ) ;
</code>```

See this code run live at IdeOne.com.

ld.toString(): 2017-12-01

If sending this value to a database, do not use a string for date-time value. Use a date-time object for date-time values.

For JDBC drivers compliant with JDBC 4.2 and later, pass the java.time types directly via setObject & getObject.

```<code>myPreparedStatement.setObject( … , ld ) ;
</code>```

If not compliant, convert briefly to the troublesome old legacy type, java.sql.Date. Use the new methods added to the old classes.

```<code>java.sql.Date d = java.sql.Date.valueOf( ld ) ;
myPreparedStatement.setDate( … , d ) ;
</code>```

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
I have CSV data to import into data base where I have date column in that CSV in that some dates are like 1-DEC-16 without a leading zero (padding zero). How to make that String as 01-DEC-2016? Can it be done with  SimpleDateFormat or is there any String format method? I tried with below but it’s not happening.

String d="1-DEC-17";

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(newstring);

Body:
d vs dd

To parse a string with a leading zero on the month or day-of-month, use a pair of formatting pattern characters. That would be dd for day-of-month.

To parse a string without a leading zero, use a single character, d for day-of-month.

Unfortunately, your input has the month name abbreviation in all uppercase. That violates the norm of the English-speaking locales I know of, such as Locale.US. So by default, a DateTimeFormatter will refuse to process that improper input. To tolerate the all-uppercase, we can set the formatter to be “lenient”.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MMM-uu" , Locale.US ).withResolverStyle( ResolverStyle.LENIENT )  ;
LocalDate ld = LocalDate.parse( "1-DEC-17" , f ) ;

See this code run live at IdeOne.com.

ld.toString(): 2017-12-01

If sending this value to a database, do not use a string for date-time value. Use a date-time object for date-time values.

For JDBC drivers compliant with JDBC 4.2 and later, pass the java.time types directly via setObject & getObject.

myPreparedStatement.setObject( … , ld ) ;

If not compliant, convert briefly to the troublesome old legacy type, java.sql.Date. Use the new methods added to the old classes.

java.sql.Date d = java.sql.Date.valueOf( ld ) ;
myPreparedStatement.setDate( … , d ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Index Qt5 in Eclipse IDE project using Cmake

Background

I'm currently using Eclipse Neon.3 and have installed the "C/C++ CMake Build Support - Experimental" package (I'm not using CMake's Eclipse generator). I have a simple program that uses Qt 5.8 which builds successfully, however, Eclipse seems unable to index Qt symbols(e.g. QCoreApplication, QDebug, etc...).

The symptoms of this are:

No code completion suggestions

#include <QtCore> and other include statements are shown as unresolved

Qt symbols such as QCoreApplication, QDebug(), and QCoreApplication.exec() are shown as not resolved.

Code

CMakeLists.txt file

```<code>cmake_minimum_required(VERSION 3.5)
project(test-program)

set(CMAKE_CXX_STANDARD 11)

# Put the CMake files for Qt5 in the Prefix path.
set(Qt5_DIR /opt/Qt/5.8/gcc_64/lib/cmake/Qt5/)

#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

#Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

#Find the Qt5Core Library
find_package(Qt5 REQUIRED COMPONENTS Core Widgets)

set(SOURCE_FILES
    src/main.cpp)

add_executable(${PROJECT_NAME} ${SOURCE_FILES})

target_link_libraries(${PROJECT_NAME} Qt5::Core)
</code>```

main.cpp (shown with eclipse annotations)

```<code>#include <QtCore> //Unresolved inclusion: <QtCore>
#include <QDebug> //Unresolved inclusion: <QDebug>

int main(int argc, char** argv){
    QCoreApplication application(argc, argv);
    //Type 'QCoreApplication' could not be resolved

    qDebug() << "Test";
    //Function 'qDebug' could not be resolved

    application.exec();
    //Method 'exec' could not be resolved

    return 0;
}
</code>```

Question

So my question is this: How can I get Eclipse to recognize Eclipse to recognize Qt symbols? Or is that just not possible at this time?

答:
Did you enable the "CDT GCC Build Output Parser"? This is an Eclipse feature to parse the output of the build and guesses the include paths automatically. You can find it unter Project Properties->C/C++ General->Preprocessor Include Paths, Macros etc. and then under the tab Providers.

In order for this feature to work properly, a detailed build report must be generated. You can achieve this by either changing the build command under Preferences->C/C++ Build to make VERBOSE=1 or by specifying set(CMAKE_VERBOSE_MAKEFILE On) inside your CMakeLists.txt.

See also Eclipse Help - Scanner Discovery Preferences

Body:
Background

I'm currently using Eclipse Neon.3 and have installed the "C/C++ CMake Build Support - Experimental" package (I'm not using CMake's Eclipse generator). I have a simple program that uses Qt 5.8 which builds successfully, however, Eclipse seems unable to index Qt symbols(e.g. QCoreApplication, QDebug, etc...).

The symptoms of this are:

No code completion suggestions

#include <QtCore> and other include statements are shown as unresolved

Qt symbols such as QCoreApplication, QDebug(), and QCoreApplication.exec() are shown as not resolved.

Code

CMakeLists.txt file

cmake_minimum_required(VERSION 3.5)
project(test-program)

set(CMAKE_CXX_STANDARD 11)

# Put the CMake files for Qt5 in the Prefix path.
set(Qt5_DIR /opt/Qt/5.8/gcc_64/lib/cmake/Qt5/)

#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

#Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

#Find the Qt5Core Library
find_package(Qt5 REQUIRED COMPONENTS Core Widgets)

set(SOURCE_FILES
    src/main.cpp)

add_executable(${PROJECT_NAME} ${SOURCE_FILES})

target_link_libraries(${PROJECT_NAME} Qt5::Core)

main.cpp (shown with eclipse annotations)

#include <QtCore> //Unresolved inclusion: <QtCore>
#include <QDebug> //Unresolved inclusion: <QDebug>

int main(int argc, char** argv){
    QCoreApplication application(argc, argv);
    //Type 'QCoreApplication' could not be resolved

    qDebug() << "Test";
    //Function 'qDebug' could not be resolved

    application.exec();
    //Method 'exec' could not be resolved

    return 0;
}

Question

So my question is this: How can I get Eclipse to recognize Eclipse to recognize Qt symbols? Or is that just not possible at this time?


问:
Symfony - trying to get all the elements in findBy attribute throws invalid argument supplied for foreach
I have a controller block in my symfony app as shown below where I am using a findBy attribute to get the elements based on the arguments passed to the controller.

This is snippet

```<code>$alldata = // all data retrieve

$data = array();
foreach ($alldata as $alldata) { //throws invalid arguments supplied in foreach
    array_push($data, $this->serializeData($alldata));
}
</code>```

Please how can I get ride of the warning and retrieve all the elements using the findBy attribute.

答:
Change this:

```<code>foreach ($alldata as $alldata) {
    array_push($data, $this->serializeData($alldata));
}
</code>```

to this:

```<code>foreach ($alldata as $all) {
    array_push($data, $this->serializeData($all));
}
</code>```

The problem is inside the foreach, you need to change the second variable with another name

Body:
I have a controller block in my symfony app as shown below where I am using a findBy attribute to get the elements based on the arguments passed to the controller.

This is snippet

$alldata = // all data retrieve

$data = array();
foreach ($alldata as $alldata) { //throws invalid arguments supplied in foreach
    array_push($data, $this->serializeData($alldata));
}

Please how can I get ride of the warning and retrieve all the elements using the findBy attribute.

Body:
Change this:

foreach ($alldata as $alldata) {
    array_push($data, $this->serializeData($alldata));
}

to this:

foreach ($alldata as $all) {
    array_push($data, $this->serializeData($all));
}

The problem is inside the foreach, you need to change the second variable with another name


问:
How to center image horizontally within a div element?
How can I center align (horizontally) an image inside its container div?

Here's the HTML and CSS. I have also included the CSS for the other elements of the thumbnail. It runs in descending order so the highest element is the container of everything and the lowest is inside everything.

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}

#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}

#artiststhumbnail:hover {
      left: 50px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--link here-->

  <div id="thumbnailwrapper">

    href="NotByDesign">

      <!--name here-->
      <b>Not By Design</b>
      <br>

      <div id="artiststhumbnail">

        href="NotByDesign">

          <!--image here-->
          <img src="../files/noprofile.jpg" height="100%" alt="Not By Design" border="1" />

      </div>

      <div id="genre">Punk</div>

  </div></code>```

Okay, I have added the markup without the PHP in so should be easier to see. Neither solution seems to work in practice. The text at top and bottom cannot be centered and the image should be centered within its container div. The container has overflow hidden so I want to see the center of the image as that's normally where the focus is.

答:
To center an image horizontally, this works:</p>

```<code><p style="text-align:center"><img src=""></p>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I center align (horizontally) an image inside its container div?

Here's the HTML and CSS. I have also included the CSS for the other elements of the thumbnail. It runs in descending order so the highest element is the container of everything and the lowest is inside everything.

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}

#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}

#artiststhumbnail:hover {
      left: 50px
}

      Not By Design

Punk

Okay, I have added the markup without the PHP in so should be easier to see. Neither solution seems to work in practice. The text at top and bottom cannot be centered and the image should be centered within its container div. The container has overflow hidden so I want to see the center of the image as that's normally where the focus is.

Body:
To center an image horizontally, this works:

<p style="text-align:center"><img src=""></p>


问:
Python declare global class accessible by several modules
If I have a module gobalcfgs containing

```<code>class Cfgs:
    ...

cfg = Cfgs()
</code>```

is there a way to share this across multiple modules in a project.
I have a main module that import utility modules. So, the import direction is

```<code>main <-- utility_1.py
main <-- utility_2.py
</code>```

However, some global variables and classed get defined in main and are used in the utility modules. Currently I have them as variables in the function call, but it would be nicer to have a global structure that can be accessed from all modules instead of sending the information over a chain of functions.

so, instead of having something like this in main

```<code>cfg.sethost(host)
data = utility.getData(cfg)
</code>```

in utility

```<code>def getData(cfg):
    getDataFromX(cfg):

def getDataFromX(cfg):
    con = openConnection(cfg):

def openConnection(cfg):
    con = mycon(cfg.host)
</code>```

Having cfg being some sort of global and then have in main

```<code>from globalcfgs import cfg
cfg.setHost(host)
data = utility.getData()
</code>```

and in utility

```<code>from globalcfgs import cfg
def openConnection():
    con = mycon(cfg.host)
</code>```

This is not exactly a real life example I have but supposed to illustrate that I need to ship information over a long chain of functions.
Is it possible to avoid this?

答:
Firstly, don't call a class globals, as that shadows the built-in globals() function. In any case, Python style is that classes use CamelCase - with initial capitals - and functions use snake_case.

That apart though, what you have is fine. You can import cfg in any module that uses it; the only thing is that you have the import statement the wrong way round, it should be from globalstuff import cfg.

Body:
If I have a module gobalcfgs containing

class Cfgs:
    ...

cfg = Cfgs()

is there a way to share this across multiple modules in a project.
I have a main module that import utility modules. So, the import direction is

main <-- utility_1.py
main <-- utility_2.py

However, some global variables and classed get defined in main and are used in the utility modules. Currently I have them as variables in the function call, but it would be nicer to have a global structure that can be accessed from all modules instead of sending the information over a chain of functions.

so, instead of having something like this in main

cfg.sethost(host)
data = utility.getData(cfg)

in utility

def getData(cfg):
    getDataFromX(cfg):

def getDataFromX(cfg):
    con = openConnection(cfg):

def openConnection(cfg):
    con = mycon(cfg.host)

Having cfg being some sort of global and then have in main

from globalcfgs import cfg
cfg.setHost(host)
data = utility.getData()

and in utility

from globalcfgs import cfg
def openConnection():
    con = mycon(cfg.host)

This is not exactly a real life example I have but supposed to illustrate that I need to ship information over a long chain of functions.
Is it possible to avoid this?


问:
Full Screen Component ReactJS
I am now working on the component, which needs to be the size of full screen. But I don't want to write external CSS for this component because it is part of a very big project, so this is a one single component, do you have any suggestions ?
Thanks in advance!

SOLVED
Using 100vh directly in the component

答:
On your component you need to specify this:

```<code><your-react-component width="100%" height="100%"></your-react-component>
</code>```

make sure that your body is also was set this way

```<code><body width="100%" height="100%"></body>
</code>```

Title: Full Screen Component ReactJS

Body:
On your component you need to specify this:

<your-react-component width="100%" height="100%"></your-react-component>

make sure that your body is also was set this way

<body width="100%" height="100%"></body>


问:
support for add_to_set defined in Mongoid::Atomic::Modifiers?
Hi I'm new to mongodb,

Need support for add_to_set method which add a document in a collection

What if add_to_set is called twice and in both time the inserted value are equal

for example

```<code>    someInstance.add_to_set(some_field: "hello_world")
</code>```

if this called twice will it be an update query for mongo??

答: It'll call mongo, cause the action is atomic, so local state is not 100% db state, but it won't sdd same item twice. So the answer is yes.</p>

Body:
Hi I'm new to mongodb,

Need support for add_to_set method which add a document in a collection

What if add_to_set is called twice and in both time the inserted value are equal

for example

    someInstance.add_to_set(some_field: "hello_world")

if this called twice will it be an update query for mongo??


问:
.append() in python just gets ignored?
So am trying to extract nouns from a csv file.
Checking each value whether its a noun or not using Textblob package.
The nouns found are appended to an empty list x.
Then finally when the looping is finished, I print the final list expecting all nouns but Nothing happens..(The data set is huge).
Some one help me out.</p>

```<code>from nltk import FreqDist
from textblob import TextBlob
import pandas as p

x = list()

data = p.DataFrame.from_csv('hl.csv', encoding = "ISO-8859-1")
data = data.reset_index()

for column in data.columns.values:
    for value in data[column]:
        blob = TextBlob(value)
##        print(blob.noun_phrases)    #this print statement gives nouns
        x.append(blob.noun_phrases)   #so I append the results to an empty list

print(x)      #When printing the final list.. NOTHING HAPPENS no empty list nothing. Python just ignores it why ???
</code>```

答:
blob.noun_phrases returns an object of type WordList. Make the following modifications to your code. See if it solves the problem.

```<code># First include Wordlist
from textblob import WordList

# Then create an instance of WOrdList
x = list()
y = WordList(x)
</code>```

and

```<code># Change `x.append(blob.noun_phrases)` to
y.extend(blob.noun_phrases)
</code>```

Title: .append() in python just gets ignored?

Body:
So am trying to extract nouns from a csv file.
Checking each value whether its a noun or not using Textblob package.
The nouns found are appended to an empty list x.
Then finally when the looping is finished, I print the final list expecting all nouns but Nothing happens..(The data set is huge).
Some one help me out.

from nltk import FreqDist
from textblob import TextBlob
import pandas as p

x = list()

data = p.DataFrame.from_csv('hl.csv', encoding = "ISO-8859-1")
data = data.reset_index()

for column in data.columns.values:
    for value in data[column]:
        blob = TextBlob(value)
##        print(blob.noun_phrases)    #this print statement gives nouns
        x.append(blob.noun_phrases)   #so I append the results to an empty list

print(x)      #When printing the final list.. NOTHING HAPPENS no empty list nothing. Python just ignores it why ???

Body:
blob.noun_phrases returns an object of type WordList. Make the following modifications to your code. See if it solves the problem.

# First include Wordlist
from textblob import WordList

# Then create an instance of WOrdList
x = list()
y = WordList(x)

and

# Change `x.append(blob.noun_phrases)` to
y.extend(blob.noun_phrases)


问:
How do I compile a C++ project with "DOS EXE" header flag == false?
I have a VS2010 C++ exe project that I want to compile so that the "DOS EXE" flag in the exe's header is set to false. This is (hopefully) to avoid the creation of a CONHOST.exe when the executable is run. The exe does not have a UI.

At the moment, I am calling ::FreeConsole on startup, to get rid of the CONHOST.exe process, but would prefer it if the CONHOST.exe were never created in the first place.

How can I do this?

Further to the selected answer, I 'fixed up' my code by adding a WinMain that calls through to the existing main, as follows:

```<code>int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
  int argc;
  LPWSTR* argv = CommandLineToArgvW(pCmdLine, &argc);
  _tmain(argc, argv);
  LocalFree(argv);
}
</code>```

答:
You can try to change SubSystem value in linker options from CONSOLE to WINDOWS. This will prevent compiler from generating console-supporting code in the binary.
Note that you will need to use WinMain() function instead of main()</p>

Body:
I have a VS2010 C++ exe project that I want to compile so that the "DOS EXE" flag in the exe's header is set to false. This is (hopefully) to avoid the creation of a CONHOST.exe when the executable is run. The exe does not have a UI.

At the moment, I am calling ::FreeConsole on startup, to get rid of the CONHOST.exe process, but would prefer it if the CONHOST.exe were never created in the first place.

How can I do this?

Further to the selected answer, I 'fixed up' my code by adding a WinMain that calls through to the existing main, as follows:

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
  int argc;
  LPWSTR* argv = CommandLineToArgvW(pCmdLine, &argc);
  _tmain(argc, argv);
  LocalFree(argv);
}


问:
Multiple line using named ranges VBA
I am attempting to plot multiple named ranges on to a chart. These named ranges (named for example Time_Series_1) are of the form:

=INDIRECT(Ranges!$AJ$3) where this argument Ranges!$AJ$3 is for example

```<code> ="'Source Data'!"&ADDRESS(N3,(Comparisons!$G$28+5))&":"&ADDRESS(N3(Comparisons!$I$28+5))
</code>```

The code I'm attempting to use to plot the these ranges (I have started with one as any more remain to be impossible as one is not working) is:

```<code>Sheets("Comparisons").Select
Sheet10.ChartObjects("Chart 2").Activate

Set Rng = range("Time_Series_1")
Set Date_Rng = range("Time_Series_Dates_1")

With ActiveChart
    .SetSourceData Source:=Rng
    .XValues = Date_Rng
End With
</code>```

It's not working! The Chart remains blank. Completely empty. What am I not updating? What am I not activating?

Thanks

答:
I have no way of testing your model, but try this:

```<code>Dim Chart_Sheet As Worksheet
Dim My_Chart As ChartObject
Dim Rng As Range
Dim Date_Rng As Range

Set Chart_Sheet = ThisWorkbook.Sheets("Comparisons")
Set My_Chart = Chart_Sheet.ChartObjects("Chart 2")
Set Rng = Range("Time_Series_1")
Set Date_Rng = Range("Time_Series_Dates_1")

With My_Chart.Chart
    .SetSourceData Source:=Rng
    .SeriesCollection(1).XValues = Date_Rng
End With
</code>```

(I am assuming that your Indirect reference works properly)

Title: Multiple line using named ranges VBA

Body:
I am attempting to plot multiple named ranges on to a chart. These named ranges (named for example Time_Series_1) are of the form:

=INDIRECT(Ranges!$AJ$3) where this argument Ranges!$AJ$3 is for example

 ="'Source Data'!"&ADDRESS(N3,(Comparisons!$G$28+5))&":"&ADDRESS(N3(Comparisons!$I$28+5))

The code I'm attempting to use to plot the these ranges (I have started with one as any more remain to be impossible as one is not working) is:

Sheets("Comparisons").Select
Sheet10.ChartObjects("Chart 2").Activate

Set Rng = range("Time_Series_1")
Set Date_Rng = range("Time_Series_Dates_1")

With ActiveChart
    .SetSourceData Source:=Rng
    .XValues = Date_Rng
End With

It's not working! The Chart remains blank. Completely empty. What am I not updating? What am I not activating?

Thanks

Body:
I have no way of testing your model, but try this:

Dim Chart_Sheet As Worksheet
Dim My_Chart As ChartObject
Dim Rng As Range
Dim Date_Rng As Range

Set Chart_Sheet = ThisWorkbook.Sheets("Comparisons")
Set My_Chart = Chart_Sheet.ChartObjects("Chart 2")
Set Rng = Range("Time_Series_1")
Set Date_Rng = Range("Time_Series_Dates_1")

With My_Chart.Chart
    .SetSourceData Source:=Rng
    .SeriesCollection(1).XValues = Date_Rng
End With

(I am assuming that your Indirect reference works properly)


问:
How to show years on X axis when using matplotlib?
I never used python and I have to do this as my first assignment. It took me 3 hours just to get to this point and I really need some help.

I have a one dimensional array with some numbers. I have to make a timeseries plot.

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

data = np.load("abnormal.npy")

x = np.array(range(1,len(data)+1))
y = np.load("abnormal.npy")

plt.plot(x,y)
plt.show()
</code>```

As you can see the X axis now is the array range of my array.
How can I change this to date time 2002-2012 ?

Body:
I never used python and I have to do this as my first assignment. It took me 3 hours just to get to this point and I really need some help.

I have a one dimensional array with some numbers. I have to make a timeseries plot.

import datetime
import matplotlib.pyplot as plt
import numpy as np

data = np.load("abnormal.npy")

x = np.array(range(1,len(data)+1))
y = np.load("abnormal.npy")

plt.plot(x,y)
plt.show()

As you can see the X axis now is the array range of my array.
How can I change this to date time 2002-2012 ?

Body:
You just like do this,

import pandas as pd

y_len = 100
x = pd.date_range("20020101", freq='D', periods=y_len).strftime("%Y-%m-%d").tolist()

you just need get Y axis's lenght and point to the y_len, for you question

y_len = len(data)

the sample code output is,

['2002-01-01', '2002-01-02', '2002-01-03', '2002-01-04', '2002-01-05', '2002-01-06', '2002-01-07', '2002-01-08', '2002-01-09', '2002-01-10', '2002-01-11', '2002-01-12', '2002-01-13', '2002-01-14', '2002-01-15', '2002-01-16', '2002-01-17', '2002-01-18', '2002-01-19', '2002-01-20', '2002-01-21', '2002-01-22', '2002-01-23', '2002-01-24', '2002-01-25', '2002-01-26', '2002-01-27', '2002-01-28', '2002-01-29', '2002-01-30', '2002-01-31', '2002-02-01', '2002-02-02', '2002-02-03', '2002-02-04', '2002-02-05', '2002-02-06', '2002-02-07', '2002-02-08', '2002-02-09', '2002-02-10', '2002-02-11', '2002-02-12', '2002-02-13', '2002-02-14', '2002-02-15', '2002-02-16', '2002-02-17', '2002-02-18', '2002-02-19', '2002-02-20', '2002-02-21', '2002-02-22', '2002-02-23', '2002-02-24', '2002-02-25', '2002-02-26', '2002-02-27', '2002-02-28', '2002-03-01', '2002-03-02', '2002-03-03', '2002-03-04', '2002-03-05', '2002-03-06', '2002-03-07', '2002-03-08', '2002-03-09', '2002-03-10', '2002-03-11', '2002-03-12', '2002-03-13', '2002-03-14', '2002-03-15', '2002-03-16', '2002-03-17', '2002-03-18', '2002-03-19', '2002-03-20', '2002-03-21', '2002-03-22', '2002-03-23', '2002-03-24', '2002-03-25', '2002-03-26', '2002-03-27', '2002-03-28', '2002-03-29', '2002-03-30', '2002-03-31', '2002-04-01', '2002-04-02', '2002-04-03', '2002-04-04', '2002-04-05', '2002-04-06', '2002-04-07', '2002-04-08', '2002-04-09', '2002-04-10']


问:
Colour cells with a date more than 20 years ago?
I have a nominal roll with the birth dates of individuals. I need to create a program that will highlight the cells of birthdays that are more than 27 years ago in red, as 27 is the age limit. Could somebody help me with this? I know it's possible with conditional formatting function on Excel but I want to do it with vba so I can filter many different categories at once. </p>

答:
For formatting condition, you may use the following:

```<code>   'for whole column A, if cell value is greater than 27
    With Range("A:A").FormatConditions.Add(xlCellValue, xlGreater, "=27")

      'color interior with red and black for font
      .Interior.Color = RGB(255, 0, 0)
      .Font.Color = RGB(0, 0, 0)
    End With
</code>```

For the birth year, you may use the following function:

```<code>    '=YearDiff(B1) <- enter this on cells as a formula with birthday parameter (from B1 on this example)
    Function YearDiff(pDate As Date) As Long
      YearDiff = DateDiff("yyyy", pDate, Now())
    End Function
</code>```

Next time, please exert effort to post your code so that we may see where you got stuck.

Body:
For formatting condition, you may use the following:

   'for whole column A, if cell value is greater than 27
    With Range("A:A").FormatConditions.Add(xlCellValue, xlGreater, "=27")

      'color interior with red and black for font
      .Interior.Color = RGB(255, 0, 0)
      .Font.Color = RGB(0, 0, 0)
    End With

For the birth year, you may use the following function:

    '=YearDiff(B1) <- enter this on cells as a formula with birthday parameter (from B1 on this example)
    Function YearDiff(pDate As Date) As Long
      YearDiff = DateDiff("yyyy", pDate, Now())
    End Function

Next time, please exert effort to post your code so that we may see where you got stuck.