问:
Wrap callback function to include extra argument when caller verifies exact callback signature
I'm trying to bind multiple callback functions across multiple properties with code that looks something like:

```<code>for key in keys:
    def callback(self, value):
        #Do stuff...
        return None

    doSomething(callback)
</code>```

This works because the calling code (that calls callback) expect exactly two parameters and the callback to return None. The issue is now I want to wrap the callback such that I can also pass the key in something like:

```<code>for key in keys:
    def wrappedCallback(self, value):
        #How do I get key in here???
        realCallback(self, key, value)
        return None

    doSomething(wrapperCallback)
</code>```

But I have no idea how to get key inside of wrapperCallback. I can't add an extra default parameter like:

```<code>...
#This throws with "expected a function taking 2 arguments, not 3"
def wrappedCallback(self, value, key=key):
    realCallback(self, key, value)
    ...
</code>```

because this will throw an error from the caller (it's C code that expects a very strict callback). I've also tried functools.partial but then I get expected a function, not a functools.partial

How do I wrap the passed callback function to include the external parameter key (from the for loop) while keeping the exact signature described?

答:
I would create a callback generator that takes your parameters (such as key) and creates your callbacks.

```<code>>>> def callback_generator(key):
...     def callback(self, value):
...         do_something_with(key, value)
...     return callback
...
>>> for key in keys:
...     doSomething(callback_generator(key))
...
</code>```

Body:
I'm trying to bind multiple callback functions across multiple properties with code that looks something like:

for key in keys:
    def callback(self, value):
        #Do stuff...
        return None

    doSomething(callback)

This works because the calling code (that calls callback) expect exactly two parameters and the callback to return None. The issue is now I want to wrap the callback such that I can also pass the key in something like:

for key in keys:
    def wrappedCallback(self, value):
        #How do I get key in here???
        realCallback(self, key, value)
        return None

    doSomething(wrapperCallback)

But I have no idea how to get key inside of wrapperCallback. I can't add an extra default parameter like:

...
#This throws with "expected a function taking 2 arguments, not 3"
def wrappedCallback(self, value, key=key):
    realCallback(self, key, value)
    ...

because this will throw an error from the caller (it's C code that expects a very strict callback). I've also tried functools.partial but then I get expected a function, not a functools.partial

How do I wrap the passed callback function to include the external parameter key (from the for loop) while keeping the exact signature described?

Body:
I would create a callback generator that takes your parameters (such as key) and creates your callbacks.

>>> def callback_generator(key):
...     def callback(self, value):
...         do_something_with(key, value)
...     return callback
...
>>> for key in keys:
...     doSomething(callback_generator(key))
...


来源: stackexchange

问:
BeautifulSoup scraping Bitcoin Price issue
I am still new to python, and especially BeautifulSoup. I've been reading up on this stuff for a few days and playing around with bunch of different codes and getting mix results. However, on this page is the Bitcoin Price I would like to scrape. The price is located in:
$16,569.40
Meaning that, I'd like to have my script print only that line where the value is. My current code prints the whole page and it doesn't look very nice, since it's printing a lot of data. Could anybody please help to improve my code?

```<code>import requests
from BeautifulSoup import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
div = soup.find('text-large2', attrs={'class': 'stripe'})

for row in soup.findAll('div'):
    for cell in row.findAll('tr'):
        print cell.text
</code>```

And this is a snip of the output I get after running the code. It doesn't look very nice or readable.

```<code>#SourcePairVolume (24h)PriceVolume (%)Updated
1BitMEXBTC/USD$3,280,130,000$15930.0016.30%Recently
2BithumbBTC/KRW$2,200,380,000$17477.6010.94%Recently
3BitfinexBTC/USD$1,893,760,000$15677.009.41%Recently
4GDAXBTC/USD$1,057,230,000$16085.005.25%Recently
5bitFlyerBTC/JPY$636,896,000$17184.403.17%Recently
6CoinoneBTC/KRW$554,063,000$17803.502.75%Recently
7BitstampBTC/USD$385,450,000$15400.101.92%Recently
8GeminiBTC/USD$345,746,000$16151.001.72%Recently
9HitBTCBCH/BTC$305,554,000$15601.901.52%Recently
</code>```

答:
Try this:

```<code>import requests
from BeautifulSoup import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
div = soup.find("div", {"class" : "col-xs-6 col-sm-8 col-md-4 text-left"
}).find("span", {"class" : "text-large2"})

for i in div:
    print i
</code>```

This prints 16051.20 for me.

Later Edit: and if you put the above code in a function and loop it it will constantly update. I get different values now.

ContentLicense: CC BY-SA 3.0

Body:
I am still new to python, and especially BeautifulSoup. I've been reading up on this stuff for a few days and playing around with bunch of different codes and getting mix results. However, on this page is the Bitcoin Price I would like to scrape. The price is located in:
$16,569.40
Meaning that, I'd like to have my script print only that line where the value is. My current code prints the whole page and it doesn't look very nice, since it's printing a lot of data. Could anybody please help to improve my code?

import requests
from BeautifulSoup import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
div = soup.find('text-large2', attrs={'class': 'stripe'})

for row in soup.findAll('div'):
    for cell in row.findAll('tr'):
        print cell.text

And this is a snip of the output I get after running the code. It doesn't look very nice or readable.

#SourcePairVolume (24h)PriceVolume (%)Updated
1BitMEXBTC/USD$3,280,130,000$15930.0016.30%Recently
2BithumbBTC/KRW$2,200,380,000$17477.6010.94%Recently
3BitfinexBTC/USD$1,893,760,000$15677.009.41%Recently
4GDAXBTC/USD$1,057,230,000$16085.005.25%Recently
5bitFlyerBTC/JPY$636,896,000$17184.403.17%Recently
6CoinoneBTC/KRW$554,063,000$17803.502.75%Recently
7BitstampBTC/USD$385,450,000$15400.101.92%Recently
8GeminiBTC/USD$345,746,000$16151.001.72%Recently
9HitBTCBCH/BTC$305,554,000$15601.901.52%Recently

Body:
Try this:

import requests
from BeautifulSoup import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
div = soup.find("div", {"class" : "col-xs-6 col-sm-8 col-md-4 text-left"
}).find("span", {"class" : "text-large2"})

for i in div:
    print i

This prints 16051.20 for me.

Later Edit: and if you put the above code in a function and loop it it will constantly update. I get different values now.


问:
devise 5: How do I modify the Flash messages from Devise to match my css for flash messages?
I'm running the latest version of devise 5 in my Rails 5.1 application. I have the following CSS code for flash messages in my stylesheet.

```<code>div.alert.alert-danger, .alert-danger { background-color: #ff0000; }
div.alert.alert-info, .alert-info { background-color: #99d7ea; }
div.alert.alert-success, .alert-success { background-color: #a3da2f; }
div.alert.alert-warning , .alert-warning { background-color: #e6c856; }
</code>```

The original code only had the first class. It works just fine. After reading some older answers regarding this I added the second one attempting to change the css for the flash messages in devise. The messages from devise show up with my default font size and color but a transparent background. I want them to match what I have defined for my flash messages. The ones I issue use my defined CSS.

Where/how can I override the devise CSS for flash messages to match mine?

答:
I realized that a part of my problem was that I need to know what devise flash types were. From this link I only found two: alert and notice.

https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_controller/metal/flash.rb#L10

Neither of these are used in rails 5. They are danger, info, success and warning. I decided to match the css for alert like danger and notice like success. From this link I found a 4 year old answer that still works with the current version of devise.

Rails 3.1 Devise How To Change Flash Message CSS From notice to success?

I added the following two statements in my stylesheet and now all messages from Devise appear like my other flash messages.

```<code>.alert-alert { @extend .alert-warning; }
.alert-notice { @extend .alert-success; }
</code>```

Body:
I'm running the latest version of devise 5 in my Rails 5.1 application. I have the following CSS code for flash messages in my stylesheet.

div.alert.alert-danger, .alert-danger { background-color: #ff0000; }
div.alert.alert-info, .alert-info { background-color: #99d7ea; }
div.alert.alert-success, .alert-success { background-color: #a3da2f; }
div.alert.alert-warning , .alert-warning { background-color: #e6c856; }

The original code only had the first class. It works just fine. After reading some older answers regarding this I added the second one attempting to change the css for the flash messages in devise. The messages from devise show up with my default font size and color but a transparent background. I want them to match what I have defined for my flash messages. The ones I issue use my defined CSS.

Where/how can I override the devise CSS for flash messages to match mine?

Body:
I realized that a part of my problem was that I need to know what devise flash types were. From this link I only found two: alert and notice.

https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_controller/metal/flash.rb#L10

Neither of these are used in rails 5. They are danger, info, success and warning. I decided to match the css for alert like danger and notice like success. From this link I found a 4 year old answer that still works with the current version of devise.

Rails 3.1 Devise How To Change Flash Message CSS From notice to success?

I added the following two statements in my stylesheet and now all messages from Devise appear like my other flash messages.

.alert-alert { @extend .alert-warning; }
.alert-notice { @extend .alert-success; }


问:
building from source Qpid Messaging API (C++, bindings) [Qpid C++ 1.37.0] - missing files
I am trying to build from sources Qpid Messaging API (C++, bindings).
Build is triggered on RHEL and all prerequisites mentioned on link below are installed.

https://git-wip-us.apache.org/repos/asf?p=qpid-cpp.git;a=blob_plain;f=INSTALL.txt;hb=HEAD

yet when reaching step: make all

what i get is this

error:

```<code>Linking CXX shared library libqpidclient.so
[ 86%] Built target qpidclient
Scanning dependencies of target qpidmessaging
[ 86%] Building CXX object src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o
In file included from /home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/AddressHelper.cpp:22:0:
/home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/PnData.h:27:27: fatal error: proton/engine.h: No such file or directory
 #include <proton/engine.h>
                           ^
compilation terminated.
make[3]: *** [src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o] Error 1
make[2]: *** [src/CMakeFiles/qpidmessaging.dir/all] Error 2
make[1]: *** [examples/messaging/CMakeFiles/client.dir/rule] Error 2
make: *** [client] Error 2
</code>```

that would indicate that "Qpid proton-c " might be missing but its installed....

any ideas ?

答:
It worked for me using these steps.

```<code>$ wget http://apache.claz.org/qpid/proton/0.18.1/qpid-proton-0.18.1.tar.gz
$ tar -xf qpid-proton-0.18.1.tar.gz
$ cd qpid-proton-0.18.1/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
$ make -j8
$ make install
$ cd ../..
$ wget http://apache.claz.org/qpid/cpp/1.37.0/qpid-cpp-1.37.0.tar.gz
$ tar -xf qpid-cpp-1.37.0.tar.gz
$ cd qpid-cpp-1.37.0/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
>>>> Here check for "Found Proton" in the cmake output <<<<
$ make -j8
$ make install
</code>```

Check that proton/engine.h is where you think it should be.  In your case, it looks like that would be /usr/local/include/proton/engine.h.

You can use the following command to see what your include search path is.

```<code>cpp -v /dev/null -o /dev/null
</code>```

Body:
I am trying to build from sources Qpid Messaging API (C++, bindings).
Build is triggered on RHEL and all prerequisites mentioned on link below are installed.

https://git-wip-us.apache.org/repos/asf?p=qpid-cpp.git;a=blob_plain;f=INSTALL.txt;hb=HEAD

yet when reaching step: make all

what i get is this

error:

Linking CXX shared library libqpidclient.so
[ 86%] Built target qpidclient
Scanning dependencies of target qpidmessaging
[ 86%] Building CXX object src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o
In file included from /home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/AddressHelper.cpp:22:0:
/home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/PnData.h:27:27: fatal error: proton/engine.h: No such file or directory
 #include <proton/engine.h>
                           ^
compilation terminated.
make[3]: *** [src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o] Error 1
make[2]: *** [src/CMakeFiles/qpidmessaging.dir/all] Error 2
make[1]: *** [examples/messaging/CMakeFiles/client.dir/rule] Error 2
make: *** [client] Error 2

that would indicate that "Qpid proton-c " might be missing but its installed....

any ideas ?

Body:
It worked for me using these steps.

$ wget http://apache.claz.org/qpid/proton/0.18.1/qpid-proton-0.18.1.tar.gz
$ tar -xf qpid-proton-0.18.1.tar.gz
$ cd qpid-proton-0.18.1/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
$ make -j8
$ make install
$ cd ../..
$ wget http://apache.claz.org/qpid/cpp/1.37.0/qpid-cpp-1.37.0.tar.gz
$ tar -xf qpid-cpp-1.37.0.tar.gz
$ cd qpid-cpp-1.37.0/
$ mkdir bld
$ cd bld
$ cmake .. -DCMAKE_INSTALL_PREFIX=/tmp/testprefix
>>>> Here check for "Found Proton" in the cmake output <<<<
$ make -j8
$ make install

Check that proton/engine.h is where you think it should be.  In your case, it looks like that would be /usr/local/include/proton/engine.h.

You can use the following command to see what your include search path is.

cpp -v /dev/null -o /dev/null


问:
TOPSY JSON [searchcount] not working except for IE9 in local machine
Im working on topsy json searchcount but when i run it on local machine, result only appear on safari and IE9. when i put it online, everything not working.

here is the script

```<code>$.getJSON("http://otter.topsy.com/searchcount.json?q=json", function(response) {
  alert(response.response.w);
 });
</code>```

i took the json from http://code.google.com/p/otterapi/wiki/Resources#/searchcount

something wrong my the script?

答:
I believe you need to append your search with a callback to use JSONP over JSON. Here's what the URL should look like

```<code>$.getJSON("http://otter.topsy.com/searchcount.json?q=json&callback=?", function(response){
 alert(response.response.w);
});
</code>```

Edit: Here's a couple of useful links
http://code.google.com/p/otterapi/wiki/ResponseFormats#Javascript_(JSONP)
http://en.wikipedia.org/wiki/Same_origin_policy

ContentLicense: CC BY-SA 2.5

Body:
Im working on topsy json searchcount but when i run it on local machine, result only appear on safari and IE9. when i put it online, everything not working.

here is the script

$.getJSON("http://otter.topsy.com/searchcount.json?q=json", function(response) {
  alert(response.response.w);
 });

i took the json from http://code.google.com/p/otterapi/wiki/Resources#/searchcount

something wrong my the script?

Body:
I believe you need to append your search with a callback to use JSONP over JSON. Here's what the URL should look like

$.getJSON("http://otter.topsy.com/searchcount.json?q=json&callback=?", function(response){
 alert(response.response.w);
});

Edit: Here's a couple of useful links
http://code.google.com/p/otterapi/wiki/ResponseFormats#Javascript_(JSONP)
http://en.wikipedia.org/wiki/Same_origin_policy


答:
This works. But I think you use older version of BeautifulSoup, try pip install bs4 in command prompt or PowerShell

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, 'html.parser')

value = soup.find('span', {'class': 'text-large2'})
print(''.join(value.stripped_strings))
</code>```

Title: BeautifulSoup scraping Bitcoin Price issue

Body:
This works. But I think you use older version of BeautifulSoup, try pip install bs4 in command prompt or PowerShell

import requests
from bs4 import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, 'html.parser')

value = soup.find('span', {'class': 'text-large2'})
print(''.join(value.stripped_strings))


问:
Migrate from legacy network in GCE
Long story short - I need to use networking between projects to have separate billing for them.

I'd like to reach all the VMs in different projects from a single point that I will use for provisioning systems (let's call it coordinator node).

It looks like VPC network peering is a perfect solution to this. But unfortunately one of the existing networks is "legacy". Here's what google docs state about legacy networks.

About legacy networks
  Note: Legacy networks are not recommended. Many newer GCP features are not supported in legacy networks.

OK, naturally the question arises: how do you migrate out of legacy network? Documentation does not address this topic. Is it not possible?

I have a bunch of VMs, and I'd be able to shutdown them one by one:

shutdown

change something

restart

unfortunately it does not seem possible to change network even when VM is down?

EDIT:
it has been suggested to recreate VMs keeping the same disks. I would still need a way to bridge legacy network with new VPC network to make migration fluent. Any thoughts on how to do that using GCE toolset?

答:
One possible solution - for each VM in the legacy network:

Get VM parameters (API get method)

Delete VM without deleting PD (persistent disk)

Create VM in the new VPC network using parameters from step 1 (and existing persistent disk)

This way stop-change-start is not so different from delete-recreate-with-changes. It's possible to write a script to fully automate this (migration of a whole network). I wouldn't be surprised if someone already did that.

UDPATE

https://github.com/googleinterns/vm-network-migration tool automates the above process, plus it supports migration of a whole Instance Group or Load Balancer, etc. Check it out.

Title: Migrate from legacy network in GCE

ContentLicense: CC BY-SA 4.0


问:
Example of Yarn Queues in Dataproc (Spark v2)
Has anyone been able to add more than the default queue to yarn on Spark 2.x in Dataproc?

Attempts that fail at cluster creation time:

capacity-scheduler:yarn.scheduler.capacity.root.queues=alpha,beta,default
yarn:yarn.scheduler.capacity.root.queues=alpha,beta,default

Additionally, setting yarn.scheduler.fair.allow-undeclared-pools=true on either of the above configuration prefixes to activate dynamic queues also fails.

All cases seem to make the daemon fail leaving the Resource Manager dead on launch.

答:
Each queue needs to have a capacity specified. The properties needed for your example are as follow:

```<code>capacity-scheduler:yarn.scheduler.capacity.root.queues=alpha,beta,default
capacity-scheduler:yarn.scheduler.capacity.root.alpha.capacity=20
capacity-scheduler:yarn.scheduler.capacity.root.beta.capacity=20
capacity-scheduler:yarn.scheduler.capacity.root.default.capacity=60
</code>```

Where all capacities specified sum to 100% of the root queues resources. The full set of configuration options for the capacity scheduler can be found in Hadoop documentation.

Body:
Each queue needs to have a capacity specified. The properties needed for your example are as follow:

capacity-scheduler:yarn.scheduler.capacity.root.queues=alpha,beta,default
capacity-scheduler:yarn.scheduler.capacity.root.alpha.capacity=20
capacity-scheduler:yarn.scheduler.capacity.root.beta.capacity=20
capacity-scheduler:yarn.scheduler.capacity.root.default.capacity=60

Where all capacities specified sum to 100% of the root queues resources. The full set of configuration options for the capacity scheduler can be found in Hadoop documentation.


问:
Not sure if my condition correlates to radio button being checked
I want to create a function in javascript whereby I check whether is the radio is being checked if so I will display the cost that is I assign in javascript itself to HTML.

The following is my HTML and javascript:

function priceCalculator(){
  var price_dict = {
    "Small":22, "Medium":28, "Large":35,

  }

  var length = Object.keys(price_dict).length;

  for(var i=0;i<length;i++){
    var dis = document.getElementsByName('Size')[i].value;
    if(document.getElementsByName('Size').checked){

      document.getElementById("DisplayPrice").innerHTML = price_dict[dis];

    }

    }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Pizza Order Form</title>

    <style>
        form {
            font-family: Arial, Helvetica, sans-serif;
            vertical-align: central;
            border: 5px solid black;
            margin:0px auto;
            width:650px;
            padding-left:0.5em;
        }
        fieldset{
            width:600px;
            box-sizing:border-box;
            border-radius: 20px;
        }

        .deliver > p > label {
            width: 70px;
            display: inline-block;
        }

        .deliver > p > input {
            width: 130px;
            display: inline-block;
        }

        #DisplayPrice{
            background-color: yellow;
        }

    </style>
</head>

<body >
    <form>
        <h1>Pizza order Form</h1>
        <p>
            <label for="Pizza Type">Pizza Type:</label>
            <select name="pizza type">
                <option value="Please select" selected>Please select...</option>
                <option value="Aloha Chicken">Aloha Chicken</option>
                <option value="Beef Pepperoni">Beef Pepperoni</option>
                <option value="Chicken Delight">Chicken Delight</option>
                <option value="Deluxe Cheese">Deluxe Cheese</option>
            </select>

            <label for="Quantity">Quantity</label>
            <input name="quantity" type="number" min="1" max="4" />
        </p>

        <!--Size-->
        <fieldset >
            <legend>Size:</legend>
            <input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
            <input type="radio" name="Size" value="Medium" onchange="priceCalculator()"/>Medium
            <input type="radio" name="Size" value="Large" onload="priceCalculator()"/>Large
        </fieldset>

        <!--Crust-->
        <fieldset>
            <legend>Crust:</legend>
            <input type="radio" name="Crust"value="Thin" />Thin
            <input type="radio" name="Crust" value="Thick" />Thick
            <input type="radio" name="Crust" value="Deep Dish" />Deep Dish
        </fieldset>

        <!--Toppings-->
        <fieldset>
            <legend>Toppings:</legend>
            <input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
            <input type="radio" name="Toppings" value="Sausage" />Sausage
            <input type="radio" name="Toppings" value="Olives" />Olives
        </fieldset>

        <!--Addons-->
        <p>
            <label for="Addons">Addons</label>
            <select name="Addons" multiple>
                <option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
                <option value="Garlic Bread">Garlic Bread</option>
            </select>
        </p>

        <div id="DisplayPrice"></div>

        <!--Delivery section-->
        <fieldset class="deliver">
            <legend>Deliver to:</legend>
            <p>
                <label for="Name">Name:</label>
                <input type="text" name="name" required/>
            </p>
            <p>
                <label for="Address">Address:</label>
                <textarea rows="2" cols="30" required></textarea>
                <label for="Postal Code">Postal Code:</label>
                <input type="text" name="Postal Code" maxlength="6" required/>
            </p>
            <p>
                <label for="Phone Number">Phone#: </label>
                <input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>
            </p>
            <p>
                <label for="email">Email:</label>
                <input type="email" form="email" required />
            </p>
            <p>
                <label for=" Date">Date:</label>
                <input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
                <label for="time">Time: </label>
                <input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>
            </p>
        </fieldset>
        <p>
            <input type="submit" value="submit">
            <input type="reset" value="reset">
        </p>

    </form>

    <script src="pizzaScript.js"></script>

</body>
</html></code>```

Also, I would like to know is the use of onclick is correct?
Thx in advance m8s!

答:
remember that getElementsByName returns a collection therefore it is not correct to do a getElementsByName('Size').checked it would be correct to access an element of a list getElementsByName('Size')[i].checked

Your event where you assign the function should change for all three, do not load as you have right now.

Also, if you declare values that will always be used price_dict and will not change in your program, you should declare it outside the function.

Your code can be greatly reduced if you pass the item from the html on the onchange

var price_dict = {
  "Small":22, "Medium":28, "Large":35,
}

function priceCalculator(elm){
  document.getElementById("DisplayPrice").innerHTML = price_dict[elm.value];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset >
  <legend>Size:</legend>
  <input type="radio" name="Size" value="Small" onchange="priceCalculator(this)" />Small
  <input type="radio" name="Size" value="Medium" onchange="priceCalculator(this)"/>Medium
  <input type="radio" name="Size" value="Large" onchange="priceCalculator(this)"/>Large
</fieldset>

<div id="DisplayPrice"></div></code>```

Body:
I want to create a function in javascript whereby I check whether is the radio is being checked if so I will display the cost that is I assign in javascript itself to HTML.

The following is my HTML and javascript:

function priceCalculator(){
  var price_dict = {
    "Small":22, "Medium":28, "Large":35,

  }

  var length = Object.keys(price_dict).length;

  for(var i=0;i<length;i++){
    var dis = document.getElementsByName('Size')[i].value;
    if(document.getElementsByName('Size').checked){

      document.getElementById("DisplayPrice").innerHTML = price_dict[dis];

    }

    }

  }

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Pizza Order Form</title>

    <form>

Pizza order Form

            Pizza Type:
            <select name="pizza type">
                <option value="Please select" selected>Please select...</option>
                <option value="Aloha Chicken">Aloha Chicken</option>
                <option value="Beef Pepperoni">Beef Pepperoni</option>
                <option value="Chicken Delight">Chicken Delight</option>
                <option value="Deluxe Cheese">Deluxe Cheese</option>
            </select>

            Quantity
            <input name="quantity" type="number" min="1" max="4" />

        <fieldset >
            <legend>Size:</legend>
            <input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
            <input type="radio" name="Size" value="Medium" onchange="priceCalculator()"/>Medium
            <input type="radio" name="Size" value="Large" onload="priceCalculator()"/>Large
        </fieldset>

        <fieldset>
            <legend>Crust:</legend>
            <input type="radio" name="Crust"value="Thin" />Thin
            <input type="radio" name="Crust" value="Thick" />Thick
            <input type="radio" name="Crust" value="Deep Dish" />Deep Dish
        </fieldset>

        <fieldset>
            <legend>Toppings:</legend>
            <input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
            <input type="radio" name="Toppings" value="Sausage" />Sausage
            <input type="radio" name="Toppings" value="Olives" />Olives
        </fieldset>

            Addons
            <select name="Addons" multiple>
                <option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
                <option value="Garlic Bread">Garlic Bread</option>
            </select>

        <fieldset class="deliver">
            <legend>Deliver to:</legend>

                Name:
                <input type="text" name="name" required/>

                Address:
                <textarea rows="2" cols="30" required></textarea>
                Postal Code:
                <input type="text" name="Postal Code" maxlength="6" required/>

                Phone#:
                <input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>

                Email:
                <input type="email" form="email" required />

                Date:
                <input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
                Time:
                <input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>

        </fieldset>

            <input type="submit" value="submit">
            <input type="reset" value="reset">

    </form>

Also, I would like to know is the use of onclick is correct?
Thx in advance m8s!

Body:
remember that getElementsByName returns a collection therefore it is not correct to do a getElementsByName('Size').checked it would be correct to access an element of a list getElementsByName('Size')[i].checked

Your event where you assign the function should change for all three, do not load as you have right now.

Also, if you declare values that will always be used price_dict and will not change in your program, you should declare it outside the function.

Your code can be greatly reduced if you pass the item from the html on the onchange

var price_dict = {
  "Small":22, "Medium":28, "Large":35,
}

function priceCalculator(elm){
  document.getElementById("DisplayPrice").innerHTML = price_dict[elm.value];
}

<fieldset >
  <legend>Size:</legend>
  <input type="radio" name="Size" value="Small" onchange="priceCalculator(this)" />Small
  <input type="radio" name="Size" value="Medium" onchange="priceCalculator(this)"/>Medium
  <input type="radio" name="Size" value="Large" onchange="priceCalculator(this)"/>Large
</fieldset>

<div id="DisplayPrice"></div>


问:
Troubles separating C++ source file into multiple files
Let me specify exactly what I'm trying to do, I need to split my foo-bar program into five separate files: main, foo.h, foo.cpp, bar.h, bar.cpp. My header files (foo.h and bar.h) are meant to contain the declarations for their corresponding classes, while the c++ files (foo.cpp and bar.cpp) are meant to define the class.

I'm using Visual Studio, and thus far the only file I have showing red flags is my main file. Here is my code thus far, and I will include the errors that are being thrown in my main file:

main.cpp

```<code>#include <iostream>
#include "foo.h"
#include "foo.cpp"
#include "bar.h"
#include "bar.cpp"
using namespace std;

int main() {
   Bar b(25); /*I am getting a red flag under the 25, stating there is no constructor that can convert int to Bar*/

   b.func1(); /*I'm getting a red flag under func1 and func2 stating neither of them are members of Bar*/
   b.func2(34);

   return 0;}
</code>```

foo.h

```<code>#ifndef foo_h
#define foo_h
#include "foo.cpp"
 class Foo {};
#endif
</code>```

foo.cpp

```<code>#ifndef foo_c
#define foo_c

#include "foo.h"
#include "bar.cpp"
private:
    int data;
public:
Foo(int d) : data(d) {}

int get_data() { return data; }

virtual void func1() = 0;

virtual int func2(int d) = 0;

#endif
</code>```

bar.h

```<code>#ifndef bar_h
#define bar_h
#include "bar.cpp"
#include "foo.h"
class Bar : public Foo {};
#endif
</code>```

bar.cpp

```<code>#ifndef bar_c
#define bar_c

#include "bar.h"
#include "foo.h"
#include "foo.cpp"

Bar(int d) : Foo(d) {}

void func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}

#endif
</code>```

My program worked until I split it up, but now it keeps throwing this message at me when I try to compile it, and there are a couple of red flags in my main code. This is what the console tells me:

No suitable constructor exists to convert int to Bar

func1 is not a member of class Bar

func2 is not a member of class Bar

My question is: What am I doing wrong, and is there a better way to go about what I'm trying to do?

Thank you in advance.

答:
You should never #include .cpp files. Instead, compile each .cpp file into an object file and link them into an executable.

During the preprocessor stage, the compiler takes all of the #included files and treats them as if they were concatenated into one large program. Sometimes, certain files may be #included multiple times. Declarations, in header files, may be repeated, but multiple definitions, from source files, cause errors. (You probably don't have this problem because you used include guards in your source files.)

When creating object files, header files are used by the compiler to check names and types, but the actual definitions are not needed. The definitions that are found are compiled into the object file. The purpose of separate object files is to separate compilation of these definitions into modular units.

Body:
Let me specify exactly what I'm trying to do, I need to split my foo-bar program into five separate files: main, foo.h, foo.cpp, bar.h, bar.cpp. My header files (foo.h and bar.h) are meant to contain the declarations for their corresponding classes, while the c++ files (foo.cpp and bar.cpp) are meant to define the class.

I'm using Visual Studio, and thus far the only file I have showing red flags is my main file. Here is my code thus far, and I will include the errors that are being thrown in my main file:

main.cpp

#include <iostream>
#include "foo.h"
#include "foo.cpp"
#include "bar.h"
#include "bar.cpp"
using namespace std;

int main() {
   Bar b(25); /*I am getting a red flag under the 25, stating there is no constructor that can convert int to Bar*/

   b.func1(); /*I'm getting a red flag under func1 and func2 stating neither of them are members of Bar*/
   b.func2(34);

   return 0;}

foo.h

#ifndef foo_h
#define foo_h
#include "foo.cpp"
 class Foo {};
#endif

foo.cpp

#ifndef foo_c
#define foo_c

#include "foo.h"
#include "bar.cpp"
private:
    int data;
public:
Foo(int d) : data(d) {}

int get_data() { return data; }

virtual void func1() = 0;

virtual int func2(int d) = 0;

#endif

bar.h

#ifndef bar_h
#define bar_h
#include "bar.cpp"
#include "foo.h"
class Bar : public Foo {};
#endif

bar.cpp

#ifndef bar_c
#define bar_c

#include "bar.h"
#include "foo.h"
#include "foo.cpp"

Bar(int d) : Foo(d) {}

void func1() {
    cout << "Inside func1\n";
    cout << "\tData is " << get_data() << endl;
}

int func2(int d) {
    cout << "Inside func2 with " << d << endl;
    cout << "\tData is " << get_data() << endl;
    return d;
}

#endif

My program worked until I split it up, but now it keeps throwing this message at me when I try to compile it, and there are a couple of red flags in my main code. This is what the console tells me:

No suitable constructor exists to convert int to Bar

func1 is not a member of class Bar

func2 is not a member of class Bar

My question is: What am I doing wrong, and is there a better way to go about what I'm trying to do?

Thank you in advance.


问:
disabled field is marked as required after passing null=True
I have a form where there is a field like quantity, rate, basic_amount(disabled), vat, other_expenses and net_amount(disabled). The basic_amount field is the calculation from quantity and rate and net_amount is the calculation of basic_amount, other_expenses and vat. For this I used signal for saving to the database when user submits the form. When i submit the form, I get an error saying basic_amount and net_amount is required, though I have passed blank=True, null=True attribute to them.

How can i now save basic_amount and net_amount?

Here is my code

```<code>class PurchaseOrder(models.Model):
    item = models.ForeignKey(Item, blank=True, null=True)
    quantity = models.PositiveIntegerField(default=0)
    rate = models.DecimalField(default=0.0, max_digits=100, decimal_places=2)
    basic_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True)
    vat = models.CharField(max_length=10, blank=True, null=True)
    other_expenses = models.DecimalField(default=0.0, max_digits=100, decimal_places=2)
    net_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True)

def save_basic_amount_and_net_amount(sender, instance, *args, **kwargs):
    if (instance.quantity and instance.rate):
        instance.basic_amount = instance.quantity * instance.rate
    if (instance.basic_amount and instance.vat and instance.other_expenses):
        instance.net_amount = instance.amount - instance.other_expenses - instance.vat
pre_save.connect(save_basic_amount_and_net_amount, sender=PurchaseOrder)

class PurchaseOrderForm(forms.ModelForm):
    basic_amount = forms.DecimalField(disabled=True)
    net_amount = forms.DecimalField(disabled=True)
    class Meta:
        model = PurchaseOrder
        exclude = ('office', 'timestamp', 'updated', )

def purchase_order(request):
    form = PurchaseOrderForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        office_instance = OfficeSetup.objects.get(owner=request.user)
        new_form = form.save(commit=False)
        new_form.office = office_instance
        new_form.save()
        messages.success(request, 'Thank you')
        return redirect('purchase-order-lists')
    messages.warning(request, "Correct the errors below")
    context = {
        "form": form,
    }
    return render(request, 'dashboard/purchase_order/purchase_order.html', context)
</code>```

答:
blank=True and null=True relate to what is permissible in the database, not the form. If the value can be blank in the form, then add required=False to the form definition. For example:

```<code>class PurchaseOrderForm(forms.ModelForm):
    basic_amount = forms.DecimalField(disabled=True, required=False)
    ...
</code>```

Body:
I have a form where there is a field like quantity, rate, basic_amount(disabled), vat, other_expenses and net_amount(disabled). The basic_amount field is the calculation from quantity and rate and net_amount is the calculation of basic_amount, other_expenses and vat. For this I used signal for saving to the database when user submits the form. When i submit the form, I get an error saying basic_amount and net_amount is required, though I have passed blank=True, null=True attribute to them.

How can i now save basic_amount and net_amount?

Here is my code

class PurchaseOrder(models.Model):
    item = models.ForeignKey(Item, blank=True, null=True)
    quantity = models.PositiveIntegerField(default=0)
    rate = models.DecimalField(default=0.0, max_digits=100, decimal_places=2)
    basic_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True)
    vat = models.CharField(max_length=10, blank=True, null=True)
    other_expenses = models.DecimalField(default=0.0, max_digits=100, decimal_places=2)
    net_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True)

def save_basic_amount_and_net_amount(sender, instance, *args, **kwargs):
    if (instance.quantity and instance.rate):
        instance.basic_amount = instance.quantity * instance.rate
    if (instance.basic_amount and instance.vat and instance.other_expenses):
        instance.net_amount = instance.amount - instance.other_expenses - instance.vat
pre_save.connect(save_basic_amount_and_net_amount, sender=PurchaseOrder)

class PurchaseOrderForm(forms.ModelForm):
    basic_amount = forms.DecimalField(disabled=True)
    net_amount = forms.DecimalField(disabled=True)
    class Meta:
        model = PurchaseOrder
        exclude = ('office', 'timestamp', 'updated', )

def purchase_order(request):
    form = PurchaseOrderForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        office_instance = OfficeSetup.objects.get(owner=request.user)
        new_form = form.save(commit=False)
        new_form.office = office_instance
        new_form.save()
        messages.success(request, 'Thank you')
        return redirect('purchase-order-lists')
    messages.warning(request, "Correct the errors below")
    context = {
        "form": form,
    }
    return render(request, 'dashboard/purchase_order/purchase_order.html', context)

Body:
blank=True and null=True relate to what is permissible in the database, not the form. If the value can be blank in the form, then add required=False to the form definition. For example:

class PurchaseOrderForm(forms.ModelForm):
    basic_amount = forms.DecimalField(disabled=True, required=False)
    ...


问:
mosso versus gogrid which is better?
I have reasonable experience to manage my own server, so gogrid style management is not a problem. But seems mosso is a tag cheaper somewhat- except the very difficult to access compute cycles terms. Anyone could share about this would be very welcomed.</p>

答:
It's simple, Mosso is just like a "reseller" hosting. They provide you everything whitelabel from billing to control panel then you sell it back to customers.

If you are developer, I recommend you choose GoGrid. Firstly, Mosso doesn't provide SSH access. Secondly, if you are RoR/Mongrel user, you are capped to limited RAM (unless you pay extra in addition to $100). Moreover, GoGrid allows you to choose server image (CentOS, Redhat, Windows) with some out-of-the-box support for RoR and LAMP.

Somemore, GoGrid provides you initial credits ($50 or $95 if you use MS-WEBFWRD) for you to try out before actually paying for it.

OwnerDisplayName: goodwill

Title: mosso versus gogrid which is better?

OwnerDisplayName: Ryan


问:
MYSQL and PHP field/ column name as variable
I want to pass a field name in as a parameter. I am very new to PHP and MYSQL. Any help would be greatly appreciated! The function takes in the position and the desired stat. it returns the standard deviation of that particular stat. I am looking to do something like this:</p>

```<code>function standevplayer($POS, $STAT)
{
    $stat = array();
    if(strcmp($POS, 'QB') === 0)
    {
            $sql = "SELECT "%" .$STAT. "%" FROM Quarterback";
    }

    if(strcmp($POS, 'RB') === 0)
    {
            $sql = "SELECT '%" .$STAT. "%' FROM Runningback";
    }

    if(strcmp($POS, 'WR') === 0)
    {
            $sql = "SELECT '%" .$STAT. "%' FROM Receiving";
    }

    $result = mysql_query($sql);
    while ($row = mysql_fetch_assoc($result))
    {
            array_push($stat, $row['$STAT']);
    }
    $SD = standard_deviation($stat);
    return $SD;
}
</code>```

答:
Why the percentage? if $STAT is your column name then just do

```<code>$sql = "SELECT ".$STAT." FROM Quarterback";
</code>```

and for getting the result just use

```<code>$row[$STAT]
</code>```

Body:
I want to pass a field name in as a parameter. I am very new to PHP and MYSQL. Any help would be greatly appreciated! The function takes in the position and the desired stat. it returns the standard deviation of that particular stat. I am looking to do something like this:

function standevplayer($POS, $STAT)
{
    $stat = array();
    if(strcmp($POS, 'QB') === 0)
    {
            $sql = "SELECT "%" .$STAT. "%" FROM Quarterback";
    }

    if(strcmp($POS, 'RB') === 0)
    {
            $sql = "SELECT '%" .$STAT. "%' FROM Runningback";
    }

    if(strcmp($POS, 'WR') === 0)
    {
            $sql = "SELECT '%" .$STAT. "%' FROM Receiving";
    }

    $result = mysql_query($sql);
    while ($row = mysql_fetch_assoc($result))
    {
            array_push($stat, $row['$STAT']);
    }
    $SD = standard_deviation($stat);
    return $SD;
}

Body:
Why the percentage? if $STAT is your column name then just do

$sql = "SELECT ".$STAT." FROM Quarterback";

and for getting the result just use

$row[$STAT]


问:
Get Axios frontend Promise to receive errors msg from Rails backend
In Rails I'm returning:

```<code>render json: { errors: e.response.body.errors }, status: 400
</code>```

In JavaScript I'm using Axios:

```<code>axios.patch('/settings/account', {}, {params: {...
    } })
  .then((e)=> {
    ...
    console.log('submitted')
  })
  .catch(function (error, res) {
    // only get error that gives 400, but not error msg here, res isn't here
    console.log(error);
  });
</code>```

How do I get the e.response.body.errors on my frontend?

答:
Axios reject promises if the server response http status code is anything but 2xx. I see you are sending an error response from the server, but are you sending this response through a http error status? If you arent, the error isnt an error to axios, so the error would show in the "then()" hook, since the promise is resolved.

If you are, then you should see the error whithin error.response.data

Body:
In Rails I'm returning:

render json: { errors: e.response.body.errors }, status: 400

In JavaScript I'm using Axios:

axios.patch('/settings/account', {}, {params: {...
    } })
  .then((e)=> {
    ...
    console.log('submitted')
  })
  .catch(function (error, res) {
    // only get error that gives 400, but not error msg here, res isn't here
    console.log(error);
  });

How do I get the e.response.body.errors on my frontend?


问:
Django: Moving data from SQLite to PostgreSQL

I've recently inherited a production codebase for a webapp written using Django. Up until now, the database the project has been using has been the default SQLite3 database, but now that more people are using the app, moving to Postgres is necessary.

I've been able to set up an empty postgres database with the project that works fine. The problem I'm encountering is in moving the data from the old project to the new one. I can run
    python manage.py dumpdata --natural-foreign > dump.json
to dump the data, which works fine, but when I switch to postgres in settings.py and run
    python manage.py loaddata dump.json
I get the following error:

```<code>Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
    self.loaddata(fixture_labels)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata
    self.load_label(fixture_label)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 147, in load_label
    obj.save(using=self.using)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 173, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 738, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 803, in _save_table
    forced_update)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 853, in _do_update
    return filtered._update(values) > 0
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/query.py", line 580, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1062, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: Problem installing fixture '/mnt/d/Code/MCJobTrack/jobtrack_project/dump.json': Could not load contenttypes.ContentType(pk=15): duplicate key value violates unique constraint "django_content_type_app_label_45f3b1d93ec8c61c_uniq"
DETAIL:  Key (app_label, model)=(jobtrack, purchaseorder) already exists.
</code>```

So far I've tried:

Running TRUNCATE django_content_type RESTART IDENTITY CASCADE; in the dbshell

Excluding contenttypes when dumping the data. (I get the error django.core.serializers.base.DeserializationError: Problem installing fixture '/mnt/d/Code/MCJobTrack/jobtrack_project/dump_no_contenttypes.json': ContentType matching query does not exist.)

Resetting the primary key sequence

Using the --natural-primary tag when dumping the data

Any help would be greatly appreciated.

答:
You probably need to use --natural-primary as well, so that the primary keys of content types are not exported to the fixture:

```<code>python manage.py dumpdata --natural-foreign --natural-primary > dump.json
</code>```

Body:
I've recently inherited a production codebase for a webapp written using Django. Up until now, the database the project has been using has been the default SQLite3 database, but now that more people are using the app, moving to Postgres is necessary.

I've been able to set up an empty postgres database with the project that works fine. The problem I'm encountering is in moving the data from the old project to the new one. I can run
    python manage.py dumpdata --natural-foreign > dump.json
to dump the data, which works fine, but when I switch to postgres in settings.py and run
    python manage.py loaddata dump.json
I get the following error:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
    self.loaddata(fixture_labels)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata
    self.load_label(fixture_label)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 147, in load_label
    obj.save(using=self.using)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 173, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 738, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 803, in _save_table
    forced_update)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/base.py", line 853, in _do_update
    return filtered._update(values) > 0
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/query.py", line 580, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1062, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/mnt/d/Code/MCJobTrack/_VENV/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: Problem installing fixture '/mnt/d/Code/MCJobTrack/jobtrack_project/dump.json': Could not load contenttypes.ContentType(pk=15): duplicate key value violates unique constraint "django_content_type_app_label_45f3b1d93ec8c61c_uniq"
DETAIL:  Key (app_label, model)=(jobtrack, purchaseorder) already exists.

So far I've tried:

Running TRUNCATE django_content_type RESTART IDENTITY CASCADE; in the dbshell

Excluding contenttypes when dumping the data. (I get the error django.core.serializers.base.DeserializationError: Problem installing fixture '/mnt/d/Code/MCJobTrack/jobtrack_project/dump_no_contenttypes.json': ContentType matching query does not exist.)

Resetting the primary key sequence

Using the --natural-primary tag when dumping the data

Any help would be greatly appreciated.

Body:
You probably need to use --natural-primary as well, so that the primary keys of content types are not exported to the fixture:

python manage.py dumpdata --natural-foreign --natural-primary > dump.json


问:
How to access Bing Images Search API in javascript on client side without exposing credentials?
Is there a way, I can access Images API from the browser, without actually exposing my API Keys and credentials ? This question applies to any API. How can we expose an API to javascript client side browsers, without exposing secrets ?</p>

答:
It's discussed here: How to protect an API Key when using JavaScript?.

Short answer, make calls from server side as much as possible. In that case, you can whitelist your client through domain/IP/login, etc. From client side alone, you can make it difficult but not impossible for somebody willing to steal your keys.

You can also regenerate keys time-to-time just to be safe and keep track of your usage just to be sure.


问:
JS: How to extract nested string of object?
I got an array with following data structure:

```<code>[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: {
      en: [{ content: 'foo', extended: 'bar' }, {...}],
      it: [{ content: 'any', extended: 'thing' }, {...}]
    },
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  },
  {...}
]
</code>```

I need to modify this array to get only string values for content by selecting the first element of a specific language.

So for the english language the result should be:

```<code>[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: 'foo',
    extended: bar,
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  }
]
</code>```

I know I could get the string with

```<code>const language = 'en'
array.forEach(doc => {
  console.log(doc.content[language][0].content)
  console.log(doc.content[language][0].extended)
})
</code>```

But how do I replace it to get my result?

答:
You can do so:</p>

```<code>  let result = data.map(e => ({
        ...e,
        content: e.content[language].content,
        extended: e.content[language].extended
  }));
