问:
Best way of using masks to select sub-vectors in Python
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

```<code>def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]
</code>```

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

答:
An array version of num2bv is:

```<code>def foo(num, n_len):
    c = np.int64(2)**np.arange(n_len)[::-1]
    return (np.bitwise_and(c,num)//c).astype(bool)

In [713]: N=16
In [714]: foo(2**(N//2)-1,N)
Out[714]:
array([False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)
In [715]: np.array(num2bv(2**(N//2)-1,N))
Out[715]:
array([False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)

In [716]: N=32
In [717]: timeit np.array(num2bv(2**(N//2)-1,N))
10000 loops, best of 3: 39.7 µs per loop
In [718]: timeit foo(2**(N//2)-1,N)
The slowest run took 4.72 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 15.7 µs per loop
</code>```

But for large N the array version starts to run into problems with the integer representation of 2**i.

For larger N, the num2bv time dominates the indexing, e.g N=1024

```<code>In [734]: timeit num2bv(2**(N//2)-1,N)
100 loops, best of 3: 4.34 ms per loop
In [735]: timeit np.nonzero(num2bv(2**(N//2)-1,N))
100 loops, best of 3: 4.4 ms per loop
In [736]: A=np.ones(N)
In [738]: timeit A[num2bv(2**(N//2)-1,N)]
100 loops, best of 3: 4.39 ms per loop
</code>```

np.binary_repr returns a string representation.  It makes use Python bin.  One way to create the mask is to split it with list and let np.array convert it to a boolean array

```<code>In [846]: np.binary_repr(100,16)
Out[846]: '0000000001100100'
In [848]: np.array(list(np.binary_repr(100,16)),bool)
Out[848]:
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)
</code>```

It's not quite as fast as to_numpy_mask_2, but still quite an improvement over num2bv.  And not subject to the size limitation of my earlier foo.

```<code>In [842]: timeit np.array(num2bv(100,120))
10000 loops, best of 3: 166 µs per loop
In [843]: timeit to_numpy_mask_2(100,120)
The slowest run took 5.07 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.6 µs per loop
In [850]: timeit np.array(list(np.binary_repr(100,120)),bool)
100000 loops, best of 3: 18 µs per loop
</code>```

Body:
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

Body:
An array version of num2bv is:

def foo(num, n_len):
    c = np.int64(2)**np.arange(n_len)[::-1]
    return (np.bitwise_and(c,num)//c).astype(bool)

In [713]: N=16
In [714]: foo(2**(N//2)-1,N)
Out[714]:
array([False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)
In [715]: np.array(num2bv(2**(N//2)-1,N))
Out[715]:
array([False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)

In [716]: N=32
In [717]: timeit np.array(num2bv(2**(N//2)-1,N))
10000 loops, best of 3: 39.7 µs per loop
In [718]: timeit foo(2**(N//2)-1,N)
The slowest run took 4.72 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 15.7 µs per loop

But for large N the array version starts to run into problems with the integer representation of 2**i.

For larger N, the num2bv time dominates the indexing, e.g N=1024

In [734]: timeit num2bv(2**(N//2)-1,N)
100 loops, best of 3: 4.34 ms per loop
In [735]: timeit np.nonzero(num2bv(2**(N//2)-1,N))
100 loops, best of 3: 4.4 ms per loop
In [736]: A=np.ones(N)
In [738]: timeit A[num2bv(2**(N//2)-1,N)]
100 loops, best of 3: 4.39 ms per loop

np.binary_repr returns a string representation.  It makes use Python bin.  One way to create the mask is to split it with list and let np.array convert it to a boolean array

In [846]: np.binary_repr(100,16)
Out[846]: '0000000001100100'
In [848]: np.array(list(np.binary_repr(100,16)),bool)
Out[848]:
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True], dtype=bool)

It's not quite as fast as to_numpy_mask_2, but still quite an improvement over num2bv.  And not subject to the size limitation of my earlier foo.

In [842]: timeit np.array(num2bv(100,120))
10000 loops, best of 3: 166 µs per loop
In [843]: timeit to_numpy_mask_2(100,120)
The slowest run took 5.07 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.6 µs per loop
In [850]: timeit np.array(list(np.binary_repr(100,120)),bool)
100000 loops, best of 3: 18 µs per loop


来源: stackexchange

问:
python list comprehension double for but keep grouping form
I have the following list

```<code>grouping = [[('Amy',1),('Bob',2)],[('Cindy',3)]]
</code>```

I hope I can extract the name but keep the grouping form

```<code>[['Amy','Bob'],['Cindy']]
</code>```

I try to use

```<code>result = [x[0] for b in grouping for x in b]
</code>```

but it will give me ['Amy','Bob','Cindy'] instead.

答:
For each sublist in grouping, you want to make a new list made up of the 0th elements of each constituent tuple.  So:

```<code>>>> grouping = [[('Amy',1),('Bob',2)],[('Cindy',3)]]
>>> [x[0] for b in grouping for x in b]
['Amy', 'Bob', 'Cindy']
>>> [[x[0] for x in b] for b in grouping]
[['Amy', 'Bob'], ['Cindy']]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following list

grouping = [[('Amy',1),('Bob',2)],[('Cindy',3)]]

I hope I can extract the name but keep the grouping form

[['Amy','Bob'],['Cindy']]

I try to use

result = [x[0] for b in grouping for x in b]

but it will give me ['Amy','Bob','Cindy'] instead.

Body:
For each sublist in grouping, you want to make a new list made up of the 0th elements of each constituent tuple.  So:

>>> grouping = [[('Amy',1),('Bob',2)],[('Cindy',3)]]
>>> [x[0] for b in grouping for x in b]
['Amy', 'Bob', 'Cindy']
>>> [[x[0] for x in b] for b in grouping]
[['Amy', 'Bob'], ['Cindy']]


问:
Wordpress wp enqueue style
I am writing my first wordpress plugin, and I am stuck. Badly.

I want to include a css file in the admin part of the plugin. But I can`t for some reason. The code I tried (and many variation of it):

```<code>// Register style sheet.
add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );

/**
 * Register style sheet.
 */
function register_plugin_styles() {
    wp_register_style( 'statistika', plugins_url( '/statistika/css/style.css' ) );
    wp_enqueue_style( 'statistika' );
}
</code>```

The paths are good I am sure of it, when I write the URL manually in the browser the style open like any other. The thing I am suspecting the error is the files I am including in the plugin php file. I only included wp-load.php in the beginning. Is that enough for the function wp_register_style to work? If it`s not that then what is the problem? Please help.

EDIT:
New problem, how to include jquery and javascript files inside the admin side of wordpress. I tried this:

```<code>wp_enqueue_script('jquery', plugins_url('/js/jquery.js', __file__));
wp_enqueue_script('jquery', plugins_url('/js/functions.js', __file__));
</code>```

I added this to the existing function in the answer.

EDIT 2:

Got it, I forgot that wordpress does not like $ as a jquery object.

答:
Most of the times scripts/styles enqueued are only relevant for specific pages.

To minimize redundant file server calls it is best to perform this action only on desired pages:

```<code>// Hook enqueue style sheet.
add_action( 'wp_enqueue_scripts', 'register_my_plugin_styles' );

//Register & Enqueue style sheet
function register_my_plugin_styles() {
    if ( is_page( 'specific-page-name' ) ) {
        wp_register_style( 'my_plugins_style', plugins_url( '/my_plugins_name/css/example.css' ) );
        wp_enqueue_style( 'my_plugins_style' );
    }
}
</code>```

This would work the same for scripts.

If you want a style/script loaded only on the homepage (front-page), you can use  is_home() instead of is_page().

Title: Wordpress wp enqueue style

Body:
I am writing my first wordpress plugin, and I am stuck. Badly.

I want to include a css file in the admin part of the plugin. But I can`t for some reason. The code I tried (and many variation of it):

// Register style sheet.
add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );

/**
 * Register style sheet.
 */
function register_plugin_styles() {
    wp_register_style( 'statistika', plugins_url( '/statistika/css/style.css' ) );
    wp_enqueue_style( 'statistika' );
}

The paths are good I am sure of it, when I write the URL manually in the browser the style open like any other. The thing I am suspecting the error is the files I am including in the plugin php file. I only included wp-load.php in the beginning. Is that enough for the function wp_register_style to work? If it`s not that then what is the problem? Please help.

EDIT:
New problem, how to include jquery and javascript files inside the admin side of wordpress. I tried this:

wp_enqueue_script('jquery', plugins_url('/js/jquery.js', __file__));
wp_enqueue_script('jquery', plugins_url('/js/functions.js', __file__));

I added this to the existing function in the answer.

EDIT 2:

Got it, I forgot that wordpress does not like $ as a jquery object.

Body:
Most of the times scripts/styles enqueued are only relevant for specific pages.

To minimize redundant file server calls it is best to perform this action only on desired pages:

// Hook enqueue style sheet.
add_action( 'wp_enqueue_scripts', 'register_my_plugin_styles' );

//Register & Enqueue style sheet
function register_my_plugin_styles() {
    if ( is_page( 'specific-page-name' ) ) {
        wp_register_style( 'my_plugins_style', plugins_url( '/my_plugins_name/css/example.css' ) );
        wp_enqueue_style( 'my_plugins_style' );
    }
}

This would work the same for scripts.

If you want a style/script loaded only on the homepage (front-page), you can use  is_home() instead of is_page().


问:
Service Error: Spreadsheets (getLastRow)
I am at my wit's end here.  I had three scripts working beautifully, and then overnight they all failed with the dreaded "Service Error".

The error always references getLastRow as the offending line.  I've tried adding and removing rows at the bottom of the sheet, removing some of the rows with data in them, unfreezing headers and columns, etc. with no luck whatsoever.  I also tried reverting back to last week's version of the script, long before the failure (first was Monday night), to no avail.

I've done a lot of research and I've noticed most often the thing that fixes these Service Errors is something completely random.  Some people say that this error is caused by memoization on Google's end.  If so, what can I do to fix this?

A huge project is basically crashing and burning because these scripts failed...any help would be awesome.  Thanks.

For reference, one of my scripts (the one that failed first).

```<code>function timeStamp2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[4];
var numRows = sheet.getLastRow()-1;   // Number of rows to process
Logger.log(numRows)
var startRow = 2;  // First row of data to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows,    sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)

for (var i = 0; i < data.length; ++i) {
var row = data[i];

var schedulingStatus = row[4];
var timeStamp = row[3];
var scheduled = "Scheduled";

  if(timeStamp === '') {
    if(schedulingStatus == scheduled ) {
      sheet.getRange(startRow + i, 3).setValue(new Date());

    }
  }
 }
}
</code>```

答:
I had a similar issue with a script I wrote.

It gave Service Error: Spreadsheets said the problem was with the line containing getLastRow.

My fix ended up making sure there was at least one row at the bottom without any data. Haven't had a problem since.

Body:
I am at my wit's end here.  I had three scripts working beautifully, and then overnight they all failed with the dreaded "Service Error".

The error always references getLastRow as the offending line.  I've tried adding and removing rows at the bottom of the sheet, removing some of the rows with data in them, unfreezing headers and columns, etc. with no luck whatsoever.  I also tried reverting back to last week's version of the script, long before the failure (first was Monday night), to no avail.

I've done a lot of research and I've noticed most often the thing that fixes these Service Errors is something completely random.  Some people say that this error is caused by memoization on Google's end.  If so, what can I do to fix this?

A huge project is basically crashing and burning because these scripts failed...any help would be awesome.  Thanks.

For reference, one of my scripts (the one that failed first).

function timeStamp2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[4];
var numRows = sheet.getLastRow()-1;   // Number of rows to process
Logger.log(numRows)
var startRow = 2;  // First row of data to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows,    sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)

for (var i = 0; i < data.length; ++i) {
var row = data[i];

var schedulingStatus = row[4];
var timeStamp = row[3];
var scheduled = "Scheduled";

  if(timeStamp === '') {
    if(schedulingStatus == scheduled ) {
      sheet.getRange(startRow + i, 3).setValue(new Date());

    }
  }
 }
}


问:
Iterators for custom datastructure
Getting along with iterators and containers, I stumbled onto a little experiment which I was trying to implement. However, I got stuck pretty early.

The idea was to create a linked list, which contains of two different types of entries, namely out and in items. All the items are linked together, while items of the same kind contain references to each other as well.

Next up, I want to be able to loop the data-structure by means of iterators, in three different ways:

Any, in which the entire data-structure is traversed.

In, in which solely the in items are traversed.

Out, in which solely the out items are traversed.

So when calling for any of the types listed above, only a begin() and end() iterator are passed to the requester.

I've got a set up for the following data structure, I'm able to loop it in the ways mentioned above, though I can't set up the iterators.

```<code>template <class T>
struct dual_node {
    /*
     * Constructors
     */
    dual_node(T data): data(data) {};

    /*
     * Operators
     */
    bool operator ==(const dual_node<T> &rhs) const {
        return this->data == rhs.data;
    }

    /*
     * Members
     */
    T data;
    dual_node *type_next = nullptr;
    dual_node *type_prev = nullptr;
};
</code>```

The wrapping class:

```<code>using namespace std;

template <class T>
class DualLinkedList {
public:
    /*
     * Mutators
     */
    template <class Direction>
    void push_front(T element){
        elements.push_front(dual_node<T>(element));
        Direction::template set_ptr<T>(elements.front(), &last_in, &last_out);
    }

    void remove(T element){
        auto it = find(elements.begin(), elements.end(), element);

        // Element found
        if(it != elements.end()){
            // If it has a previous
            if(it->type_prev) {
                it->type_prev->type_next = it->type_next;
            }else{
                // No previous, so last_in or last_out should match.
                if(*last_in == *it){
                    last_in = it->type_next;
                }

                if(*last_out == *it){
                    last_out = it->type_next;
                }
            }

            // Remove from forward_list
            elements.remove(*it);
        }

    }
//private:
    forward_list<dual_node<T>> elements;
    dual_node<T> *last_in;
    dual_node<T> *last_out;
};
</code>```

Direction classes:

```<code>struct in {
        static edge_list& get_list(pair<edge_list, edge_list> &a) {
            return a.first;
        }
        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_in){
            // Return iterator starting at last_in, following type_next pointers
        }

        template <class T>
        static void set_ptr(dual_node<T> &element, dual_node<T>** last_in, dual_node<T>** last_out){
            // If last incoming exists.
            if(*last_in) {
                (**last_in).type_prev = &element;
            }
            element.type_next = *last_in;
            *last_in = &element;
        }
    };

    struct out {
        static edge_list& get_list(pair<edge_list, edge_list> &a) {
            return a.second;
        }

        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_out){
            // Return iterator starting at last_out, following type_next ptrs
        }

        template <class T>
        static void set_ptr(dual_node<T> &element, dual_node<T>** last_in, dual_node<T>** last_out) {
            // If last outgoing exists.
            if(*last_out) {
                (**last_out).type_prev = &element;
            }
            element.type_next = *last_out;
            *last_out = &element;
        }
    };

    struct any {
        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_out){
            // Returning iterator starting at last out following forward_list
        }
    };
</code>```

答:
I'm not too terribly familiar with iterators, but have you tried browsing through some of these tutorials?

https://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterator-define.html

How to correctly implement custom iterators and const_iterators?

Creating my own Iterators

Title: Iterators for custom datastructure

Body:
Getting along with iterators and containers, I stumbled onto a little experiment which I was trying to implement. However, I got stuck pretty early.

The idea was to create a linked list, which contains of two different types of entries, namely out and in items. All the items are linked together, while items of the same kind contain references to each other as well.

Next up, I want to be able to loop the data-structure by means of iterators, in three different ways:

Any, in which the entire data-structure is traversed.

In, in which solely the in items are traversed.

Out, in which solely the out items are traversed.

So when calling for any of the types listed above, only a begin() and end() iterator are passed to the requester.

I've got a set up for the following data structure, I'm able to loop it in the ways mentioned above, though I can't set up the iterators.

template <class T>
struct dual_node {
    /*
     * Constructors
     */
    dual_node(T data): data(data) {};

    /*
     * Operators
     */
    bool operator ==(const dual_node<T> &rhs) const {
        return this->data == rhs.data;
    }

    /*
     * Members
     */
    T data;
    dual_node *type_next = nullptr;
    dual_node *type_prev = nullptr;
};

The wrapping class:

using namespace std;

template <class T>
class DualLinkedList {
public:
    /*
     * Mutators
     */
    template <class Direction>
    void push_front(T element){
        elements.push_front(dual_node<T>(element));
        Direction::template set_ptr<T>(elements.front(), &last_in, &last_out);
    }

    void remove(T element){
        auto it = find(elements.begin(), elements.end(), element);

        // Element found
        if(it != elements.end()){
            // If it has a previous
            if(it->type_prev) {
                it->type_prev->type_next = it->type_next;
            }else{
                // No previous, so last_in or last_out should match.
                if(*last_in == *it){
                    last_in = it->type_next;
                }

                if(*last_out == *it){
                    last_out = it->type_next;
                }
            }

            // Remove from forward_list
            elements.remove(*it);
        }

    }
//private:
    forward_list<dual_node<T>> elements;
    dual_node<T> *last_in;
    dual_node<T> *last_out;
};

Direction classes:

struct in {
        static edge_list& get_list(pair<edge_list, edge_list> &a) {
            return a.first;
        }
        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_in){
            // Return iterator starting at last_in, following type_next pointers
        }

        template <class T>
        static void set_ptr(dual_node<T> &element, dual_node<T>** last_in, dual_node<T>** last_out){
            // If last incoming exists.
            if(*last_in) {
                (**last_in).type_prev = &element;
            }
            element.type_next = *last_in;
            *last_in = &element;
        }
    };

    struct out {
        static edge_list& get_list(pair<edge_list, edge_list> &a) {
            return a.second;
        }

        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_out){
            // Return iterator starting at last_out, following type_next ptrs
        }

        template <class T>
        static void set_ptr(dual_node<T> &element, dual_node<T>** last_in, dual_node<T>** last_out) {
            // If last outgoing exists.
            if(*last_out) {
                (**last_out).type_prev = &element;
            }
            element.type_next = *last_out;
            *last_out = &element;
        }
    };

    struct any {
        // conceptual
        static pair<iterator, iterator> get_it_pair(dual_node<T>** last_out){
            // Returning iterator starting at last out following forward_list
        }
    };


问:
Rendering a Loading Bar in React
I have a state in my component progress and I am confused about when is the best time in the lifecycle to update the progress state I am making an http request promise in componentDidMount(). So I would like the progress bar to be rendering while the data is not ready to be rendered.

I am using Axios to make the request and I am creating a couple of bluebird Promises inside that request.

At the end I update the progress state to 100,

```<code>componentDidMount() {
    axios.get('/api/property/documents.json')
        .then((res) => {
            // save an object with the variable representation of the variable and the string
            // this will allow a forEach loop for teh promises of data
            let complianceStatus = {
                needsUploading: 'needsUploading',
                pendingApproval: 'pendingApproval',
                approved: 'approved'
            }

            function filterer(status, target) { return status === target }

            for(let status in complianceStatus) {
                let current = status;
                Promise.map(res.data.compliance, (record) => {
                    return Promise.all([filterer(record.type, complianceStatus[status]), record]);
                }).then((values) => {
                    status = values.filter((value) => {
                        return value[0] == true
                    }).map((value) => {
                        return value[1];
                    });
                    this.setState({ [complianceStatus[current]]: status })
                })
            }
            // general data
            Promise.map(res.data.general, (record) => {
                    return record;
                }).then((generalDocs) => {
                    this.setState({ generalDocs })
                })
        }).then(() => {
            this.setState({ progress: 100, isLoading: false });
        })
        .catch((err) => {
            console.log(err);
        });
}
</code>```

My <ProgressBar percent={ this.state.progress } autoIncrement={ true } spinner={ false } />is just sitting in my return of the render method.

答:
It won't be super-accurate, but you can make something that shows the user that progress is happening, and gives a rough idea of the progress so far.  I've extracted progress bar update logic into another function on the class:

```<code>getProgressUpdater() {
    let maxTicks = 0;
    let currentTick = 0;
    let isTicking = false;

    const setTick = ( progress ) => {
        this.setState({ progress });
    }

    const tick = () => {
        setTick(++currentTick);
        if( currentTick < maxTicks ) {
            isTicking = true;
            setTimeout(tick, 100);
        } else {
            isTicking = false;
        }
    }

    const setMaxTicks = ( progress ) => {
         maxTicks = progress;
         if (!isTicking) {
             tick();
         }
    }

    const incrementMaxTicks = ( increment ) => {
         maxTicks += increment;
         if (!isTicking) {
             tick();
         }
    }

    return {
         setMaxTicks,
         incrementMaxTicks,
         setTick
    }
}
</code>```

Which you could use throughout your async calls to give progress updates:

```<code>componentDidMount() {
  const progressUpdater = this.getProgressUpdater();
  progressUpdater.setMaxTicks(10);
  axios.get('/api/property/documents.json')
    .then((res) => {
        // save an object with the variable representation of the variable and the string
        // this will allow a forEach loop for teh promises of data
        let complianceStatus = {
            needsUploading: 'needsUploading',
            pendingApproval: 'pendingApproval',
            approved: 'approved'
        }

        function filterer(status, target) { return status === target }

        for(let status in complianceStatus) {
            progressUpdater.incrementMaxTicks(25);
            let current = status;
            Promise.map(res.data.compliance, (record) => {
                return Promise.all([filterer(record.type, complianceStatus[status]), record]);
            }).then((values) => {
                status = values.filter((value) => {
                    return value[0] == true
                }).map((value) => {
                    return value[1];
                });
                this.setState({ [complianceStatus[current]]: status })
            })
        }

        progressUpdater.setMaxTicks(90)

        // general data
        Promise.map(res.data.general, (record) => {
                return record;
            }).then((generalDocs) => {
                this.setState({ generalDocs })
            })
    }).then(() => {
        progressUpdater.setTick(100);
    })
    .catch((err) => {
        console.log(err);
    });
}
</code>```

Title: Rendering a Loading Bar in React

Body:
I have a state in my component progress and I am confused about when is the best time in the lifecycle to update the progress state I am making an http request promise in componentDidMount(). So I would like the progress bar to be rendering while the data is not ready to be rendered.

I am using Axios to make the request and I am creating a couple of bluebird Promises inside that request.

At the end I update the progress state to 100,

componentDidMount() {
    axios.get('/api/property/documents.json')
        .then((res) => {
            // save an object with the variable representation of the variable and the string
            // this will allow a forEach loop for teh promises of data
            let complianceStatus = {
                needsUploading: 'needsUploading',
                pendingApproval: 'pendingApproval',
                approved: 'approved'
            }

            function filterer(status, target) { return status === target }

            for(let status in complianceStatus) {
                let current = status;
                Promise.map(res.data.compliance, (record) => {
                    return Promise.all([filterer(record.type, complianceStatus[status]), record]);
                }).then((values) => {
                    status = values.filter((value) => {
                        return value[0] == true
                    }).map((value) => {
                        return value[1];
                    });
                    this.setState({ [complianceStatus[current]]: status })
                })
            }
            // general data
            Promise.map(res.data.general, (record) => {
                    return record;
                }).then((generalDocs) => {
                    this.setState({ generalDocs })
                })
        }).then(() => {
            this.setState({ progress: 100, isLoading: false });
        })
        .catch((err) => {
            console.log(err);
        });
}

My <ProgressBar percent={ this.state.progress } autoIncrement={ true } spinner={ false } />is just sitting in my return of the render method.

Body:
It won't be super-accurate, but you can make something that shows the user that progress is happening, and gives a rough idea of the progress so far.  I've extracted progress bar update logic into another function on the class:

getProgressUpdater() {
    let maxTicks = 0;
    let currentTick = 0;
    let isTicking = false;

    const setTick = ( progress ) => {
        this.setState({ progress });
    }

    const tick = () => {
        setTick(++currentTick);
        if( currentTick < maxTicks ) {
            isTicking = true;
            setTimeout(tick, 100);
        } else {
            isTicking = false;
        }
    }

    const setMaxTicks = ( progress ) => {
         maxTicks = progress;
         if (!isTicking) {
             tick();
         }
    }

    const incrementMaxTicks = ( increment ) => {
         maxTicks += increment;
         if (!isTicking) {
             tick();
         }
    }

    return {
         setMaxTicks,
         incrementMaxTicks,
         setTick
    }
}

Which you could use throughout your async calls to give progress updates:

componentDidMount() {
  const progressUpdater = this.getProgressUpdater();
  progressUpdater.setMaxTicks(10);
  axios.get('/api/property/documents.json')
    .then((res) => {
        // save an object with the variable representation of the variable and the string
        // this will allow a forEach loop for teh promises of data
        let complianceStatus = {
            needsUploading: 'needsUploading',
            pendingApproval: 'pendingApproval',
            approved: 'approved'
        }

        function filterer(status, target) { return status === target }

        for(let status in complianceStatus) {
            progressUpdater.incrementMaxTicks(25);
            let current = status;
            Promise.map(res.data.compliance, (record) => {
                return Promise.all([filterer(record.type, complianceStatus[status]), record]);
            }).then((values) => {
                status = values.filter((value) => {
                    return value[0] == true
                }).map((value) => {
                    return value[1];
                });
                this.setState({ [complianceStatus[current]]: status })
            })
        }

        progressUpdater.setMaxTicks(90)

        // general data
        Promise.map(res.data.general, (record) => {
                return record;
            }).then((generalDocs) => {
                this.setState({ generalDocs })
            })
    }).then(() => {
        progressUpdater.setTick(100);
    })
    .catch((err) => {
        console.log(err);
    });
}


问:
Filtering in Scala
So suppose I have the following data (only the first few rows, this data covers an entire year) -

```<code>(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)
</code>```

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

```<code>error: value xxxx is not a member of (org.joda.time.DateTime, String)
</code>```

Is there another way of doing this?

Title: Filtering in Scala

Body:
So suppose I have the following data (only the first few rows, this data covers an entire year) -

(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

error: value xxxx is not a member of (org.joda.time.DateTime, String)

Is there another way of doing this?

Body:
Here's a function that takes a date, a list of datetime-name pairs, and returns a list of names for the date:

def getNames(d: String, l: List[(String, String)]): List[String] = {
  val date = """^([^T]*).*""".r

  val dateMap = list.map {
    case (x, y) => ( x match { case date(z) => z }, y )
  }.
  groupBy(_._1) mapValues( _.map(_._2) )

  dateMap.getOrElse(d, List[String]())
}

val list = List(
  ("2014-08-31T00:05:00.000+01:00", "John"),
  ("2014-08-31T00:11:00.000+01:00", "Sarah"),
  ("2014-08-31T00:12:00.000+01:00", "George"),
  ("2014-08-31T00:05:00.000+01:00", "John"),
  ("2014-09-01T00:05:00.000+01:00", "Sarah"),
  ("2014-09-01T00:05:00.000+01:00", "George"),
  ("2014-09-01T00:05:00.000+01:00", "Jason")
)

getNames("2014-09-01", list)
res1: List[String] = List(Sarah, George, Jason)


问:
Get the last record in a belongsToMany association
I have a belongsToMany association between Appointment and Status models. The below query returns all of the statuses and I want to alter it to pull the last status assigned to the appointment.

```<code>$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);
</code>```

I have tried altering the query with this but it doesn't work.

```<code>$query->with('statuses')->latest();
</code>```

This is my raw query:

```<code>select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')
</code>```

So this works, but it runs two queries on Statuses

```<code>$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);
</code>```

答:
In order to get the latest record from the database, you should have a created_at column to reach that. In this case, you can do something like that:

```<code>Appointment::with(['statuses' => function ($query) {
    $query->orderBy('created_at', 'desc')->first();
}])->get();
</code>```

Body:
I have a belongsToMany association between Appointment and Status models. The below query returns all of the statuses and I want to alter it to pull the last status assigned to the appointment.

$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

I have tried altering the query with this but it doesn't work.

$query->with('statuses')->latest();

This is my raw query:

select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')

So this works, but it runs two queries on Statuses

$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

Body:
In order to get the latest record from the database, you should have a created_at column to reach that. In this case, you can do something like that:

Appointment::with(['statuses' => function ($query) {
    $query->orderBy('created_at', 'desc')->first();
}])->get();


问:
How to create a gradient that goes across different rectangles in D3JS?
In D3JS V4: Suppose that you have six rectangles. How would you create a gradient that flows through from the first to the last?

I tried creating a group for the rectangles and then add the color-gradient-id to the group, but it still causes for the gradient to happen within each rectangle individually.

答:
You have to set gradientUnits to userSpaceOnUse. According to the docs, userSpaceOnUse:

...represent values in the coordinate system that results from taking the current user coordinate system in place at the time when the gradient element is referenced

Here is a demo without userSpaceOnUse, which result is not what you want:

var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%");

gradient.append("stop")
  .attr("offset", "0%")
  .attr("stop-color", "Black")
  .attr("stop-opacity", 1);

gradient.append("stop")
  .attr("offset", "100%")
  .attr("stop-color", "white")
  .attr("stop-opacity", 1);

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg></code>```

Now a demo with userSpaceOnUse:

var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%")
  .attr("gradientUnits","userSpaceOnUse");

gradient.append("stop")
  .attr("offset", "0%")
  .attr("stop-color", "Black")
  .attr("stop-opacity", 1);

gradient.append("stop")
  .attr("offset", "100%")
  .attr("stop-color", "white")
  .attr("stop-opacity", 1);

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg></code>```

Body:
You have to set gradientUnits to userSpaceOnUse. According to the docs, userSpaceOnUse:

...represent values in the coordinate system that results from taking the current user coordinate system in place at the time when the gradient element is referenced

Here is a demo without userSpaceOnUse, which result is not what you want:

var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%");

gradient.append("stop")
  .attr("offset", "0%")
  .attr("stop-color", "Black")
  .attr("stop-opacity", 1);

gradient.append("stop")
  .attr("offset", "100%")
  .attr("stop-color", "white")
  .attr("stop-opacity", 1);

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>

Now a demo with userSpaceOnUse:

var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%")
  .attr("gradientUnits","userSpaceOnUse");

gradient.append("stop")
  .attr("offset", "0%")
  .attr("stop-color", "Black")
  .attr("stop-opacity", 1);

gradient.append("stop")
  .attr("offset", "100%")
  .attr("stop-color", "white")
  .attr("stop-opacity", 1);

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>


问:
How to build a Grails Plugin and deploy it to local Ivy repository?
Is there a way to build a Grails Plugin and deploy the artifacts to the local Ivy repository?

With Maven, I would do this:

```<code>mvn install
</code>```

答:
Use the ivy publish task

```<code><ivy:publish resolver="local" pubrevision="1.0">
   <artifacts pattern="build/[artifact].[ext]" />
</ivy:publish>
</code>```

Note 1

Your ivy file must list the artifacts you plan to publish

```<code><ivy-module version="2.0">
  <info organisation="myorg" module="mymodule"/>
  <publications>
    <artifact name="mymodule" type="zip"/>
  </publications>
</ivy-module>
</code>```

Maven derives this information from the module declaration in the POM file. One of the advantages of using ivy is that you can publish more than one artifact.

Note 2

The ivy local repository is located in the following location by default:

```<code>${user.dir}/.ivy2/local
</code>```

You can of course create your own custom repositories by declaring alternative resolvers in you settings file

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to build a Grails Plugin and deploy the artifacts to the local Ivy repository?

With Maven, I would do this:

mvn install

Body:
Use the ivy publish task

<ivy:publish resolver="local" pubrevision="1.0">
   <artifacts pattern="build/[artifact].[ext]" />
</ivy:publish>

Note 1

Your ivy file must list the artifacts you plan to publish

<ivy-module version="2.0">
  <info organisation="myorg" module="mymodule"/>
  <publications>
    <artifact name="mymodule" type="zip"/>
  </publications>
</ivy-module>

Maven derives this information from the module declaration in the POM file. One of the advantages of using ivy is that you can publish more than one artifact.

Note 2

The ivy local repository is located in the following location by default:

${user.dir}/.ivy2/local

You can of course create your own custom repositories by declaring alternative resolvers in you settings file


问:
Fullscreen NSWindow on Secondary Monitor - Swift
I have seen many posts on this in Obj C. Not too many in swift, and I just can't get it to work. I want to be able to make a window fullscreen on a specific NSScreen. The 'ToggleFullscreen' method isn't the best way because there aren't many options (for external displays). I tried:

```<code>    // screen is my variable already set
    outputWindow!.window!.setFrame(screen.frame, display: true, animate: true)
    outputWindow!.window!.styleMask = NSFullScreenWindowMask
    outputWindow!.window!.level = Int(CGShieldingWindowLevel())

    // the above one doesn't make it fullscreen.
    // it has a title bar and shows the menu on the screen.

    // then i tried....
    fullscreenWindow = NSWindow(contentRect: screen.frame, styleMask:NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false, screen: screen)
    fullscreenWindow.level = Int(CGShieldingWindowLevel())
    fullscreenWindow.makeKeyAndOrderFront(nil)

    //that one works on my main display (somewhat). and does nothing on externals.
</code>```

One thing I noticed with making my own fullscreen is that I get stuck into it. It's not like the OS X fullscreen where you can press esc to escape it. Are there any tricks to this? Thanks

答:
This is a pseudo answer:

[in a inherited class of NSWondowController]

```<code>var fullscreen:Bool {
    set {
        if newValue == true {

            if fullscreen == true {
                return
            }

            frameOrig = self.window?.frame
            self.window?.setFrame((NSScreen.main()?.frame)!, display: true)
        }
        else {
            self.window?.setFrame(frameOrig!, display: true)
        }
    }
    get {
        return self.window?.frame == NSScreen.main()?.frame
    }
}
</code>```

I also trapped key events on both the calling-window and fullscreen window and point them to the above function so that toggling is possible. Like so:

[in some viewcontroller]:

```<code>override func keyUp(with event: NSEvent) {
    switch event.keyCode {
    case 53:
        debugPrint("ESC - randomviewcontroller")
        (randomView.window?.windowController as! RandomWindowController).fullscreen = !(RandomView.window?.windowController as! RandomWindowController).fullscreen;
        break
    default:
        super.keyUp(with: event)
    }
}
</code>```

I think the above can be done much better & smarter... (picked up Swift a month ago...) but as the saying goes: "It worked on my computer!"

Hope it helps.

Body:
I have seen many posts on this in Obj C. Not too many in swift, and I just can't get it to work. I want to be able to make a window fullscreen on a specific NSScreen. The 'ToggleFullscreen' method isn't the best way because there aren't many options (for external displays). I tried:

    // screen is my variable already set
    outputWindow!.window!.setFrame(screen.frame, display: true, animate: true)
    outputWindow!.window!.styleMask = NSFullScreenWindowMask
    outputWindow!.window!.level = Int(CGShieldingWindowLevel())

    // the above one doesn't make it fullscreen.
    // it has a title bar and shows the menu on the screen.

    // then i tried....
    fullscreenWindow = NSWindow(contentRect: screen.frame, styleMask:NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false, screen: screen)
    fullscreenWindow.level = Int(CGShieldingWindowLevel())
    fullscreenWindow.makeKeyAndOrderFront(nil)

    //that one works on my main display (somewhat). and does nothing on externals.

One thing I noticed with making my own fullscreen is that I get stuck into it. It's not like the OS X fullscreen where you can press esc to escape it. Are there any tricks to this? Thanks

Body:
This is a pseudo answer:

[in a inherited class of NSWondowController]

var fullscreen:Bool {
    set {
        if newValue == true {

            if fullscreen == true {
                return
            }

            frameOrig = self.window?.frame
            self.window?.setFrame((NSScreen.main()?.frame)!, display: true)
        }
        else {
            self.window?.setFrame(frameOrig!, display: true)
        }
    }
    get {
        return self.window?.frame == NSScreen.main()?.frame
    }
}

I also trapped key events on both the calling-window and fullscreen window and point them to the above function so that toggling is possible. Like so:

[in some viewcontroller]:

override func keyUp(with event: NSEvent) {
    switch event.keyCode {
    case 53:
        debugPrint("ESC - randomviewcontroller")
        (randomView.window?.windowController as! RandomWindowController).fullscreen = !(RandomView.window?.windowController as! RandomWindowController).fullscreen;
        break
    default:
        super.keyUp(with: event)
    }
}

I think the above can be done much better & smarter... (picked up Swift a month ago...) but as the saying goes: "It worked on my computer!"

Hope it helps.


问:
Trouble getting total count using .Take() and .Skip()
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

```<code>public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}
</code>```

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

答:
Normally, we call them pageIndex and pageSize.

Please check pageIndex whether 0 as start index or 1 as start index depending on your requirement.

```<code>public List<Thing> GetThings(ObjectParameter[] params, int pageIndex, int pageSize)
{
    if (pageSize <= 0)
        pageSize = 1;

    if (pageIndex < 0)
        pageIndex = 0;

    var source = Context.ExecuteFunction<Something>("function", params);

    var total = source.Count();

    var things = (from t in source select new Thing { ID = t.ID })
                .Skip(pageIndex * pageSize).Take(pageSize).ToList();

    return things.ToList();
}
</code>```

Body:
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

Body:
Normally, we call them pageIndex and pageSize.

Please check pageIndex whether 0 as start index or 1 as start index depending on your requirement.

public List<Thing> GetThings(ObjectParameter[] params, int pageIndex, int pageSize)
{
    if (pageSize <= 0)
        pageSize = 1;

    if (pageIndex < 0)
        pageIndex = 0;

    var source = Context.ExecuteFunction<Something>("function", params);

    var total = source.Count();

    var things = (from t in source select new Thing { ID = t.ID })
                .Skip(pageIndex * pageSize).Take(pageSize).ToList();

    return things.ToList();
}


问:
In Rust, is Option compiled to a runtime check or an instruction jump?
In Rust, Option is defined as:

```<code>pub enum Option<T> {
    None,
    Some(T),
}
</code>```

Used like so:

```<code>fn may_return_none() -> Option<i32> {
    if is_full_moon {
        None
    } else {
        Some(1)
    }
}

fn main() {
    let optional = may_return_none();
    match optional {
        None => println!("None"),
        Some(v) => println!("Some"),
    }
}
</code>```

I'm not familiar with Rust internals, but initially I assumed it might work similar to Nullable in .NET, so the compiled logic of my above Rust code would be like so:

// occupies `sizeof(T) + 1` memory space, possibly more depending on `Bool`'s alignment, so `Nullable<Int32>` consumes 5 bytes.
struct Nullable<T> {
    Bool hasValue;
    T value;
}

Nullable<Int32> MayReturnNone() {
    if( isFullMoon )
        // as a `struct`, the Nullable<Int32> instance is returned via the stack
        return Nullable<Int32>() { HasValue = false }
    else
        return Nullable<Int32>() { HasValue = true, Value = 1 }
}

void Test() {
    Nullable<Int32> optional = may_return_none();
    if( !optional.HasValue ) println("None");
    else                     println("Some");
}
```

<p>However this isn't a zero-cost abstraction because of the space required for the <code>Bool hasValue</code> flag - and Rust makes a point of providing zero-cost abstractions.</p>

<p>I realise that <code>Option</code> could be implemented via a direct return-jump by the compiler, though it would need the exact jump-to values to be provided as arguments on the stack - as though you can push multiple return addresses:</p>

<p>(Psuedocode)</p>

```mayReturnNone(returnToIfNone, returnToIfHasValue) {

    if( isFullMoon ) {
        cleanup-current-stackframe
        jump-to returnToIfNone
    else {
        cleanup-current-stackframe
        push-stack 1
        jump-to returnToIfHasValue
    }

test() {

    mayReturnNone( instructionAddressOf( ifHasValue ), instructionAddressOf( ifNoValue ) )
ifHasValue:
    println("Some")
ifNoValue:
    println("None")
}
```

Is this how it's implemented? This approach also works for other enum types in Rust - but this specific application I've demonstrated is very brittle and breaks if you want to execute code in-between the call to mayReturnNone and the match statement, for example (as mayReturnNone will jump directly to the match, skipping intermediate instructions).

答:
Warning: this comes from the debug build, not release. See the other answer for an optimised version which behaves differently.

You can check the code on the Rust playground

The function compiles to:

```<code>    .cfi_startproc
    pushq   %rbp
.Ltmp6:
    .cfi_def_cfa_offset 16
.Ltmp7:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
.Ltmp8:
    .cfi_def_cfa_register %rbp
    subq    $16, %rsp
.Ltmp9:
    .loc    1 6 0 prologue_end
    callq   is_full_moon@PLT
    movb    %al, -9(%rbp)
    movb    -9(%rbp), %al
    testb   $1, %al
    jne .LBB1_3
    jmp .LBB1_4
.LBB1_3:
    .loc    1 7 0
    movl    $0, -8(%rbp)
    .loc    1 6 0
    jmp .LBB1_5
.LBB1_4:
    .loc    1 10 0
    movl    $1, -8(%rbp)
    movl    $1, -4(%rbp)
.LBB1_5:
    .loc    1 12 0
    movq    -8(%rbp), %rax
    addq    $16, %rsp
    popq    %rbp
    retq
.Ltmp10:
.Lfunc_end1:
    .size   _ZN8rust_out15may_return_none17hb9719b83eae05d85E, .Lfunc_end1-_ZN8rust_out15may_return_none17hb9719b83eae05d85E
    .cfi_endproc
</code>```

Which isn't really returning to different places. The space for Option<i32> contains the i32 value as well. That means your function is writing either just the None/Some marker:

```<code>movl    $0, -8(%rbp)
</code>```

Or the value as well:

```<code>movl    $1, -8(%rbp)
movl    $1, -4(%rbp)
</code>```

So I guess the answer to your question is that this:

Rust makes a point of providing zero-cost abstractions

is an assumption that doesn't apply to every single case.

Body:
In Rust, Option is defined as:

pub enum Option<T> {
    None,
    Some(T),
}

Used like so:

fn may_return_none() -> Option<i32> {
    if is_full_moon {
        None
    } else {
        Some(1)
    }
}

fn main() {
    let optional = may_return_none();
    match optional {
        None => println!("None"),
        Some(v) => println!("Some"),
    }
}

I'm not familiar with Rust internals, but initially I assumed it might work similar to Nullable in .NET, so the compiled logic of my above Rust code would be like so:

// occupies `sizeof(T) + 1` memory space, possibly more depending on `Bool`'s alignment, so `Nullable<Int32>` consumes 5 bytes.
struct Nullable<T> {
    Bool hasValue;
    T value;
}

Nullable<Int32> MayReturnNone() {
    if( isFullMoon )
        // as a `struct`, the Nullable<Int32> instance is returned via the stack
        return Nullable<Int32>() { HasValue = false }
    else
        return Nullable<Int32>() { HasValue = true, Value = 1 }
}

void Test() {
    Nullable<Int32> optional = may_return_none();
    if( !optional.HasValue ) println("None");
    else                     println("Some");
}

However this isn't a zero-cost abstraction because of the space required for the Bool hasValue flag - and Rust makes a point of providing zero-cost abstractions.

I realise that Option could be implemented via a direct return-jump by the compiler, though it would need the exact jump-to values to be provided as arguments on the stack - as though you can push multiple return addresses:

(Psuedocode)

mayReturnNone(returnToIfNone, returnToIfHasValue) {

    if( isFullMoon ) {
        cleanup-current-stackframe
        jump-to returnToIfNone
    else {
        cleanup-current-stackframe
        push-stack 1
        jump-to returnToIfHasValue
    }

test() {

    mayReturnNone( instructionAddressOf( ifHasValue ), instructionAddressOf( ifNoValue ) )
ifHasValue:
    println("Some")
ifNoValue:
    println("None")
}

Is this how it's implemented? This approach also works for other enum types in Rust - but this specific application I've demonstrated is very brittle and breaks if you want to execute code in-between the call to mayReturnNone and the match statement, for example (as mayReturnNone will jump directly to the match, skipping intermediate instructions).

Body:
Warning: this comes from the debug build, not release. See the other answer for an optimised version which behaves differently.

You can check the code on the Rust playground

The function compiles to:

    .cfi_startproc
    pushq   %rbp
.Ltmp6:
    .cfi_def_cfa_offset 16
.Ltmp7:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
.Ltmp8:
    .cfi_def_cfa_register %rbp
    subq    $16, %rsp
.Ltmp9:
    .loc    1 6 0 prologue_end
    callq   is_full_moon@PLT
    movb    %al, -9(%rbp)
    movb    -9(%rbp), %al
    testb   $1, %al
    jne .LBB1_3
    jmp .LBB1_4
.LBB1_3:
    .loc    1 7 0
    movl    $0, -8(%rbp)
    .loc    1 6 0
    jmp .LBB1_5
.LBB1_4:
    .loc    1 10 0
    movl    $1, -8(%rbp)
    movl    $1, -4(%rbp)
.LBB1_5:
    .loc    1 12 0
    movq    -8(%rbp), %rax
    addq    $16, %rsp
    popq    %rbp
    retq
.Ltmp10:
.Lfunc_end1:
    .size   _ZN8rust_out15may_return_none17hb9719b83eae05d85E, .Lfunc_end1-_ZN8rust_out15may_return_none17hb9719b83eae05d85E
    .cfi_endproc

Which isn't really returning to different places. The space for Option<i32> contains the i32 value as well. That means your function is writing either just the None/Some marker:

movl    $0, -8(%rbp)

Or the value as well:

movl    $1, -8(%rbp)
movl    $1, -4(%rbp)

So I guess the answer to your question is that this:

Rust makes a point of providing zero-cost abstractions

is an assumption that doesn't apply to every single case.


问:
How to get interface name from IPv4 ip address using only fs and bash in Linux?
How to get interface name from IPv4 ip address using only filesystem like /proc, /dev, /sys and bash? Is this possible without using the commands (such as ip, ifconfig, etc.)? I am also not able to use any packages or install any tools.

Edit:
The reason for this is I am trying to get host's interface names and ip addresses from within a Docker container. The container is mounted with host's root and has access to host's filesystem. However, since the container is in a separate namespace, ip commands (and other similar command such as ifconfig) will only return the container's network. Hence, I believe the only way of getting the host's interface names and ip addresses is through the host's root (/hostroot/proc, /hostroot/sys, etc.). Note that I cannot have the --net=host flag when starting the container (which tells the container to use the host's net namespace).

I tried finding all my network interface IP addresses (IPv4) from the /proc/net/fib_trie file. I read at https://regexit.com/3-ways-to-get-your-ip-on-a-linux-system/ which basically says that I can do cat /proc/net/fib_trie | grep -B 1 "32 host LOCAL" to find the IP addresses. I also see in https://stackoverflow.com/a/42082822 , that we can filter the fib_trie by pattern matching the string "32 host" to get the local network interface addresses. After getting the IP addresses from the above method (using the /proc/net/fib_trie), I try to match those IP address with the "destination" IP address in /proc/net/route to get the network interface name. However, my /proc/net/route contains multiple entry for some interfaces (such as enp0s3). For example, there are two enp0s3 entries with different IP addresss ("Destination column). Moreover, the network interfaces in route file does have ip close to what is indicated by the ip command but not exactly.

Is there a better way of getting the network interface name after getting the IP address from fib_trie?

Output I need will be all the host's network interface name and corresponding IPv4 IP addresses.

答:
I think you have sufficient information there. The /proc/net/route file doesn't really list addresses. It's supposed to tell you how to route packets. But you can glean information about the interfaces from it. On my system (ubuntu 14 so different interface name format but otherwise should be similar), it shows this:

```<code>Iface   Destination Gateway     Flags   RefCnt  Use Metric  Mask        MTU Window  IRTT
eth0    00000000    0100A8C0    0003    0   0   0   00000000    0   0   0
eth0    0000A8C0    00000000    0001    0   0   1   00FFFFFF    0   0   0
eth1    0028A8C0    00000000    0001    0   0   1   00FFFFFF    0   0   0
</code>```

The destination and mask fields are in hexadecimal -- and byte-reversed on little-endian machine -- and give you the range of the network. Interpretation is:

Anything destined for the 192.168.0.0/24 network (0000A8C0 + 00FFFFFF) goes to eth0 with no gateway needed (in other words, it's on the same subnet as this machine).

Anything destined for 192.168.40.0/24 (0028A8C0 + 00FFFFFF) goes to eth1 with no gateway needed.

Packets destined for any other address (00000000 + 00000000) go to the default gateway 192.168.0.1.
(Not sure; it's possible that the extra flag bit or the "metric" value in this line marks this as a default gateway. But in any case, if it doesn't have a non-zero mask or is in the 0.0.0.0 address range, it's not going to be useful for routing in the real world.)

From this I can infer that my system has IP addresses in the 192.168.0.0/24 and 192.168.40.0/24 networks. The output from the grep command on /proc/net/fib_trie shows on my system:

```<code>           |-- 127.0.0.1
              /32 host LOCAL
           |-- 192.168.0.104
              /32 host LOCAL
           |-- 192.168.40.129
              /32 host LOCAL
</code>```

So that makes it clear that my local IP addresses are 192.168.0.104 (eth0) and 192.168.40.129 (eth1). (We can ignore 127.0.0.1; it's always the loopback interface.)

Body:
I think you have sufficient information there. The /proc/net/route file doesn't really list addresses. It's supposed to tell you how to route packets. But you can glean information about the interfaces from it. On my system (ubuntu 14 so different interface name format but otherwise should be similar), it shows this:

Iface   Destination Gateway     Flags   RefCnt  Use Metric  Mask        MTU Window  IRTT
eth0    00000000    0100A8C0    0003    0   0   0   00000000    0   0   0
eth0    0000A8C0    00000000    0001    0   0   1   00FFFFFF    0   0   0
eth1    0028A8C0    00000000    0001    0   0   1   00FFFFFF    0   0   0

The destination and mask fields are in hexadecimal -- and byte-reversed on little-endian machine -- and give you the range of the network. Interpretation is:

Anything destined for the 192.168.0.0/24 network (0000A8C0 + 00FFFFFF) goes to eth0 with no gateway needed (in other words, it's on the same subnet as this machine).

Anything destined for 192.168.40.0/24 (0028A8C0 + 00FFFFFF) goes to eth1 with no gateway needed.

Packets destined for any other address (00000000 + 00000000) go to the default gateway 192.168.0.1.
(Not sure; it's possible that the extra flag bit or the "metric" value in this line marks this as a default gateway. But in any case, if it doesn't have a non-zero mask or is in the 0.0.0.0 address range, it's not going to be useful for routing in the real world.)

From this I can infer that my system has IP addresses in the 192.168.0.0/24 and 192.168.40.0/24 networks. The output from the grep command on /proc/net/fib_trie shows on my system:

           |-- 127.0.0.1
              /32 host LOCAL
           |-- 192.168.0.104
              /32 host LOCAL
           |-- 192.168.40.129
              /32 host LOCAL

So that makes it clear that my local IP addresses are 192.168.0.104 (eth0) and 192.168.40.129 (eth1). (We can ignore 127.0.0.1; it's always the loopback interface.)


问:
Find index of an element in javascript array of objects
I am new to javascript and want to find the index of the given key-value at the bottom but not able to do so. Where am i wrong? The data in the array is copied form a json file which is valid as checked on jsonlint.

var productArray=[
{
 "name1":"Electronics",
 "id1":{
         "products1":{
                   "id":1.1,
                   "name":"Microsoft Keyboard",
                   "description":"good keyboard",
                   "rating":3,
                   "price":500,
                   "freeDeliv":true,
                   "seller":"MS",
                   "quanAvl":10
                     },
         "products2":{
                   "id":1.2,
                   "name":"ASUS phone",
                   "description":"good phone",
                   "rating":4,
                   "price":10000,
                   "freeDeliv":true,
                   "seller":"ASUS",
                   "quanAvl":10
                     },
         "products3":{
                   "id":1.3,
                   "name":"iPhone",
                   "description":"good phone",
                   "rating":3,
                   "price":50000,
                   "freeDeliv":false,
                   "seller":"Apple",
                   "quanAvl":100
                     }
       },

 "name2":"Clothing",
 "id2":{
         "products4":{
                   "id":2.1,
                   "name":"Jeans",
                   "description":"good Jeans",
                   "rating":3,
                   "price":800,
                   "freeDeliv":true,
                   "seller":"Levis",
                   "quanAvl":100
                     },
         "products5":{
                   "id":2.2,
                   "name":"TShirt",
                   "description":"good TShirt",
                   "rating":4,
                   "price":1000,
                   "freeDeliv":true,
                   "seller":"Peter",
                   "quanAvl":1000
                     },
         "products6":{
                   "id":2.3,
                   "name":"Sherwani",
                   "description":"very good",
                   "rating":4,
                   "price":50000,
                   "freeDeliv":false,
                   "seller":"Maanyavar",
                   "quanAvl":1000
                     }

}},

];

var display=function(productArray,prodKey,value){
 for(x in productArray)
 {
  if(productArray[x][prodKey]==value)
  {
   console.log(x);
  }
  else{
   alert("Not Found");
  }
 }
}
display(productArray,"name","Sherwani");```

答:
Name you are looking for in your example is one level deeper. This should work:</p>

```<code>var display = function(productArray, prodKey, value){
    for (x in productArray) {
        for (prod in productArray[x]) {
            if (productArray[x][prod][prodKey] == value) {
                console.log(x);
            } else {
                alert("Not Found");
            }
        }
    }
}
</code>```

Body:
Name you are looking for in your example is one level deeper. This should work:

var display = function(productArray, prodKey, value){
    for (x in productArray) {
        for (prod in productArray[x]) {
            if (productArray[x][prod][prodKey] == value) {
                console.log(x);
            } else {
                alert("Not Found");
            }
        }
    }
}


问:
Vuejs global function with Google Auth Signin
I am using vuejs 2 and I am having issues with using the Google auth signin.

I successfully setup and got the sign out and user profile functions working using vue:

```<code>export default {

  data() {
    return {
      user: null
    };
  },

  methods: {
    getUserProfile() {
          const profile = gapi.auth2.currentUser.get().getBasicProfile();

          console.log(profile.getIdToken());
      },

      signOut() {
          const auth2 = gapi.auth2.getAuthInstance();

          auth2.signOut().then(function () {
              console.log('user signed out');
          });
      }
  },
};
</code>```

My main issue here is the onSignIn(googleUser) function from

The data-onsuccess="onSignIn" is looking for a js function outside the vue instance.
I tried adding the onSignIn(googleUser) function in my HTML file like:

```<code><script>
    function onSignIn(googleUser) {
        const auth2 = gapi.auth2.init();

        if (auth2.isSignedIn.get()) {
            const profile = auth2.currentUser.get().getBasicProfile();

            console.log(profile.getName());
            console.log(googleUser.getAuthResponse().id_token);
            console.log(googleUser.getAuthResponse().uid);
            console.log(auth2.currentUser.get().getId());
        }
    }
</script>
</code>```

This works as expected, but I wanted to know if it would be possible to add this in my vue file instead of a native javascript way, since inside this function, I will be calling other vue methods.

Or is there a way where I could add the onSignIn(googleUser) function in vue and then call it when Google Auth finishes?

答:
The solution here is to use gapi.signin2.render to render the sign-in button inside your component's mounted hook

```<code><template>
  <div id="google-signin-btn"></div>
</template>

<script>
export default {
  methods: {
    onSignIn (user) {
      // do stuff, for example
      const profile = user.getBasicProfile()
    }
  },
  mounted() {
    gapi.signin2.render('google-signin-btn', { // this is the button "id"
      onsuccess: this.onSignIn // note, no "()" here
    })
  }
}
</script>
</code>```

See https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid_options

Body:
I am using vuejs 2 and I am having issues with using the Google auth signin.

I successfully setup and got the sign out and user profile functions working using vue:

export default {

  data() {
    return {
      user: null
    };
  },

  methods: {
    getUserProfile() {
          const profile = gapi.auth2.currentUser.get().getBasicProfile();

          console.log(profile.getIdToken());
      },

      signOut() {
          const auth2 = gapi.auth2.getAuthInstance();

          auth2.signOut().then(function () {
              console.log('user signed out');
          });
      }
  },
};

My main issue here is the onSignIn(googleUser) function from

The data-onsuccess="onSignIn" is looking for a js function outside the vue instance.
I tried adding the onSignIn(googleUser) function in my HTML file like:

This works as expected, but I wanted to know if it would be possible to add this in my vue file instead of a native javascript way, since inside this function, I will be calling other vue methods.

Or is there a way where I could add the onSignIn(googleUser) function in vue and then call it when Google Auth finishes?

Body:
The solution here is to use gapi.signin2.render to render the sign-in button inside your component's mounted hook

<template>
  <div id="google-signin-btn"></div>
</template>

<script>
export default {
  methods: {
    onSignIn (user) {
      // do stuff, for example
      const profile = user.getBasicProfile()
    }
  },
  mounted() {
    gapi.signin2.render('google-signin-btn', { // this is the button "id"
      onsuccess: this.onSignIn // note, no "()" here
    })
  }
}
</script>

See https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid_options

ContentLicense: CC BY-SA 4.0


问:
Cloudera Manager : Failed to start service YARN (MR2 Included) , Failed to start Resource manager

Error starting ResourceManager
  java.lang.NullPointerException
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:188)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:193)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at >org.apache.hadoop.yarn.proto.YarnServerResourceManagerRecoveryProtos$ApplicationA>ttemptStateDataProto.parseFrom(YarnServerResourceManagerRecoveryProtos.java:2470)
  Failed to load/recover state
  java.lang.NullPointerException
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:188)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:193)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)

答:
Did you configure the following in yarn-site.xml ?

yarn.resourcemanager.hostname
yarn.resourcemanager.address


问:
What Wordpress Function can I use for A search query like this?
I want to output the URL value from my database base on the "Area".

```<code>$the_query = $wpdb->get_results("SELECT `URL`FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'");
</code>```

Do you know what function I can use for this? $wpdb->get_results don't work.

答:
There is error in your SQL Query,
Use this code to see error.

```<code>$the_query = $wpdb->get_results("SELECT `URL`FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'") or die(mysql_error());
</code>```

Here is corrected SQL Query and should look like

```<code>"SELECT `URL` FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'"
</code>```

There should be space between 'URL'FROM

Body:
I want to output the URL value from my database base on the "Area".

$the_query = $wpdb->get_results("SELECT `URL`FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'");

Do you know what function I can use for this? $wpdb->get_results don't work.

Body:
There is error in your SQL Query,
Use this code to see error.

$the_query = $wpdb->get_results("SELECT `URL`FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'") or die(mysql_error());

Here is corrected SQL Query and should look like

"SELECT `URL` FROM  `wp_nearby_locations` WHERE  `Area` =  'Area Name'"

There should be space between 'URL'FROM


问:
UI is not updating with NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier
I am downloading hundreds of files with NSURLSessionConfiguration. I am updating a progress label for each downloaded file, from method

```<code> -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location.
</code>```

Suddenly it stopped updating progress label. I have tried performSelectorOnMainThread,dispatch_async(dispatch_get_main_queue() but to no avail.

What could be wrong? How can I update UI from didFinishDownloadingToURL method?

Any help would be appreciated. Thanks

答:
Does it run on main thread?

The most reliable solution for UIView is

```<code>[View performSelectorOnMainThread:@selector(Update:) withObject: ProgressObj waitUntilDone:FALSE];
</code>```

It will guarantee that the UI update is being executed on correct thread. If you are using Core Graphics - keep Context pointer as your class variable. However, I prefer CALayer object for such kind manipulations

Body:
I am downloading hundreds of files with NSURLSessionConfiguration. I am updating a progress label for each downloaded file, from method

 -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location.

Suddenly it stopped updating progress label. I have tried performSelectorOnMainThread,dispatch_async(dispatch_get_main_queue() but to no avail.

What could be wrong? How can I update UI from didFinishDownloadingToURL method?

Any help would be appreciated. Thanks

Body:
Does it run on main thread?

The most reliable solution for UIView is

[View performSelectorOnMainThread:@selector(Update:) withObject: ProgressObj waitUntilDone:FALSE];

It will guarantee that the UI update is being executed on correct thread. If you are using Core Graphics - keep Context pointer as your class variable. However, I prefer CALayer object for such kind manipulations


问:
how to use rank on rows return from Left Outer join on inner select query in oracle?
Hi All I have below 3 tables

```<code> Table1
 -------
 EMP001

 table2: Emp     Date1     Date2
 ----------------------------------
        EMP001  01/01/12  12/31/12
        EMP001  01/01/13  12/31/13
        EMP001  01/01/14  12/31/14

table3: Emp     Date1      Date2
-----------------------------------
       EMP001   01/01/12  12/31/15
       EMP001   01/01/13  12/31/15
</code>```

Here table3 has overlapping span dates which is a bad data.

when i join

```<code> select * from
 table1 left outer join table2
 on table1.emp = table2.emp
 left outer join table3
 on table1.emp = table3.emp
 and table2.date1 between table3.date1 and table3.date2
</code>```

Above query returns 4 rows as table3 has overlapping spans.

```<code> EMP     Table2.Date1   Table2.Date2      Table3.Date1    Table3.Date2
 ----------------------------------------------------------------------
 EMP001  01/01/12        12/31/12         01/01/12       12/31/15
 EMP001  01/01/13        12/31/13         01/01/12       12/31/15
 EMP001  01/01/13        12/31/13         01/01/13       12/31/15
 EMP001  01/01/14        12/31/14
</code>```

Here I need only one row for each row of table2. From table3 I need data as max(date1) and table2.date1 between table3.date1 and table3.date1

I can't join table 3 as below as costs huge for performance.

```<code> select * from
 table1
 left outer join table2
 on table2.emp = table2.emp
 left outer join
 (select table2.date1 as t2date1, table3.*, rom_number() over (partition by table3.emp, table2.date1) as Rank
 from table3,table2
 where table2.emp = table3.emp
 and table2.date1 between table3.date1 and table3.date2) tbl3
 on table1.emp = tbl3.emp
 and table2.date1 = tbl3.t2date1
</code>```

Is there a way to avoid 2 tables join inside inner select query and get the single row for table2 dates.
Thanks in advance.

答:
Please try this. Sorry for syntax errors if any.
Place primary key fields of table1 and table2 instead of table1.rowid, table2.rowid:

```<code>select
  emp, t2_date1, t2_date2, t3_date1
from (
    select
      table1.emp,
      table2.Date1 as t2_date1,
      table2.Date2 as t2_date2,
      table3.Date1 as t3_date1,
      row_number() over (partition by table1.rowid, table2.rowid order by t3.date1 desc) as rn
    from
     table1
     left outer join table2
     on table1.emp = table2.emp
     left outer join table3
     on table1.emp = table3.emp
     and table2.date1 between table3.date1 and table3.date2
)
where rn = 1
;
</code>```

Body:
Hi All I have below 3 tables

 Table1
 -------
 EMP001

 table2: Emp     Date1     Date2
 ----------------------------------
        EMP001  01/01/12  12/31/12
        EMP001  01/01/13  12/31/13
        EMP001  01/01/14  12/31/14

table3: Emp     Date1      Date2
-----------------------------------
       EMP001   01/01/12  12/31/15
       EMP001   01/01/13  12/31/15

Here table3 has overlapping span dates which is a bad data.

when i join

 select * from
 table1 left outer join table2
 on table1.emp = table2.emp
 left outer join table3
 on table1.emp = table3.emp
 and table2.date1 between table3.date1 and table3.date2

Above query returns 4 rows as table3 has overlapping spans.

 EMP     Table2.Date1   Table2.Date2      Table3.Date1    Table3.Date2
 ----------------------------------------------------------------------
 EMP001  01/01/12        12/31/12         01/01/12       12/31/15
 EMP001  01/01/13        12/31/13         01/01/12       12/31/15
 EMP001  01/01/13        12/31/13         01/01/13       12/31/15
 EMP001  01/01/14        12/31/14

Here I need only one row for each row of table2. From table3 I need data as max(date1) and table2.date1 between table3.date1 and table3.date1

I can't join table 3 as below as costs huge for performance.

 select * from
 table1
 left outer join table2
 on table2.emp = table2.emp
 left outer join
 (select table2.date1 as t2date1, table3.*, rom_number() over (partition by table3.emp, table2.date1) as Rank
 from table3,table2
 where table2.emp = table3.emp
 and table2.date1 between table3.date1 and table3.date2) tbl3
 on table1.emp = tbl3.emp
 and table2.date1 = tbl3.t2date1

Is there a way to avoid 2 tables join inside inner select query and get the single row for table2 dates.
Thanks in advance.

Body:
Please try this. Sorry for syntax errors if any.
Place primary key fields of table1 and table2 instead of table1.rowid, table2.rowid:

select
  emp, t2_date1, t2_date2, t3_date1
from (
    select
      table1.emp,
      table2.Date1 as t2_date1,
      table2.Date2 as t2_date2,
      table3.Date1 as t3_date1,
      row_number() over (partition by table1.rowid, table2.rowid order by t3.date1 desc) as rn
    from
     table1
     left outer join table2
     on table1.emp = table2.emp
     left outer join table3
     on table1.emp = table3.emp
     and table2.date1 between table3.date1 and table3.date2
)
where rn = 1
;


问:
How to make a class that returns a child from the hierarchy?
I'm trying to make a class find the type of the object with which it was initialized and I want it to become the object class that corresponds to the type of the object 'typ' that was sent in.

So if if were to do something like the following example, I'd like the variable 'this' to be an instance of TypeA.

How would one go about that?

```<code>class Master():
    def __init__(self, typ):
        if typ == 'a':
            return TypeA()
        else:
            return  TypeB()

def TypeA():
    def  __init__(self):
        pass

    def boop():
        print "type A"

def TypeB():
    def  __init__(self):
            pass

    def meep():
        print "type B"

this = Master('a')
this.boop()
</code>```

(if this means anything to anyone, I want to emulate the behaviour that PyMel has when you create an object with pm.PyNode('object_name'), in which pm.PyNode gives you the lowest child in the hierarchy.)

答:
it seems that you want a factory. maybe something among these lines:

```<code>class Master(object):  # i would rather do a plain function but i'll limit to mimic your lines.

    @staticmethod
    def factory(typ, *args, **kwargs):
        mapping = {
            'a': TypeA,
            'b': TypeB
        }
        return mapping[typ](*args, **kwargs)
</code>```

so then you can call it:

```<code>this = Master.factory('a')
print this

$ <__main__.TypeA object at 0x7f6cbbec65d0>
</code>```

Body:
I'm trying to make a class find the type of the object with which it was initialized and I want it to become the object class that corresponds to the type of the object 'typ' that was sent in.

So if if were to do something like the following example, I'd like the variable 'this' to be an instance of TypeA.

How would one go about that?

class Master():
    def __init__(self, typ):
        if typ == 'a':
            return TypeA()
        else:
            return  TypeB()

def TypeA():
    def  __init__(self):
        pass

    def boop():
        print "type A"

def TypeB():
    def  __init__(self):
            pass

    def meep():
        print "type B"

this = Master('a')
this.boop()

(if this means anything to anyone, I want to emulate the behaviour that PyMel has when you create an object with pm.PyNode('object_name'), in which pm.PyNode gives you the lowest child in the hierarchy.)

Body:
it seems that you want a factory. maybe something among these lines:

class Master(object):  # i would rather do a plain function but i'll limit to mimic your lines.

    @staticmethod
    def factory(typ, *args, **kwargs):
        mapping = {
            'a': TypeA,
            'b': TypeB
        }
        return mapping[typ](*args, **kwargs)

so then you can call it:

this = Master.factory('a')
print this

$ <__main__.TypeA object at 0x7f6cbbec65d0>


问:
C, HTTP 1.1 and Socket Send troubles
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

```<code>int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}
</code>```

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

```<code>void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}
</code>```

If I were to add

```<code>Send("Oh end of HTML Sending eh?");
</code>```

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

```<code>SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");
</code>```

This should result in the Browser showing:

HAaaaii!!lolwut?

答:
Do you add newline after each header?

You can test your application by using telnet, of course and see what's the output.

No, it's not required to have only one send. Assume streaming a 2GB file. It's simply not logical.

OwnerDisplayName: Filip Ekberg

Title: C, HTTP 1.1 and Socket Send troubles

Body:
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}

If I were to add

Send("Oh end of HTML Sending eh?");

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");

This should result in the Browser showing:

HAaaaii!!lolwut?

OwnerDisplayName: Mehrdad Afshari


问:
Navigating forms using HTML?
is there a way to navigate to another form using HTML ?

for example, a link in side my innerHTML

```<code><a href="goto form 2 here">Form2</a>
</code>```

it is just HTML i was hardcoding into the innerHTML property of a TW3ScrollControl. Some of the HTML is static, some is dynamic data (e.g. question & answer) I get from my JSON file

for example

```<code>Who is  the president of the United States?

     Hillary Clinton
     Bernie Sanders
     Joseph Biden
     Donald Trump
</code>```

so, giving something like this off the top of my head, how would on do a GotoForm if one of these names were clicked?

```<code><div>
    <p>Who is  the president of the United States?</p>
    <br>
    <center>
     <A href=""> Hillary Clinton </A><br>
     <A href=""> Bernie Sanders </A<br>
     <A href=""> Joseph Biden </A<br>
     <A href=""> Donald Trump </A<br>
    </center>
</div>
</code>```

thanx

答:
with a little help from facebook friend :) I was able to come up with the following</p>

```<code>var i: integer;
      IdStr: String;
begin
 fQuestion.content.InnerHTML:= '<div style="text-align: center; position: relative;">' +
  '<br><center><p>' + fQuestions.questions[fIndex].question + '</p></center><br>' +
   '<center>' +
     '<A id="answer1" href="">' + fQuestions.questions[fIndex].answers[0] + '</A><br>' +
     '<A id="answer2" href="">' + fQuestions.questions[fIndex].answers[1] + '</A><br>' +
     '<A id="answer3" href="">' + fQuestions.questions[fIndex].answers[2] + '</A><br>' +
     '<A id="answer4" href="">' + fQuestions.questions[fIndex].answers[3] + '</A><br>' +
    '</center>' +
  '</div>';

  for i:= 1 to 4 do
  begin
   IdStr:= 'answer' + intToStr(i);
    var h:= BrowserAPI.Document.getElementById(idStr);
    if (h) then
    begin
     h.onclick := procedure (ev: variant)
     begin
       //do something here
     end;
    end;
 end;
end;
</code>```

Title: Navigating forms using HTML?

Body:
is there a way to navigate to another form using HTML ?

for example, a link in side my innerHTML

Form2

it is just HTML i was hardcoding into the innerHTML property of a TW3ScrollControl. Some of the HTML is static, some is dynamic data (e.g. question & answer) I get from my JSON file

for example

Who is  the president of the United States?

     Hillary Clinton
     Bernie Sanders
     Joseph Biden
     Donald Trump

so, giving something like this off the top of my head, how would on do a GotoForm if one of these names were clicked?

Who is  the president of the United States?

      Hillary Clinton

      Bernie Sanders </A

      Joseph Biden </A

      Donald Trump </A

thanx

Body:
with a little help from facebook friend :) I was able to come up with the following

var i: integer;
      IdStr: String;
begin
 fQuestion.content.InnerHTML:= '<div style="text-align: center; position: relative;">' +
  '<br><center><p>' + fQuestions.questions[fIndex].question + '</p></center><br>' +
   '<center>' +
     '<A id="answer1" href="">' + fQuestions.questions[fIndex].answers[0] + '</A><br>' +
     '<A id="answer2" href="">' + fQuestions.questions[fIndex].answers[1] + '</A><br>' +
     '<A id="answer3" href="">' + fQuestions.questions[fIndex].answers[2] + '</A><br>' +
     '<A id="answer4" href="">' + fQuestions.questions[fIndex].answers[3] + '</A><br>' +
    '</center>' +
  '</div>';

  for i:= 1 to 4 do
  begin
   IdStr:= 'answer' + intToStr(i);
    var h:= BrowserAPI.Document.getElementById(idStr);
    if (h) then
    begin
     h.onclick := procedure (ev: variant)
     begin
       //do something here
     end;
    end;
 end;
end;


问:
PyCharm not displaying Google style docstrings in tooltips
I would like to use Google style docstrings for Python. I've specified that Pycharm should expect Google docstrings:

For some reason PyCharm will not show my docstrings in tooltips:

I'm referencing the examples here for the proper Google docstring format: http://www.sphinx-doc.org/en/stable/ext/example_google.html

It's unclear to me why PyCharm is not displaying my docstrings.

答:
After contacting JetBrains they notified me that this was a known problem: https://youtrack.jetbrains.com/oauth?state=%2Fissue%2FPY-22445

The solution is to update the "pockets" package.

They plan to fix in next release.

Issue is due to using python version 3.6!