问:
add two numbers in a linked list
I'm trying to add numbers from two linked lists and put it in a third one. It adds well but my code blocks compiler stops responding while running this code possibly because of an infinite loop or some exception.

Following code adds two numbers stored in reverse order in a linked list.

```<code>struct Node{
    int x;
    Node* next;
};

class LinkedList{

    public:
        Node* head;
        LinkedList(){
            head = NULL;
        }

        void addNode(int num){
            Node* n = new Node();
            n->x = num;
            n->next = NULL;
            if(head == NULL){
                head = n;
            }else{
                Node* n1 = head;
                while(n1 != NULL){
                    if(n1->next == NULL){
                        n1->next = n;
                        break;
                    }
                    n1 = n1->next;
                }
            }
        }

        int popNode(){
            int num = NULL;
            if (head != NULL){
                num = head->x;
                head = head->next;
            }else{
                cout << "Yay" << "\n";
                num = NULL;
            }

            return num;
        }

        void printList(){
            Node* n1 = head;
            while(n1 != NULL){
                if(n1->next == NULL){
                    cout << n1->x << "\n";
                }else{
                    cout << n1->x << "->";
                }

                n1 = n1->next;
            }
        }

};

LinkedList* add_nums(LinkedList* l1, LinkedList* l2) {
    LinkedList l3;

    int num1= (*l1).popNode();
    int num2= (*l2).popNode();
    int carry = 0;

    while(num1 != NULL || num2 != NULL){
        int num3 = num1+num2+carry;

        if (num3 > 9){
            int temp = num3 % 10;
            carry = (num3 - temp)/10;
            num3 = temp;
        }

        l3.addNode(num3);
        l3.printList();
        num1 = (*l1).popNode();
        num2 = (*l2).popNode();
    }

    return &l3;

}

int main(int argc, char const *argv[]) {
  LinkedList list1;
  LinkedList list2;
  list1.addNode(2);
  list1.addNode(4);
  list1.addNode(3);
  list2.addNode(5);
  list2.addNode(6);
  list2.addNode(4);
  (*(add_nums(&list1, &list2))).printList();
  return 0;
}
</code>```

Can anyone tell me what I'm doing wrong?

Changes to code i should do after inputs from answers below:

I should change integer initializations from NULL to 0.

Should use LinkedList objects to terminate my loop.

Should change how i access the functions from a pointer

Thanks everyone.

答:
As others in comments say, your error is this one: return &l3;

l3 is a local object and is deleted just before the end of the function, like any object that is not dinamically allocated. This is because of the scope of your LinkedList object.

You should have written:

```<code>LinkedList* l3 = new LinkedList();
//...
//...
return l3;
</code>```

this function now returns a pointer to your object.

NB: the variable l3, which contains the pointer, is deleted just before the function, but it doesn't matter because the object lifetime is not bound to the function anymore.

Title: add two numbers in a linked list

Body:
I'm trying to add numbers from two linked lists and put it in a third one. It adds well but my code blocks compiler stops responding while running this code possibly because of an infinite loop or some exception.

Following code adds two numbers stored in reverse order in a linked list.

struct Node{
    int x;
    Node* next;
};

class LinkedList{

    public:
        Node* head;
        LinkedList(){
            head = NULL;
        }

        void addNode(int num){
            Node* n = new Node();
            n->x = num;
            n->next = NULL;
            if(head == NULL){
                head = n;
            }else{
                Node* n1 = head;
                while(n1 != NULL){
                    if(n1->next == NULL){
                        n1->next = n;
                        break;
                    }
                    n1 = n1->next;
                }
            }
        }

        int popNode(){
            int num = NULL;
            if (head != NULL){
                num = head->x;
                head = head->next;
            }else{
                cout << "Yay" << "\n";
                num = NULL;
            }

            return num;
        }

        void printList(){
            Node* n1 = head;
            while(n1 != NULL){
                if(n1->next == NULL){
                    cout << n1->x << "\n";
                }else{
                    cout << n1->x << "->";
                }

                n1 = n1->next;
            }
        }

};

LinkedList* add_nums(LinkedList* l1, LinkedList* l2) {
    LinkedList l3;

    int num1= (*l1).popNode();
    int num2= (*l2).popNode();
    int carry = 0;

    while(num1 != NULL || num2 != NULL){
        int num3 = num1+num2+carry;

        if (num3 > 9){
            int temp = num3 % 10;
            carry = (num3 - temp)/10;
            num3 = temp;
        }

        l3.addNode(num3);
        l3.printList();
        num1 = (*l1).popNode();
        num2 = (*l2).popNode();
    }

    return &l3;

}

int main(int argc, char const *argv[]) {
  LinkedList list1;
  LinkedList list2;
  list1.addNode(2);
  list1.addNode(4);
  list1.addNode(3);
  list2.addNode(5);
  list2.addNode(6);
  list2.addNode(4);
  (*(add_nums(&list1, &list2))).printList();
  return 0;
}

Can anyone tell me what I'm doing wrong?

Changes to code i should do after inputs from answers below:

I should change integer initializations from NULL to 0.

Should use LinkedList objects to terminate my loop.

Should change how i access the functions from a pointer

Thanks everyone.

Body:
As others in comments say, your error is this one: return &l3;

l3 is a local object and is deleted just before the end of the function, like any object that is not dinamically allocated. This is because of the scope of your LinkedList object.

You should have written:

LinkedList* l3 = new LinkedList();
//...
//...
return l3;

this function now returns a pointer to your object.

NB: the variable l3, which contains the pointer, is deleted just before the function, but it doesn't matter because the object lifetime is not bound to the function anymore.


来源: stackexchange

问:
Docker: How to curl local server xyz.example.com running on host machine from within a docker container
On my host machine, I have a server xyz.example.com running on nginx. It is not dockerized and not accessible to the outside world, it is simply used for local dev environment.

I would like to be able to access it from within a docker container.

For example, I'd like to be able to do the following from within my docker container:

```<code>curl xyz.example.com
</code>```

and to see the same output I see when I run the command on my host machine.

Also, I am using docker-compose.

答: It's probably not routing directly to the host's network. This question may help.</p>

ContentLicense: CC BY-SA 3.0

Body:
On my host machine, I have a server xyz.example.com running on nginx. It is not dockerized and not accessible to the outside world, it is simply used for local dev environment.

I would like to be able to access it from within a docker container.

For example, I'd like to be able to do the following from within my docker container:

curl xyz.example.com

and to see the same output I see when I run the command on my host machine.

Also, I am using docker-compose.


问:
Upload of APK to Google Play fails because of different package names
I have a problem uploading my APK to the Google Play store because of different package names.

What I've done is the following:

I uploaded the APK without any problems.

The app is not published yet; the state is announced with "design".

Now I renamed the Java packages.

I changed the "package" attribute in AndroidManifest.xml to the new name.

I changed the android:versionCode from 1 to 2.

Then I built the APK and tried to upload to Google Dev Console but it fails with the message that the package names are different.

Is there a way to solve this conflict? I know I could "reset" my Java project to the old name but I want to keep the new package name and publish this one to Google Play for all future versions.

答:
don't forget to check the "Update references" checkbox when you rename your project.

Check this answer :

https://stackoverflow.com/a/3698165/8239508


问:
HIVE - Manual parse data enclosed by double quotes and separated by comma
I've seen some similar questions but since the problem is not exactly the same or then solutions do not apply in my case, I post my issue here.

I am parsing a table that contains a csv rows in a csv_line column.
The issue is that some columns have commas, which is also the field separator. Those columns are embedded in quotes.

The parsing I was doing is:

```<code>with
sample as (
select 'field1,field3,"http://another.domain/abc/...eIds=111,222,333,444,...,",CustomerX,end' as csv_line)

select

 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){1}') as f1
 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){n}') as fn

from raw_sample
</code>```

I have tried to replace characters/commas.

I know that OpenCSVSerde allows to define the separator character and escape double-quotes, in the Create table, but I am looking perhaps to a property that can be set, or perhaps a regular expression, that can do the split in the correct way.

Thanks in advance

Body:
I've seen some similar questions but since the problem is not exactly the same or then solutions do not apply in my case, I post my issue here.

I am parsing a table that contains a csv rows in a csv_line column.
The issue is that some columns have commas, which is also the field separator. Those columns are embedded in quotes.

The parsing I was doing is:

with
sample as (
select 'field1,field3,"http://another.domain/abc/...eIds=111,222,333,444,...,",CustomerX,end' as csv_line)

select

 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){1}') as f1
 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){n}') as fn

from raw_sample

I have tried to replace characters/commas.

I know that OpenCSVSerde allows to define the separator character and escape double-quotes, in the Create table, but I am looking perhaps to a property that can be set, or perhaps a regular expression, that can do the split in the correct way.

Thanks in advance

Body:
with raw_sample as (
select 'field1,field2,fiend3,123,456,"http://some.domain/abc/Player.aspx?playerID=111&BrowseIds=2221,423062611,423870887,424044345,...,",THIS_IS_MY,en,20 294 998 1001,end' as raw_line
)

select  regexp_extract(raw_line,'(,?(".*?"|[^,]*)){01}',2) as c01
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){02}',2) as c02
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){03}',2) as c03
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){04}',2) as c04
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){05}',2) as c05
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){06}',2) as c06
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){07}',2) as c07
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){08}',2) as c08
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){09}',2) as c09
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){10}',2) as c10

from    raw_sample
;

+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+
|  c01   |  c02   |  c03   | c04 | c05 |                                                 c06                                                 |    c07     | c08 |       c09       | c10 |
+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+
| field1 | field2 | fiend3 | 123 | 456 | "http://some.domain/abc/Player.aspx?playerID=111&BrowseIds=2221,423062611,423870887,424044345,...," | THIS_IS_MY | en  | 20 294 998 1001 | end |
+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+


问:
Highlight metronic icons only on hover
I created a fullscreen icon using metronic theme :

       Fullscreen me

    Content

