问:
Alternative to Initializer List of References
I really needed and Initializer List of References but it seems that is not possible. The problem of being a copy is that I wanted to disable copy construction and because these copies call the destrutor afterwards what releases the resources(and should not happend).

My current (bad) alternative is using a bool to track if it was copy constructed so the resources are not released.

Another alternative is an Initializer List of Pointers but that makes it more verbose and would accept nullptr as well as being conceptually incorrect in my opinion.

I would really like an alternative using references or something along those lines (maybe move? I can't seem to make that work)

答:
I assume you want an initializer list of references of references to put in a container. So, you are looking for a reference type, right? If it's so, check the Reference Wrappers. It allows references to be the type of containers:

```<code>#include <iostream>
#include <functional>

struct A {
    A() { std::cout << "A()" << std::endl; }
    A(const A&) = delete;
    ~A() { std::cout << "~A()" << std::endl; }
};

int main(int argc, char const *argv[])
{
    A a1;
    A a2;
    A a3;

    {
        // OK: don't call copy constructor during creation
        std::initializer_list<std::reference_wrapper<A>> ilist{ a1, a2, a3 };
        // OK: don't call destructor when "ilist" leaves the scope
    }

    {
        // ERROR: can't create the list because copy constructor is deleted
        std::initializer_list<A> va{ a1, a2, a3 };
    }

    // Destructors called here

    return 0;
}
</code>```

Body:
I assume you want an initializer list of references of references to put in a container. So, you are looking for a reference type, right? If it's so, check the Reference Wrappers. It allows references to be the type of containers:

#include <iostream>
#include <functional>

struct A {
    A() { std::cout << "A()" << std::endl; }
    A(const A&) = delete;
    ~A() { std::cout << "~A()" << std::endl; }
};

int main(int argc, char const *argv[])
{
    A a1;
    A a2;
    A a3;

    {
        // OK: don't call copy constructor during creation
        std::initializer_list<std::reference_wrapper<A>> ilist{ a1, a2, a3 };
        // OK: don't call destructor when "ilist" leaves the scope
    }

    {
        // ERROR: can't create the list because copy constructor is deleted
        std::initializer_list<A> va{ a1, a2, a3 };
    }

    // Destructors called here

    return 0;
}


来源: stackexchange

问:
How can i access the Intel CPU Counter
Is there any small tool that gives me access to the data gathered by the Intel CPU Counters (like L1/L2 cache misses, branch prediction failures ... you know there are hunderts of them on modern Core2 CPU's).

It must work on Windows (while being able to use it with Solaris, FreeBSD, Linux, MacOSX would of course be nice).

答: This thread seems a little old but if you're still interested, I wrote a howto recently on this topic using nothing more than rdmsr and wrmsr in Linux.  It only deals with the performance counters on an Intel uncore for Westmere, but the process I described might help you figure out what you need if you haven't already.  I'm sure Windows has some equivalent program or function call to RDMSR and WRMSR.  The problem is you need to be ring 0 (kernel mode) to read MSRs.  I have no idea how to do that in Windows.  I won't be able to help with any Windows questions but may be able to answer some MSR-related questions if you have any.  I'm by no means an expert though.</p>

ContentLicense: CC BY-SA 2.5

Title: How can i access the Intel CPU Counter


问:
how to icmp ping thousands of IP addresses simultaneously every second?
I'm looking for solution, how to be able to ping some 5000 (up to 10000) IP addresses on a local network each 1 second and immediatelly, when any icmp packet timeouts, it will write output to a file with the unix epoch time of the lost packet and IP address. So I'll be able to measure the length of the network outages in seconds to every IP address.

I'm trying to run that much ping commands in a infinite cycle for each IP address now (so I have a lot of running processes - for all IP addresses I'm sending just one packet. Than ping command finishes itself, I manage its output and run ping command again and so on). But I somehow feel this is not the best way how to do this :|

I can write scripts just in bash and PHP but not in C++, ... So I prefer if you have a solution for my skills :)

Thank you in advance.
Pep.

PS: I guess I know how fping works, and I think it is too much slow. It can not ping 5000 IP addresses every second am I right?

答:
```<code>ping IP_ADDRESS_HERE /n NUMBER_OF_PINGS_HERE -l PACKET_SIZE_HERE & ping IP_ADDRESS_HERE /n NUMBER_OF_PINGS_HERE -l PACKET_SIZE_HERE
</code>```

Two pings running in one line. Very simple. Add more by adding a & mark.

ContentLicense: CC BY-SA 3.0

Body:
ping IP_ADDRESS_HERE /n NUMBER_OF_PINGS_HERE -l PACKET_SIZE_HERE & ping IP_ADDRESS_HERE /n NUMBER_OF_PINGS_HERE -l PACKET_SIZE_HERE

Two pings running in one line. Very simple. Add more by adding a & mark.


问:
How to make selector choose div class and with tag name of p?
Hello I am kind of stuck right now. I am trying to make my script choose all paragraph inside a div class of change but I don't really understand how to do it. The html looks something like this in the body

```<code><body>
<div id="top" class="change">
<p> Microsoft </p>
<p> Apple </p>
<p> Sony </p>
</div>

<div id="middle">
<p> Disney </p>
<p> Nintendo </p>
<p> Sony </p>
</div>

<div id="bottom" class="change">
<p> Ice</p>
<p> Tea</p>
<p> Water</p>
</div>
</body>
</code>```

I am trying to make it so when the mouse cursor touches anything that has a class of change in a paragraph, it will change the color to a color of my choice but I don't know how to do it with selectors with pure javascript. This is the current code I have but it is not working. I can only use javascript

```<code>var fontChange = document.getElementsByClass("change").getElementsByTagName("p");

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseover=function() {
        this.style.color = "red";
    }
}

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseout=function() {
        this.style.color = "black";
    }
}
</code>```

答:
You can achieve what you want without javascript, just add this code to your css</p>

```<code>.change p:hover {
    color: red;
 }
</code>```

Body:
Hello I am kind of stuck right now. I am trying to make my script choose all paragraph inside a div class of change but I don't really understand how to do it. The html looks something like this in the body

 Microsoft

 Apple

 Sony

 Disney

 Nintendo

 Sony

 Ice

 Tea

 Water

I am trying to make it so when the mouse cursor touches anything that has a class of change in a paragraph, it will change the color to a color of my choice but I don't know how to do it with selectors with pure javascript. This is the current code I have but it is not working. I can only use javascript

var fontChange = document.getElementsByClass("change").getElementsByTagName("p");

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseover=function() {
        this.style.color = "red";
    }
}

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseout=function() {
        this.style.color = "black";
    }
}

Body:
You can achieve what you want without javascript, just add this code to your css

.change p:hover {
    color: red;
 }


问:
Python check if element of array contains string
I have an array that has 1 element. This element contains:
print(results_read[0])

```<code>[(u'n04019541', u'puck', 0.57829314), (u'n02974003', u'car_wheel', 0.24903433), (u'n03483316', u'hand_blower', 0.025689969), (u'n02910353', u'buckle', 0.015434729), (u'n04542943', u'waffle_iron', 0.012205523)]
</code>```

How can I check if it contains 'car_wheel'?
I tried:

```<code>if 'car_wheel' in results_read:
      print('yes')
else:
    print('no')
</code>```

Is there any other way to do this?

答:
It seems you have a list of list of tuples, you need to loop through the list to do the check one by one; If you just want to know if any tuple contains car_wheel, you can use any for that:

```<code>any('car_wheel' in t for t in results_read[0])
# True
</code>```

Body:
I have an array that has 1 element. This element contains:
print(results_read[0])

[(u'n04019541', u'puck', 0.57829314), (u'n02974003', u'car_wheel', 0.24903433), (u'n03483316', u'hand_blower', 0.025689969), (u'n02910353', u'buckle', 0.015434729), (u'n04542943', u'waffle_iron', 0.012205523)]

How can I check if it contains 'car_wheel'?
I tried:

if 'car_wheel' in results_read:
      print('yes')
else:
    print('no')

Is there any other way to do this?

Body:
It seems you have a list of list of tuples, you need to loop through the list to do the check one by one; If you just want to know if any tuple contains car_wheel, you can use any for that:

any('car_wheel' in t for t in results_read[0])
# True


问:
Immutable.js - TypeError: get(...).toJS is not a function
struggling on ImmutableJS... getting error:

TypeError: this.props.dataTable.get(...).toJS is not a function

relating to this line:

```<code>let tbodyRows = this.props.dataTable.get('data').toJS();
</code>```

When I do console.log this.props.dataTable.get('data') I get Array[1] and this array contains a single object of data (which is what I would expect).

答: In order to use .toJS(), this.props.dataTable.get('data') should be returning a List (in this case) not an Array.

Body:
struggling on ImmutableJS... getting error:

TypeError: this.props.dataTable.get(...).toJS is not a function

relating to this line:

let tbodyRows = this.props.dataTable.get('data').toJS();

When I do console.log this.props.dataTable.get('data') I get Array[1] and this array contains a single object of data (which is what I would expect).


Title: Python check if element of array contains string

Body:
You can do something like this :

results_read = [(u'n04019541', u'puck', 0.57829314), (u'n02974003', u'car_wheel', 0.24903433), (u'n03483316', u'hand_blower', 0.025689969), (u'n02910353', u'buckle', 0.015434729), (u'n04542943', u'waffle_iron', 0.012205523)]

if 'car_wheel' in [results[1] for results in results_read] :
      print('yes')
else:
    print('no')

This will result in :

yes


答:
try this

added this code