</code>```

Body:
I got an array with following data structure:

[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: {
      en: [{ content: 'foo', extended: 'bar' }, {...}],
      it: [{ content: 'any', extended: 'thing' }, {...}]
    },
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  },
  {...}
]

I need to modify this array to get only string values for content by selecting the first element of a specific language.

So for the english language the result should be:

[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: 'foo',
    extended: bar,
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  }
]

I know I could get the string with

const language = 'en'
array.forEach(doc => {
  console.log(doc.content[language][0].content)
  console.log(doc.content[language][0].extended)
})

But how do I replace it to get my result?

Body:
You can do so:

  let result = data.map(e => ({
        ...e,
        content: e.content[language].content,
        extended: e.content[language].extended
  }));


问:
Apply global scope based on user role in Laravel 5.5
For some model, I need to apply a global scope if the logged in user is not super admin. In model's boot() method I tried something like this:

```<code><?php

namespace App;

use Auth;
use App\Scopes\RoleScope;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected static function boot()
    {
        parent::boot();

        if( Auth::check() && ! Auth::user()->isSuperAdmin() ){
            static::addGlobalScope(new RoleScope);
        }
    }
}
</code>```

The scop never applied! What did I do wrong here? How can I achieve the goal to apply the scope based on the user role? thanks

答:
You cannot access the currently authenticated user in the boot method of the Eloquent model - the Auth middleware hasn't run yet at this point.

What you should do is to perform the super admin check within the apply method of your RoleScope.

Body:
For some model, I need to apply a global scope if the logged in user is not super admin. In model's boot() method I tried something like this:

<?php

namespace App;

use Auth;
use App\Scopes\RoleScope;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected static function boot()
    {
        parent::boot();

        if( Auth::check() && ! Auth::user()->isSuperAdmin() ){
            static::addGlobalScope(new RoleScope);
        }
    }
}

The scop never applied! What did I do wrong here? How can I achieve the goal to apply the scope based on the user role? thanks


问:
Rake gems:install says "could not find table", rake db:migrate says "required gems missing"
I just cloned a github repo on a fresh Ubuntu machine, running sqlite3 for all environments. rake db:create says development.sqlite3 already exists. rake db:migrate says I'm missing a bunch of required gems and should run rake gems:install. rake gems:install, of course, says it Could not find table 'studies', which sounds to me like something rake db:migrate should fix.

I looked around the net and while lots of people have gotten 'could not find table' errors, they all got them from rake db:migrate, not rake gems:install. I'm suspecting it's an application-specific error, but still, any ideas would be appreciated.

PS: Ruby 1.8.7, Rails 2.3.8.

答: You can always install separate gems with gem install -r <gem name> or gem install -v=<gem version> -r <gem name> command, not using rake.


答:
You can loop through the elements and find the correct price from the dictionary.

```<code>var sizeElements = Array.from(document.getElementsByName('Size'));
      var value = sizeElements.length && sizeElements.find(r => r.checked).value;