```

This created a div which looks like this in chrome:
Div Preview

Whenever it is clicked for fullscreen, the button changes into this:
weird looking icon
and it remains like that until we click somewhere else.

I think this problem is caused because it remains highlighted even after click; and hence this could be solved if the highlighting of icons occurs only on mouse hover. Any ideas on how to solve this small glitch?

答:
Looks like your anchor tag is showing an underline on focus.  Try adding this to your CSS stylesheet:</p>

```<code>.fullscreen:focus { text-decoration: none; }
</code>```

Title: Highlight metronic icons only on hover

Body:
I created a fullscreen icon using metronic theme :

       Fullscreen me

    Content

This created a div which looks like this in chrome:
Div Preview

Whenever it is clicked for fullscreen, the button changes into this:
weird looking icon
and it remains like that until we click somewhere else.

I think this problem is caused because it remains highlighted even after click; and hence this could be solved if the highlighting of icons occurs only on mouse hover. Any ideas on how to solve this small glitch?

Body:
Looks like your anchor tag is showing an underline on focus.  Try adding this to your CSS stylesheet:

.fullscreen:focus { text-decoration: none; }


问:
Bootstrap 4 change tooltip arrow color
I want to change the tooltip arrow color to red. I've googled about for an hour and the snippets that I found did not work.

My last attempt was:

```<code>.tooltip-arrow {
  border-right-color: red;
  border-left-color: red;
  border-bottom-color: red;
  border-top-color: red;
}
</code>```

The tooltip is positioned right, poiting left.

答:
The selector you are looking for is .tooltip.bs-tether-element-attached-left .tooltip-inner::before:

```<code>.tooltip.bs-tether-element-attached-left .tooltip-inner::before {
    border-right-color: red;
}
</code>```

If you want every tooltip arrow red - jsfiddle:

```<code>.tooltip.bs-tether-element-attached-bottom .tooltip-inner::before {
    border-top-color: red;
}

.tooltip.bs-tether-element-attached-top .tooltip-inner::before {
    border-bottom-color: red;
}

.tooltip.bs-tether-element-attached-left .tooltip-inner::before {
    border-right-color: red;
}

.tooltip.bs-tether-element-attached-right .tooltip-inner::before {
    border-left-color: red;
}
</code>```

Title: Bootstrap 4 change tooltip arrow color

Body:
I want to change the tooltip arrow color to red. I've googled about for an hour and the snippets that I found did not work.

My last attempt was:

.tooltip-arrow {
  border-right-color: red;
  border-left-color: red;
  border-bottom-color: red;
  border-top-color: red;
}

The tooltip is positioned right, poiting left.

Body:
The selector you are looking for is .tooltip.bs-tether-element-attached-left .tooltip-inner::before:

.tooltip.bs-tether-element-attached-left .tooltip-inner::before {
    border-right-color: red;
}

If you want every tooltip arrow red - jsfiddle:

.tooltip.bs-tether-element-attached-bottom .tooltip-inner::before {
    border-top-color: red;
}

.tooltip.bs-tether-element-attached-top .tooltip-inner::before {
    border-bottom-color: red;
}

.tooltip.bs-tether-element-attached-left .tooltip-inner::before {
    border-right-color: red;
}

.tooltip.bs-tether-element-attached-right .tooltip-inner::before {
    border-left-color: red;
}


问:
mysqli_fetch_assoc() returning data twice
I recently decided to test my really old project that I had with the newer version of PHP, so I had to switch from mysql_fetch_assoc() to mysqli_fetch_assoc().

However, on running it on my localhost the data is being returned two times.

Here is the code snippet. Any help will be appreciated.

Thanks in Advance :)

```<code><?php
$query = 'SELECT people_id, people_fullname FROM people WHERE people_isactor = 1 ORDER BY people_fullname;';
$result = mysqli_query($con,$query)  or die(mysqli_error($con));

//populate the select options with the result
while($row = mysqli_fetch_assoc($result)){
    foreach($row as $value){
        if($row['people_id'] == $movie_leadactor){
            echo '<option value="'.$row['people_id'].'"selected="selected">';
        }else{
            echo '<option value="'.$row['people_id'].'">';
        }
        echo $row['people_fullname'].'<option>';
    }
}
?>
</code>```

答:
1.Remove foreach()

2.Last<option> need to be </option>.

Do like below:-

```<code><?php
$query = 'SELECT people_id, people_fullname FROM people WHERE people_isactor = 1 ORDER BY people_fullname;';
$result = mysqli_query($con,$query)  or die(mysqli_error($con));

//populate the select options with the result
while($row = mysqli_fetch_assoc($result)){

    if($row['people_id'] == $movie_leadactor){
        echo '<option value="'.$row['people_id'].'"selected="selected">'.$row['people_fullname'].'</option>';
    }else{
        echo '<option value="'.$row['people_id'].'">'.$row['people_fullname'].'</option>';
    }
}
?>
</code>```

Body:
I recently decided to test my really old project that I had with the newer version of PHP, so I had to switch from mysql_fetch_assoc() to mysqli_fetch_assoc().

However, on running it on my localhost the data is being returned two times.

Here is the code snippet. Any help will be appreciated.

Thanks in Advance :)

<?php
$query = 'SELECT people_id, people_fullname FROM people WHERE people_isactor = 1 ORDER BY people_fullname;';
$result = mysqli_query($con,$query)  or die(mysqli_error($con));

//populate the select options with the result
while($row = mysqli_fetch_assoc($result)){
    foreach($row as $value){
        if($row['people_id'] == $movie_leadactor){
            echo '<option value="'.$row['people_id'].'"selected="selected">';
        }else{
            echo '<option value="'.$row['people_id'].'">';
        }
        echo $row['people_fullname'].'<option>';
    }
}
?>

Body:
1.Remove foreach()

2.Last<option> need to be </option>.

Do like below:-

<?php
$query = 'SELECT people_id, people_fullname FROM people WHERE people_isactor = 1 ORDER BY people_fullname;';
$result = mysqli_query($con,$query)  or die(mysqli_error($con));

//populate the select options with the result
while($row = mysqli_fetch_assoc($result)){

    if($row['people_id'] == $movie_leadactor){
        echo '<option value="'.$row['people_id'].'"selected="selected">'.$row['people_fullname'].'</option>';
    }else{
        echo '<option value="'.$row['people_id'].'">'.$row['people_fullname'].'</option>';
    }
}
?>


问:
How to create a list of string in nth position of every line in Python
What would be a pythonic way to create a list of (to illustrate with an example) the fifth string of every line of a text file, assuming it ressembles something like this:

12, 27.i, 3, 6.7, Hello, 438

In this case, the script would add "Hello" (without quotes) to the list.

In other words (to generalize), with an input "input.txt", how could I get a list in python that takes the nth string (n being a defined number) of every line?

Many thanks in advance!

答:
Since you mentioned that you are using a .txt file, you can try this:</p>

```<code>f = open('filename.txt').readlines()
f = [i.strip('\n').split(",") for i in f]
new_f = [i[4] for i in f]
</code>```

Body:
Since you mentioned that you are using a .txt file, you can try this:

f = open('filename.txt').readlines()
f = [i.strip('\n').split(",") for i in f]
new_f = [i[4] for i in f]


问:
jQuery Horizontal Scale/Dial/Rule
Trying to find a jQuery plugin that will do a scale like this but I haven't been able to find anything. Basically, the arrows would stay put and you can slide the rule left/right to change the value.

Any thoughts?

答:
I think the only way to achieve this would be to use a linear gauge (as i've stated in my comment) and use some custom javascript to force it to behave as you'd like, here's a super basic fiddle to show you what i mean:

https://jsfiddle.net/vb4ak4zx/4/

HTML:

```<code><button class="testbtn">
CHANGE VALUE
</button>
<div style="height:150px">
    <div id="lineargauge"></div>
</div>
</code>```

javascript/jquery

```<code>$(function () {
            $("#lineargauge").igLinearGauge({
                height: "80px",
                width: "100%",
                value: 150,
                minimumValue: 100,
                maximumValue: 200,
                ranges: [
                    {
                        startValue: 100, endValue: 150, name: "range1"
                    },
                    {
                        startValue: 150, endValue: 200, name: "range2"
                    }
                ]
            });
        });

        $(document).on("click", ".testbtn", function(){
        $("#lineargauge").igLinearGauge({
                height: "80px",
                width: "100%",
                value: 50,
                minimumValue: 0,
                maximumValue: 100,
                ranges: [
                    {
                        startValue: 0, endValue: 50, name: "range1"
                    },
                    {
                        startValue: 50, endValue: 100, name: "range2"
                    }
                ]
            });
        });