```<code>sum(case when pr_grades.Grade='Grade1' then pf_harvest.quantity else 0 end)) [Grade1],
      sum(case when pr_grades.Grade='Grade2' then pf_harvest.quantity else 0 end)) [Grade2]
</code>```

```<code>SELECT
  pr_products.product AS PRODUCT,
  pr_varieties.variety AS VARIETY,
  sum(case when pr_grades.Grade='Grade1' then pf_harvest.quantity else 0 end)) [Grade1],
  sum(case when pr_grades.Grade='Grade2' then pf_harvest.quantity else 0 end)) [Grade2],
  SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance
  ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products
  ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties
  ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades
  ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = '2017-03-22'
GROUP BY pf_harvest.id_product,
         pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade;
</code>```

Title: Show query result differently

Body:
I have this query:

SELECT pr_products.product AS PRODUCT, pr_varieties.variety AS VARIETY, pr_grades.GRADE, SUM(pf_harvest.quantity) AS QUANTITY
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = '2017-03-22'
GROUP BY pf_harvest.id_product, pf_harvest.id_variety, pf_harvest.id_grade
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade;

Which shows me the following result:

-------------------------------------------------------------------
   PRODUCT     |     VARIETY     |     GRADE      |     QUANTITY  |
-------------------------------------------------------------------
   ROSE        |     ROSEV1      |     GRADE1     |     1000      |
-------------------------------------------------------------------
   ROSE        |     ROSEV1      |     GRADE2     |     5000      |
-------------------------------------------------------------------
   ROSE        |     ROSEV2      |     GRADE1     |     2000      |
-------------------------------------------------------------------
   ROSE1       |     ROSE1V1     |     GRADE1     |     3500      |
-------------------------------------------------------------------

Is it possible to display the query result as follows?

-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GRADE1  |  GRADE2 |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ROSEV1    |  1000    |  5000   |  6000          |
-------------------------------------------------------------------
   ROSE       |   ROSEV2    |  2000    |    0    |  2000          |
-------------------------------------------------------------------
   ROSE1      |   ROSE1V1   |  3500    |    0    |  3500          |
-------------------------------------------------------------------

I tried to change the query but I could not and I would like to know if it is possible, I hope someone can help me.

UPDATED
NOTE: There may be more GRADES in the query result (GRADE1, GRADE2, GRADE3...).

Thanks!

Body:
try this

added this code

sum(case when pr_grades.Grade='Grade1' then pf_harvest.quantity else 0 end)) [Grade1],
      sum(case when pr_grades.Grade='Grade2' then pf_harvest.quantity else 0 end)) [Grade2]

SELECT
  pr_products.product AS PRODUCT,
  pr_varieties.variety AS VARIETY,
  sum(case when pr_grades.Grade='Grade1' then pf_harvest.quantity else 0 end)) [Grade1],
  sum(case when pr_grades.Grade='Grade2' then pf_harvest.quantity else 0 end)) [Grade2],
  SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance
  ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products
  ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties
  ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades
  ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = '2017-03-22'
GROUP BY pf_harvest.id_product,
         pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade;


问:
Compiling driver for ARMv7 vs ARMv5
I've managed to compile a driver for an ARM based device, but the driver crashed when I try to load it.
here is the output from cpuinfo:

```<code>Processor       : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 999.42
Features        : swp half thumb fastmult vfp edsp neon vfpv3
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc08
CPU revision    : 2
</code>```

Here is the uname -r output

```<code>2.6.37
</code>```

modinfo driver.ko

```<code>filename:       cp210x.ko
description:    Silicon Labs CP210x RS232 serial adaptor driver
license:        GPL
vermagic:       2.6.37 mod_unload ARMv7
vermagic:       2.6.37 mod_unload modversions ARMv5
parm:           debug:Enable verbose debugging messages
</code>```

As you can I've added an extra vermagic (2.6.37 mod_unload ARMv7) so it will match the target system.

So if I understand this correct, I've compiled this module for an ARMv5 cpu, while the target is v7. Could this be the cause of the device driver crashing?

The device has this driver, but its embedded into an other driver package from the hw producer. This package also load some drivers that we cannot use. This driver package is not load, but I guess this indicate that this driver should work on this hardware some how.

here is the crash log

```<code>modprobe cp210x.ko
Unable to handle kernel NULL pointer dereference at virtual address 0000000a
pgd = ca1fc000
[0000000a] *pgd=870dd031, *pte=00000000, *ppte=00000000
Internal error: Oops: 17 [#1]
last sysfs file: /sys/kernel/uevent_seqnum
Modules linked in: dahdi_dummy dahdi cmemk syslink ipt_MASQUERADE nf_nat iptable_filter ip_tables ipt_LOG xt_state nf_conntrack_ftp nf_conntrack_ipv4 nf_conntrack nf_defrag_ipv4 xt_recent xt_mac xt_limit work_led reset_button ipv6
CPU: 0    Not tainted  (2.6.37 #1)
PC is at sys_init_module+0xfe0/0x1460
LR is at sys_init_module+0xe7c/0x1460
pc : [<c00836e8>]    lr : [<c0083584>]    psr: 20000013
sp : cc5e9ed0  ip : bf3828dc  fp : cc5e8000
r10: bf385ca8  r9 : cf3bcb4e  r8 : 000000c5
r7 : 00000027  r6 : bf382544  r5 : bf38266c  r4 : bf385ca8
r3 : 00000000  r2 : c7c9f000  r1 : 0000000a  r0 : 0000000a
Flags: nzCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
Control: 10c5387d  Table: 8a1fc019  DAC: 00000015
Process modprobe (pid: 2676, stack limit = 0xcc5e82e8)
Stack: (0xcc5e9ed0 to 0xcc5ea000)
9ec0:                                     bf382544 00000001 000ac048 bf382550
9ee0: 000000c5 cf3bd5a4 cf3b8000 000055f4 cf3bd20c cf3bd128 cf3bc2a0 c7c9f000
9f00: 0000266c 000028dc 00000000 00000000 00000017 00000018 00000010 0000000d
9f20: 00000009 00000000 6e72656b 00006c65 00000000 00000000 00000000 00000000
9f40: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
9f60: 00000000 00000000 c9a19540 00000000 ca2403c0 00000006 c9a19540 00000000
9f80: ca2403c0 000055f4 00000000 00000006 00000080 c0037c28 cc5e8000 00000000
9fa0: 00000001 c0037a80 000055f4 00000000 000ac998 000055f4 000ac048 000ac978
9fc0: 000055f4 00000000 00000006 00000080 000ac008 000ac028 000ac998 00000001
9fe0: bebaf968 bebaf958 00017764 40214740 60000010 000ac998 c1e38bcc 03de8ad9
[<c00836e8>] (sys_init_module+0xfe0/0x1460) from [<c0037a80>] (ret_fast_syscall+0x0/0x30)
Code: e7923103 e1a03133 e3130001 15963128 (17d33000)
---[ end trace 6e8943127db36208 ]---
Segmentation fault
</code>```

答:
Are you trying to load a kernel module that was compiled for one kernel into another kernel?   Linux modules (what you call drivers) are only supposed to be loaded into the kernel that they were compiled for.  Even the same version of the kernel with different configuration or compiler settings could render the module incompatible.  So playing with version magic is very dangerous.

The reason your driver is crashing is because it is trying to access kernel data structures using incorrect layout, so it is not actually reading the attributes it thinks it should be reading.

Changing architecture from ARMv7 to ARMv5 is very drastic configuration change that will completely change the memory layout of kernel data structures.

Unlike some other operating systems like Windows,  Linux does not have an abstraction layer or fixed memory layouts that let you load the same loadable module into different versions of the kernel.

Title: Compiling driver for ARMv7 vs ARMv5

Body:
I've managed to compile a driver for an ARM based device, but the driver crashed when I try to load it.
here is the output from cpuinfo:

Processor       : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 999.42
Features        : swp half thumb fastmult vfp edsp neon vfpv3
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc08
CPU revision    : 2

Here is the uname -r output

2.6.37

modinfo driver.ko

filename:       cp210x.ko
description:    Silicon Labs CP210x RS232 serial adaptor driver
license:        GPL
vermagic:       2.6.37 mod_unload ARMv7
vermagic:       2.6.37 mod_unload modversions ARMv5
parm:           debug:Enable verbose debugging messages

As you can I've added an extra vermagic (2.6.37 mod_unload ARMv7) so it will match the target system.

So if I understand this correct, I've compiled this module for an ARMv5 cpu, while the target is v7. Could this be the cause of the device driver crashing?

The device has this driver, but its embedded into an other driver package from the hw producer. This package also load some drivers that we cannot use. This driver package is not load, but I guess this indicate that this driver should work on this hardware some how.

here is the crash log