</code>```

Working example given below

For the onClick vs onChange: You should probably use onClick. You can read more about it at this question: What the difference between .click and .change on a checkbox

function priceCalculator(){
  var price_dict = {
    "Small":22, "Medium":28, "Large":35,

  }

  var sizeElements = Array.from(document.getElementsByName('Size'));
  var value = sizeElements.length && sizeElements.find(r => r.checked).value;

  return price_dict[value] // use returned price elsewhere
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Pizza Order Form</title>

    <style>
        form {
            font-family: Arial, Helvetica, sans-serif;
            vertical-align: central;
            border: 5px solid black;
            margin:0px auto;
            width:650px;
            padding-left:0.5em;
        }
        fieldset{
            width:600px;
            box-sizing:border-box;
            border-radius: 20px;
        }

        .deliver > p > label {
            width: 70px;
            display: inline-block;
        }

        .deliver > p > input {
            width: 130px;
            display: inline-block;
        }

        #DisplayPrice{
            background-color: yellow;
        }

    </style>
</head>

<body >
    <form>
        <h1>Pizza order Form</h1>
        <p>
            <label for="Pizza Type">Pizza Type:</label>
            <select name="pizza type">
                <option value="Please select" selected>Please select...</option>
                <option value="Aloha Chicken">Aloha Chicken</option>
                <option value="Beef Pepperoni">Beef Pepperoni</option>
                <option value="Chicken Delight">Chicken Delight</option>
                <option value="Deluxe Cheese">Deluxe Cheese</option>
            </select>

            <label for="Quantity">Quantity</label>
            <input name="quantity" type="number" min="1" max="4" />
        </p>

        <!--Size-->
        <fieldset >
            <legend>Size:</legend>
            <input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
            <input type="radio" name="Size" value="Medium" onclick="priceCalculator()"/>Medium
            <input type="radio" name="Size" value="Large" onclick="priceCalculator()"/>Large
        </fieldset>

        <!--Crust-->
        <fieldset>
            <legend>Crust:</legend>
            <input type="radio" name="Crust"value="Thin" />Thin
            <input type="radio" name="Crust" value="Thick" />Thick
            <input type="radio" name="Crust" value="Deep Dish" />Deep Dish
        </fieldset>

        <!--Toppings-->
        <fieldset>
            <legend>Toppings:</legend>
            <input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
            <input type="radio" name="Toppings" value="Sausage" />Sausage
            <input type="radio" name="Toppings" value="Olives" />Olives
        </fieldset>

        <!--Addons-->
        <p>
            <label for="Addons">Addons</label>
            <select name="Addons" multiple>
                <option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
                <option value="Garlic Bread">Garlic Bread</option>
            </select>
        </p>

        <div id="DisplayPrice"></div>

        <!--Delivery section-->
        <fieldset class="deliver">
            <legend>Deliver to:</legend>
            <p>
                <label for="Name">Name:</label>
                <input type="text" name="name" required/>
            </p>
            <p>
                <label for="Address">Address:</label>
                <textarea rows="2" cols="30" required></textarea>
                <label for="Postal Code">Postal Code:</label>
                <input type="text" name="Postal Code" maxlength="6" required/>
            </p>
            <p>
                <label for="Phone Number">Phone#: </label>
                <input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>
            </p>
            <p>
                <label for="email">Email:</label>
                <input type="email" form="email" required />
            </p>
            <p>
                <label for=" Date">Date:</label>
                <input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
                <label for="time">Time: </label>
                <input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>
            </p>
        </fieldset>
        <p>
            <input type="submit" value="submit">
            <input type="reset" value="reset">
        </p>

    </form>

    <script src="pizzaScript.js"></script>

</body>
</html></code>```