</code>```

Title: jQuery Horizontal Scale/Dial/Rule

Body:
I think the only way to achieve this would be to use a linear gauge (as i've stated in my comment) and use some custom javascript to force it to behave as you'd like, here's a super basic fiddle to show you what i mean:

https://jsfiddle.net/vb4ak4zx/4/

HTML:

<button class="testbtn">
CHANGE VALUE
</button>
<div style="height:150px">
    <div id="lineargauge"></div>
</div>

javascript/jquery

$(function () {
            $("#lineargauge").igLinearGauge({
                height: "80px",
                width: "100%",
                value: 150,
                minimumValue: 100,
                maximumValue: 200,
                ranges: [
                    {
                        startValue: 100, endValue: 150, name: "range1"
                    },
                    {
                        startValue: 150, endValue: 200, name: "range2"
                    }
                ]
            });
        });

        $(document).on("click", ".testbtn", function(){
        $("#lineargauge").igLinearGauge({
                height: "80px",
                width: "100%",
                value: 50,
                minimumValue: 0,
                maximumValue: 100,
                ranges: [
                    {
                        startValue: 0, endValue: 50, name: "range1"
                    },
                    {
                        startValue: 50, endValue: 100, name: "range2"
                    }
                ]
            });
        });


问:
Random Boolean array with 10 elements where 3 out of 10 are True
I have been searching all over the forum and google but I think I am using the wrong key words or I do not understand the solution. What I am looking for is to create a list or array with 10 random Boolean elements where I can decide that 1 or 2 or 3 or 4 etc. elements are True. The order must be random, in the end I want a result like this e.g. (a 0.3 chance):

```<code>False
True
False
False
True
False
False
False
True
False
</code>```

Thnx.

答:
Why not create them in a know order (true, true, true, false, ....) and then use a good algorithm to shuffle them?

An option is the good old Fisher-Yates shuffle

Body:
I have been searching all over the forum and google but I think I am using the wrong key words or I do not understand the solution. What I am looking for is to create a list or array with 10 random Boolean elements where I can decide that 1 or 2 or 3 or 4 etc. elements are True. The order must be random, in the end I want a result like this e.g. (a 0.3 chance):

False
True
False
False
True
False
False
False
True
False

Thnx.


问:
Evenly spread files in directories using UUID splits
I am investigating the best way to build an evenly distributed two level directory structure for storing files received by a distributed application (files come in with no file name).  To achieve this, my initial plan was to take the first two chars of a hash string for directory 1 and the next two for directory 2 e.g.:

A hash of 67cabf2cf7418461ad53d9fd7e067049 can be used to store a file by the same name in a directory structure as follows: /67/ca/ 67cabf2cf7418461ad53d9fd7e067049

I then realised that as I have to create a unique file name (UUID) for each incoming 'blob' perhaps I could just use the first four characters of the UUID itself saving myself the need to hash the UUID.  e.g.:

A UUID of ea5dc4cf-1b91-4a8f-8d56-69b7223d8954 can be used to store a file by the same name in a directory structure as follows:
/ea/5d/ ea5dc4cf-1b91-4a8f-8d56-69b7223d8954

I have a good understanding of the uniqueness of UUIDs but I can't find any decisive explanation as to whether the randomness of the first four characters will be as evenly spread as the first four characters of a hash especially given that the first octet is rooted in a timestamp (source https://www.rfc-editor.org/rfc/rfc4122).

I did find this previous question but it seems far from decisively answered!

Is anyone able to help me understand this better or explain why the spread may or may not be as even as a hash?

Body:
So, I ran a test with a set of 10,000,000 UUIDs (version 4) and I conclude that the spread is very even.  The results are as follows, I hope it helps someone.

+---------------+------------+--+----------------+------------+
| First 2 chars | frequency  |  | Second 2 chars | frequency  |
+---------------+------------+--+----------------+------------+
| ea            | 39781      |  | 3c             | 39624      |
+---------------+------------+--+----------------+------------+
| 57            | 39589      |  | 6e             | 39575      |
+---------------+------------+--+----------------+------------+
| 63            | 39566      |  | f6             | 39524      |
+---------------+------------+--+----------------+------------+
| etc.          | etc.       |  | etc.           | etc.       |
+---------------+------------+--+----------------+------------+
| middle rows of results removed to keep this concise.        |
+---------------+------------+--+----------------+------------+
+---------------+------------+--+----------------+------------+
| b3            | 38455      |  | cf             | 38572      |
+---------------+------------+--+----------------+------------+
| f8            | 38454      |  | 4a             | 38549      |
+---------------+------------+--+----------------+------------+
| d7            | 38448      |  | b1             | 38540      |
+---------------+------------+--+----------------+------------+
| Total         | 10,000,000 |  |                | 10,000,000 |
+---------------+------------+--+----------------+------------+


问:
how to prevent calling virtual function in constructor or desturctor?
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

```<code># include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}
</code>```

output:

```<code>void CAT::f()  //not we expected!!!
</code>```

Thanks

答:
You need to throw those "C++ materials" to the garbage bin.

You certainly can call virtual functions from the constructor or destructor. And they will do their job. You simply need to be aware of the language specification that clearly states that virtual dispatch mechanism works in accordance with the current dynamic type of the object, not with its final intended dynamic type. These types are not the same for an object under construction/destruction, which often confuses newbies when they attempt to invoke virtual functions from constructors/destructors. Nevertheless, calling virtual functions from constructor and destructor is useful feature of the language, as long as you know what they do and how they work in such cases. Why would you want to "prevent" it?

It is like saying that division operator is dangerous since one can divide something by zero, and asking how to "prevent" its use in the program.

ContentLicense: CC BY-SA 2.5

Body:
Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(

sorry ,I think it's better to change to

Some C++ materials mention we'd better not to  call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

# include < iostream >
using namespace std;

class CAT
{
public:
    CAT(){ f();}
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}
};

class SMALLCAT :public CAT
{
public:
    SMALLCAT():CAT()
    {
    }
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}
};

int main()
{
    SMALLCAT sc;

}

output:

void CAT::f()  //not we expected!!!

Thanks


答:
I found the solution by using the statement GROUP BY,

```<code>SELECT * FROM products WHERE sold = 0 GROUP BY group
</code>```

in the results now, i get only one record for each group and the minimal id without adding any other statement, and in my real table i am using product_group instead of group because it's a reserved word.

Title: How to select only one record of each category?

Body:
Products :
--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   3    |     B     |   Dell   |    1     |
--------------------------------------------
|   4    |     B     |   Dell   |    1     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------
|   6    |     C     |   Dell   |    1     |
--------------------------------------------

Hi everyone, i have a table (products) stored in MySql with many records, for now i'm using this query SELECT * FROM products WHERE sold = 0, in results i get :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

i want to get only one record from each group, so the results will be like :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

Body:
I found the solution by using the statement GROUP BY,

SELECT * FROM products WHERE sold = 0 GROUP BY group

in the results now, i get only one record for each group and the minimal id without adding any other statement, and in my real table i am using product_group instead of group because it's a reserved word.


问:
Laravel db migration - renameColumn error - Unknown database type enum requested
I am using Laravel 4.2. I have the following library loaded in my composer.json

```<code>"doctrine/dbal": "2.4.*",
</code>```

I created the following migration:

```<code>class RenameDeliveryNotesColumnOnOrderHeaderTable extends Migration {

    public function up()
    {
        Schema::table('order_header', function(Blueprint $table)
        {
            $table->renameColumn('delivery_notes', 'packing_notes');
        });
    }

}
</code>```

Where delivery_notes column type is text.

When I run the migration, I get the following error:

[Doctrine\DBAL\DBALException]   Unknown database type enum requested,
  Doctrine\DBAL\Platforms\MySqlPlatform may not support it.

Any idea why I am getting this error? How should I go about fixing this? I need to rename a column in my table. Are there any alternative way to rename the column?

答:
Here is the answer for Laravel 5.2.45+ (might work in 5.1 as well, have not tested or checked yet, please let me know so I can update this question.)

Add this line in your up method:

```<code>Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
</code>```

Something like this:

```<code>public function up()
{
    Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
    Schema::table('users', function (Blueprint $table) {
         $table->text('bio')->change();
    });
}
</code>```

Body:
I am using Laravel 4.2. I have the following library loaded in my composer.json

"doctrine/dbal": "2.4.*",

I created the following migration:

class RenameDeliveryNotesColumnOnOrderHeaderTable extends Migration {

    public function up()
    {
        Schema::table('order_header', function(Blueprint $table)
        {
            $table->renameColumn('delivery_notes', 'packing_notes');
        });
    }

}

Where delivery_notes column type is text.

When I run the migration, I get the following error:

[Doctrine\DBAL\DBALException]   Unknown database type enum requested,
  Doctrine\DBAL\Platforms\MySqlPlatform may not support it.

Any idea why I am getting this error? How should I go about fixing this? I need to rename a column in my table. Are there any alternative way to rename the column?

Body:
Here is the answer for Laravel 5.2.45+ (might work in 5.1 as well, have not tested or checked yet, please let me know so I can update this question.)

Add this line in your up method:

Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

Something like this:

public function up()
{
    Schema::getConnection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
    Schema::table('users', function (Blueprint $table) {
         $table->text('bio')->change();
    });
}

ContentLicense: CC BY-SA 4.0


问:
C# Adding multiple elements to a list using xdocument
```<code><?xml version="1.0" encoding="utf-8" ?>
<root>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>configurationtestbucket</UploadBucket>
    <FileType>
      <type>*.txt</type>
      <type>*.OpticomCfg</type>
    </FileType>
  </fileUploadSpecification>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>loguploadbucket</UploadBucket>
    <FileType>
      <type>*.Xml</type>
      <type>*.Json</type>
    </FileType>
  </fileUploadSpecification>
</root>
</code>```

This is the XML file I need to parse, I want to get each instance of fileUploadSpecification so that I can put each set of details into a list, I think some type of for loop would be appropriate, where I loop through and add the first set of upload details and then loop through and add the second. This is what I currently have, but it never gets to the second fileUploadSpecification element, it just returns the same one again.
The idea would be to create a new SettingsData for every set of fileUploadSpecification elements, whether it be two like shown above, or 10.

```<code>public interface ISettingsEngine
{

    IEnumerable<SettingsData> GetSettings();
}

public class SettingsEngine : ISettingsEngine
{

    public IEnumerable<SettingsData> GetSettings()
    {
        List<SettingsData> dataList = new List<SettingsData>();
        try
        {

            var xDoc = XDocument.Load("File1.xml");

            var instancesToParse = xDoc.Root.Elements().Count();

            var fileCount = xDoc.Root.Elements("FileType").Count();

            for (int x = 0; x < instancesToParse; x++)
            {
                var newSettingsData = new SettingsData();

                newSettingsData.UploadBucket = xDoc.Root.Element("fileUploadSpecification").Element("UploadBucket").Value;
                newSettingsData.Region = xDoc.Root.Element("fileUploadSpecification").Element("Region").Value;
                newSettingsData.DirectoryPath = xDoc.Root.Element("fileUploadSpecification").Element("DirectoryPath").Value;
                var query = xDoc.Root.Descendants("FileType").Elements("type");

                foreach (XElement e in query)
                {
                    newSettingsData.FileType.Add(e.Value);
                }
dataList.Add(newSettingsData);

            }

            return dataList;
        }
        catch(Exception)
        {
            return dataList;
        }
    }
}