modprobe cp210x.ko
Unable to handle kernel NULL pointer dereference at virtual address 0000000a
pgd = ca1fc000
[0000000a] *pgd=870dd031, *pte=00000000, *ppte=00000000
Internal error: Oops: 17 [#1]
last sysfs file: /sys/kernel/uevent_seqnum
Modules linked in: dahdi_dummy dahdi cmemk syslink ipt_MASQUERADE nf_nat iptable_filter ip_tables ipt_LOG xt_state nf_conntrack_ftp nf_conntrack_ipv4 nf_conntrack nf_defrag_ipv4 xt_recent xt_mac xt_limit work_led reset_button ipv6
CPU: 0    Not tainted  (2.6.37 #1)
PC is at sys_init_module+0xfe0/0x1460
LR is at sys_init_module+0xe7c/0x1460
pc : [<c00836e8>]    lr : [<c0083584>]    psr: 20000013
sp : cc5e9ed0  ip : bf3828dc  fp : cc5e8000
r10: bf385ca8  r9 : cf3bcb4e  r8 : 000000c5
r7 : 00000027  r6 : bf382544  r5 : bf38266c  r4 : bf385ca8
r3 : 00000000  r2 : c7c9f000  r1 : 0000000a  r0 : 0000000a
Flags: nzCv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
Control: 10c5387d  Table: 8a1fc019  DAC: 00000015
Process modprobe (pid: 2676, stack limit = 0xcc5e82e8)
Stack: (0xcc5e9ed0 to 0xcc5ea000)
9ec0:                                     bf382544 00000001 000ac048 bf382550
9ee0: 000000c5 cf3bd5a4 cf3b8000 000055f4 cf3bd20c cf3bd128 cf3bc2a0 c7c9f000
9f00: 0000266c 000028dc 00000000 00000000 00000017 00000018 00000010 0000000d
9f20: 00000009 00000000 6e72656b 00006c65 00000000 00000000 00000000 00000000
9f40: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
9f60: 00000000 00000000 c9a19540 00000000 ca2403c0 00000006 c9a19540 00000000
9f80: ca2403c0 000055f4 00000000 00000006 00000080 c0037c28 cc5e8000 00000000
9fa0: 00000001 c0037a80 000055f4 00000000 000ac998 000055f4 000ac048 000ac978
9fc0: 000055f4 00000000 00000006 00000080 000ac008 000ac028 000ac998 00000001
9fe0: bebaf968 bebaf958 00017764 40214740 60000010 000ac998 c1e38bcc 03de8ad9
[<c00836e8>] (sys_init_module+0xfe0/0x1460) from [<c0037a80>] (ret_fast_syscall+0x0/0x30)
Code: e7923103 e1a03133 e3130001 15963128 (17d33000)
---[ end trace 6e8943127db36208 ]---
Segmentation fault


问:
bash script to run multiple C++ codes only after previous code has been finished
I want to run multiple C++ codes using bash script on a Linux cluster. I am able to do that but as multiple codes run at the same time on the cluster it becomes slow. Therefore, I want to run these simulations using bash script such that, the next code only starts running when the previous one has been completed.

I have been using sleep command for now by specifying number of hours it might run but as I do not know the run time before hand it is very inefficient. The next code has to wait till the sleep time is over.

This how my current bash script looks

```<code>#!/bin/bash
cd /home/Rectilinear_box_Loverl_16
make clean
make -f Makefile
echo "L/l = 16 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 16 completed"

cd /home/Rectilinear_box_Loverl_14
make clean
make -f Makefile
echo "\nL/l = 14 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 14 completed"

cd /home/Rectilinear_box_Loverl_12
make clean
make -f Makefile
echo "\nL/l = 12 started"
./Rod input_file.xml > log &
echo "L/l = 12 completed"
</code>```

each code takes different amount of time to finish but I have specified the maximum amount of time to be safe.

Could someone suggest a good way to do it?

答:
If you do not run your programs in the background, it will not move to the next command until that particular run is complete.

For example, remove your sleep commands and do this:

```<code>./Rod input_file.xml > log
</code>```

And NOT:

```<code>./Rod input_file.xml > log &
</code>```

Remove the ampersand indicating it should run.  Also I recommend putting this at the top:
    touch log

And use the >> instead of > to append to the log.

Body:
I want to run multiple C++ codes using bash script on a Linux cluster. I am able to do that but as multiple codes run at the same time on the cluster it becomes slow. Therefore, I want to run these simulations using bash script such that, the next code only starts running when the previous one has been completed.

I have been using sleep command for now by specifying number of hours it might run but as I do not know the run time before hand it is very inefficient. The next code has to wait till the sleep time is over.

This how my current bash script looks

#!/bin/bash
cd /home/Rectilinear_box_Loverl_16
make clean
make -f Makefile
echo "L/l = 16 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 16 completed"

cd /home/Rectilinear_box_Loverl_14
make clean
make -f Makefile
echo "\nL/l = 14 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 14 completed"

cd /home/Rectilinear_box_Loverl_12
make clean
make -f Makefile
echo "\nL/l = 12 started"
./Rod input_file.xml > log &
echo "L/l = 12 completed"

each code takes different amount of time to finish but I have specified the maximum amount of time to be safe.

Could someone suggest a good way to do it?

Body:
If you do not run your programs in the background, it will not move to the next command until that particular run is complete.

For example, remove your sleep commands and do this:

./Rod input_file.xml > log

And NOT:

./Rod input_file.xml > log &

Remove the ampersand indicating it should run.  Also I recommend putting this at the top:
    touch log

And use the >> instead of > to append to the log.


问:
AmChart- After updating fieldMappings and dataSet,Graph is not plotting
Problem Statement:

after updating fieldMappings and dataSet during runtime(After clicking on a button) for a stockgraph, validateNow() / validteData() is not plotting the graph.

Note: MACD0 is added from 25th element onward and expoSignalLine0 is added from 33rd element onward in the dataprovider and fieldMapping is also getting updated and can be verified same in console.enter code here

Following is the Code snippet:
(addMACD function is called on click of a button)

```<code>function addMACD() {
    var chart = AmCharts.charts[ 0 ];
    AmCharts.MACDGraphs = 0;
    AmCharts.expoSignalLineGraphs = 0;
    var MACDField = "MACD"+ AmCharts.MACDGraphs;
    var expoSignalLineField = "expoSignalLine"+ AmCharts.expoSignalLineGraphs;

    chart.dataSets[0].fieldMappings.push( {
            fromField : MACDField,
            toField : MACDField
    },

    {
            fromField : expoSignalLineField,
            toField : expoSignalLineField
    });

     var currClose;
     var prevClose;
     var twelveDayEMA =[];
     var twentySixDayEMA =[];
     var MACDarray = [];
     var signalLineArray = [];
     var MACDperiod = 9 ;// 9 day exponential average
    for ( var i = 1; i < (chart.dataSets[0].dataProvider.length); i++) {

            var dp = chart.dataSets[0].dataProvider[i - 1];
            prevClose = parseFloat(dp["close"]);

            var dp = chart.dataSets[0].dataProvider[i];
            currClose = parseFloat(dp["close"]);
            if( i==1){
                    twelveDayEMA[i] = (0.15*currClose) + (0.85*prevClose);
                    twentySixDayEMA[i] = (0.075*currClose) + (0.925*prevClose);
            }
            else{
                    twelveDayEMA[i] = (0.15*currClose) + (0.85*twelveDayEMA[i - 1]);
                    twentySixDayEMA[i] = (0.075*currClose) + (0.925*twentySixDayEMA[i - 1]);
            }

            if(i >= 25){

                    MACDarray[i] = twelveDayEMA[i] - twentySixDayEMA[i] ;
                    dp[MACDField] = MACDarray[i];

                    if(i == 25){
                            signalLineArray[i] =  MACDarray[i];

                    }
                    else{
                            signalLineArray[i] = ( MACDarray[i]*(2/( MACDperiod + 1)) ) + ( signalLineArray[i - 1]*(1-(2/( MACDperiod + 1))) )
                    }
            }
            if(i >=33){
                    dp[expoSignalLineField] = signalLineArray[i];
            }

    }
    console.log(chart);

  if ( chart.panels.length == 1 || chart.panels.length == 2 || chart.panels.length == 3 || chart.panels.length == 4 || chart.panels.length == 5) {

var newPanel = new AmCharts.StockPanel();
newPanel.allowTurningOff = true;
newPanel.title = "MACD";
newPanel.showCategoryAxis = false;

graph1 = new AmCharts.StockGraph();
graph1.valueField = MACDField;
graph1.useDataSetColors = false;
graph1.lineColor="#6699FF";
graph1.title = "MACD";
newPanel.stockGraphs.push( graph1 );

graph2 = new AmCharts.StockGraph();
graph2.valueField =expoSignalLineField;
graph2.useDataSetColors = false;
graph2.lineColor = "#990000";
graph2.title = "MACD2";
newPanel.stockGraphs.push( graph2 );

var legend = new AmCharts.StockLegend();
legend.markerType = "none";
legend.markerSize = 0;
newPanel.stockLegend = legend;
chart.addPanelAt( newPanel, 1 );

 chart.validateData();
 chart.validateNow();
 //chart.write("chartdiv");
  }
 }
</code>```

答:
You have to call validateNow first, then call validateData.

Alternatively, you can call validateNow(true, false) which has the same effect as calling the two functions separately.

Updated fiddle

Body:
Problem Statement:

after updating fieldMappings and dataSet during runtime(After clicking on a button) for a stockgraph, validateNow() / validteData() is not plotting the graph.

Note: MACD0 is added from 25th element onward and expoSignalLine0 is added from 33rd element onward in the dataprovider and fieldMapping is also getting updated and can be verified same in console.enter code here

Following is the Code snippet:
(addMACD function is called on click of a button)

function addMACD() {
    var chart = AmCharts.charts[ 0 ];
    AmCharts.MACDGraphs = 0;
    AmCharts.expoSignalLineGraphs = 0;
    var MACDField = "MACD"+ AmCharts.MACDGraphs;
    var expoSignalLineField = "expoSignalLine"+ AmCharts.expoSignalLineGraphs;

    chart.dataSets[0].fieldMappings.push( {
            fromField : MACDField,
            toField : MACDField
    },

    {
            fromField : expoSignalLineField,
            toField : expoSignalLineField
    });

     var currClose;
     var prevClose;
     var twelveDayEMA =[];
     var twentySixDayEMA =[];
     var MACDarray = [];
     var signalLineArray = [];
     var MACDperiod = 9 ;// 9 day exponential average
    for ( var i = 1; i < (chart.dataSets[0].dataProvider.length); i++) {

            var dp = chart.dataSets[0].dataProvider[i - 1];
            prevClose = parseFloat(dp["close"]);

            var dp = chart.dataSets[0].dataProvider[i];
            currClose = parseFloat(dp["close"]);
            if( i==1){
                    twelveDayEMA[i] = (0.15*currClose) + (0.85*prevClose);
                    twentySixDayEMA[i] = (0.075*currClose) + (0.925*prevClose);
            }
            else{
                    twelveDayEMA[i] = (0.15*currClose) + (0.85*twelveDayEMA[i - 1]);
                    twentySixDayEMA[i] = (0.075*currClose) + (0.925*twentySixDayEMA[i - 1]);
            }

            if(i >= 25){

                    MACDarray[i] = twelveDayEMA[i] - twentySixDayEMA[i] ;
                    dp[MACDField] = MACDarray[i];

                    if(i == 25){
                            signalLineArray[i] =  MACDarray[i];

                    }
                    else{
                            signalLineArray[i] = ( MACDarray[i]*(2/( MACDperiod + 1)) ) + ( signalLineArray[i - 1]*(1-(2/( MACDperiod + 1))) )
                    }
            }
            if(i >=33){
                    dp[expoSignalLineField] = signalLineArray[i];
            }

    }
    console.log(chart);

  if ( chart.panels.length == 1 || chart.panels.length == 2 || chart.panels.length == 3 || chart.panels.length == 4 || chart.panels.length == 5) {

var newPanel = new AmCharts.StockPanel();
newPanel.allowTurningOff = true;
newPanel.title = "MACD";
newPanel.showCategoryAxis = false;

graph1 = new AmCharts.StockGraph();
graph1.valueField = MACDField;
graph1.useDataSetColors = false;
graph1.lineColor="#6699FF";
graph1.title = "MACD";
newPanel.stockGraphs.push( graph1 );

graph2 = new AmCharts.StockGraph();
graph2.valueField =expoSignalLineField;
graph2.useDataSetColors = false;
graph2.lineColor = "#990000";
graph2.title = "MACD2";
newPanel.stockGraphs.push( graph2 );

var legend = new AmCharts.StockLegend();
legend.markerType = "none";
legend.markerSize = 0;
newPanel.stockLegend = legend;
chart.addPanelAt( newPanel, 1 );

 chart.validateData();
 chart.validateNow();
 //chart.write("chartdiv");
  }
 }


问:
Hide elements based on routing in Angular2 rc1
I have some elements I want on every page except the login page. I'd like to use ngIf or possibly the hidden property of the elements to hide those elements when the user is on the login page.

I have tried this:

```<code><div [hidden]="router.isRouteActive(router.generate('/login'))">
</code>```

based on this question and answer: In Angular 2 how do you determine the active route?

And have also tried this:

```<code> <div *ngIf="!router.isRouteActive(router.generate('/login'))">
</code>```

but haven't had any success.

For reference here is the component that matches this html.

```<code>import { Component, OnInit } from 'node_modules/@angular/core';
import { HTTP_PROVIDERS, XHRBackend } from 'node_modules/@angular/http';
import { Routes, Router, ROUTER_DIRECTIVES } from 'node_modules/@angular/router';

import { LoginService } from './login/login.service';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';

@Component({
    selector: 'portal',
    templateUrl: 'portal/portal.component.html',
    directives: [ROUTER_DIRECTIVES, LoginComponent, UserComponent ],
    providers: [
        HTTP_PROVIDERS,
        LoginService
    ]
})

@Routes([
    { path: '/login', component: LoginComponent},
    { path: '/user/:username', component: UserComponent}
])

export class PortalComponent implements OnInit{
    private router: Router
    constructor() {}

    ngOnInit() {
        this.router.navigate(['/login']);
    }
}
</code>```

The documentation for isRouteActive is pretty slim, the same for generate. Any direction on a better way to achieve this behavior?

答:
At least with more recent versions of angular 2 and depending on the specific use case.You can transclude the content and only add it on the route component where you want it. Much better than maintaining a list of routes and using ngIf conditions.

In your component template.
Add an ngcontent element and use select to give it a name

```<code><ng-content select="[content-name]"></ng-content>
</code>```

Then you can use that component and transclude the content.

```<code><component>
<div content-name> transcluded content</div>
</component>
</code>```

Or use it without referencing the transcluded content

```<code><component>
</component>
</code>```

Body:
I have some elements I want on every page except the login page. I'd like to use ngIf or possibly the hidden property of the elements to hide those elements when the user is on the login page.

I have tried this:

based on this question and answer: In Angular 2 how do you determine the active route?

And have also tried this:

but haven't had any success.

For reference here is the component that matches this html.

import { Component, OnInit } from 'node_modules/@angular/core';
import { HTTP_PROVIDERS, XHRBackend } from 'node_modules/@angular/http';
import { Routes, Router, ROUTER_DIRECTIVES } from 'node_modules/@angular/router';

import { LoginService } from './login/login.service';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';

@Component({
    selector: 'portal',
    templateUrl: 'portal/portal.component.html',
    directives: [ROUTER_DIRECTIVES, LoginComponent, UserComponent ],
    providers: [
        HTTP_PROVIDERS,
        LoginService
    ]
})

@Routes([
    { path: '/login', component: LoginComponent},
    { path: '/user/:username', component: UserComponent}
])

export class PortalComponent implements OnInit{
    private router: Router
    constructor() {}

    ngOnInit() {
        this.router.navigate(['/login']);
    }
}

The documentation for isRouteActive is pretty slim, the same for generate. Any direction on a better way to achieve this behavior?

Body:
At least with more recent versions of angular 2 and depending on the specific use case.You can transclude the content and only add it on the route component where you want it. Much better than maintaining a list of routes and using ngIf conditions.

In your component template.
Add an ngcontent element and use select to give it a name

<ng-content select="[content-name]"></ng-content>

Then you can use that component and transclude the content.

<component>
<div content-name> transcluded content</div>
</component>

Or use it without referencing the transcluded content

<component>
</component>


问:
jQuery: make checkboxes act like radio buttons?
Is there a way to make checkboxes act like radio buttons? I assume this could be done with jQuery?

```<code><input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />

<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
</code>```

If one box was checked the others in the group would uncheck.

答:
The solution given doesn't care about the initial state, which is different from the radio buttons behavior. Plus, it also triggers a change event when clicking on an already checked input.

var $elements = $('input:checkbox');

// Allow only one input to be selected
$elements.filter(':checked:not(:last)').prop('checked', false);

// Get selected input
var selected = $elements.filter(':checked')[0] || {};

// Handle event
$(document).on('click', 'input:checkbox', function(e) {
  if (e.currentTarget === selected) {
    e.preventDefault();
  } else {
    selected.checked = false;
    selected = e.currentTarget;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input type="checkbox" value="0" /> test 0</label>
<label><input type="checkbox" value="1" checked /> test 1</label>
<label><input type="checkbox" value="2" checked /> test 2</label>
<label><input type="checkbox" value="3" /> test 3</label></code>```

I also agree that doing that is a bad idea, but if you have a different name for each input (and can't change them), there is no other choice...

Body:
Is there a way to make checkboxes act like radio buttons? I assume this could be done with jQuery?

<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />

<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />

If one box was checked the others in the group would uncheck.

Body:
The solution given doesn't care about the initial state, which is different from the radio buttons behavior. Plus, it also triggers a change event when clicking on an already checked input.

var $elements = $('input:checkbox');

// Allow only one input to be selected
$elements.filter(':checked:not(:last)').prop('checked', false);

// Get selected input
var selected = $elements.filter(':checked')[0] || {};

// Handle event
$(document).on('click', 'input:checkbox', function(e) {
  if (e.currentTarget === selected) {
    e.preventDefault();
  } else {
    selected.checked = false;
    selected = e.currentTarget;
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input type="checkbox" value="0" /> test 0</label>
<label><input type="checkbox" value="1" checked /> test 1</label>
<label><input type="checkbox" value="2" checked /> test 2</label>
<label><input type="checkbox" value="3" /> test 3</label>

I also agree that doing that is a bad idea, but if you have a different name for each input (and can't change them), there is no other choice...


答:
You may start a background process (in this example sleep 5 is the background process) and wait for it. Try this example:

```<code>#!/bin/bash

# Do job #1
sleep 5 &
sleeppid=$!

# Wait for job #1 to finish
echo sleep started: $(date)
wait "$sleeppid"
echo sleep ended: $(date)

# Do job #2
sleep 5 &
sleeppid=$!

# Wait for job #2 to finish
echo sleep started: $(date)
wait "$sleeppid"
echo sleep ended: $(date)
</code>```

Title: bash script to run multiple C++ codes only after previous code has been finished

Body:
You may start a background process (in this example sleep 5 is the background process) and wait for it. Try this example:

#!/bin/bash

# Do job #1
sleep 5 &
sleeppid=$!

# Wait for job #1 to finish
echo sleep started: $(date)
wait "$sleeppid"
echo sleep ended: $(date)

# Do job #2
sleep 5 &
sleeppid=$!

# Wait for job #2 to finish
echo sleep started: $(date)
wait "$sleeppid"
echo sleep ended: $(date)


问:
How do you add real time viewer count for a livestream?
Currently it seems that JWPlayer does not support the display of unique viewers on a livestream (the feature is only available for VOD, according to JWPlayer documentation).

I found the following two links on Wowza's forums:

How to send connection and stream statistics to Google Analytics (Analytics)

How to get connection counts for server, applications, application instances and streams with an HTTP Provider

Having read through several Stack overflow articles, it appears that unique viewers is defined by more than connection count. Any advice or direction toward (even toward other resources) would be greatly appreciated.

Context: I'm working on a livestreaming and VOD application using JWPlayer, Wowza Streaming Engine, and Wirecast.

答: If you use Wowza, you can use WMSPanel unique viewers metric. It's based on a combination of IP and user agent within 24 hours time slot.</p>


问:
HTML/CSS Gives Image with Transparent Background a White Background
I am essentially trying to create an image with a play button in the bottom left corner, that will link to another page to play an audio file. However, I am having a couple issues. First and foremost, even though I specifically am using a play button with a transparent background, it gives it a white background which covers up the image it's on. I tried "background-color: transparent;" for the play button, but that didn't work. Additionally, I am not sure how to resize my play button. I've tried to change the width and height of the image via the "post" class and "post0001" id, but it doesn't seem to work. I apologize if this is too many questions for one post. My code is below. Thank you very much.

* {
  margin: 0;
  padding: 0;
  background-color: rgb(300, 300, 300);
}

.topnav {
  padding-top: 50px;
  /*padding-left: 200px;*/
  position: relative;
  letter-spacing: 2px;
  float: left;
}

.topnav a {
  font-size: 20px;
  color: black;
  text-decoration: none;
  border-bottom-width: 5px;
  border-bottom-style: solid;
  margin-bottom: 35px;
  margin-left: 80px;
}

#episodes {
  border-bottom-color: rgb(219, 50, 54);
}

#sources {
  border-bottom-color: rgb(72, 133, 237);
}

#about {
  border-bottom-color: rgb(244, 194, 13);
  /*padding-left: 15px;
        padding-right: 15px;*/
}

#contact {
  border-bottom-color: rgb(60, 186, 84);
}

.post {
  position: fixed;
  margin-top: auto;
  width: auto;
  top: 120px;
}

#post0001 {
  width: 500px;
  height: 500px;
  background-image: url(https://static.pexels.com/photos/298611/pexels-photo-298611.jpeg);
  background-repeat: no-repeat;
  padding-bottom: 200px;
  padding-right: 350px;
  padding-left: 15px;
  padding-top: 45px;
}

.logo {
  font-size: 80px;
  color: black;
  font-family: sans-serif;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="dontgoogleit.css">
  <div class=l ogo>
    DGI
    <!-- <img src = -->
  </div>
  <title>
    pls dnt
  </title>
  <div class="topnav" id="myTopnav">
    EPISODES
    SOURCES
    ABOUT
    CONTACT US
  </div>
</head>

<body>
  <div class="post" id="post0001">
    <img src="http://www.pngmart.com/files/3/Play-Button-Transparent-Background.png" alt="Play Button" href="#episodeOne">
  </div>

</html></code>```

答:
The problem is simply that you set a global background colour of white:

```<code>* {
  background-color: rgb(300, 300, 300);
}
</code>```

The * denotes that every element should have the background colour, including your image. Simply remove this, and your button will display as transparent.

Alternatively, you can ensure the image background is transparent by explicitly stating that it should be:

```<code>.post img {
  background: transparent;
}
</code>```

Also, if you just want the navigation to have the background, you need to specify that with:

```<code>.topnav {
  background-color: rgb(300, 300, 300);
}
</code>```

I've created a JSFiddle showcasing this here.

Hope this helps! :)

ContentLicense: CC BY-SA 4.0

Body:
I am essentially trying to create an image with a play button in the bottom left corner, that will link to another page to play an audio file. However, I am having a couple issues. First and foremost, even though I specifically am using a play button with a transparent background, it gives it a white background which covers up the image it's on. I tried "background-color: transparent;" for the play button, but that didn't work. Additionally, I am not sure how to resize my play button. I've tried to change the width and height of the image via the "post" class and "post0001" id, but it doesn't seem to work. I apologize if this is too many questions for one post. My code is below. Thank you very much.

* {
  margin: 0;
  padding: 0;
  background-color: rgb(300, 300, 300);
}

.topnav {
  padding-top: 50px;
  /*padding-left: 200px;*/
  position: relative;
  letter-spacing: 2px;
  float: left;
}

.topnav a {
  font-size: 20px;
  color: black;
  text-decoration: none;
  border-bottom-width: 5px;
  border-bottom-style: solid;
  margin-bottom: 35px;
  margin-left: 80px;
}

#episodes {
  border-bottom-color: rgb(219, 50, 54);
}

#sources {
  border-bottom-color: rgb(72, 133, 237);
}

#about {
  border-bottom-color: rgb(244, 194, 13);
  /*padding-left: 15px;
        padding-right: 15px;*/
}

#contact {
  border-bottom-color: rgb(60, 186, 84);
}