Title: Not sure if my condition correlates to radio button being checked

Body:
You can loop through the elements and find the correct price from the dictionary.

var sizeElements = Array.from(document.getElementsByName('Size'));
      var value = sizeElements.length && sizeElements.find(r => r.checked).value;

Working example given below

For the onClick vs onChange: You should probably use onClick. You can read more about it at this question: What the difference between .click and .change on a checkbox

function priceCalculator(){
  var price_dict = {
    "Small":22, "Medium":28, "Large":35,

  }

  var sizeElements = Array.from(document.getElementsByName('Size'));
  var value = sizeElements.length && sizeElements.find(r => r.checked).value;

  return price_dict[value] // use returned price elsewhere
  }

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Pizza Order Form</title>

    <style>
        form {
            font-family: Arial, Helvetica, sans-serif;
            vertical-align: central;
            border: 5px solid black;
            margin:0px auto;
            width:650px;
            padding-left:0.5em;
        }
        fieldset{
            width:600px;
            box-sizing:border-box;
            border-radius: 20px;
        }

        .deliver > p > label {
            width: 70px;
            display: inline-block;
        }

        .deliver > p > input {
            width: 130px;
            display: inline-block;
        }

        #DisplayPrice{
            background-color: yellow;
        }

    </style>
</head>