public class SettingsData
{

    public List<string> FileType { get; set; }
    public string DirectoryPath { get; set; }
    public string Region { get; set; }
    public string UploadBucket { get; set; }

    public SettingsData()
    {
        FileType = new List<string>();
    }
}
</code>```

答:
Each time through the loop, you're looking up the first fileUploadSpecification element all over again. You used the Elements() method already, in a few places. That's the one you want. Always favor foreach over for in C#, when you're looping over a collection. It's quicker (to code, not at runtime) and less error prone.

```<code>foreach (var uploadSpec in xDoc.Root.Elements("fileUploadSpecification"))
{
    var newSettingsData = new SettingsData();

    newSettingsData.UploadBucket = uploadSpec.Element("UploadBucket").Value;
    newSettingsData.Region = uploadSpec.Element("Region").Value;
    newSettingsData.DirectoryPath = uploadSpec.Element("DirectoryPath").Value;

    var types = uploadSpec.Descendants("FileType").Elements("type").Select(e => e.Value);

    foreach (var type in types)
    {
        newSettingsData.FileType.Add(type);
    }

    //  Or if newSettingsData.FileType is List<String>...
    //newSettingsData.FileType.AddRange(types);

    dataList.Add(newSettingsData);
}
</code>```

James Curran's answer is functionally the same, but it's better form.

Body:
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>configurationtestbucket</UploadBucket>
    <FileType>
      <type>*.txt</type>
      <type>*.OpticomCfg</type>
    </FileType>
  </fileUploadSpecification>
  <fileUploadSpecification>
    <DirectoryPath>C:\watchFolder</DirectoryPath>
    <Region>us-west-2</Region>
    <UploadBucket>loguploadbucket</UploadBucket>
    <FileType>
      <type>*.Xml</type>
      <type>*.Json</type>
    </FileType>
  </fileUploadSpecification>
</root>

This is the XML file I need to parse, I want to get each instance of fileUploadSpecification so that I can put each set of details into a list, I think some type of for loop would be appropriate, where I loop through and add the first set of upload details and then loop through and add the second. This is what I currently have, but it never gets to the second fileUploadSpecification element, it just returns the same one again.
The idea would be to create a new SettingsData for every set of fileUploadSpecification elements, whether it be two like shown above, or 10.

public interface ISettingsEngine
{

    IEnumerable<SettingsData> GetSettings();
}

public class SettingsEngine : ISettingsEngine
{

    public IEnumerable<SettingsData> GetSettings()
    {
        List<SettingsData> dataList = new List<SettingsData>();
        try
        {

            var xDoc = XDocument.Load("File1.xml");

            var instancesToParse = xDoc.Root.Elements().Count();

            var fileCount = xDoc.Root.Elements("FileType").Count();

            for (int x = 0; x < instancesToParse; x++)
            {
                var newSettingsData = new SettingsData();

                newSettingsData.UploadBucket = xDoc.Root.Element("fileUploadSpecification").Element("UploadBucket").Value;
                newSettingsData.Region = xDoc.Root.Element("fileUploadSpecification").Element("Region").Value;
                newSettingsData.DirectoryPath = xDoc.Root.Element("fileUploadSpecification").Element("DirectoryPath").Value;
                var query = xDoc.Root.Descendants("FileType").Elements("type");

                foreach (XElement e in query)
                {
                    newSettingsData.FileType.Add(e.Value);
                }
dataList.Add(newSettingsData);

            }

            return dataList;
        }
        catch(Exception)
        {
            return dataList;
        }
    }
}

public class SettingsData
{

    public List<string> FileType { get; set; }
    public string DirectoryPath { get; set; }
    public string Region { get; set; }
    public string UploadBucket { get; set; }

    public SettingsData()
    {
        FileType = new List<string>();
    }
}

Body:
Each time through the loop, you're looking up the first fileUploadSpecification element all over again. You used the Elements() method already, in a few places. That's the one you want. Always favor foreach over for in C#, when you're looping over a collection. It's quicker (to code, not at runtime) and less error prone.

foreach (var uploadSpec in xDoc.Root.Elements("fileUploadSpecification"))
{
    var newSettingsData = new SettingsData();

    newSettingsData.UploadBucket = uploadSpec.Element("UploadBucket").Value;
    newSettingsData.Region = uploadSpec.Element("Region").Value;
    newSettingsData.DirectoryPath = uploadSpec.Element("DirectoryPath").Value;

    var types = uploadSpec.Descendants("FileType").Elements("type").Select(e => e.Value);

    foreach (var type in types)
    {
        newSettingsData.FileType.Add(type);
    }

    //  Or if newSettingsData.FileType is List<String>...
    //newSettingsData.FileType.AddRange(types);

    dataList.Add(newSettingsData);
}

James Curran's answer is functionally the same, but it's better form.


问:
Convert time in seconds from the Epoch to day of the year?
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

```<code>time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);
</code>```

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

```<code>char buffer[80];
</code>```

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

答:
Your actual problem here is that localtime( &rawtime ) fails to convert rawtime.  When the function fails it returns a null pointer.  Dereferencing that pointer and trying to copy its value is causing the segfault.

The most likely issue is that your value is much to large.  If you do

```<code>std::time_t t = std::time(nullptr);
std::cout << t << std::endl;
</code>```

You get

```<code>1499367157
</code>```

Which makes 1498493536984926976 a date in the way far future.

Body:
I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

char buffer[80];

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

Body:
Your actual problem here is that localtime( &rawtime ) fails to convert rawtime.  When the function fails it returns a null pointer.  Dereferencing that pointer and trying to copy its value is causing the segfault.

The most likely issue is that your value is much to large.  If you do

std::time_t t = std::time(nullptr);
std::cout << t << std::endl;

You get

1499367157

Which makes 1498493536984926976 a date in the way far future.


问:
JavaScript unit testing with external module
I am working on an existing node project where the code structure for most of the js files looks something like following.

```<code>    var mod1 = require("mod1");
    var mod2 = require("mod2");
    var modn = require("moden");

    function func1(data, callback) {
        // Do some validation with data etc..
        // Use one or more imported modules here

    }

    function func2(data, callback) {
        // Do some validation with data etc..
        // Use one or more imported modules here

    }

    exports.func1 = func1
    exports.func2 = func2
</code>```

How can unit test func1, while not being dependent on the imported modules? How can I mock/stub them?
I come from the Java world so I am familiar with the mocking concepts, but here I am not sure how can I mock the globally declared module imports using require.

Currently we are using nodeunit for the unit testing purpose, but it tests very small part of the code.

I am reading about simon.js and testdouble but not sure how to use them to mock the global variables.

Any help/direction is appreciated.

答:
For overriding dependencies during testing I recommend to use in your situation the https://github.com/thlorenz/proxyquire module

For quick exmple I paste example from project github

foo.js:

```<code>var path = require('path');

module.exports.extnameAllCaps = function (file) {
 return path.extname(file).toUpperCase();
};

module.exports.basenameAllCaps = function (file) {
 return path.basename(file).toUpperCase();
}
</code>```

foo.test.js:

```<code>var proxyquire =  require('proxyquire')
, assert     =  require('assert')
, pathStub   =  { };

// when no overrides are specified, path.extname behaves normally
var foo = proxyquire('./foo', { 'path': pathStub });
assert.equal(foo.extnameAllCaps('file.txt'), '.TXT');
</code>```

Body:
I am working on an existing node project where the code structure for most of the js files looks something like following.

    var mod1 = require("mod1");
    var mod2 = require("mod2");
    var modn = require("moden");

    function func1(data, callback) {
        // Do some validation with data etc..
        // Use one or more imported modules here

    }

    function func2(data, callback) {
        // Do some validation with data etc..
        // Use one or more imported modules here

    }

    exports.func1 = func1
    exports.func2 = func2

How can unit test func1, while not being dependent on the imported modules? How can I mock/stub them?
I come from the Java world so I am familiar with the mocking concepts, but here I am not sure how can I mock the globally declared module imports using require.

Currently we are using nodeunit for the unit testing purpose, but it tests very small part of the code.

I am reading about simon.js and testdouble but not sure how to use them to mock the global variables.

Any help/direction is appreciated.

Body:
For overriding dependencies during testing I recommend to use in your situation the https://github.com/thlorenz/proxyquire module

For quick exmple I paste example from project github

foo.js:

var path = require('path');

module.exports.extnameAllCaps = function (file) {
 return path.extname(file).toUpperCase();
};

module.exports.basenameAllCaps = function (file) {
 return path.basename(file).toUpperCase();
}

foo.test.js:

var proxyquire =  require('proxyquire')
, assert     =  require('assert')
, pathStub   =  { };

// when no overrides are specified, path.extname behaves normally
var foo = proxyquire('./foo', { 'path': pathStub });
assert.equal(foo.extnameAllCaps('file.txt'), '.TXT');


问:
Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails
I'm getting this error:

Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.

I have a standard add function to EF 6

```<code>    public Logs AddLog(Logs p)
    {
        Logs.Add(p);
        SaveChanges();
        return p;
    }