.post {
  position: fixed;
  margin-top: auto;
  width: auto;
  top: 120px;
}

#post0001 {
  width: 500px;
  height: 500px;
  background-image: url(https://static.pexels.com/photos/298611/pexels-photo-298611.jpeg);
  background-repeat: no-repeat;
  padding-bottom: 200px;
  padding-right: 350px;
  padding-left: 15px;
  padding-top: 45px;
}

.logo {
  font-size: 80px;
  color: black;
  font-family: sans-serif;
  float: left;
}

<!DOCTYPE html>

  <link rel="stylesheet" href="dontgoogleit.css">

    DGI

  <title>
    pls dnt
  </title>

    EPISODES
    SOURCES
    ABOUT
    CONTACT US

Body:
The problem is simply that you set a global background colour of white:

* {
  background-color: rgb(300, 300, 300);
}

The * denotes that every element should have the background colour, including your image. Simply remove this, and your button will display as transparent.

Alternatively, you can ensure the image background is transparent by explicitly stating that it should be:

.post img {
  background: transparent;
}

Also, if you just want the navigation to have the background, you need to specify that with:

.topnav {
  background-color: rgb(300, 300, 300);
}

I've created a JSFiddle showcasing this here.

Hope this helps! :)


问:
Draw a line between to "Max/Min" Points
Well, I'm back with another brain buster :)