<body >
    <form>
        <h1>Pizza order Form</h1>
        <p>
            <label for="Pizza Type">Pizza Type:</label>
            <select name="pizza type">
                <option value="Please select" selected>Please select...</option>
                <option value="Aloha Chicken">Aloha Chicken</option>
                <option value="Beef Pepperoni">Beef Pepperoni</option>
                <option value="Chicken Delight">Chicken Delight</option>
                <option value="Deluxe Cheese">Deluxe Cheese</option>
            </select>

            <label for="Quantity">Quantity</label>
            <input name="quantity" type="number" min="1" max="4" />
        </p>

        <!--Size-->
        <fieldset >
            <legend>Size:</legend>
            <input type="radio" name="Size" value="Small" onclick="priceCalculator()" />Small
            <input type="radio" name="Size" value="Medium" onclick="priceCalculator()"/>Medium
            <input type="radio" name="Size" value="Large" onclick="priceCalculator()"/>Large
        </fieldset>

        <!--Crust-->
        <fieldset>
            <legend>Crust:</legend>
            <input type="radio" name="Crust"value="Thin" />Thin
            <input type="radio" name="Crust" value="Thick" />Thick
            <input type="radio" name="Crust" value="Deep Dish" />Deep Dish
        </fieldset>

        <!--Toppings-->
        <fieldset>
            <legend>Toppings:</legend>
            <input type="radio" name="Toppings" value="Mushrooms" />Mushrooms
            <input type="radio" name="Toppings" value="Sausage" />Sausage
            <input type="radio" name="Toppings" value="Olives" />Olives
        </fieldset>

        <!--Addons-->
        <p>
            <label for="Addons">Addons</label>
            <select name="Addons" multiple>
                <option value="Side of Buffalo Wings">Side of Buffalo Wings</option>
                <option value="Garlic Bread">Garlic Bread</option>
            </select>
        </p>

        <div id="DisplayPrice"></div>

        <!--Delivery section-->
        <fieldset class="deliver">
            <legend>Deliver to:</legend>
            <p>
                <label for="Name">Name:</label>
                <input type="text" name="name" required/>
            </p>
            <p>
                <label for="Address">Address:</label>
                <textarea rows="2" cols="30" required></textarea>
                <label for="Postal Code">Postal Code:</label>
                <input type="text" name="Postal Code" maxlength="6" required/>
            </p>
            <p>
                <label for="Phone Number">Phone#: </label>
                <input type="tel" name="Phone#" maxlength="8" pattern="^[896]\d{7}" required/>
            </p>
            <p>
                <label for="email">Email:</label>
                <input type="email" form="email" required />
            </p>
            <p>
                <label for=" Date">Date:</label>
                <input type="date" name="Date" min="1 November 2017" max="31 December 2017" required/>
                <label for="time">Time: </label>
                <input type="time" value="10:00" name="Time" min="10:00" max="22:00" step="15" required/>
            </p>
        </fieldset>
        <p>
            <input type="submit" value="submit">
            <input type="reset" value="reset">
        </p>

    </form>

    <script src="pizzaScript.js"></script>