</code>```

I've defined the field in my class as:

```<code>    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime EntryDate { get; set; }
</code>```

Should I be populating this field in my controller at all?

答: I added a constraint on the EntryDate field in SQL Server to default this field to GETDATE()</p>

Body:
I'm getting this error:

Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.

I have a standard add function to EF 6

    public Logs AddLog(Logs p)
    {
        Logs.Add(p);
        SaveChanges();
        return p;
    }

I've defined the field in my class as:

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime EntryDate { get; set; }

Should I be populating this field in my controller at all?


问:
how to use the quantile() function to split a variable into 3 classes of identical values
please a have a dataframe called wine with variables among which is the variable
Spice of integer type.

I will like to split this variable(Spice) using the quantile() function into 3 classes of identical values

NB :USING the quantile()  function please

答:
Like MrFlick said, your question is ill formed. Do you want to split what? Spice or wine? If Spice is integer the quantiles will generally not split it in groups of equal sizes. Anyway here is code to do something similar to what you've tried to ask.

```<code>set.seed(4124)
wine <- data.frame(Spice = sample(5, 20, TRUE))
qq <- quantile(wine$Spice, probs = seq(0, 1, 1/3))
split(wine, findInterval(wine$Spice, qq, all.inside = TRUE))
</code>```

Body:
Like MrFlick said, your question is ill formed. Do you want to split what? Spice or wine? If Spice is integer the quantiles will generally not split it in groups of equal sizes. Anyway here is code to do something similar to what you've tried to ask.

set.seed(4124)
wine <- data.frame(Spice = sample(5, 20, TRUE))
qq <- quantile(wine$Spice, probs = seq(0, 1, 1/3))
split(wine, findInterval(wine$Spice, qq, all.inside = TRUE))


问:
Run separate queries in MySQL using a single link
I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.

I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.

I basically owuld like to update the icon and execute the required SQL stmnt.

Any help is appreciated.

What I have so far:

JAVASCRIPT:

```<code>    //update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        //update the table
        deleteFavorites();
    }
    else {
        $('#staricon'+id).addClass('star-color');
        addFavorites();
    }
}
}

//delete the item from the table

function deleteFavorite(){

        $.ajax({
            type: "POST",
            url: "somePHPFile.php",
            cache: false,
            data:{id:'#staricon'+id},
        }).done(function( msg ) {  console.log(msg);
        });
}
</code>```

PHP:

```<code>//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);

if ($is_fav > 0) {
echo '<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" class="star-color"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
 }
 else {
 echo '<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
 }
</code>```

I have update my code to reflect the following:

JAVASCRIPT:

```<code>function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data(id),
                enabled: !$(this).hasClass('star-color') //delete
            },
        })
    }
    else {
        $('#staricon'+id).addClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data("id"),
                enabled: $(this).hasClass('star-color') //insert
            },
        })

    }
}
</code>```

PHP:

```<code>echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo '<a  class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" class="star-color"
onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons "
title="Favorite" >star</i></span></a>';
}
else {
echo '<a  class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id .
')"><i  class=" material-icons " title="Favorite" >star</i></span></a>';
}
if (isset($_POST['enabled'])){

if($_POST['enabled']) {  // INSERT query

    $sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
    $sql->execute();
} else {// Delete query
}
}
</code>```

My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.

答:
Use prepared statements because you're opening yourself to injection attacks.

Try this query

```<code>$query = "SELECT * FROM favourites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->getResult();
print_r($result);
</code>```

Body:
I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.

I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.

I basically owuld like to update the icon and execute the required SQL stmnt.

Any help is appreciated.

What I have so far:

JAVASCRIPT:

    //update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        //update the table
        deleteFavorites();
    }
    else {
        $('#staricon'+id).addClass('star-color');
        addFavorites();
    }
}
}

//delete the item from the table

function deleteFavorite(){

        $.ajax({
            type: "POST",
            url: "somePHPFile.php",
            cache: false,
            data:{id:'#staricon'+id},
        }).done(function( msg ) {  console.log(msg);
        });
}

PHP:

//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);

if ($is_fav > 0) {
echo 'star';
 }
 else {
 echo 'star';
 }

I have update my code to reflect the following:

JAVASCRIPT:

function updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data(id),
                enabled: !$(this).hasClass('star-color') //delete
            },
        })
    }
    else {
        $('#staricon'+id).addClass('star-color');
        $.ajax({
            type: "POST",
            url: "showStoryCards.php",
            data: {
                id: $(this).data("id"),
                enabled: $(this).hasClass('star-color') //insert
            },
        })

    }
}

PHP:

echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo 'star';
}
else {
echo 'star';
}
if (isset($_POST['enabled'])){

if($_POST['enabled']) {  // INSERT query

    $sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
    $sql->execute();
} else {// Delete query
}
}

My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.

Body:
Use prepared statements because you're opening yourself to injection attacks.

Try this query

$query = "SELECT * FROM favourites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->getResult();
print_r($result);


问:
Why is Postgres not using index on a simple GROUP BY?
I have created a 36M rows table with an index on type column:

```<code>CREATE TABLE items AS
  SELECT
    (random()*36000000)::integer AS id,
    (random()*10000)::integer AS type,
    md5(random()::text) AS s
  FROM
    generate_series(1,36000000);
CREATE INDEX items_type_idx ON items USING btree ("type");
</code>```

I run this simple query and expect postgresql to use my index:

```<code>explain select count(*) from "items" group by "type";
</code>```

But the query planner decides to use Seq Scan instead:

```<code>HashAggregate  (cost=734592.00..734627.90 rows=3590 width=12) (actual time=6477.913..6478.344 rows=3601 loops=1)
  Group Key: type
  ->  Seq Scan on items  (cost=0.00..554593.00 rows=35999800 width=4) (actual time=0.044..1820.522 rows=36000000 loops=1)
Planning time: 0.107 ms
Execution time: 6478.525 ms
</code>```

Time without EXPLAIN: 5s 979ms

I have tried several solutions from here and here:

Run VACUUM ANALYZE or VACUUM ANALYZE

Configure default_statistics_target, random_page_cost, work_mem

but nothing helps apart from setting enable_seqscan = OFF:

```<code>SET enable_seqscan = OFF;
explain select count(*) from "items" group by "type";

GroupAggregate  (cost=0.56..1114880.46 rows=3590 width=12) (actual time=5.637..5256.406 rows=3601 loops=1)
  Group Key: type
  ->  Index Only Scan using items_type_idx on items  (cost=0.56..934845.56 rows=35999800 width=4) (actual time=0.074..2783.896 rows=36000000 loops=1)
        Heap Fetches: 0
Planning time: 0.103 ms
Execution time: 5256.667 ms
</code>```

Time without EXPLAIN: 659ms

Query with index scan is about 10x faster on my machine.

Is there a better solution than setting enable_seqscan?

UPD1

My postgresql version is 9.6.3, work_mem = 4MB (tried 64MB), random_page_cost = 4 (tried 1.1), max_parallel_workers_per_gather = 0 (tried 4).

UPD2

I have tried to fill type column not with random numbers, but with i / 10000 to make pg_stats.correlation = 1 - still seqscan.

UPD3

@jgh is 100% right:

This typically only happens when the table's row width is much wider than some indexes

I've made large column data and now postgres use index. Thanks everyone!

答:
The Index-only scans wiki says

It is important to realise that the planner is concerned with
  minimising the total cost of the query. With databases, the cost of
  I/O typically dominates. For that reason, "count(*) without any
  predicate" queries will only use an index-only scan if the index is
  significantly smaller than its table. This typically only happens when
  the table's row width is much wider than some indexes'.

and

Index-only scans are only used when the planner surmises that that
  will reduce the total amount of I/O required, according to its
  imperfect cost-based modelling. This all heavily depends on visibility
  of tuples, if an index would be used anyway (i.e. how selective a
  predicate is, etc), and if there is actually an index available that
  could be used by an index-only scan in principle

Accordingly, your index is not considered "significantly smaller" and the entire dataset is to be read, which leads the planner in using a seq scan

Body:
I have created a 36M rows table with an index on type column:

CREATE TABLE items AS
  SELECT
    (random()*36000000)::integer AS id,
    (random()*10000)::integer AS type,
    md5(random()::text) AS s
  FROM
    generate_series(1,36000000);
CREATE INDEX items_type_idx ON items USING btree ("type");

I run this simple query and expect postgresql to use my index:

explain select count(*) from "items" group by "type";

But the query planner decides to use Seq Scan instead:

HashAggregate  (cost=734592.00..734627.90 rows=3590 width=12) (actual time=6477.913..6478.344 rows=3601 loops=1)
  Group Key: type
  ->  Seq Scan on items  (cost=0.00..554593.00 rows=35999800 width=4) (actual time=0.044..1820.522 rows=36000000 loops=1)
Planning time: 0.107 ms
Execution time: 6478.525 ms

Time without EXPLAIN: 5s 979ms

I have tried several solutions from here and here:

Run VACUUM ANALYZE or VACUUM ANALYZE

Configure default_statistics_target, random_page_cost, work_mem

but nothing helps apart from setting enable_seqscan = OFF:

SET enable_seqscan = OFF;
explain select count(*) from "items" group by "type";

GroupAggregate  (cost=0.56..1114880.46 rows=3590 width=12) (actual time=5.637..5256.406 rows=3601 loops=1)
  Group Key: type
  ->  Index Only Scan using items_type_idx on items  (cost=0.56..934845.56 rows=35999800 width=4) (actual time=0.074..2783.896 rows=36000000 loops=1)
        Heap Fetches: 0
Planning time: 0.103 ms
Execution time: 5256.667 ms

Time without EXPLAIN: 659ms

Query with index scan is about 10x faster on my machine.

Is there a better solution than setting enable_seqscan?

UPD1

My postgresql version is 9.6.3, work_mem = 4MB (tried 64MB), random_page_cost = 4 (tried 1.1), max_parallel_workers_per_gather = 0 (tried 4).

UPD2

I have tried to fill type column not with random numbers, but with i / 10000 to make pg_stats.correlation = 1 - still seqscan.

UPD3

@jgh is 100% right:

This typically only happens when the table's row width is much wider than some indexes

I've made large column data and now postgres use index. Thanks everyone!


问:
spatie error while publishing the migration file
```<code>I have just install laravel 5.4 & using xampp server
facing issue in spatie. after installing by 'composer require         spatie/laravel-permission'

adding Spatie\Permission\PermissionServiceProvider::class, to service             providers, in config/app.php