I need to draw a line between 2 shots that are the max spread.

I am using the below code, but it draws the lines between the rectangle corners.  I know this is wrong, but not sure how to find the points using this code.

I updated the code very long hand (so my brain can wrap around it).

Basically one of the "L" variables will test out to be the longest.  I then need to grab the corresponding points to that "L" variable.

```<code> Private Sub DrawMaxCTCLine(g As Graphics)
            Dim minx, miny, maxx, maxy As Integer
    Dim P1, P2, P3, P4 As Point
    Dim L1, L2, L3, L4, L5, L6 As Decimal

    maxx = shotList.Max(Function(point) point.X)
    maxy = shotList.Max(Function(point) point.Y)
    minx = shotList.Min(Function(point) point.X)
    miny = shotList.Min(Function(point) point.Y)

    P1 = shotList.Find(Function(point) point.X = maxx)
    P2 = shotList.Find(Function(point) point.Y = maxy)
    P3 = shotList.Find(Function(point) point.X = minx)
    P4 = shotList.Find(Function(point) point.Y = miny)

    L1 = Math.Sqrt((P1.X - P2.X) ^ 2 + (P1.Y - P2.Y) ^ 2)
    L2 = Math.Sqrt((P1.X - P3.X) ^ 2 + (P1.Y - P3.Y) ^ 2)
    L3 = Math.Sqrt((P1.X - P4.X) ^ 2 + (P1.Y - P4.Y) ^ 2)
    L4 = Math.Sqrt((P2.X - P3.X) ^ 2 + (P2.Y - P3.Y) ^ 2)
    L5 = Math.Sqrt((P2.X - P4.X) ^ 2 + (P2.Y - P4.Y) ^ 2)
    L6 = Math.Sqrt((P3.X - P4.X) ^ 2 + (P3.Y - P4.Y) ^ 2)
</code>```

here is a better image of the line i am talking about (highlighted)

Here is an image when only 2 shots are shown (which works)