</body>
</html>


问:
Closure array parameter in function
I need to make a function that takes in an array of buttons and an array of closures. In the end, I am aiming to attach to each button an action from the array, and set up each button in my notification. Here's my function:

```<code>func makeButtons(buttons: [UIButton], withActions actions: [() -> Void]){

    var bottomAnchor: NSLayoutYAxisAnchor?
    bottomAnchor = notificationView.bottomAnchor

    buttons.forEach({ (button) in
        button.actionHandle(controlEvent: .touchUpInside, action: actions[buttons.index(of: button)!])

        notificationView.addSubview(button)

        button.bottomAnchor.constraint(equalTo: bottomAnchor!, constant: -20).isActive = true
        button.rightAnchor.constraint(equalTo: notificationView.rightAnchor, constant: -20).isActive = true
        button.leftAnchor.constraint(equalTo: notificationView.leftAnchor, constant: 20).isActive = true
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true

        bottomAnchor = button.topAnchor
    })
}
</code>```

I am indeed using an extension to be able to add a closure for UIButton target using actionHandle(). I got it off Stack. Here's that:

```<code>extension UIButton {
    private func actionHandleBlock(action:(() -> Void)? = nil) {
        struct __ {
            static var action :(() -> Void)?
        }
        if action != nil {
            __.action = action
        } else {
            __.action?()
        }
    }

    @objc private func triggerActionHandleBlock() {
        self.actionHandleBlock()
    }

    func actionHandle(controlEvent control: UIControlEvents, action:@escaping () -> Void) {
        self.actionHandleBlock(action: action)
        self.addTarget(self, action: #selector(triggerActionHandleBlock), for: control)
    }
}
</code>```

Also, here's how I'm using the make Buttons function:

```<code>func setButtonsWithAction(){
        let button1 = UIButton()
        let button2 = UIButton()

        addButtons(buttons: [button1, button2], withActions: [self.sayHi, self.sayGoodbye])
    }

func sayHi(){
            print("Hi there")
        }

func sayGoodbye(){
    print("Goodbye")
}
</code>```

All sets up ok, just as I want. However, the problem I am facing is that regardless on which button I click, it performs the last function from my closure array. So in this case it prints "Goodbye" regardless of which button I click.
What I need is:

```<code>click button1 -> print Hi
click button2 -> print Goodbye
</code>```

What is the problem, I can't seem to figure this out.

答:
This should definitely show you the way.
Let me know how it goes. </p>

```<code>fileprivate func toolbarButton(title: String, closure: Selector ) -> UIButton {
    let button = UIButton(type: .system)
    button.setTitle(title, for: .normal)
    button.tintColor = .darkGray
    button.addTarget(self, action: closure, for: .touchUpInside)
    return button
}
</code>```

<p>use like this: </p>

```<code>lazy var nearButton = toolbarButton(title: "Near Me", closure: #selector(handleToolButtonNear))
</code>```

Title: Closure array parameter in function

Body:
I need to make a function that takes in an array of buttons and an array of closures. In the end, I am aiming to attach to each button an action from the array, and set up each button in my notification. Here's my function:

func makeButtons(buttons: [UIButton], withActions actions: [() -> Void]){

    var bottomAnchor: NSLayoutYAxisAnchor?
    bottomAnchor = notificationView.bottomAnchor

    buttons.forEach({ (button) in
        button.actionHandle(controlEvent: .touchUpInside, action: actions[buttons.index(of: button)!])

        notificationView.addSubview(button)

        button.bottomAnchor.constraint(equalTo: bottomAnchor!, constant: -20).isActive = true
        button.rightAnchor.constraint(equalTo: notificationView.rightAnchor, constant: -20).isActive = true
        button.leftAnchor.constraint(equalTo: notificationView.leftAnchor, constant: 20).isActive = true
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true

        bottomAnchor = button.topAnchor
    })
}

I am indeed using an extension to be able to add a closure for UIButton target using actionHandle(). I got it off Stack. Here's that:

extension UIButton {
    private func actionHandleBlock(action:(() -> Void)? = nil) {
        struct __ {
            static var action :(() -> Void)?
        }
        if action != nil {
            __.action = action
        } else {
            __.action?()
        }
    }

    @objc private func triggerActionHandleBlock() {
        self.actionHandleBlock()
    }