next when i use this command
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="m
</code>```

igrations",
    I receive this error as below

```<code>PHP Fatal error: Call to a member function connection() on null in C:\xampp\htdocs\project\laravel\vendor\laravel\frame
</code>```

work\src\Illuminate\Database\Eloquent\Model.php on line 1041

```<code>[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function connection() on null
</code>```

答:
after installing the package make sure you have included the service provider in config/app.php providers array then run the following command</p>

```<code>php artisan vendor:publish
</code>```

Body:
I have just install laravel 5.4 & using xampp server
facing issue in spatie. after installing by 'composer require         spatie/laravel-permission'

adding Spatie\Permission\PermissionServiceProvider::class, to service             providers, in config/app.php

next when i use this command
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="m

igrations",
    I receive this error as below

PHP Fatal error: Call to a member function connection() on null in C:\xampp\htdocs\project\laravel\vendor\laravel\frame

work\src\Illuminate\Database\Eloquent\Model.php on line 1041

[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function connection() on null

Body:
after installing the package make sure you have included the service provider in config/app.php providers array then run the following command

php artisan vendor:publish


问:
Extending a nested class to use with modernizr etc
I've been struggling to make a coherent mixin for this issue. I'm using modernizr.js to detect features, and in an effort to keep my stylesheet lean I've been trying to push classes out of the nested structure and extend the classes that modernizr has put in.
I should add that I'm using Compass as well for the extra features.

What I'm hoping to achieve is this:

```<code>.csstransitions, .csstransitions div, .csstransitions .some-class{
  -moz-transition-property: background;
  -webkit-transition-property: background;
  -o-transition-property: background;
}
</code>```

So far I have this, but it's broken:

```<code>.csstransitions{
    @include transition-property(background-image);
}
@mixin csstransitions($element:"div"){
    @extend .csstransitions(nest(".csstransitions",$element));
}
</code>```

The idea is that I can invoke the mixin from within the css structure...
Thanks

答:
I think simple nesting should be good enough here, why do you need all this complexity with mixins and inheritance?

```<code>@import "compass/css3";
div {
  background-image: url(/images/foo.png);
  .csstransitions & {
    @include transition-property(background-image);
  }
}
</code>```

This will give you the following output:

```<code>div {
  background-image: url(/images/foo.png);
}
.csstransitions div {
  -moz-transition-property: background-image;
  -webkit-transition-property: background-image;
  -o-transition-property: background-image;
  transition-property: background-image;
}
</code>```

But as far as I can see, you don't even need this scoping at all. A browser will ignore any property that it does not understand. So I suggest the following:

```<code>@import "compass/css3";
div {
  background-image: url(/images/foo.png);
  @include transition-property(background-image);
}
</code>```

Body:
I've been struggling to make a coherent mixin for this issue. I'm using modernizr.js to detect features, and in an effort to keep my stylesheet lean I've been trying to push classes out of the nested structure and extend the classes that modernizr has put in.
I should add that I'm using Compass as well for the extra features.

What I'm hoping to achieve is this:

.csstransitions, .csstransitions div, .csstransitions .some-class{
  -moz-transition-property: background;
  -webkit-transition-property: background;
  -o-transition-property: background;
}

So far I have this, but it's broken:

.csstransitions{
    @include transition-property(background-image);
}
@mixin csstransitions($element:"div"){
    @extend .csstransitions(nest(".csstransitions",$element));
}

The idea is that I can invoke the mixin from within the css structure...
Thanks

Body:
I think simple nesting should be good enough here, why do you need all this complexity with mixins and inheritance?

@import "compass/css3";
div {
  background-image: url(/images/foo.png);
  .csstransitions & {
    @include transition-property(background-image);
  }
}

This will give you the following output:

div {
  background-image: url(/images/foo.png);
}
.csstransitions div {
  -moz-transition-property: background-image;
  -webkit-transition-property: background-image;
  -o-transition-property: background-image;
  transition-property: background-image;
}

But as far as I can see, you don't even need this scoping at all. A browser will ignore any property that it does not understand. So I suggest the following:

@import "compass/css3";
div {
  background-image: url(/images/foo.png);
  @include transition-property(background-image);
}


答:
These lines are your problem:

```<code>char *buffer;

strftime (buffer,sizeof(buffer),"%j",&date);
</code>```

You've allocated a char * but it doesn't point to anything. It's just a random value, so you're passing a wild pointer into strftime(). Also, sizeof(buffer) will be the size of the pointer (4 or 8 bytes depending on your architecture), not the size of the array that buffer is supposed to point at.

Change char * buffer to char buffer[32]; or something like that.

Title: Convert time in seconds from the Epoch to day of the year?

Body:
These lines are your problem:

char *buffer;

strftime (buffer,sizeof(buffer),"%j",&date);

You've allocated a char * but it doesn't point to anything. It's just a random value, so you're passing a wild pointer into strftime(). Also, sizeof(buffer) will be the size of the pointer (4 or 8 bytes depending on your architecture), not the size of the array that buffer is supposed to point at.

Change char * buffer to char buffer[32]; or something like that.


问:
Perl - call an instance of a class
Is there way to catch the event of calling an instance of a Perl class?

```<code>my $obj = ExampleClass->new();
$obj(); # do something without producing error
</code>```

I would like to be able to handle this from within the class/module definition. Something similar to the __call__ method in Python, or the __call metamethod in Lua.

答:
I'm still not sure what the use case is, but you can overload the class to handle code dereferencing.

```<code>package ExampleClass;
use overload '&{}' => \&__call__;   # Or an anon sub.
sub new {
   bless {@_}, shift;
}
sub __call__ {
    sub { warn "calling an instance event" };
}

package main;
my $obj = ExampleClass->new;
$obj->();
&$obj();      # same as $obj->()
</code>```

Typical output:

```<code>$ perl 44956235.pl
calling an instance event at 44956235.pl line 7.
calling an instance event at 44956235.pl line 7.
</code>```

Title: Perl - call an instance of a class

Body:
Is there way to catch the event of calling an instance of a Perl class?

my $obj = ExampleClass->new();
$obj(); # do something without producing error

I would like to be able to handle this from within the class/module definition. Something similar to the __call__ method in Python, or the __call metamethod in Lua.

Body:
I'm still not sure what the use case is, but you can overload the class to handle code dereferencing.

package ExampleClass;
use overload '&{}' => \&__call__;   # Or an anon sub.
sub new {
   bless {@_}, shift;
}
sub __call__ {
    sub { warn "calling an instance event" };
}

package main;
my $obj = ExampleClass->new;
$obj->();
&$obj();      # same as $obj->()

Typical output:

$ perl 44956235.pl
calling an instance event at 44956235.pl line 7.
calling an instance event at 44956235.pl line 7.


问:
Symfony 2.3 getRequest()->headers not showing Authorization Bearer Token
I am passing an Authorization: Bearer { Token } as a HTTP request to my Symfony Rest Controller.

My Request:

```<code>GET /app_dev.php/api/members HTTP/1.1
Host: localhost
Authorization: Bearer 123456789
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
</code>```

Inside My controller:

```<code>$this->getRequest()->headers;
</code>```

For some reason when I use Symfony's Request method the Authorization header isn't available to my controller. When I use PHP's getallheaders() the Authorization header shows up as expected. Any Ideas on why Symfony isn't seeing it?

Thanks

答: You can also use apache_request_headers(); to get the original headers which will have the Authorization header.  </p>

Body:
I am passing an Authorization: Bearer { Token } as a HTTP request to my Symfony Rest Controller.

My Request:

GET /app_dev.php/api/members HTTP/1.1
Host: localhost
Authorization: Bearer 123456789
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

Inside My controller:

$this->getRequest()->headers;

For some reason when I use Symfony's Request method the Authorization header isn't available to my controller. When I use PHP's getallheaders() the Authorization header shows up as expected. Any Ideas on why Symfony isn't seeing it?

Thanks


问:
Python schedule a job at specific time
Is there any way to have a script with python that schedule a a job on a given datetime? For instance schedule a tweet at 01-09-2017 09:30:00.

So far I have seen the schedule and apscheduler libraries but I haven't find that allows me to schedule at a given time only for once.

Thanks!

答:
Question: schedule a tweet at 01-09-2017 09:30:00.

Simple Solution, for example:

```<code>if __name__ == __main__:
    starttime = datetime.datetime(2017, 9, 1, hour=9, minute=30, second=0)
    while True:
        if datetime.today() > starttime:
            break
        time.sleep(60)

    main()
</code>```

Title: Python schedule a job at specific time

Body:
Question: schedule a tweet at 01-09-2017 09:30:00.

Simple Solution, for example:

if __name__ == __main__:
    starttime = datetime.datetime(2017, 9, 1, hour=9, minute=30, second=0)
    while True:
        if datetime.today() > starttime:
            break
        time.sleep(60)

    main()


问:
std::ostream interface to an OLE IStream
I have a Visual Studio 2008 C++ application using IStreams. I would like to use the IStream connection in a std::ostream. Something like this:

```<code>IStream* stream = /*create valid IStream instance...*/;
IStreamBuf< WIN32_FIND_DATA > sb( stream );
std::ostream os( &sb );

WIN32_FIND_DATA d = { 0 };
// send the structure along the IStream
os << d;
</code>```

To accomplish this, I've implemented the following code:

```<code>template< class _CharT, class _Traits >
inline std::basic_ostream< _CharT, _Traits >&
operator<<( std::basic_ostream< _CharT, _Traits >& os, const WIN32_FIND_DATA& i )
{
    const _CharT* c = reinterpret_cast< const _CharT* >( &i );
    const _CharT* const end = c + sizeof( WIN32_FIND_DATA ) / sizeof( _CharT );
    for( c; c < end; ++c ) os << *c;
    return os;
}

template< typename T >
class IStreamBuf : public std::streambuf
{
public:
    IStreamBuf( IStream* stream ) : stream_( stream )
    {
        setp( reinterpret_cast< char* >( &buffer_ ),
              reinterpret_cast< char* >( &buffer_ ) + sizeof( buffer_ ) );
    };

    virtual ~IStreamBuf()
    {
        sync();
    };

protected:
    traits_type::int_type FlushBuffer()
    {
        int bytes = std::min< int >( pptr() - pbase(), sizeof( buffer_ ) );

        DWORD written = 0;
        HRESULT hr = stream_->Write( &buffer_, bytes, &written );
        if( FAILED( hr ) )
        {
            return traits_type::eof();
        }

        pbump( -bytes );
        return bytes;
    };

    virtual int sync()
    {
        if( FlushBuffer() == traits_type::eof() )
            return -1;
        return 0;
    };

    traits_type::int_type overflow( traits_type::int_type ch )
    {
        if( FlushBuffer() == traits_type::eof() )
            return traits_type::eof();

        if( ch != traits_type::eof() )
        {
            *pptr() = ch;
            pbump( 1 );
        }

        return ch;
    };

private:
    /// data queued up to be sent
    T buffer_;

    /// output stream
    IStream* stream_;
}; // class IStreamBuf
</code>```

Yes, the code compiles and seems to work, but I've not had the pleasure of implementing a std::streambuf before. So, I'd just like to know if it's correct and complete.

Thanks,
PaulH

答:
Here's an implementation I wrote a while ago: https://github.com/senderista/UnbufferedOLEStreamBuf

For the most part you just need to mechanically translate between STL and Windows/COM types. This translation is tedious and error-prone, though, so you would probably be best off using the implementation I linked. It's only 150 lines, it was used in a production application, and there are few places for bugs to hide.

Since apparently links in answers are cause for deletion, here's the code in its entirety:

```<code>//Copyright (c) 2010 Tobin Baker
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

#include <ios>
#include <streambuf>
#include <windows.h>

// Read-write unbuffered streambuf implementation which uses no
// internal buffers (conventional wisdom says this can't be done
// except for write-only streams, but I adapted Matt Austern's example
// from http://www.drdobbs.com/184401305).

class UnbufferedOLEStreamBuf : public std::streambuf {
public:
    UnbufferedOLEStreamBuf(IStream *stream, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    ~UnbufferedOLEStreamBuf();

protected:
    virtual int overflow(int ch = traits_type::eof());
    virtual int underflow();
    virtual int uflow();
    virtual int pbackfail(int ch = traits_type::eof());
    virtual int sync();
    virtual std::streampos seekpos(std::streampos sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    virtual std::streampos seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    virtual std::streamsize xsgetn(char *s, std::streamsize n);
    virtual std::streamsize xsputn(const char *s, std::streamsize n);
    virtual std::streamsize showmanyc();

private:
    IStream *stream_;
    bool readOnly_;
    bool backup();
};

UnbufferedOLEStreamBuf::UnbufferedOLEStreamBuf(IStream *stream, std::ios_base::openmode which)
: std::streambuf(), stream_(stream), readOnly_(!(which & std::ios_base::out)) {}

UnbufferedOLEStreamBuf::~UnbufferedOLEStreamBuf() { if (!readOnly_) UnbufferedOLEStreamBuf::sync(); }

bool UnbufferedOLEStreamBuf::backup() {
    LARGE_INTEGER liMove;
    liMove.QuadPart = -1LL;
    return SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_CUR, NULL));
}

int UnbufferedOLEStreamBuf::overflow(int ch) {
    if (ch != traits_type::eof()) {
        if (SUCCEEDED(stream_->Write(&ch, 1, NULL))) {
            return ch;
        }
    }
    return traits_type::eof();
}

int UnbufferedOLEStreamBuf::underflow() {
    char ch = UnbufferedOLEStreamBuf::uflow();
    if (ch != traits_type::eof()) {
        ch = backup() ? ch : traits_type::eof();
    }
    return ch;
}

int UnbufferedOLEStreamBuf::uflow() {
    char ch;
    ULONG cbRead;
    // S_FALSE indicates we've reached end of stream
    return (S_OK == stream_->Read(&ch, 1, &cbRead))
        ? ch : traits_type::eof();
}

int UnbufferedOLEStreamBuf::pbackfail(int ch) {
    if (ch != traits_type::eof()) {
        ch = backup() ? ch : traits_type::eof();
    }
    return ch;
}

int UnbufferedOLEStreamBuf::sync() {
    return SUCCEEDED(stream_->Commit(STGC_DEFAULT)) ? 0 : -1;
}

std::ios::streampos UnbufferedOLEStreamBuf::seekpos(std::ios::streampos sp, std::ios_base::openmode which) {
    LARGE_INTEGER liMove;
    liMove.QuadPart = sp;
    return SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_SET, NULL)) ? sp : -1;
}