Here is an image when 3 or more shots are shown (which doesn't work work)
Note the line is drawn to the upper left corner and not the shot

答:
Here is how I got it to work, the long way.  Open to anything that is more concise.</p>

```<code>  Private Sub DrawMaxCTCLine(g As Graphics)
    Dim minx, miny, maxx, maxy As Integer
    Dim P1, P2, P3, P4 As Point
    Dim L1, L2, L3, L4, L5, L6 As Decimal
    Dim maxSpread As Decimal = 0

    maxx = shotList.Max(Function(point) point.X)
    maxy = shotList.Max(Function(point) point.Y)
    minx = shotList.Min(Function(point) point.X)
    miny = shotList.Min(Function(point) point.Y)

    P1 = shotList.Find(Function(point) point.X = maxx)
    P2 = shotList.Find(Function(point) point.Y = maxy)
    P3 = shotList.Find(Function(point) point.X = minx)
    P4 = shotList.Find(Function(point) point.Y = miny)

    L1 = Math.Sqrt((P1.X - P2.X) ^ 2 + (P1.Y - P2.Y) ^ 2)
    L2 = Math.Sqrt((P1.X - P3.X) ^ 2 + (P1.Y - P3.Y) ^ 2)
    L3 = Math.Sqrt((P1.X - P4.X) ^ 2 + (P1.Y - P4.Y) ^ 2)
    L4 = Math.Sqrt((P2.X - P3.X) ^ 2 + (P2.Y - P3.Y) ^ 2)
    L5 = Math.Sqrt((P2.X - P4.X) ^ 2 + (P2.Y - P4.Y) ^ 2)
    L6 = Math.Sqrt((P3.X - P4.X) ^ 2 + (P3.Y - P4.Y) ^ 2)

    Dim lList As New List(Of Decimal)
    lList.Add(L1)
    lList.Add(L2)
    lList.Add(L3)
    lList.Add(L4)
    lList.Add(L5)
    lList.Add(L6)

    maxSpread = lList.Max()

    Dim pn As New Pen(My.Settings.Max_Spread_Line, 1)
    Dim Dash As Single() = {2, 5, 2, 5}

    pn.DashPattern = Dash

    Select Case maxSpread
        Case L1
            g.DrawLine(pn, P1, P2)
        Case L2
            g.DrawLine(pn, P1, P3)
        Case L3
            g.DrawLine(pn, P1, P4)
        Case L4
            g.DrawLine(pn, P2, P3)
        Case L5
            g.DrawLine(pn, P2, P4)
        Case L6
            g.DrawLine(pn, P3, P4)
    End Select

    pn.Dispose()
    lList.Clear()

    Console.WriteLine("P1" & P1.ToString & vbCrLf & "P2" & P2.ToString & vbCrLf & "P3" & P3.ToString & vbCrLf & "P4" & P4.ToString)
    Console.WriteLine(L1.ToString & vbCrLf & L2.ToString & vbCrLf & L3.ToString & vbCrLf & L4.ToString & vbCrLf & L5.ToString & vbCrLf & L6.ToString)
    Console.WriteLine(maxSpread)

End Sub
</code>```

Title: Draw a line between to "Max/Min" Points

Body:
Well, I'm back with another brain buster :)

I need to draw a line between 2 shots that are the max spread.

I am using the below code, but it draws the lines between the rectangle corners.  I know this is wrong, but not sure how to find the points using this code.

I updated the code very long hand (so my brain can wrap around it).

Basically one of the "L" variables will test out to be the longest.  I then need to grab the corresponding points to that "L" variable.

 Private Sub DrawMaxCTCLine(g As Graphics)
            Dim minx, miny, maxx, maxy As Integer
    Dim P1, P2, P3, P4 As Point
    Dim L1, L2, L3, L4, L5, L6 As Decimal

    maxx = shotList.Max(Function(point) point.X)
    maxy = shotList.Max(Function(point) point.Y)
    minx = shotList.Min(Function(point) point.X)
    miny = shotList.Min(Function(point) point.Y)

    P1 = shotList.Find(Function(point) point.X = maxx)
    P2 = shotList.Find(Function(point) point.Y = maxy)
    P3 = shotList.Find(Function(point) point.X = minx)
    P4 = shotList.Find(Function(point) point.Y = miny)

    L1 = Math.Sqrt((P1.X - P2.X) ^ 2 + (P1.Y - P2.Y) ^ 2)
    L2 = Math.Sqrt((P1.X - P3.X) ^ 2 + (P1.Y - P3.Y) ^ 2)
    L3 = Math.Sqrt((P1.X - P4.X) ^ 2 + (P1.Y - P4.Y) ^ 2)
    L4 = Math.Sqrt((P2.X - P3.X) ^ 2 + (P2.Y - P3.Y) ^ 2)
    L5 = Math.Sqrt((P2.X - P4.X) ^ 2 + (P2.Y - P4.Y) ^ 2)
    L6 = Math.Sqrt((P3.X - P4.X) ^ 2 + (P3.Y - P4.Y) ^ 2)

here is a better image of the line i am talking about (highlighted)

Here is an image when only 2 shots are shown (which works)

Here is an image when 3 or more shots are shown (which doesn't work work)
Note the line is drawn to the upper left corner and not the shot

Body:
Here is how I got it to work, the long way.  Open to anything that is more concise.

  Private Sub DrawMaxCTCLine(g As Graphics)
    Dim minx, miny, maxx, maxy As Integer
    Dim P1, P2, P3, P4 As Point
    Dim L1, L2, L3, L4, L5, L6 As Decimal
    Dim maxSpread As Decimal = 0

    maxx = shotList.Max(Function(point) point.X)
    maxy = shotList.Max(Function(point) point.Y)
    minx = shotList.Min(Function(point) point.X)
    miny = shotList.Min(Function(point) point.Y)

    P1 = shotList.Find(Function(point) point.X = maxx)
    P2 = shotList.Find(Function(point) point.Y = maxy)
    P3 = shotList.Find(Function(point) point.X = minx)
    P4 = shotList.Find(Function(point) point.Y = miny)

    L1 = Math.Sqrt((P1.X - P2.X) ^ 2 + (P1.Y - P2.Y) ^ 2)
    L2 = Math.Sqrt((P1.X - P3.X) ^ 2 + (P1.Y - P3.Y) ^ 2)
    L3 = Math.Sqrt((P1.X - P4.X) ^ 2 + (P1.Y - P4.Y) ^ 2)
    L4 = Math.Sqrt((P2.X - P3.X) ^ 2 + (P2.Y - P3.Y) ^ 2)
    L5 = Math.Sqrt((P2.X - P4.X) ^ 2 + (P2.Y - P4.Y) ^ 2)
    L6 = Math.Sqrt((P3.X - P4.X) ^ 2 + (P3.Y - P4.Y) ^ 2)

    Dim lList As New List(Of Decimal)
    lList.Add(L1)
    lList.Add(L2)
    lList.Add(L3)
    lList.Add(L4)
    lList.Add(L5)
    lList.Add(L6)

    maxSpread = lList.Max()

    Dim pn As New Pen(My.Settings.Max_Spread_Line, 1)
    Dim Dash As Single() = {2, 5, 2, 5}

    pn.DashPattern = Dash

    Select Case maxSpread
        Case L1
            g.DrawLine(pn, P1, P2)
        Case L2
            g.DrawLine(pn, P1, P3)
        Case L3
            g.DrawLine(pn, P1, P4)
        Case L4
            g.DrawLine(pn, P2, P3)
        Case L5
            g.DrawLine(pn, P2, P4)
        Case L6
            g.DrawLine(pn, P3, P4)
    End Select

    pn.Dispose()
    lList.Clear()

    Console.WriteLine("P1" & P1.ToString & vbCrLf & "P2" & P2.ToString & vbCrLf & "P3" & P3.ToString & vbCrLf & "P4" & P4.ToString)
    Console.WriteLine(L1.ToString & vbCrLf & L2.ToString & vbCrLf & L3.ToString & vbCrLf & L4.ToString & vbCrLf & L5.ToString & vbCrLf & L6.ToString)
    Console.WriteLine(maxSpread)

End Sub


问:
Getting segmentation fault while printing output
I am trying to know how the array in c is working. so i was implementing some basic array concepts. when i run the program i got the exact output but at the end of the output it says segmentation fault.

```<code>int main(void)
{
    int a[] = {};
    printf("Enter the number:");
    int n = get_int();
    int m = 0;

    for(int i = 0; i<n; i++)
    {
        printf("insert:");
        m = get_int();
        a[i] = m;
    }

    for(int j = 0; j < n; j++)
    {
        printf("%d\n", a[j]);
    }

}
</code>```

output:

```<code>Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault
</code>```

see for the first output it has a size of 3 it doesn't show segmentation fault but for second one it has a size of 5 it shows. so why its happening and what mistake i made.

答:
You need to allocate memory for the array.  Something like:</p>

```<code>int main(void)    {
   int *a;
   ...
   int n = get_int();
   ...
   a = malloc(n * sizeof(int));
   if (!a) {
      // Add error handling here
   }
   ...
}
</code>```

Body:
I am trying to know how the array in c is working. so i was implementing some basic array concepts. when i run the program i got the exact output but at the end of the output it says segmentation fault.

int main(void)
{
    int a[] = {};
    printf("Enter the number:");
    int n = get_int();
    int m = 0;

    for(int i = 0; i<n; i++)
    {
        printf("insert:");
        m = get_int();
        a[i] = m;
    }

    for(int j = 0; j < n; j++)
    {
        printf("%d\n", a[j]);
    }

}

output:

Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault

see for the first output it has a size of 3 it doesn't show segmentation fault but for second one it has a size of 5 it shows. so why its happening and what mistake i made.

Body:
You need to allocate memory for the array.  Something like:

int main(void)    {
   int *a;
   ...
   int n = get_int();
   ...
   a = malloc(n * sizeof(int));
   if (!a) {
      // Add error handling here
   }
   ...
}


问:
paypal the merchant does not accept payment of this type
We are having major trouble when we pay using direct credit card payment from mobile application development. To the live transaction we cannot able to use direct credit card payment.

While using Credit Card: "The merchant does not accept payments of this type."

We are developing the mobile application using ionic framework. Using the ionic-paypal plugin we implemented and Sandbox flow has been verified success using Paypal  REST API. For the live account not working.  Paypal develper page i cannot able to enable the "credit card payment" from the following url "https://developer.paypal.com/developer/accountStatus"

Any additional permission require to live transaction or any other steps and solutions to complete this

答:
PayPal REST API Credit Card payment instrument currently available for US and UK PRO account. If you tried with some other countries except from these two, you'll get an error.

You can read here


问:
Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?
I'm very frustrated. I have a website running on Visual Web Developer 2008 Express with my local database, everything works great. I also have the same web site running on a production server. Everything was working great but tonight I did a "reset" on production.

I deleted a couple of table, re-created them and inserted data. Everything was ok at this time.

I deleted ALL the files via the FTP.

I used the module called "Copy website" in visual studio and copy the site to the website via FTP.

When I log on my website, here is the error I got:

Server Error in '/' Application.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Nothing has changed related to SQL connection, this is OLD code that I always used.
My website is completely paralysed because of this and I feel sick inside because I feel there is nothing I can do.

Can anyone help me please?

答:
I've resolved the issue. It was due to the SQL browser service.

Solution to such problem is one among below -

Check the spelling of the SQL Server instance name that is specified in the connection string.

Use the SQL Server Surface Area Configuration tool to enable SQL Server to accept remote connections over the TCP or named pipes protocols. For more information about the SQL Server Surface Area Configuration Tool, see Surface Area Configuration for Services and Connections.

Make sure that you have configured the firewall on the server instance of SQL Server to open ports for SQL Server and the SQL Server Browser port (UDP 1434).

Make sure that the SQL Server Browser service is started on the server.

link - http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1


问:
Binary Search in 2D Array
I wonder, can binary search  be applied on a 2D array?

What would the conditions on the array be? Sorted on 2D??

What would be the time complexity for it?

How would the algorithm change the boundary of the search (minX,maxX,minY,maxY) ??

Edit:

Binary Search on 1D maintains 2 pointers minX and maxX..
It selects the middle index (minX+maxX)/2 and compare it with the search value, if greater then change maxX, else change minX... until minX>=maxX

Pseudo code for normal binary seacrh:

```<code> min := 1;
  max := N; {array size: var A : array [1..N] of integer}
  repeat
    mid := min + (max - min) div 2;
    if x > A[mid] then
      min := mid + 1
    else
      max := mid - 1;
  until (A[mid] = x) or (min > max);
</code>```

Thanks

答: You can transform 2D array into 1D array and do the binary search here. Complexity is O(log(m * n)) for mxn array.

Title: Binary Search in 2D Array

Body:
I wonder, can binary search  be applied on a 2D array?

What would the conditions on the array be? Sorted on 2D??

What would be the time complexity for it?

How would the algorithm change the boundary of the search (minX,maxX,minY,maxY) ??

Edit:

Binary Search on 1D maintains 2 pointers minX and maxX..
It selects the middle index (minX+maxX)/2 and compare it with the search value, if greater then change maxX, else change minX... until minX>=maxX

Pseudo code for normal binary seacrh:

 min := 1;
  max := N; {array size: var A : array [1..N] of integer}
  repeat
    mid := min + (max - min) div 2;
    if x > A[mid] then
      min := mid + 1
    else
      max := mid - 1;
  until (A[mid] = x) or (min > max);

Thanks


答:
Modify your current query by not grouping on the GRADE column, but instead pivot on that column.  Then, use conditional aggregation to compute the GRADE1 and GRADE2 columns.

```<code>SELECT t3.product AS PRODUCT,
       t4.variety AS VARIETY,
       SUM(CASE WHEN t5.GRADE = 'GRADE1' THEN t1.quantity ELSE 0 END) AS GRADE1,
       SUM(CASE WHEN t5.GRADE = 'GRADE2' THEN t1.quantity ELSE 0 END) AS GRADE2,
       SUM(CASE WHEN t5.GRADE = 'GRADE3' THEN t1.quantity ELSE 0 END) AS GRADE3,
       -- hopefully it is clear how to add more grades
       SUM(t1.quantity) AS TOTAL
FROM pf_harvest t1
INNER JOIN pf_performance t2
    ON t2.id = t1.id_performance
INNER JOIN pr_products t3
    ON t3.id = pf_harvest.id_product
INNER JOIN pr_varieties t4
    ON t4.id = t1.id_variety
INNER JOIN pr_grades t5
    ON t5.id = t1.id_grade
WHERE t2.status = 100 AND
      t1.id_tenant = 1 AND
      t1.date = '2017-03-22'
GROUP BY t1.id_product,
         t1.id_variety
ORDER BY t1.id_product,
         t4.variety,
         t1.id_grade;
</code>```

Title: Show query result differently

Body:
I have this query:

SELECT pr_products.product AS PRODUCT, pr_varieties.variety AS VARIETY, pr_grades.GRADE, SUM(pf_harvest.quantity) AS QUANTITY
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = '2017-03-22'
GROUP BY pf_harvest.id_product, pf_harvest.id_variety, pf_harvest.id_grade
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade;

Which shows me the following result:

-------------------------------------------------------------------
   PRODUCT     |     VARIETY     |     GRADE      |     QUANTITY  |
-------------------------------------------------------------------
   ROSE        |     ROSEV1      |     GRADE1     |     1000      |
-------------------------------------------------------------------
   ROSE        |     ROSEV1      |     GRADE2     |     5000      |
-------------------------------------------------------------------
   ROSE        |     ROSEV2      |     GRADE1     |     2000      |
-------------------------------------------------------------------
   ROSE1       |     ROSE1V1     |     GRADE1     |     3500      |
-------------------------------------------------------------------

Is it possible to display the query result as follows?

-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GRADE1  |  GRADE2 |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ROSEV1    |  1000    |  5000   |  6000          |
-------------------------------------------------------------------
   ROSE       |   ROSEV2    |  2000    |    0    |  2000          |
-------------------------------------------------------------------
   ROSE1      |   ROSE1V1   |  3500    |    0    |  3500          |
-------------------------------------------------------------------

I tried to change the query but I could not and I would like to know if it is possible, I hope someone can help me.

UPDATED
NOTE: There may be more GRADES in the query result (GRADE1, GRADE2, GRADE3...).

Thanks!

Body:
Modify your current query by not grouping on the GRADE column, but instead pivot on that column.  Then, use conditional aggregation to compute the GRADE1 and GRADE2 columns.

SELECT t3.product AS PRODUCT,
       t4.variety AS VARIETY,
       SUM(CASE WHEN t5.GRADE = 'GRADE1' THEN t1.quantity ELSE 0 END) AS GRADE1,
       SUM(CASE WHEN t5.GRADE = 'GRADE2' THEN t1.quantity ELSE 0 END) AS GRADE2,
       SUM(CASE WHEN t5.GRADE = 'GRADE3' THEN t1.quantity ELSE 0 END) AS GRADE3,
       -- hopefully it is clear how to add more grades
       SUM(t1.quantity) AS TOTAL
FROM pf_harvest t1
INNER JOIN pf_performance t2
    ON t2.id = t1.id_performance
INNER JOIN pr_products t3
    ON t3.id = pf_harvest.id_product
INNER JOIN pr_varieties t4
    ON t4.id = t1.id_variety
INNER JOIN pr_grades t5
    ON t5.id = t1.id_grade
WHERE t2.status = 100 AND
      t1.id_tenant = 1 AND
      t1.date = '2017-03-22'
GROUP BY t1.id_product,
         t1.id_variety
ORDER BY t1.id_product,
         t4.variety,
         t1.id_grade;


问:
Splitting a list into N parts of approximately equal length
What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.

I'm looking for something like even_split(L, n) that breaks L into n parts.

```<code>def chunks(L, n):
    """ Yield successive n-sized chunks from L.
    """
    for i in range(0, len(L), n):
        yield L[i:i+n]
</code>```

The code above gives chunks of 3, rather than 3 chunks.  I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.

答:
This is the raison d'être for numpy.array_split*:

```<code>>>> import numpy as np
>>> print(*np.array_split(range(10), 3))
[0 1 2 3] [4 5 6] [7 8 9]
>>> print(*np.array_split(range(10), 4))
[0 1 2] [3 4 5] [6 7] [8 9]
>>> print(*np.array_split(range(10), 5))
[0 1] [2 3] [4 5] [6 7] [8 9]
</code>```

*credit to Zero Piraeus in room 6

Body:
What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.

I'm looking for something like even_split(L, n) that breaks L into n parts.

def chunks(L, n):
    """ Yield successive n-sized chunks from L.
    """
    for i in range(0, len(L), n):
        yield L[i:i+n]

The code above gives chunks of 3, rather than 3 chunks.  I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.

Body:
This is the raison d'être for numpy.array_split*:

>>> import numpy as np
>>> print(*np.array_split(range(10), 3))
[0 1 2 3] [4 5 6] [7 8 9]
>>> print(*np.array_split(range(10), 4))
[0 1 2] [3 4 5] [6 7] [8 9]
>>> print(*np.array_split(range(10), 5))
[0 1] [2 3] [4 5] [6 7] [8 9]

*credit to Zero Piraeus in room 6


问:
HexString "0x05" to Hex Number 0x05 Lua
How can I in Lua

from HexString "0x05" to Convert Hex  0x05 number?

I need a hex number like this 0x05 ! Type = number

No string! Not the number 5!

答:
Use tonumber("0x05"):

```<code>print(tonumber("0x05") == 0x05)
</code>```

Title: HexString "0x05" to Hex Number 0x05 Lua

Body:
Use tonumber("0x05"):

print(tonumber("0x05") == 0x05)


问:
Comparing2 different Javascript Constructor method
I am new to JavaScript and found that the 2 different methods below are able to instantiate object.

I looked the object created from both constructors and it appears to be same to me.

But I am not sure what is the difference between these 2 method? and in which scenario a method is better than another?

Can anyone please explain? Thank you.

Person1.js

```<code>function Person1(name){
    this.name = name;
    this.initialize();
}

Person1.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 1 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 1 class"+this);
    console.log(this);
    console.log("F1 Person 1 class caller"+caller);
    console.log(caller);
}
</code>```

Person2.js

```<code>var Person2 = (function(){

function Person2(name){
    this.name = name;
    this.initialize();
}

Person2.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 2 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 2 class"+this);
    console.log(this);
    console.log("F1 Person 2 class caller"+caller);
    console.log(caller);
}

return Person2;
})();
</code>```

Instantiate the object with this code:

```<code>var p1 = new Person1("P1");
var p2 = new Person2("P2");

console.log("Completed ");
console.log("P1 ");
console.log(p1);
console.log("P2 ");
console.log(p2);
</code>```

答:
Person2 is wrapped in what's called an immediately invoked funciton expression (or IIFE). You'll notice that at the end, it returns Person2, and that's why the assignment on the first line of the example works.

The reason you would consider using this method is that wrapping up code in an IIFE keeps you global scope clean (meaning, that in a browser for example, the window object doesn't get cluttered with a bunch of global properties).

As a beginner, I might go for the Person1 method, as it's visually simpler and easier to track what's going on. As you progress, however, keep the above in mind and think about what's best for the maintainability of your code base.

Body:
I am new to JavaScript and found that the 2 different methods below are able to instantiate object.

I looked the object created from both constructors and it appears to be same to me.

But I am not sure what is the difference between these 2 method? and in which scenario a method is better than another?

Can anyone please explain? Thank you.

Person1.js

function Person1(name){
    this.name = name;
    this.initialize();
}

Person1.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 1 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 1 class"+this);
    console.log(this);
    console.log("F1 Person 1 class caller"+caller);
    console.log(caller);
}

Person2.js

var Person2 = (function(){

function Person2(name){
    this.name = name;
    this.initialize();
}

Person2.prototype.initialize = function (todoName) {
    console.log("Initalize function Person 2 class"+this);
    f1(this);
}

function f1(caller) {
    console.log("F1 Person 2 class"+this);
    console.log(this);
    console.log("F1 Person 2 class caller"+caller);
    console.log(caller);
}

return Person2;
})();

Instantiate the object with this code:

var p1 = new Person1("P1");
var p2 = new Person2("P2");

console.log("Completed ");
console.log("P1 ");
console.log(p1);
console.log("P2 ");
console.log(p2);


问:
How to get errback from interrupted response using klein?
This page describes how to set an errback that fires when the connection to
the client is lost before the response is generated.

Is there a way to do something similar using klein?
Code from referenced page is below, which works with twisted.web. I would like something like:
    request.notifyFinish().addErrback(self._responseFailed, call)
which is code to fire an errback when request does not finish, that works with klein.

```<code>from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor

class DelayedResource(Resource):
    def _delayedRender(self, request):
        request.write("<html><body>Sorry to keep you waiting.</body></html>")
        request.finish()

    def _responseFailed(self, err, call):
        call.cancel()

    def render_GET(self, request):
       call = reactor.callLater(5, self._delayedRender, request)
       request.notifyFinish().addErrback(self._responseFailed, call)
       return NOT_DONE_YET

resource = DelayedResource()
</code>```

答: Klein handlers are passed a regular Twisted Web Request object.  You can use the same notifyFinish method on it to get interrupted response notification.

Body:
This page describes how to set an errback that fires when the connection to
the client is lost before the response is generated.

Is there a way to do something similar using klein?
Code from referenced page is below, which works with twisted.web. I would like something like:
    request.notifyFinish().addErrback(self._responseFailed, call)
which is code to fire an errback when request does not finish, that works with klein.

from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import reactor

class DelayedResource(Resource):
    def _delayedRender(self, request):
        request.write("Sorry to keep you waiting.")
        request.finish()

    def _responseFailed(self, err, call):
        call.cancel()

    def render_GET(self, request):
       call = reactor.callLater(5, self._delayedRender, request)
       request.notifyFinish().addErrback(self._responseFailed, call)
       return NOT_DONE_YET

resource = DelayedResource()


问:
Custom wordpress post filter
So I have a page of posts and I would like to be able to filter the posts by month, category, and a keyword filter that a user enters. I have found some examples online of plugins that will accomplish the keyword and category and keyword fields, but I am not seeing an easy way to add the month selector. Would it be easier to make a custom filter form myself? The only issue I am seeing with that is the keyword filter. </p>

<p>Any pointers would be greatly appreciated. </p>

答: I think the best solution is using AJAX. You can create inputs in template where all posts show then define logic and javasctipt files in functions.php and finally add js files.</p>

Title: Custom wordpress post filter

Body:
So I have a page of posts and I would like to be able to filter the posts by month, category, and a keyword filter that a user enters. I have found some examples online of plugins that will accomplish the keyword and category and keyword fields, but I am not seeing an easy way to add the month selector. Would it be easier to make a custom filter form myself? The only issue I am seeing with that is the keyword filter.

Any pointers would be greatly appreciated.


问:
Trying to override Django User model username validation
I am trying to override the django default User model username field to allow hashtags in usernames.

I know the model itself will let me do this but the standard form registration doesn't seem to allow it. I'm using django-allauth as well.

How do I replace the regex in the default User model form to allow a hashtag in the username?

答:
django-allauth has a lot of configuration, one of its options is set the validators for username

```<code>ACCOUNT_USERNAME_VALIDATORS
</code>```

for a better reference you can check https://django-allauth.readthedocs.io/en/latest/configuration.html

The ACCOUNT_USERNAME_VALIDATORS accept a list of paths of custom username validators. So, you can define something like:

```<code>ACCOUNT_USERNAME_VALIDATORS = ('myproject.myapp.validators.custom_username_validators')
</code>```

and in the specified path 'myproject.myapp.validators.CustomUsernameValidtor' you must define a validator class like:

```<code>import re
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _

@deconstructible
class CustomUsernameValidator(object):
    message = _('Invalid username')

    def __call__(self, value):
        if not re.match(r'[a-zA-Z0-9_@#-]+', value)
            raise DjangoValidationError(self.message, code='invalid_username')
</code>```

Hope this can help you.

Regards.

Body:
django-allauth has a lot of configuration, one of its options is set the validators for username

ACCOUNT_USERNAME_VALIDATORS

for a better reference you can check https://django-allauth.readthedocs.io/en/latest/configuration.html

The ACCOUNT_USERNAME_VALIDATORS accept a list of paths of custom username validators. So, you can define something like:

ACCOUNT_USERNAME_VALIDATORS = ('myproject.myapp.validators.custom_username_validators')

and in the specified path 'myproject.myapp.validators.CustomUsernameValidtor' you must define a validator class like:

import re
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _

@deconstructible
class CustomUsernameValidator(object):
    message = _('Invalid username')

    def __call__(self, value):
        if not re.match(r'[a-zA-Z0-9_@#-]+', value)
            raise DjangoValidationError(self.message, code='invalid_username')

Hope this can help you.

Regards.


答:
If you know the size of the array you want to make ahead of time, declare it like int a[128]; instead of just int a[]; so a at indices 0 to 127 will be safe to write to (and subsequently read from).

If you want to declare an array of size n at runtime, use int a[] = malloc(n * sizeof(int)); or int *a = malloc(n * sizeof(int));. Make sure a is not NULL before using it, and remember to call free(a); when you are done with it to avoid a memory leak.

Title: Getting segmentation fault while printing output


问:
hadoop No FileSystem for scheme: file
I am trying to run a simple NaiveBayesClassifer using hadoop, getting this error

```<code>Exception in thread "main" java.io.IOException: No FileSystem for scheme: file
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1375)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:95)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:180)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
    at org.apache.mahout.classifier.naivebayes.NaiveBayesModel.materialize(NaiveBayesModel.java:100)
</code>```

Code :

```<code>    Configuration configuration = new Configuration();
    NaiveBayesModel model = NaiveBayesModel.materialize(new Path(modelPath), configuration);// error in this line..
</code>```

modelPath is pointing to NaiveBayes.bin file, and configuration object is printing - Configuration: core-default.xml, core-site.xml

I think its because of jars, any ideas?

答:
It took me sometime to figure out fix from given answers, due to my newbieness. This is what I came up with, if anyone else needs help from the very beginning:

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object MyObject {
  def main(args: Array[String]): Unit = {

    val mySparkConf = new SparkConf().setAppName("SparkApp").setMaster("local[*]").set("spark.executor.memory","5g");
    val sc = new SparkContext(mySparkConf)

    val conf = sc.hadoopConfiguration

    conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
    conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)
</code>```

I am using Spark 2.1

And I have this part in my build.sbt

```<code>assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}
</code>```

Title: hadoop No FileSystem for scheme: file

Body:
I am trying to run a simple NaiveBayesClassifer using hadoop, getting this error

Exception in thread "main" java.io.IOException: No FileSystem for scheme: file
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1375)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:95)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:180)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
    at org.apache.mahout.classifier.naivebayes.NaiveBayesModel.materialize(NaiveBayesModel.java:100)

Code :

    Configuration configuration = new Configuration();
    NaiveBayesModel model = NaiveBayesModel.materialize(new Path(modelPath), configuration);// error in this line..

modelPath is pointing to NaiveBayes.bin file, and configuration object is printing - Configuration: core-default.xml, core-site.xml

I think its because of jars, any ideas?

Body:
It took me sometime to figure out fix from given answers, due to my newbieness. This is what I came up with, if anyone else needs help from the very beginning:

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object MyObject {
  def main(args: Array[String]): Unit = {

    val mySparkConf = new SparkConf().setAppName("SparkApp").setMaster("local[*]").set("spark.executor.memory","5g");
    val sc = new SparkContext(mySparkConf)

    val conf = sc.hadoopConfiguration

    conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
    conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)

I am using Spark 2.1

And I have this part in my build.sbt

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}