    func actionHandle(controlEvent control: UIControlEvents, action:@escaping () -> Void) {
        self.actionHandleBlock(action: action)
        self.addTarget(self, action: #selector(triggerActionHandleBlock), for: control)
    }
}

Also, here's how I'm using the make Buttons function:

func setButtonsWithAction(){
        let button1 = UIButton()
        let button2 = UIButton()

        addButtons(buttons: [button1, button2], withActions: [self.sayHi, self.sayGoodbye])
    }

func sayHi(){
            print("Hi there")
        }

func sayGoodbye(){
    print("Goodbye")
}

All sets up ok, just as I want. However, the problem I am facing is that regardless on which button I click, it performs the last function from my closure array. So in this case it prints "Goodbye" regardless of which button I click.
What I need is:

click button1 -> print Hi
click button2 -> print Goodbye

What is the problem, I can't seem to figure this out.

Body:
This should definitely show you the way.
Let me know how it goes.

fileprivate func toolbarButton(title: String, closure: Selector ) -> UIButton {
    let button = UIButton(type: .system)
    button.setTitle(title, for: .normal)
    button.tintColor = .darkGray
    button.addTarget(self, action: closure, for: .touchUpInside)
    return button
}

use like this:

lazy var nearButton = toolbarButton(title: "Near Me", closure: #selector(handleToolButtonNear))


问:
TCP chat in c not reading/sending strings correctly
I'm trying to implement a multi-client chat, using tcp socket-based connections and threads to manage the clients and inputs. However the reading and writing of the sent or received string aren't being executed correctly, and i can't quite figure out why.

Server:

```<code>#define IP "127.0.0.1"
#define PORT 9000
#define MAX_CONNECTION_Q 10
#define CLIENTS 10
#define BUFFSIZE 1024
#define NAMELEN 32
#define COMMANDS 16
#define MESSAGESIZE 256
#define LINENUM 512

struct chat{
  char userlist[CLIENTS][NAMELEN];
  char admin[NAMELEN];
  char ID[NAMELEN];
  char logg[512][216];
  struct chat *next;
  int pos;
};

struct client_info{
  pthread_t client_ID;
  int sockfd;
  struct chat chats;
  char user[NAMELEN];
  struct client_info *next;
};

struct header{
  struct client_info *fnode, *lnode;
}*client_head;

struct chat_head{
  struct chat *fnode,*lnode;
}*chat_head;

int sockfd, clinfo;
struct client_info thread_info[CLIENTS];
struct header client_list;
pthread_mutex_t mutex;

void list_init() {
  client_head = malloc(sizeof(struct header));
  chat_head = malloc(sizeof(struct chat_head));
  client_head->fnode = NULL;
  chat_head->fnode = NULL;
}

int compare(int a, int b){
  return (a-b);
}

void chat_insert(struct chat *node){
  if(chat_head->fnode == NULL){
    chat_head->fnode = node;
    chat_head->lnode = node;
  }
  else{
    chat_head->lnode->next = node;
    chat_head->lnode = node;
  }
}

int search_cli(char *name){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    if(strcmp(tmp->user,name) == 0){
      return tmp->sockfd;
    }
    tmp = tmp->next;
  }
  return -1;
}

void client_insert(struct client_info *node){
  if(client_head->fnode == NULL){
    client_head->fnode = node;
    client_head->lnode = node;
    node->next = NULL;
  }
  else{
    client_head->lnode->next = node;
    client_head->lnode = node;
    node->next = NULL;
  }
}

void client_delete(struct client_info *node){
  struct client_info *last = client_head->fnode;
  struct client_info *tmp = last->next;
  if(client_head->fnode == NULL){
    return;
  }
  if(compare(last->sockfd, node->sockfd) == 0){
    client_head->fnode = tmp;

    free(last);

    if(client_head->fnode == NULL){

      client_head->lnode = NULL;

    }

    return;
  }
  while(tmp!=NULL){
    if(compare(tmp->sockfd, node->sockfd) == 0) {
      last->next = tmp->next;

      free(tmp);
      return;
    }

    tmp = tmp->next;
  }

}

void display_clients(){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    printf("Username: %s\nSocket: %d\n--------------------\n",tmp->user,tmp->sockfd);
    tmp = tmp->next;
  }
}

void change_username(int sock,char *sender){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    if(tmp->sockfd == sock){
      strcpy(tmp->user,sender);
      break;
    }
    tmp = tmp->next;
  }
}

void *client_commands_handler(void *fd){
  struct client_info *clinfo = (struct client_info *)fd;
  char *buffer = malloc(NAMELEN);
  char receiver[NAMELEN],sender[NAMELEN],message[BUFFSIZE];
  recv(clinfo->sockfd,buffer,NAMELEN,0);
  strcpy(clinfo->user,buffer);
  memset(buffer,0,sizeof(buffer));
  int nbytes;
  while(1){
    memset(buffer,0,sizeof(buffer));
    nbytes = recv(clinfo->sockfd, buffer, BUFFSIZE, 0);
    if(nbytes<=0) {
      printf("%s lost connection\n", clinfo->user);
      pthread_mutex_lock(&mutex);
      client_delete(clinfo);
      pthread_mutex_unlock(&mutex);
      break;
    }
    printf("%s\n",buffer);
    else if(strncmp(buffer, "private", 7) == 0) {
      int sockid;
      sscanf(buffer,"private %s %s %s",sender,receiver,message);
      printf("%s%s%s",sender,receiver,message);
      if((sockid = search_cli(sender)) == -1){
        char *server = malloc(NAMELEN);
        strcpy(server,"<Server> User doesn't exist\n");
        write(clinfo->sockfd,server,strlen(server));
      }
      else{
        struct chat new_chat;
        new_chat.pos = 0;
        strcpy(new_chat.logg[new_chat.pos],message);
        new_chat.pos++;
        strcpy(new_chat.userlist[0],sender);
        strcpy(new_chat.userlist[1],receiver);
      sprintf(new_chat.ID,"%s%s",new_chat.userlist[0],new_chat.userlist[1]);
        new_chat.next = NULL;
        pthread_mutex_lock(&mutex);
        chat_insert(&new_chat);
        pthread_mutex_unlock(&mutex);
        send(sockid,message,strlen(message),0);
      }
    }
    else {
      fprintf(stderr, "Garbage data from [%d] %s...\n", clinfo->sockfd, clinfo->user);
    }
  }
  close(clinfo->sockfd);
  return NULL;
}

void *server_commands_handler() {

}

int main() {
  int size,clientfd;
  struct sockaddr_in server_addr, client_addr;
  pthread_t server_commands;
  list_init();
  pthread_mutex_init(&mutex, NULL);
  if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Couldn't get server socket");
    exit(0);
  }
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT);
  server_addr.sin_addr.s_addr = inet_addr(IP);
  memset(&(server_addr.sin_zero), 0, 8);
  if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
    perror("Couldn't bind socket");
    exit(0);
  }
  if(listen(sockfd, MAX_CONNECTION_Q) == -1){
    perror("Couldn't listen");
    exit(0);
  }
  if(pthread_create(&server_commands, NULL, *server_commands_handler, NULL) != 0){
    perror("Couldn't create thread");
    exit(0);
  }
  while(1){
    size = sizeof(struct sockaddr_in);
    if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr,(socklen_t*)&size))==-1){
      perror("Connection failed");
      exit(0);
    }
    printf("Client accepted\n");
    struct client_info clinfo;
    clinfo.sockfd = clientfd;
    clinfo.next = NULL;
    pthread_mutex_lock(&mutex);
    client_insert(&clinfo);
    pthread_mutex_unlock(&mutex);
    pthread_create(&clinfo.client_ID, NULL, client_commands_handler, (void *)&clinfo);
  }
  return 0;
}
</code>```

client:

```<code>#define SERVERIP "127.0.0.1"
#define SERVERPORT 9000
#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct threadinfo{
  pthread_t thread_ID;
  int sockfd;
};

struct USER{
  char user[USERLEN];
  int sockfd;
  char current_convo[USERLEN];
};

int isconnected, sockfd, sent;
char option[BUFFSIZE];
struct USER me;

int connect_with_server();
void logout(struct USER *me);
void login(struct USER *me);
void *receiver();

void login(struct USER *me){
  if(isconnected){
    printf("Already connected\n");
    return;
  }
  sockfd = connect_with_server();
  if(sockfd == -1){
    perror("Couldn't connect to server\n");
  }
  if(sockfd >= 0) {
    isconnected = 1;
    me->sockfd = sockfd;
    printf("Logged in as %s\n", me->user);
    struct threadinfo thread;
    pthread_create(&thread.thread_ID, NULL, receiver, (void *)&thread);
  }
  else {
    printf("Couldn't connect.\n");
    exit(0);
  }
}

void *receiver(){
  int recvd;
  char msg[BUFFSIZE];
  while(isconnected){
    memset(msg,0,sizeof(msg));
    recvd = read(sockfd, msg, sizeof(msg));
      if(!recvd) {
        printf("Connection Lost from Server\n");
        isconnected = 0;
        close(sockfd);
        break;
      }
      if(recvd > 0) {
        fputs(msg,stdout);
      }
  }
  return NULL;
}

int main() {
    memset(&me, 0, sizeof(struct USER));
    char msg[BUFFSIZE];
    char *token;
    while(fgets(option,BUFFSIZE-1,stdin)){
      memset(msg,0,sizeof(msg));
      if(strncmp(option,"exit", 4) == 0){
        logout(&me);
        break;
      }
      else if(strncmp(option, "login", 5) == 0){
        token = strtok(option, " ");
        token = strtok(NULL, "\n");
        memset(me.user, 0, sizeof(char)*USERLEN);
        if(token != NULL) {
          strcpy(me.user, token);
          login(&me);
        }
        else{
          printf("Couldn't get valid username\n");
        }
      }
      else if(strncmp(option, "private", 7) == 0){
        if(isconnected == 0){
          printf("User not connected\n");
        }
        else{
          char *tmp = malloc(USERLEN);
          token = strtok(option, " ");
          token = strtok(NULL, " ");
          strcpy(tmp,token);
          token = strtok(NULL, "\n");
          sprintf(msg,"private %s %s %s",me.user,tmp,token);
          send(sockfd, msg, strlen(msg),0);
        }
      }
  return 0;
}
</code>```

the code has a lot o code unnecessary to a simple two-way input based connection, however it will have more feature in the long haul that i'm trying to implement.There are many thing to fix here but my question is mainly focused towards sending a string through the "private" input that should be as follows:

private (username of receiver) (message to send)

答:
I am still looking at it but I noticed a few things.  In your server, you have

```<code>  char *buffer = malloc(NAMELEN);
  char receiver[NAMELEN],sender[NAMELEN],message[BUFFSIZE];
  recv(clinfo->sockfd,buffer,NAMELEN,0);
  strcpy(clinfo->user,buffer);
  memset(buffer,0,sizeof(buffer));
  int nbytes;
  while(1){
    memset(buffer,0,sizeof(buffer));
    nbytes = recv(clinfo->sockfd, buffer, BUFFSIZE, 0);
</code>```

The buffer variable receives a pointer to a block of NAMELEN (32) bytes.  You recv NAMELEN bytes without looking at the status.  So far so good.  You then clear the first sizeof buffer bytes (since buffer is a pointer, you are clearing 4 or 8 bytes).  A short time later, you recv BUFFSIZE (1024) bytes into your poor 32 byte buffer.

What I would suggest is you get the server running by testing with telnet

```<code>telnet 127.0.0.1 9000
</code>```

and typing what your program expects. Keep in mind that the data is only transmitted when you hit return.

The client could be similarly exercised with netcat with:

```<code>nc -l 127.0.0.1 9000
</code>```

While I am at it, why is your client multithreaded? It would simplify things if you called receiver() directly rather than creating another thread.

Also keep an eye on your mallocs and make sure they are paired with a free. I see a number of places where you malloc a fixed size block of memory and then to do not free it.  This could be accomplished a lot cleaner with a local variable.  Those go away when you return.  Alternatively, look into alloca(), that also goes away when you return.  It is not available everywhere but it is pretty useful.

Body:
I'm trying to implement a multi-client chat, using tcp socket-based connections and threads to manage the clients and inputs. However the reading and writing of the sent or received string aren't being executed correctly, and i can't quite figure out why.

Server:

#define IP "127.0.0.1"
#define PORT 9000
#define MAX_CONNECTION_Q 10
#define CLIENTS 10
#define BUFFSIZE 1024
#define NAMELEN 32
#define COMMANDS 16
#define MESSAGESIZE 256
#define LINENUM 512

struct chat{
  char userlist[CLIENTS][NAMELEN];
  char admin[NAMELEN];
  char ID[NAMELEN];
  char logg[512][216];
  struct chat *next;
  int pos;
};

struct client_info{
  pthread_t client_ID;
  int sockfd;
  struct chat chats;
  char user[NAMELEN];
  struct client_info *next;
};

struct header{
  struct client_info *fnode, *lnode;
}*client_head;

struct chat_head{
  struct chat *fnode,*lnode;
}*chat_head;

int sockfd, clinfo;
struct client_info thread_info[CLIENTS];
struct header client_list;
pthread_mutex_t mutex;

void list_init() {
  client_head = malloc(sizeof(struct header));
  chat_head = malloc(sizeof(struct chat_head));
  client_head->fnode = NULL;
  chat_head->fnode = NULL;
}

int compare(int a, int b){
  return (a-b);
}

void chat_insert(struct chat *node){
  if(chat_head->fnode == NULL){
    chat_head->fnode = node;
    chat_head->lnode = node;
  }
  else{
    chat_head->lnode->next = node;
    chat_head->lnode = node;
  }
}

int search_cli(char *name){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    if(strcmp(tmp->user,name) == 0){
      return tmp->sockfd;
    }
    tmp = tmp->next;
  }
  return -1;
}

void client_insert(struct client_info *node){
  if(client_head->fnode == NULL){
    client_head->fnode = node;
    client_head->lnode = node;
    node->next = NULL;
  }
  else{
    client_head->lnode->next = node;
    client_head->lnode = node;
    node->next = NULL;
  }
}

void client_delete(struct client_info *node){
  struct client_info *last = client_head->fnode;
  struct client_info *tmp = last->next;
  if(client_head->fnode == NULL){
    return;
  }
  if(compare(last->sockfd, node->sockfd) == 0){
    client_head->fnode = tmp;

    free(last);

    if(client_head->fnode == NULL){

      client_head->lnode = NULL;

    }

    return;
  }
  while(tmp!=NULL){
    if(compare(tmp->sockfd, node->sockfd) == 0) {
      last->next = tmp->next;

      free(tmp);
      return;
    }

    tmp = tmp->next;
  }

}

void display_clients(){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    printf("Username: %s\nSocket: %d\n--------------------\n",tmp->user,tmp->sockfd);
    tmp = tmp->next;
  }
}