std::streampos UnbufferedOLEStreamBuf::seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which) {
    STREAM_SEEK sk;
    switch (way) {
        case std::ios_base::beg: sk = STREAM_SEEK_SET; break;
        case std::ios_base::cur: sk = STREAM_SEEK_CUR; break;
        case std::ios_base::end: sk = STREAM_SEEK_END; break;
        default: return -1;
    }
    LARGE_INTEGER liMove;
    liMove.QuadPart = static_cast<LONGLONG>(off);
    ULARGE_INTEGER uliNewPos;
    return SUCCEEDED(stream_->Seek(liMove, sk, &uliNewPos))
        ? static_cast<std::streampos>(uliNewPos.QuadPart) : -1;
}

std::streamsize UnbufferedOLEStreamBuf::xsgetn(char *s, std::streamsize n) {
    ULONG cbRead;
    return SUCCEEDED(stream_->Read(s, static_cast<ULONG>(n), &cbRead))
        ? static_cast<std::streamsize>(cbRead) : 0;
}

std::streamsize UnbufferedOLEStreamBuf::xsputn(const char *s, std::streamsize n) {
    ULONG cbWritten;
    return SUCCEEDED(stream_->Write(s, static_cast<ULONG>(n), &cbWritten))
        ? static_cast<std::streamsize>(cbWritten) : 0;
}

std::streamsize UnbufferedOLEStreamBuf::showmanyc() {
    STATSTG stat;
    if (SUCCEEDED(stream_->Stat(&stat, STATFLAG_NONAME))) {
        std::streampos lastPos = static_cast<std::streampos>(stat.cbSize.QuadPart - 1);
        LARGE_INTEGER liMove;
        liMove.QuadPart = 0LL;
        ULARGE_INTEGER uliNewPos;
        if (SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_CUR, &uliNewPos))) {
            return std::max<std::streamsize>(lastPos - static_cast<std::streampos>(uliNewPos.QuadPart), 0);
        }
    }
    return 0;
}

std::streambuf* StdStreamBufFromOLEStream(IStream *pStream, std::ios_base::openmode which)
{
    return new (std::nothrow) UnbufferedOLEStreamBuf(pStream, which);
}
</code>```

Hope this helps.

Body:
I have a Visual Studio 2008 C++ application using IStreams. I would like to use the IStream connection in a std::ostream. Something like this:

IStream* stream = /*create valid IStream instance...*/;
IStreamBuf< WIN32_FIND_DATA > sb( stream );
std::ostream os( &sb );

WIN32_FIND_DATA d = { 0 };
// send the structure along the IStream
os << d;

To accomplish this, I've implemented the following code:

template< class _CharT, class _Traits >
inline std::basic_ostream< _CharT, _Traits >&
operator<<( std::basic_ostream< _CharT, _Traits >& os, const WIN32_FIND_DATA& i )
{
    const _CharT* c = reinterpret_cast< const _CharT* >( &i );
    const _CharT* const end = c + sizeof( WIN32_FIND_DATA ) / sizeof( _CharT );
    for( c; c < end; ++c ) os << *c;
    return os;
}

template< typename T >
class IStreamBuf : public std::streambuf
{
public:
    IStreamBuf( IStream* stream ) : stream_( stream )
    {
        setp( reinterpret_cast< char* >( &buffer_ ),
              reinterpret_cast< char* >( &buffer_ ) + sizeof( buffer_ ) );
    };

    virtual ~IStreamBuf()
    {
        sync();
    };

protected:
    traits_type::int_type FlushBuffer()
    {
        int bytes = std::min< int >( pptr() - pbase(), sizeof( buffer_ ) );

        DWORD written = 0;
        HRESULT hr = stream_->Write( &buffer_, bytes, &written );
        if( FAILED( hr ) )
        {
            return traits_type::eof();
        }

        pbump( -bytes );
        return bytes;
    };

    virtual int sync()
    {
        if( FlushBuffer() == traits_type::eof() )
            return -1;
        return 0;
    };

    traits_type::int_type overflow( traits_type::int_type ch )
    {
        if( FlushBuffer() == traits_type::eof() )
            return traits_type::eof();

        if( ch != traits_type::eof() )
        {
            *pptr() = ch;
            pbump( 1 );
        }

        return ch;
    };

private:
    /// data queued up to be sent
    T buffer_;

    /// output stream
    IStream* stream_;
}; // class IStreamBuf

Yes, the code compiles and seems to work, but I've not had the pleasure of implementing a std::streambuf before. So, I'd just like to know if it's correct and complete.

Thanks,
PaulH

Body:
Here's an implementation I wrote a while ago: https://github.com/senderista/UnbufferedOLEStreamBuf

For the most part you just need to mechanically translate between STL and Windows/COM types. This translation is tedious and error-prone, though, so you would probably be best off using the implementation I linked. It's only 150 lines, it was used in a production application, and there are few places for bugs to hide.

Since apparently links in answers are cause for deletion, here's the code in its entirety:

//Copyright (c) 2010 Tobin Baker
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

#include <ios>
#include <streambuf>
#include <windows.h>

// Read-write unbuffered streambuf implementation which uses no
// internal buffers (conventional wisdom says this can't be done
// except for write-only streams, but I adapted Matt Austern's example
// from http://www.drdobbs.com/184401305).

class UnbufferedOLEStreamBuf : public std::streambuf {
public:
    UnbufferedOLEStreamBuf(IStream *stream, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    ~UnbufferedOLEStreamBuf();

protected:
    virtual int overflow(int ch = traits_type::eof());
    virtual int underflow();
    virtual int uflow();
    virtual int pbackfail(int ch = traits_type::eof());
    virtual int sync();
    virtual std::streampos seekpos(std::streampos sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    virtual std::streampos seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    virtual std::streamsize xsgetn(char *s, std::streamsize n);
    virtual std::streamsize xsputn(const char *s, std::streamsize n);
    virtual std::streamsize showmanyc();

private:
    IStream *stream_;
    bool readOnly_;
    bool backup();
};

UnbufferedOLEStreamBuf::UnbufferedOLEStreamBuf(IStream *stream, std::ios_base::openmode which)
: std::streambuf(), stream_(stream), readOnly_(!(which & std::ios_base::out)) {}

UnbufferedOLEStreamBuf::~UnbufferedOLEStreamBuf() { if (!readOnly_) UnbufferedOLEStreamBuf::sync(); }

bool UnbufferedOLEStreamBuf::backup() {
    LARGE_INTEGER liMove;
    liMove.QuadPart = -1LL;
    return SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_CUR, NULL));
}

int UnbufferedOLEStreamBuf::overflow(int ch) {
    if (ch != traits_type::eof()) {
        if (SUCCEEDED(stream_->Write(&ch, 1, NULL))) {
            return ch;
        }
    }
    return traits_type::eof();
}

int UnbufferedOLEStreamBuf::underflow() {
    char ch = UnbufferedOLEStreamBuf::uflow();
    if (ch != traits_type::eof()) {
        ch = backup() ? ch : traits_type::eof();
    }
    return ch;
}

int UnbufferedOLEStreamBuf::uflow() {
    char ch;
    ULONG cbRead;
    // S_FALSE indicates we've reached end of stream
    return (S_OK == stream_->Read(&ch, 1, &cbRead))
        ? ch : traits_type::eof();
}

int UnbufferedOLEStreamBuf::pbackfail(int ch) {
    if (ch != traits_type::eof()) {
        ch = backup() ? ch : traits_type::eof();
    }
    return ch;
}

int UnbufferedOLEStreamBuf::sync() {
    return SUCCEEDED(stream_->Commit(STGC_DEFAULT)) ? 0 : -1;
}

std::ios::streampos UnbufferedOLEStreamBuf::seekpos(std::ios::streampos sp, std::ios_base::openmode which) {
    LARGE_INTEGER liMove;
    liMove.QuadPart = sp;
    return SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_SET, NULL)) ? sp : -1;
}

std::streampos UnbufferedOLEStreamBuf::seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which) {
    STREAM_SEEK sk;
    switch (way) {
        case std::ios_base::beg: sk = STREAM_SEEK_SET; break;
        case std::ios_base::cur: sk = STREAM_SEEK_CUR; break;
        case std::ios_base::end: sk = STREAM_SEEK_END; break;
        default: return -1;
    }
    LARGE_INTEGER liMove;
    liMove.QuadPart = static_cast<LONGLONG>(off);
    ULARGE_INTEGER uliNewPos;
    return SUCCEEDED(stream_->Seek(liMove, sk, &uliNewPos))
        ? static_cast<std::streampos>(uliNewPos.QuadPart) : -1;
}

std::streamsize UnbufferedOLEStreamBuf::xsgetn(char *s, std::streamsize n) {
    ULONG cbRead;
    return SUCCEEDED(stream_->Read(s, static_cast<ULONG>(n), &cbRead))
        ? static_cast<std::streamsize>(cbRead) : 0;
}

std::streamsize UnbufferedOLEStreamBuf::xsputn(const char *s, std::streamsize n) {
    ULONG cbWritten;
    return SUCCEEDED(stream_->Write(s, static_cast<ULONG>(n), &cbWritten))
        ? static_cast<std::streamsize>(cbWritten) : 0;
}

std::streamsize UnbufferedOLEStreamBuf::showmanyc() {
    STATSTG stat;
    if (SUCCEEDED(stream_->Stat(&stat, STATFLAG_NONAME))) {
        std::streampos lastPos = static_cast<std::streampos>(stat.cbSize.QuadPart - 1);
        LARGE_INTEGER liMove;
        liMove.QuadPart = 0LL;
        ULARGE_INTEGER uliNewPos;
        if (SUCCEEDED(stream_->Seek(liMove, STREAM_SEEK_CUR, &uliNewPos))) {
            return std::max<std::streamsize>(lastPos - static_cast<std::streampos>(uliNewPos.QuadPart), 0);
        }
    }
    return 0;
}

std::streambuf* StdStreamBufFromOLEStream(IStream *pStream, std::ios_base::openmode which)
{
    return new (std::nothrow) UnbufferedOLEStreamBuf(pStream, which);
}

Hope this helps.


问:
Showing only actual column data in SQL*Plus
I'm spooling out delimited text files from SQL*Plus, but every column is printed as the full size per its definition, rather than the data actually in that row.

For instance, a column defined as 10 characters, with a row value of "test", is printing out as "test      " instead of "test". I can confirm this by selecting the column along with the value of its LENGTH function. It prints "test      |4".

It kind of defeats the purpose of a delimiter if it forces me into fixed-width. Is there a SET option that will fix this, or some other way to make it print only the actual column data.

I don't want to add TRIM to every column, because if a value is actually stored with spaces I want to be able to keep them.

Thanks

答:
Generally, I'd forget SQL Plus as a method for getting CSV out of Oracle.

Tom Kyte has written a nice little Pro-C unloader

Personally I've written a utility which does similar but in perl


问:
How to implement fair division(?) with buffer in javascript?
For the sake of explaining, imagine I have 101 entities. The entities are all people.

In the first entity, it has x amount of "potatoes", I want it to have y potatoes, for now I shall use 950 as an example, intentionally choosing a more awkward number than 1000 for testing.

```<code>var personOne = {
     ...
     potatoes: 100
}
</code>```

I have 100 more of these entities which may have any number of potatoes, but I set a constant buffer that at least 100 for the sake of example again - have to remain with each person.

This means for all of the entities that have over 100, I will be taking some from them - I want this to be shared proportionally across all of them, so that 850 aren't taken from the first two or three, but 10 or 5 taken from all those that are capable of providing such an amount.

Any ideas for an approach?

Optionally: I am using more properties than one "potatoes" property, but I plan on looping through each type and re-using the method that I find to each. I am unsure as to whether this could affect the answer.

Important / Simplified

The one entitiy is pulling "potatoes" from all of the other entities, they are not being distributed evenly across all of them - they are being taken to one entity. I just do not want to do it in a way that is not proportional across all other 100 entities.

This is more taxation than cake-cutting. I am struggling to google for or think of the correct name for the mathematical problem.

答:
I hope this time i understood the problem. I would calculate the percentage of excess potatoes needed to get the desired amount of potatoes and take that percentage of each participant's excess potatoes, or all if there are not enough total.

Here is some demonstration code to clarify. It is probably overly verbose but should only serve to show the intention anyways. I assumed a very precise potato-cutter is available, as there was no rule specified about what to do about rounding. The outputs are the potatoes of the participants before and after the redistribution. I set NUMBER_OF_PARTICIPANTS to 4 so the output is somewhat readable.

const MAXIMUM_START_POTATOES = 1234;
const MINIMUM_KEPT_POTATOES = 100;
const ENTITY_TAKING_POTATOES = 0;
const DESIRED_POTATOES = 950;
const NUMBER_OF_PARTICIPANTS = 4;

//generate NUMBER_OF_PARTICIPANTS entities with random amount of potatoes
let entities = [];
for (let i = 0; i < NUMBER_OF_PARTICIPANTS; i++) {
  entities.push(Math.floor(Math.random() * (MAXIMUM_START_POTATOES + 1)));
}

console.log(entities);

let required_potatoes = DESIRED_POTATOES - entities[ENTITY_TAKING_POTATOES];

if (required_potatoes <= 0) console.log("nothing to do.");
else {
  let excess_potatoes = 0;
  //Sum excess available potatoes
  for (let i = 0; i < NUMBER_OF_PARTICIPANTS; i++) {
    if (i === ENTITY_TAKING_POTATOES) continue;
    excess_potatoes += Math.max(0, entities[i] - MINIMUM_KEPT_POTATOES);
  }

  if (excess_potatoes < required_potatoes) {
    //just take all excess potatoes
    for (let i = 0; i < NUMBER_OF_PARTICIPANTS; i++) {
      if (i === ENTITY_TAKING_POTATOES) continue;
      entities[i] = Math.min(entities[i], MINIMUM_KEPT_POTATOES);
    }
    entities[ENTITY_TAKING_POTATOES] += excess_potatoes;
  } else {
    //calculate percentage of the excess potatoes that is needed
    let percentage_required = required_potatoes / excess_potatoes;
    //Take that percentage off every participant's excess potatoes
    for (let i = 0; i < NUMBER_OF_PARTICIPANTS; i++) {
      if (i === ENTITY_TAKING_POTATOES) continue;
      entities[i] -= Math.max(0, entities[i] - MINIMUM_KEPT_POTATOES) *  percentage_required;
    }
    //Assume double precision is enough for this to never be an issue
    entities[ENTITY_TAKING_POTATOES] = DESIRED_POTATOES;
  }
  console.log(entities);
}```

Body:
For the sake of explaining, imagine I have 101 entities. The entities are all people.

In the first entity, it has x amount of "potatoes", I want it to have y potatoes, for now I shall use 950 as an example, intentionally choosing a more awkward number than 1000 for testing.

var personOne = {
     ...
     potatoes: 100
}

I have 100 more of these entities which may have any number of potatoes, but I set a constant buffer that at least 100 for the sake of example again - have to remain with each person.

This means for all of the entities that have over 100, I will be taking some from them - I want this to be shared proportionally across all of them, so that 850 aren't taken from the first two or three, but 10 or 5 taken from all those that are capable of providing such an amount.

Any ideas for an approach?

Optionally: I am using more properties than one "potatoes" property, but I plan on looping through each type and re-using the method that I find to each. I am unsure as to whether this could affect the answer.

Important / Simplified

The one entitiy is pulling "potatoes" from all of the other entities, they are not being distributed evenly across all of them - they are being taken to one entity. I just do not want to do it in a way that is not proportional across all other 100 entities.

This is more taxation than cake-cutting. I am struggling to google for or think of the correct name for the mathematical problem.