void change_username(int sock,char *sender){
  struct client_info *tmp = client_head->fnode;
  while(tmp!=NULL){
    if(tmp->sockfd == sock){
      strcpy(tmp->user,sender);
      break;
    }
    tmp = tmp->next;
  }
}

void *client_commands_handler(void *fd){
  struct client_info *clinfo = (struct client_info *)fd;
  char *buffer = malloc(NAMELEN);
  char receiver[NAMELEN],sender[NAMELEN],message[BUFFSIZE];
  recv(clinfo->sockfd,buffer,NAMELEN,0);
  strcpy(clinfo->user,buffer);
  memset(buffer,0,sizeof(buffer));
  int nbytes;
  while(1){
    memset(buffer,0,sizeof(buffer));
    nbytes = recv(clinfo->sockfd, buffer, BUFFSIZE, 0);
    if(nbytes<=0) {
      printf("%s lost connection\n", clinfo->user);
      pthread_mutex_lock(&mutex);
      client_delete(clinfo);
      pthread_mutex_unlock(&mutex);
      break;
    }
    printf("%s\n",buffer);
    else if(strncmp(buffer, "private", 7) == 0) {
      int sockid;
      sscanf(buffer,"private %s %s %s",sender,receiver,message);
      printf("%s%s%s",sender,receiver,message);
      if((sockid = search_cli(sender)) == -1){
        char *server = malloc(NAMELEN);
        strcpy(server,"<Server> User doesn't exist\n");
        write(clinfo->sockfd,server,strlen(server));
      }
      else{
        struct chat new_chat;
        new_chat.pos = 0;
        strcpy(new_chat.logg[new_chat.pos],message);
        new_chat.pos++;
        strcpy(new_chat.userlist[0],sender);
        strcpy(new_chat.userlist[1],receiver);
      sprintf(new_chat.ID,"%s%s",new_chat.userlist[0],new_chat.userlist[1]);
        new_chat.next = NULL;
        pthread_mutex_lock(&mutex);
        chat_insert(&new_chat);
        pthread_mutex_unlock(&mutex);
        send(sockid,message,strlen(message),0);
      }
    }
    else {
      fprintf(stderr, "Garbage data from [%d] %s...\n", clinfo->sockfd, clinfo->user);
    }
  }
  close(clinfo->sockfd);
  return NULL;
}

void *server_commands_handler() {

}

int main() {
  int size,clientfd;
  struct sockaddr_in server_addr, client_addr;
  pthread_t server_commands;
  list_init();
  pthread_mutex_init(&mutex, NULL);
  if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Couldn't get server socket");
    exit(0);
  }
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT);
  server_addr.sin_addr.s_addr = inet_addr(IP);
  memset(&(server_addr.sin_zero), 0, 8);
  if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
    perror("Couldn't bind socket");
    exit(0);
  }
  if(listen(sockfd, MAX_CONNECTION_Q) == -1){
    perror("Couldn't listen");
    exit(0);
  }
  if(pthread_create(&server_commands, NULL, *server_commands_handler, NULL) != 0){
    perror("Couldn't create thread");
    exit(0);
  }
  while(1){
    size = sizeof(struct sockaddr_in);
    if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr,(socklen_t*)&size))==-1){
      perror("Connection failed");
      exit(0);
    }
    printf("Client accepted\n");
    struct client_info clinfo;
    clinfo.sockfd = clientfd;
    clinfo.next = NULL;
    pthread_mutex_lock(&mutex);
    client_insert(&clinfo);
    pthread_mutex_unlock(&mutex);
    pthread_create(&clinfo.client_ID, NULL, client_commands_handler, (void *)&clinfo);
  }
  return 0;
}

client:

#define SERVERIP "127.0.0.1"
#define SERVERPORT 9000
#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct threadinfo{
  pthread_t thread_ID;
  int sockfd;
};

struct USER{
  char user[USERLEN];
  int sockfd;
  char current_convo[USERLEN];
};

int isconnected, sockfd, sent;
char option[BUFFSIZE];
struct USER me;

int connect_with_server();
void logout(struct USER *me);
void login(struct USER *me);
void *receiver();

void login(struct USER *me){
  if(isconnected){
    printf("Already connected\n");
    return;
  }
  sockfd = connect_with_server();
  if(sockfd == -1){
    perror("Couldn't connect to server\n");
  }
  if(sockfd >= 0) {
    isconnected = 1;
    me->sockfd = sockfd;
    printf("Logged in as %s\n", me->user);
    struct threadinfo thread;
    pthread_create(&thread.thread_ID, NULL, receiver, (void *)&thread);
  }
  else {
    printf("Couldn't connect.\n");
    exit(0);
  }
}

void *receiver(){
  int recvd;
  char msg[BUFFSIZE];
  while(isconnected){
    memset(msg,0,sizeof(msg));
    recvd = read(sockfd, msg, sizeof(msg));
      if(!recvd) {
        printf("Connection Lost from Server\n");
        isconnected = 0;
        close(sockfd);
        break;
      }
      if(recvd > 0) {
        fputs(msg,stdout);
      }
  }
  return NULL;
}

int main() {
    memset(&me, 0, sizeof(struct USER));
    char msg[BUFFSIZE];
    char *token;
    while(fgets(option,BUFFSIZE-1,stdin)){
      memset(msg,0,sizeof(msg));
      if(strncmp(option,"exit", 4) == 0){
        logout(&me);
        break;
      }
      else if(strncmp(option, "login", 5) == 0){
        token = strtok(option, " ");
        token = strtok(NULL, "\n");
        memset(me.user, 0, sizeof(char)*USERLEN);
        if(token != NULL) {
          strcpy(me.user, token);
          login(&me);
        }
        else{
          printf("Couldn't get valid username\n");
        }
      }
      else if(strncmp(option, "private", 7) == 0){
        if(isconnected == 0){
          printf("User not connected\n");
        }
        else{
          char *tmp = malloc(USERLEN);
          token = strtok(option, " ");
          token = strtok(NULL, " ");
          strcpy(tmp,token);
          token = strtok(NULL, "\n");
          sprintf(msg,"private %s %s %s",me.user,tmp,token);
          send(sockfd, msg, strlen(msg),0);
        }
      }
  return 0;
}

the code has a lot o code unnecessary to a simple two-way input based connection, however it will have more feature in the long haul that i'm trying to implement.There are many thing to fix here but my question is mainly focused towards sending a string through the "private" input that should be as follows:

private (username of receiver) (message to send)

Body:
I am still looking at it but I noticed a few things.  In your server, you have

  char *buffer = malloc(NAMELEN);
  char receiver[NAMELEN],sender[NAMELEN],message[BUFFSIZE];
  recv(clinfo->sockfd,buffer,NAMELEN,0);
  strcpy(clinfo->user,buffer);
  memset(buffer,0,sizeof(buffer));
  int nbytes;
  while(1){
    memset(buffer,0,sizeof(buffer));
    nbytes = recv(clinfo->sockfd, buffer, BUFFSIZE, 0);

The buffer variable receives a pointer to a block of NAMELEN (32) bytes.  You recv NAMELEN bytes without looking at the status.  So far so good.  You then clear the first sizeof buffer bytes (since buffer is a pointer, you are clearing 4 or 8 bytes).  A short time later, you recv BUFFSIZE (1024) bytes into your poor 32 byte buffer.

What I would suggest is you get the server running by testing with telnet

telnet 127.0.0.1 9000

and typing what your program expects. Keep in mind that the data is only transmitted when you hit return.

The client could be similarly exercised with netcat with:

nc -l 127.0.0.1 9000

While I am at it, why is your client multithreaded? It would simplify things if you called receiver() directly rather than creating another thread.

Also keep an eye on your mallocs and make sure they are paired with a free. I see a number of places where you malloc a fixed size block of memory and then to do not free it.  This could be accomplished a lot cleaner with a local variable.  Those go away when you return.  Alternatively, look into alloca(), that also goes away when you return.  It is not available everywhere but it is pretty useful.