问:
Class to manipulate bits c++
I am trying to understand what the following classes does, in particular function func. I looked up what each line roughly does. It's definitely manipulating bits by shifting them, but I can't understand the big picture.

```<code> template<class T>
    class classX
    {
        public:
            classX(int _z) : z(_z){}

            size_t operator()(T x) const
            {
                union { T a; size_t b; } u;
                u.b = 0;
                u.a = x;

                unsigned char rng1 = cvRNG(z*(z+1) + u.b);// cvRNG returns the input if number>0, else return  (uint64_t)(int64_t)-1
                return (size_t)( cvRandReal(&rng1)*(double)(UINT32_MAX) );// cvRandReal returns random floating-point number between 0 and 1
            }

        private:
            int  z;
    };

template<class T,class H=classX<T>>
class classY
{
    public:
    classY(int nb, int nh)
      : l_(0),c_(0),arr_(0)
    {
        b_   = nb;
        l_   = nb / 8 + 1;
        arr_ = new unsigned char[l_];

        for(int i=1; i<=nh; i++)
            ff.push_back( H(i) );
    }
void func(const T& x)

        {
            for(size_t j=0; j<ff.size(); j++){
                size_t key = ff[j](x) % b_;
            arr_[ key / 8 ] |= (unsigned char)(1 << (key % 8));
        }
        c_++;
    }
bool func2(const T& x) const
{
    size_t z = 0;
    for(size_t j=0; j<ff.size(); j++){
        size_t key  = ff[j](x) % b_;
        z += (arr_[ key / 8 ] & (unsigned char)(1 << (key % 8)) ) > 0 ? 1 : 0;
    }
    return ( z == ff.size() );
}
private:
        unsigned char*    arr_;
        int               l_;
        int               c_;
        size_t            b_;
        std::vector<H>    ff;
    };
</code>```

I am trying to understand what the following classes does, in particular function func. I looked up what each line roughly does. It's definitely manipulating bits by shifting them.

答:
This code build a bitmap hash for the hash set.

```<code>// Calc Hash for a class
template<class T>
    class classX
    {
        public:
            classX(int _z) : z(_z){}   // construct hash

            // Method returns a hashcode for x based on seed z.
            size_t operator()(T x) const
            {
                // It is a nice try to read first 4 bytes form object x.
                // union share the memory for a & b
                union { T a; size_t b; } u;
                u.b = 0; // just clean the memory
                u.a = x; // since u.a share the memory with u.b, this line init u.b with first 4 bytes of x.
                // If x is an instance if class with virtual methods, it will be pointer to vtable (same for all instances of the same calss).
                //  If x is a struct, it will be fist 4 bytes of x data.
                // Most likely x is must be a struct.

                // rnd1 is a base seed for the cvRandReal function. Note, u.b not a 0!
                unsigned char rng1 = cvRNG(z*(z+1) + u.b);// cvRNG returns the input if number>0, else return  (uint64_t)(int64_t)-1
                // if rng1 a seed, line below just a hash function
                return (size_t)( cvRandReal(&rng1)*(double)(UINT32_MAX) );// cvRandReal returns random floating-point number between 0 and 1
            }

        private:
            int  z; // base seed
    };

// Bitmap Hash for Hash Set with Objects T, H - hash functions
template<class T,class H=classX<T>>
class classY
{
    public:
    // nb: size of bitmap hash in bits
    // nh: number of hash functions.
    // Both this number suppose to reduce probability of hash collision
    classY(int nb, int nh)
      : l_(0),c_(0),arr_(0)
    {
        b_   = nb;    // size of bitmap hash in bits
        l_   = nb / 8 + 1; // size of bitmap hash in bytes
        arr_ = new unsigned char[l_];  // bitmap array - hash data

        // init hash functions. Start from 1, because 0 seeder is not good.
        for(int i=1; i<=nh; i++)
            ff.push_back( H(i) );
    }
    // Add x into the hash bitmap (add x to the set)
    void func(const T& x)
    {
        // for all hash fucntions
        for(size_t j=0; j<ff.size(); j++)
        {
                size_t key = ff[j](x) % b_; // calc hash code and normalize it by number if bits in the map
                // key - is a bit number in the bitmap
                // Just a rise a key bit in the bitmap
                // key / 8  - byte number
                // key % 8  - bit number
                arr_[ key / 8 ] |= (unsigned char)(1 << (key % 8));
        }
        c_++; // increase number of object that was processed to build a hash
    }
    // Check if X into the set (Check if X was added with func before)
    // It return False if X wasn't added
    // It return True of X probably be added (high probability that X was added, but not 100%)
    bool func2(const T& x) const
    {
        size_t z = 0; // number of passed hash tests
        for(size_t j=0; j<ff.size(); j++){
            size_t key  = ff[j](x) % b_;   // calc hash code and normalize it by number if bits in the map, like in func()

            // Increment z (number of passed hash tests) if key bit is in the bitmask
            z += (arr_[ key / 8 ] & (unsigned char)(1 << (key % 8)) ) > 0 ? 1 : 0;
        }
        return ( z == ff.size() ); // return true if all tests from hash functions was passed.
    }
private:
        unsigned char*    arr_; // hash bitmap
        int               l_;// size of bitmap in bytes
        int               c_;// number of object that was processed to build a hash
        size_t            b_;// size of bitmap in bits
        std::vector<H>    ff; // hash functions
    };
</code>```

Title: Class to manipulate bits c++

Body:
I am trying to understand what the following classes does, in particular function func. I looked up what each line roughly does. It's definitely manipulating bits by shifting them, but I can't understand the big picture.

 template<class T>
    class classX
    {
        public:
            classX(int _z) : z(_z){}

            size_t operator()(T x) const
            {
                union { T a; size_t b; } u;
                u.b = 0;
                u.a = x;

                unsigned char rng1 = cvRNG(z*(z+1) + u.b);// cvRNG returns the input if number>0, else return  (uint64_t)(int64_t)-1
                return (size_t)( cvRandReal(&rng1)*(double)(UINT32_MAX) );// cvRandReal returns random floating-point number between 0 and 1
            }

        private:
            int  z;
    };

template<class T,class H=classX<T>>
class classY
{
    public:
    classY(int nb, int nh)
      : l_(0),c_(0),arr_(0)
    {
        b_   = nb;
        l_   = nb / 8 + 1;
        arr_ = new unsigned char[l_];

        for(int i=1; i<=nh; i++)
            ff.push_back( H(i) );
    }
void func(const T& x)

        {
            for(size_t j=0; j<ff.size(); j++){
                size_t key = ff[j](x) % b_;
            arr_[ key / 8 ] |= (unsigned char)(1 << (key % 8));
        }
        c_++;
    }
bool func2(const T& x) const
{
    size_t z = 0;
    for(size_t j=0; j<ff.size(); j++){
        size_t key  = ff[j](x) % b_;
        z += (arr_[ key / 8 ] & (unsigned char)(1 << (key % 8)) ) > 0 ? 1 : 0;
    }
    return ( z == ff.size() );
}
private:
        unsigned char*    arr_;
        int               l_;
        int               c_;
        size_t            b_;
        std::vector<H>    ff;
    };

I am trying to understand what the following classes does, in particular function func. I looked up what each line roughly does. It's definitely manipulating bits by shifting them.

Body:
This code build a bitmap hash for the hash set.

// Calc Hash for a class
template<class T>
    class classX
    {
        public:
            classX(int _z) : z(_z){}   // construct hash

            // Method returns a hashcode for x based on seed z.
            size_t operator()(T x) const
            {
                // It is a nice try to read first 4 bytes form object x.
                // union share the memory for a & b
                union { T a; size_t b; } u;
                u.b = 0; // just clean the memory
                u.a = x; // since u.a share the memory with u.b, this line init u.b with first 4 bytes of x.
                // If x is an instance if class with virtual methods, it will be pointer to vtable (same for all instances of the same calss).
                //  If x is a struct, it will be fist 4 bytes of x data.
                // Most likely x is must be a struct.

                // rnd1 is a base seed for the cvRandReal function. Note, u.b not a 0!
                unsigned char rng1 = cvRNG(z*(z+1) + u.b);// cvRNG returns the input if number>0, else return  (uint64_t)(int64_t)-1
                // if rng1 a seed, line below just a hash function
                return (size_t)( cvRandReal(&rng1)*(double)(UINT32_MAX) );// cvRandReal returns random floating-point number between 0 and 1
            }

        private:
            int  z; // base seed
    };

// Bitmap Hash for Hash Set with Objects T, H - hash functions
template<class T,class H=classX<T>>
class classY
{
    public:
    // nb: size of bitmap hash in bits
    // nh: number of hash functions.
    // Both this number suppose to reduce probability of hash collision
    classY(int nb, int nh)
      : l_(0),c_(0),arr_(0)
    {
        b_   = nb;    // size of bitmap hash in bits
        l_   = nb / 8 + 1; // size of bitmap hash in bytes
        arr_ = new unsigned char[l_];  // bitmap array - hash data

        // init hash functions. Start from 1, because 0 seeder is not good.
        for(int i=1; i<=nh; i++)
            ff.push_back( H(i) );
    }
    // Add x into the hash bitmap (add x to the set)
    void func(const T& x)
    {
        // for all hash fucntions
        for(size_t j=0; j<ff.size(); j++)
        {
                size_t key = ff[j](x) % b_; // calc hash code and normalize it by number if bits in the map
                // key - is a bit number in the bitmap
                // Just a rise a key bit in the bitmap
                // key / 8  - byte number
                // key % 8  - bit number
                arr_[ key / 8 ] |= (unsigned char)(1 << (key % 8));
        }
        c_++; // increase number of object that was processed to build a hash
    }
    // Check if X into the set (Check if X was added with func before)
    // It return False if X wasn't added
    // It return True of X probably be added (high probability that X was added, but not 100%)
    bool func2(const T& x) const
    {
        size_t z = 0; // number of passed hash tests
        for(size_t j=0; j<ff.size(); j++){
            size_t key  = ff[j](x) % b_;   // calc hash code and normalize it by number if bits in the map, like in func()

            // Increment z (number of passed hash tests) if key bit is in the bitmask
            z += (arr_[ key / 8 ] & (unsigned char)(1 << (key % 8)) ) > 0 ? 1 : 0;
        }
        return ( z == ff.size() ); // return true if all tests from hash functions was passed.
    }
private:
        unsigned char*    arr_; // hash bitmap
        int               l_;// size of bitmap in bytes
        int               c_;// number of object that was processed to build a hash
        size_t            b_;// size of bitmap in bits
        std::vector<H>    ff; // hash functions
    };


来源: stackexchange

问:
Transform Angular 2 Observable Into a non observable
I am using 6.3 of NGX Data Table which cannot bind to an observable collection.  How do I transform an Angular Observable Collection into a regular non-observable Array?

Here is what I have for the service:

```<code>private _productUrl = '../../api/todos/todos.json';

constructor(private _http: Http) { }

getToDos(): Observable<IToDo[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IToDo[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}
</code>```

Here is what I have for the component.ts.  It gives me an error on the foreach loop: Cannot read property 'length' of undefined

```<code>ngOnInit() {
    this._toDoService.getToDos()
        .subscribe(
          toDos => this.toDos = toDos,
          error => this.errorMessage = <any>error);

    this.rows = this.transform(this.toDos);
}

transform(source: IToDo[]): IToDo[] {
    let dest: IToDo[] = [];

    for (let sourceItem of source)
    {
      let destItem: IToDo = {
        toDoId: sourceItem.toDoId,
        name: sourceItem.name,
        priority: sourceItem.priority,
        dueDate: sourceItem.dueDate,
        completed: sourceItem.completed
      };
      dest.push(destItem);
    }

    return dest;
}
</code>```

答:
You can also unwrap the input Observable using the async pipe.</p>

```<code> <ngx-datatable
        class="material"
        [rows]="todos | async"
        ......
 </ngx-datatable>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using 6.3 of NGX Data Table which cannot bind to an observable collection.  How do I transform an Angular Observable Collection into a regular non-observable Array?

Here is what I have for the service:

private _productUrl = '../../api/todos/todos.json';

constructor(private _http: Http) { }

getToDos(): Observable<IToDo[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IToDo[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

Here is what I have for the component.ts.  It gives me an error on the foreach loop: Cannot read property 'length' of undefined

ngOnInit() {
    this._toDoService.getToDos()
        .subscribe(
          toDos => this.toDos = toDos,
          error => this.errorMessage = <any>error);

    this.rows = this.transform(this.toDos);
}

transform(source: IToDo[]): IToDo[] {
    let dest: IToDo[] = [];

    for (let sourceItem of source)
    {
      let destItem: IToDo = {
        toDoId: sourceItem.toDoId,
        name: sourceItem.name,
        priority: sourceItem.priority,
        dueDate: sourceItem.dueDate,
        completed: sourceItem.completed
      };
      dest.push(destItem);
    }

    return dest;
}

Body:
You can also unwrap the input Observable using the async pipe.

 <ngx-datatable
        class="material"
        [rows]="todos | async"
        ......
 </ngx-datatable>


问:
Export individual cell in IPython/Jupyter notebook
I am able to export the entire notebook as HTML, but I would like to export just a single cell, together with its output.

Is there some way of doing this?

答:
One way to do this is to use a custom preprocessor.

I explain how to do this briefly in response to Simple way to choose which cells to run in ipython notebook during run all.

To summarize: you can extend nbconvert.preprocessors.ExecutePreprocessor to create a preprocessor that checks cell metadata to determine whether that cell should be executed and/or output.

I use Jupyter Notebooks for report generation all the time, so I wrote a collection of custom processors to extend nbconvert behavior:

meta-language to determine what cells get executed and included in the final report (if/else logic on entire notebook sections)

executing code in markdown cells

removing code cells from output.

taking input arguments from the command line

I haven't had time to wrap these in an distributable extension, but you can see the code here: https://gist.github.com/brazilbean/3ebb31324f6dad212817b3663c7a0219.

Please feel free to use/modify/do-great-things with these examples. :)


问:
Disable next page on uiGrid
I am using external pagination with ui-grid and angularjs.

The server has 70 items mocked at the moment, but I will not know the items count from the server.
The pageSize is set to 50.

So it should have 2 pages (one with 50 items on it and one with 20).

The button for next page is NOT disabled on the second page but on the third one when there are no items in the grid to show.

I would like it disabled on the second page!

Link to the plunk: http://plnkr.co/edit/OuM8lN0R06Xudn1frLax?p=preview

app.js

```<code>var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.pagination']);

app.service('foo', ['$q', function ($q) {
    var items = [];
    for (var i = 0; i < 70; i++) {
        items.push({
            "firstName": "firstName" + i,
            "lastName": "lastName" + i,
            "company": "company" + i,
            "employed": i % 4 === 0
        });
    }

    this.bar = function (page, pageSize) {
        var deferred = $q.defer();

        var start = (page - 1) * pageSize;
        deferred.resolve(items.slice(start, start + pageSize));

        return deferred.promise;
    };

    return this;
}]);

app.controller('MainCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', 'foo', function ($scope, $http, $log, $timeout, uiGridConstants, foo) {
    var paginationOptions = {
        pageNumber: 1,
        pageSize: 50,
        sort: null
    };

    $scope.selectedIds = [];

    $scope.gridOptions = getOptions();

    function getOptions() {
        return {
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 2,

            enableRowSelection: true,
            enableFullRowSelection: true,
            multiSelect: true,

            paginationPageSizes: [50, 100],
            paginationPageSize: 50,
            useExternalPagination: true,

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                getPage(1, 50);

                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage;
                    paginationOptions.pageSize = pageSize;
                    getPage(newPage, pageSize);
                });
            }
        };
    }

    function getPage(page, pageSize) {
        foo.bar(page, pageSize)
            .then(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.totalItems = undefined;
            });
    }

    getPage(1, 50);
}]);
</code>```

index.html

```<code><!doctype html>
<html ng-app="app">

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-touch.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
    <script src="http://ui-grid.info/release/ui-grid.js"></script>
    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">
</head>

<body>

    <div ng-controller="MainCtrl">
        <div class="grid" ui-grid="gridOptions" ui-grid-pagination ui-grid-selection></div>
    </div>

    <script src="app.js"></script>
</body>

</html>
</code>```

答: You have to give the value if gridOptions.totalItems, in your case 70. This is how ui-grid figures out how many pages to show. I've updated your plnkr to reflect the changes.

Title: Disable next page on uiGrid

Body:
I am using external pagination with ui-grid and angularjs.

The server has 70 items mocked at the moment, but I will not know the items count from the server.
The pageSize is set to 50.

So it should have 2 pages (one with 50 items on it and one with 20).

The button for next page is NOT disabled on the second page but on the third one when there are no items in the grid to show.

I would like it disabled on the second page!

Link to the plunk: http://plnkr.co/edit/OuM8lN0R06Xudn1frLax?p=preview

app.js

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.pagination']);

app.service('foo', ['$q', function ($q) {
    var items = [];
    for (var i = 0; i < 70; i++) {
        items.push({
            "firstName": "firstName" + i,
            "lastName": "lastName" + i,
            "company": "company" + i,
            "employed": i % 4 === 0
        });
    }

    this.bar = function (page, pageSize) {
        var deferred = $q.defer();

        var start = (page - 1) * pageSize;
        deferred.resolve(items.slice(start, start + pageSize));

        return deferred.promise;
    };

    return this;
}]);

app.controller('MainCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', 'foo', function ($scope, $http, $log, $timeout, uiGridConstants, foo) {
    var paginationOptions = {
        pageNumber: 1,
        pageSize: 50,
        sort: null
    };

    $scope.selectedIds = [];

    $scope.gridOptions = getOptions();

    function getOptions() {
        return {
            enableHorizontalScrollbar: 0,
            enableVerticalScrollbar: 2,

            enableRowSelection: true,
            enableFullRowSelection: true,
            multiSelect: true,

            paginationPageSizes: [50, 100],
            paginationPageSize: 50,
            useExternalPagination: true,

            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                getPage(1, 50);

                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage;
                    paginationOptions.pageSize = pageSize;
                    getPage(newPage, pageSize);
                });
            }
        };
    }

    function getPage(page, pageSize) {
        foo.bar(page, pageSize)
            .then(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.totalItems = undefined;
            });
    }

    getPage(1, 50);
}]);

index.html

<!doctype html>

    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">


问:
Eclipse fails to open .vue files in Web Page Editor
I would like to open .vue files as regular HTML files in Eclipse. I tried to to right click a .vue file and then Open WithWeb Page Editor. I've also linked .vue in the preferences as a new file association to the Web Page Editor.

Doing exactly the above steps leads to the following error after opening the file. It also throws a NullPointerException:

Failed to create the part's controls

Is this a bug in Eclipse or am I doing something wrong?

My Eclipse version is:

```<code>Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500
</code>```

I've seen in the Error Log, that the following message appears, after opening a .vue file in the Web Page Editor:

```<code>eclipse.buildId=4.6.3.M20170301-0400
java.version=1.8.0_92
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_CH
Framework arguments:  -product org.eclipse.epp.package.jee.product -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product -data file:/C:/Users/sebsc/eclipse-workspace/ -product org.eclipse.epp.package.jee.product

org.eclipse.jst.pagedesigner
Error
Wed Mar 29 19:27:35 CEST 2017
Unable to display palette for App.vue.  Unknown content type for file.
</code>```

Here is the stack trace of the NullPointerException:

```<code>java.lang.NullPointerException
    at org.eclipse.wst.sse.ui.StructuredTextEditor.createModelDependentFields(StructuredTextEditor.java:1503)
    at org.eclipse.wst.sse.ui.StructuredTextEditor.update(StructuredTextEditor.java:3156)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.sash_createAndAddDesignSourcePage(HTMLEditor.java:297)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.createPages(HTMLEditor.java:458)
    at org.eclipse.ui.part.MultiPageEditorPart.createPartControl(MultiPageEditorPart.java:363)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.createPartControl(CompatibilityPart.java:150)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor.createPartControl(CompatibilityEditor.java:99)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create(CompatibilityPart.java:340)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:966)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:931)
    at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:151)
    at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:375)
    at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:294)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:105)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:74)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:56)
    at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:129)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:975)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:651)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:757)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$0(PartRenderingEngine.java:728)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$2.run(PartRenderingEngine.java:722)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:706)
    at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1317)
    at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40)
    at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:233)
    at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145)
    at org.eclipse.swt.widgets.Display.syncExec(Display.java:4821)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36)
    at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:201)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135)
    at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78)
    at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39)
    at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:94)
    at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:60)
    at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374)
    at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:173)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:617)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:581)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:770)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:401)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1214)
    at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3261)
    at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3176)
    at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3158)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3153)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3117)
    at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:324)
    at org.eclipse.ui.actions.OpenWithMenu.lambda$0(OpenWithMenu.java:180)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
</code>```

答:
I found out what the problem is. The Error Log view showed more detailed information about the problem.

The HTML/Web Page Editor requires a file extension to have a valid content type. Because .vue files do not have a predefined content type, the editor just crashes.

As a workaround, you can simply add *.vue to the HTML content type. You can find this setting in Preferences → General → Content Types. Then add *.vue to HTML under Text.

You probably also want to set the default editor for .vue files to the HTML/Web Page Editor. You can do this in Preferences → General → Editors → File Associations

Sorry, that I cannot give out the bounty to anybody =)

Body:
I would like to open .vue files as regular HTML files in Eclipse. I tried to to right click a .vue file and then Open WithWeb Page Editor. I've also linked .vue in the preferences as a new file association to the Web Page Editor.

Doing exactly the above steps leads to the following error after opening the file. It also throws a NullPointerException:

Failed to create the part's controls

Is this a bug in Eclipse or am I doing something wrong?

My Eclipse version is:

Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500

I've seen in the Error Log, that the following message appears, after opening a .vue file in the Web Page Editor:

eclipse.buildId=4.6.3.M20170301-0400
java.version=1.8.0_92
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_CH
Framework arguments:  -product org.eclipse.epp.package.jee.product -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product -data file:/C:/Users/sebsc/eclipse-workspace/ -product org.eclipse.epp.package.jee.product

org.eclipse.jst.pagedesigner
Error
Wed Mar 29 19:27:35 CEST 2017
Unable to display palette for App.vue.  Unknown content type for file.

Here is the stack trace of the NullPointerException:

java.lang.NullPointerException
    at org.eclipse.wst.sse.ui.StructuredTextEditor.createModelDependentFields(StructuredTextEditor.java:1503)
    at org.eclipse.wst.sse.ui.StructuredTextEditor.update(StructuredTextEditor.java:3156)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.sash_createAndAddDesignSourcePage(HTMLEditor.java:297)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.createPages(HTMLEditor.java:458)
    at org.eclipse.ui.part.MultiPageEditorPart.createPartControl(MultiPageEditorPart.java:363)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.createPartControl(CompatibilityPart.java:150)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor.createPartControl(CompatibilityEditor.java:99)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create(CompatibilityPart.java:340)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:966)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:931)
    at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:151)
    at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:375)
    at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:294)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:105)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:74)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:56)
    at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:129)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:975)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:651)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:757)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$0(PartRenderingEngine.java:728)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$2.run(PartRenderingEngine.java:722)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:706)
    at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1317)
    at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40)
    at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:233)
    at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145)
    at org.eclipse.swt.widgets.Display.syncExec(Display.java:4821)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36)
    at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:201)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135)
    at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78)
    at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39)
    at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:94)
    at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:60)
    at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374)
    at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:173)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:617)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:581)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:770)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:401)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1214)
    at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3261)
    at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3176)
    at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3158)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3153)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3117)
    at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:324)
    at org.eclipse.ui.actions.OpenWithMenu.lambda$0(OpenWithMenu.java:180)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1519)


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
It depends a bit on how the HTML is produced. If it's somewhat controlled you can get away with:</p>

```<code>re.findall(r'''<link\s+.*?href=['"](.*?)['"].*?(?:</link|/)>''', html, re.I)
</code>```

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

Body:
It depends a bit on how the HTML is produced. If it's somewhat controlled you can get away with:

re.findall(r'''<link\s+.*?href=['"](.*?)['"].*?(?:</link|/)>''', html, re.I)

OwnerDisplayName: PEZ

ContentLicense: CC BY-SA 2.5


问:
Get module.exports from within the same file
In a file I have this code:

```<code>module.exports.greet = function() {...}
</code>```

I want to use that function from within the same file.

I thought this would work:

```<code>this.greet()
</code>```

But it didn't.

What is the reference I have to use?

答:
Normally, this should work just fine, but let's see why this might fail.

Some Background first

What happens is that exports is an object that, along with a few other things like require, module, __dirname etc. ,  gets passed into the closure that wraps the modules contents, exports is then returned by require().

See: https://github.com/ry/node/blob/master/src/node.js#L327

this inside the module refers to the exports object, the module object then holds a reference to the exports object. The name space inside the module is provided via the closure.

In the end there's also the global object which provides the global name space and hosts things like process.

Examples

```<code>// main.js
this.bla = function(){} // sets bla on the the exports object
require('./sub');
console.log(this); // { bla: [Function] }
console.log(exports); // { bla: [Function] }
console.log(module); /* { id: '.',
                          exports: { bla: [Function] },
                          parent: undefined,
                          filename: '/home/ivo/Desktop/main.js',
                          loaded: false,
                          exited: false,
                          children: [] } */

// sub.js
this.greet = function() {} // sets greet on the exports object
console.log(this); // { greet: [Function] }
console.log(exports); // { greet: [Function] }
console.log(module); /* { id: './sub',
                          exports: { greet: [Function] },
                          parent:
                          { id: '.',
                            exports: { bla: [Function] },
                            parent: undefined,
                            filename: '/home/ivo/Desktop/main.js',
                            loaded: false,
                            exited: false,
                            children: [] },
                         filename: '/home/ivo/Desktop/sub.js',
                         loaded: false,
                         exited: false,
                         children: [] } */
</code>```

Cause of the problem

The only explanation for the fact that your code doesn't work is that the environment variable NODE_MODULE_CONTEXTS was set to an integer bigger than zero.

In this case the modules get run in their own context. this inside the main module will now refer to the global object and inside sub modules, it will refer to a sandbox object. Therefore this.foo will not set any property on the exports object.

See: https://github.com/ry/node/blob/master/src/node.js#L98

And: https://github.com/ry/node/blob/master/src/node.js#L296

Fixing the problem

You can check the environment variables that were passed to the node process:

```<code>console.log(process.env); // get a list of all variables

// get just the one that's causing trouble, if this returns a number > 0 then it's in effect
console.log(process.env['NODE_MODULE_CONTEXTS']);
</code>```

In case that NODE_MODULE_CONTEXTS is in effect, you need to check your ~/.bashrc and ~/.bash_profile files for something like export NODE_MODULE_CONTEXTS=1; and remove it.

Make sure to open up a new terminal, since changes those two files are only read in when one is created.

Body:
In a file I have this code:

module.exports.greet = function() {...}

I want to use that function from within the same file.

I thought this would work:

this.greet()

But it didn't.

What is the reference I have to use?

Body:
Normally, this should work just fine, but let's see why this might fail.

Some Background first

What happens is that exports is an object that, along with a few other things like require, module, __dirname etc. ,  gets passed into the closure that wraps the modules contents, exports is then returned by require().

See: https://github.com/ry/node/blob/master/src/node.js#L327

this inside the module refers to the exports object, the module object then holds a reference to the exports object. The name space inside the module is provided via the closure.

In the end there's also the global object which provides the global name space and hosts things like process.

Examples

// main.js
this.bla = function(){} // sets bla on the the exports object
require('./sub');
console.log(this); // { bla: [Function] }
console.log(exports); // { bla: [Function] }
console.log(module); /* { id: '.',
                          exports: { bla: [Function] },
                          parent: undefined,
                          filename: '/home/ivo/Desktop/main.js',
                          loaded: false,
                          exited: false,
                          children: [] } */

// sub.js
this.greet = function() {} // sets greet on the exports object
console.log(this); // { greet: [Function] }
console.log(exports); // { greet: [Function] }
console.log(module); /* { id: './sub',
                          exports: { greet: [Function] },
                          parent:
                          { id: '.',
                            exports: { bla: [Function] },
                            parent: undefined,
                            filename: '/home/ivo/Desktop/main.js',
                            loaded: false,
                            exited: false,
                            children: [] },
                         filename: '/home/ivo/Desktop/sub.js',
                         loaded: false,
                         exited: false,
                         children: [] } */

Cause of the problem

The only explanation for the fact that your code doesn't work is that the environment variable NODE_MODULE_CONTEXTS was set to an integer bigger than zero.

In this case the modules get run in their own context. this inside the main module will now refer to the global object and inside sub modules, it will refer to a sandbox object. Therefore this.foo will not set any property on the exports object.

See: https://github.com/ry/node/blob/master/src/node.js#L98

And: https://github.com/ry/node/blob/master/src/node.js#L296

Fixing the problem

You can check the environment variables that were passed to the node process:

console.log(process.env); // get a list of all variables

// get just the one that's causing trouble, if this returns a number > 0 then it's in effect
console.log(process.env['NODE_MODULE_CONTEXTS']);

In case that NODE_MODULE_CONTEXTS is in effect, you need to check your ~/.bashrc and ~/.bash_profile files for something like export NODE_MODULE_CONTEXTS=1; and remove it.

Make sure to open up a new terminal, since changes those two files are only read in when one is created.


问:
Should use android:showAsAction when not using the appcompat library
I have a weird problem, I was using a menu.xml file in my android application like this:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:compat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:title="@string/action_refresh"
        android:icon="@drawable/toc"
        compat:showAsAction="always"/>
</menu>
</code>```

and it was working well, but some days ago i was updating my eclipse to the last version, and after that, the app:showAsAction="always" shows the error:

Should use android:showAsAction when not using the appcompat library
  and after that my action bar icons was moved to the overflow bar and not showing the in the action bar at all.

anyway, the appcompat library is the parent of my base style.
what should I do to resolve that?

答:
All you need to do is add the following line to your item element to suppress the warning. Having the namespace as compat vs app for "http://schemas.android.com/apk/res-auto" doesn't actually do anything special.

tools:ignore="AppCompatResource"

full code:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:compat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:title="@string/action_refresh"
        android:icon="@drawable/toc"
        tools:ignore="AppCompatResource"
        compat:showAsAction="always"/>
</menu>
</code>```

Note: the compat tag could be app or whatever you want.

Body:
I have a weird problem, I was using a menu.xml file in my android application like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:compat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:title="@string/action_refresh"
        android:icon="@drawable/toc"
        compat:showAsAction="always"/>
</menu>

and it was working well, but some days ago i was updating my eclipse to the last version, and after that, the app:showAsAction="always" shows the error:

Should use android:showAsAction when not using the appcompat library
  and after that my action bar icons was moved to the overflow bar and not showing the in the action bar at all.

anyway, the appcompat library is the parent of my base style.
what should I do to resolve that?

Body:
All you need to do is add the following line to your item element to suppress the warning. Having the namespace as compat vs app for "http://schemas.android.com/apk/res-auto" doesn't actually do anything special.

tools:ignore="AppCompatResource"

full code:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:compat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:title="@string/action_refresh"
        android:icon="@drawable/toc"
        tools:ignore="AppCompatResource"
        compat:showAsAction="always"/>
</menu>

Note: the compat tag could be app or whatever you want.


问:
What does `log = True` actually do in matplotlib?
My MCVE:

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

    #normal sample
    mu, sigma = 100, 15
    x = mu + sigma*np.random.randn(10000)

    #histogram
    n, bins, patches = plt.hist(x, 50)
    plt.axis([40, 160, 0, 800])
    n2, bins2, patches2 = plt.hist(x,50,log=True)
    n1 = np.log(n)
</code>```

now why n2 is different from n1? I thought that the log = True scaled everything logarithmically.. but it doesn't. So what is it doing? Same thing happens for bins2 and bins1 = np.log(bins).

edit
This

```<code>    mu, sigma = 100, 15
    x = mu + sigma*np.random.randn(10000)
    hist, bin_edges = np.histogram(x,50)
    nwidth = bin_edges[7]-bin_edges[6]   #just difference between two random bins
    plt.bar(np.delete(bin_edges,len(bin_edges)-1),hist,nwidth)  #so I have the right number of bins
    plt.show()
</code>```

gives me

then by doing

```<code>histsq = np.sqrt(np.log(hist))
plt.bar(np.delete(bin_edges,len(bin_edges)-1),histsq,nwidth)
plt.show()
</code>```

I obtain

答:
When you set log = True, the histogram axis (not return parameters) is in log scale. The return parameters (n,bins), ie the values of the bins and the edges of the bins are the same for log = True and log = False. What that means is n==n2 and bins == bins2 are both True.

See the code below to see if that is true

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

#normal sample
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

#histogram
plt.subplot(3, 1, 1)
n, bins, patches = plt.hist(x, 50)
# plt.axis([40, 160, 0, 800])

plt.subplot(3, 1, 2)
n2, bins2, patches2 = plt.hist(x,50,log=True)

if (all(n==n2) and all(bins==bins2)):
    print 'Return parameters of hist with log option or without log option are always the same'

#if you want to apply two transformation on the return data and visualize it.
n1 = np.log(n)
plt.subplot(3, 1, 3)
xx = bins[1:]
yy = np.sqrt(n1)
plt.bar(xx,yy, width = xx[1]-xx[0])

# square root of inverted parabola is not a linear line, but has some curvature

x = np.arange(-1,1.1,.1)
y = 10-(x)**2 # inverted parabola
y1 = np.sqrt(y) # square of inverted parabola

fig, ax1 = plt.subplots()
ax1.plot(x, y, 'b-')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('inverted parabola', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
ax2.plot(x, y1, 'r.')
ax2.set_ylabel('sqrt of inverted parabola', color='r')
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()
</code>```

will return

```<code>Return parameters of hist method with log option or without log option are always the same
</code>```

Body:
My MCVE:

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

    #normal sample
    mu, sigma = 100, 15
    x = mu + sigma*np.random.randn(10000)

    #histogram
    n, bins, patches = plt.hist(x, 50)
    plt.axis([40, 160, 0, 800])
    n2, bins2, patches2 = plt.hist(x,50,log=True)
    n1 = np.log(n)

now why n2 is different from n1? I thought that the log = True scaled everything logarithmically.. but it doesn't. So what is it doing? Same thing happens for bins2 and bins1 = np.log(bins).

edit
This

    mu, sigma = 100, 15
    x = mu + sigma*np.random.randn(10000)
    hist, bin_edges = np.histogram(x,50)
    nwidth = bin_edges[7]-bin_edges[6]   #just difference between two random bins
    plt.bar(np.delete(bin_edges,len(bin_edges)-1),hist,nwidth)  #so I have the right number of bins
    plt.show()

gives me

then by doing

histsq = np.sqrt(np.log(hist))
plt.bar(np.delete(bin_edges,len(bin_edges)-1),histsq,nwidth)
plt.show()

I obtain

Body:
When you set log = True, the histogram axis (not return parameters) is in log scale. The return parameters (n,bins), ie the values of the bins and the edges of the bins are the same for log = True and log = False. What that means is n==n2 and bins == bins2 are both True.

See the code below to see if that is true

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

#normal sample
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

#histogram
plt.subplot(3, 1, 1)
n, bins, patches = plt.hist(x, 50)
# plt.axis([40, 160, 0, 800])

plt.subplot(3, 1, 2)
n2, bins2, patches2 = plt.hist(x,50,log=True)

if (all(n==n2) and all(bins==bins2)):
    print 'Return parameters of hist with log option or without log option are always the same'

#if you want to apply two transformation on the return data and visualize it.
n1 = np.log(n)
plt.subplot(3, 1, 3)
xx = bins[1:]
yy = np.sqrt(n1)
plt.bar(xx,yy, width = xx[1]-xx[0])

# square root of inverted parabola is not a linear line, but has some curvature

x = np.arange(-1,1.1,.1)
y = 10-(x)**2 # inverted parabola
y1 = np.sqrt(y) # square of inverted parabola

fig, ax1 = plt.subplots()
ax1.plot(x, y, 'b-')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('inverted parabola', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
ax2.plot(x, y1, 'r.')
ax2.set_ylabel('sqrt of inverted parabola', color='r')
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()

will return

Return parameters of hist method with log option or without log option are always the same


问:
How to take data from URL
I am developing API for my company. Normally, we use POST & GET method to send form data to other website or another page. But what I want, If we want to send data in URL like
      http://www.example.com/data1/data2/data3

like that.
In that case, Data1, Data2, Data3 is our data and I want this data in PHP.
I am searching on that but I can't find what I want.

答:
you can do it by simply fetching the entire URL and preg_split() the string as below code

```<code>$path = $_SERVER['REQUEST_URI']; // this gives you /folder1/folder2/THIS_ONE/file.php
$folders = preg_split('/', $path); // splits folders in array
$what_we_need = $folders[3];
</code>```

Title: How to take data from URL

Body:
you can do it by simply fetching the entire URL and preg_split() the string as below code

$path = $_SERVER['REQUEST_URI']; // this gives you /folder1/folder2/THIS_ONE/file.php
$folders = preg_split('/', $path); // splits folders in array
$what_we_need = $folders[3];


问:
Shrinking the JPanel in Swing
I am trying to make a login page but unfortunately my formPanel's border is so out of bounds. Here in the pic you can see the titled border is way out. I need it to be more around my panel with login form:

I see that when creating this formPanel it is that big and the border just surround it. I tried with setPrefferedSize but its not working. How can I fix it?

Here is my code:

```<code>public class LoginPanel extends JPanel {
private JLabel title;

public LoginPanel() {
    this.setBackground(new Color(0, 128, 43));
    this.setBorder(new EmptyBorder(10, 10, 10, 10));
    this.setLayout(new BorderLayout());

    //adding the title
    title = new JLabel("<html><h1><strong><i>Krisko Beatz Quiz</i></strong></h1><hr></html>");
    title.setForeground(Color.BLACK);
    JPanel titlePanel = new JPanel();
    titlePanel.setBackground(new Color(0, 128, 43));
    titlePanel.add(title);
    this.add(titlePanel, BorderLayout.PAGE_START);

    //creating the login form
    JPanel formPanel = new JPanel(new GridBagLayout());
    formPanel.setBackground(new Color(0, 128, 43));

    //gbc
    GridBagConstraints gbc = new GridBagConstraints();

    //gbc for username
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(5, 0, 0, 0);

    JLabel username = new JLabel("Username: ");
    username.setForeground(Color.BLACK);
    formPanel.add(username, gbc);

    //gbc for textfield
    gbc.gridx = 1;
    gbc.gridy = 0;

    JTextField usernameField = new JTextField(10);
    formPanel.add(usernameField, gbc);

    //gbc for pass
    gbc.gridx = 0;
    gbc.gridy = 1;

    JLabel password = new JLabel("Password: ");
    password.setForeground(Color.BLACK);
    formPanel.add(password, gbc);

    //gbc for pass field
    gbc.gridx = 1;
    gbc.gridy = 1;

    JPasswordField passField = new JPasswordField(10);
    formPanel.add(passField, gbc);

    //gbc for button
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 2;
    gbc.anchor = GridBagConstraints.PAGE_END;

    JButton loginButton = new JButton("Login");
    formPanel.add(loginButton, gbc);

    //add border to the form panel
    TitledBorder title = BorderFactory.createTitledBorder("Login");
    formPanel.setBorder(title);

    this.add(formPanel, BorderLayout.CENTER);
}
}
</code>```

答:
I tried with setPrefferedSize but its not working.

Don't try to manage the preferredSize of a component.

I would guess the problem is that you are using setSize(...) instead of pack().

You should be using pack() AFTER all the components have been added to the frame. Then all the components will be displayed at their preferred size.

Edit:

I originally misread your question and changed my original answer. The point in my original answer of using the "wrapper" panel is to give extra space to the wrapper panel, while keeping the "formPanel" at a fixed size. This way the titled border will remain around the formPanel even as the frame size is changed.

So again the basic approach for this type of solution is:

```<code>JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add(formPanel, new GridBagConstraints());
this.add(wrapper, BorderLayout.CENTER);
//this.add(formPanel, BorderLayout.CENTER);
</code>```

Title: Shrinking the JPanel in Swing

Body:
I am trying to make a login page but unfortunately my formPanel's border is so out of bounds. Here in the pic you can see the titled border is way out. I need it to be more around my panel with login form:

I see that when creating this formPanel it is that big and the border just surround it. I tried with setPrefferedSize but its not working. How can I fix it?

Here is my code:

public class LoginPanel extends JPanel {
private JLabel title;

public LoginPanel() {
    this.setBackground(new Color(0, 128, 43));
    this.setBorder(new EmptyBorder(10, 10, 10, 10));
    this.setLayout(new BorderLayout());

    //adding the title
    title = new JLabel("
Krisko Beatz Quiz

");
    title.setForeground(Color.BLACK);
    JPanel titlePanel = new JPanel();
    titlePanel.setBackground(new Color(0, 128, 43));
    titlePanel.add(title);
    this.add(titlePanel, BorderLayout.PAGE_START);

    //creating the login form
    JPanel formPanel = new JPanel(new GridBagLayout());
    formPanel.setBackground(new Color(0, 128, 43));

    //gbc
    GridBagConstraints gbc = new GridBagConstraints();

    //gbc for username
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(5, 0, 0, 0);

    JLabel username = new JLabel("Username: ");
    username.setForeground(Color.BLACK);
    formPanel.add(username, gbc);

    //gbc for textfield
    gbc.gridx = 1;
    gbc.gridy = 0;

    JTextField usernameField = new JTextField(10);
    formPanel.add(usernameField, gbc);

    //gbc for pass
    gbc.gridx = 0;
    gbc.gridy = 1;

    JLabel password = new JLabel("Password: ");
    password.setForeground(Color.BLACK);
    formPanel.add(password, gbc);

    //gbc for pass field
    gbc.gridx = 1;
    gbc.gridy = 1;

    JPasswordField passField = new JPasswordField(10);
    formPanel.add(passField, gbc);

    //gbc for button
    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.gridwidth = 2;
    gbc.anchor = GridBagConstraints.PAGE_END;

    JButton loginButton = new JButton("Login");
    formPanel.add(loginButton, gbc);

    //add border to the form panel
    TitledBorder title = BorderFactory.createTitledBorder("Login");
    formPanel.setBorder(title);

    this.add(formPanel, BorderLayout.CENTER);
}
}

Body:
I tried with setPrefferedSize but its not working.

Don't try to manage the preferredSize of a component.

I would guess the problem is that you are using setSize(...) instead of pack().

You should be using pack() AFTER all the components have been added to the frame. Then all the components will be displayed at their preferred size.

Edit:

I originally misread your question and changed my original answer. The point in my original answer of using the "wrapper" panel is to give extra space to the wrapper panel, while keeping the "formPanel" at a fixed size. This way the titled border will remain around the formPanel even as the frame size is changed.

So again the basic approach for this type of solution is:

JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add(formPanel, new GridBagConstraints());
this.add(wrapper, BorderLayout.CENTER);
//this.add(formPanel, BorderLayout.CENTER);


问:
How to determine distance to a point on arc perpendicular from tangent?
Given the following from the image below:

The green circle has a radius equal to B

The yellow line is tangent to the green circle

The vertical purple line is parallel to the green line and perpendicular to the yellow line.

The yellow line is perpendicular to both the green line and the vertical purple line

The purple point is centered on the green circle's edge

A and B are known values

I realize several of these constraints overlap, just trying to be thorough.
Pythagorean's theorem can provide the value of C, just to illustrate what I know we can determine already.

What is the formula/equation to determine D, where D is the perpendicular distance from the tangent yellow line to the arc/circle (at the purple point)?

Update

Replacing previous attempts to illustrate solution now with one that I can now visualize as the correct representation of the answer and comments provided by John

答:
As you mentioned C is the easy part. However with A,B,C and the cosine theorem you can work out the angel opposite to B (b):

```<code>cos(b) = (a^2 + c^2 -b^2)/(2ac)
</code>```

knowing b and that A and D have a right angel you can work out the angle between C and D (b'):

```<code>b' = 90° - b
</code>```

given that D lies on the circle you know that the distance from the center to D is B so you now have a triangle with sides B,D and C where you know two of the sides and one of the angles. With the cosine law again:

```<code>B^2 = C^2 + D^2 - 2CD cos(b')
</code>```

so in one more step we can find:

```<code>B^2 - C^2 = D^2 - 2CD cos(b') + (C cos(b'))^2 -(C cos(b'))^2 <=>
B^2 - C^2 + (C cos(b'))^2 = (D - C cos(b'))^2 <=>
sqrt(B^2 - C^2 + (C cos(b'))^2) + C cos(b') = D
</code>```

hope I didn't put stupid mistakes in there and this helps...

Body:
As you mentioned C is the easy part. However with A,B,C and the cosine theorem you can work out the angel opposite to B (b):

cos(b) = (a^2 + c^2 -b^2)/(2ac)

knowing b and that A and D have a right angel you can work out the angle between C and D (b'):

b' = 90° - b

given that D lies on the circle you know that the distance from the center to D is B so you now have a triangle with sides B,D and C where you know two of the sides and one of the angles. With the cosine law again:

B^2 = C^2 + D^2 - 2CD cos(b')

so in one more step we can find:

B^2 - C^2 = D^2 - 2CD cos(b') + (C cos(b'))^2 -(C cos(b'))^2 <=>
B^2 - C^2 + (C cos(b'))^2 = (D - C cos(b'))^2 <=>
sqrt(B^2 - C^2 + (C cos(b'))^2) + C cos(b') = D

hope I didn't put stupid mistakes in there and this helps...


问:
Java input check using negative lookahead regex
I am trying to using a regex negative lookahead to check if any invalid characters have been entered.  The characters I want to check for are everything but 0-9, whitespace, *, /, +, -, r, x.

```<code>String word = "(l4+3q)*(5+7-8)/(5)";
Pattern p  = Pattern.compile("(?![\\d\\srx*+-/)]+)");
Matcher m = p.matcher(word);

if(m.matches()) System.out.println("NO");
</code>```

In this current test code, every string I use returns false.

Could anyone provide me with some direction on how to modify this regular expression to work for my specifications.

答:
You don't want to use this +-/ in that order in the class.

The - used this way is a range operator, not a literal -.

To make it literal, add it to the end or beginning, or escape it

and it can be anywhere.

Basically, you want to match anything not in that class.

Pattern p  = Pattern.compile("[^\\d\\srx*+\\-/)]");

If it matches if( m.matches() ) it did find an illegal character.

or,

If it doesn't match if( !m.matches() ) it didn't find an illegal character.

Body:
I am trying to using a regex negative lookahead to check if any invalid characters have been entered.  The characters I want to check for are everything but 0-9, whitespace, *, /, +, -, r, x.

String word = "(l4+3q)*(5+7-8)/(5)";
Pattern p  = Pattern.compile("(?![\\d\\srx*+-/)]+)");
Matcher m = p.matcher(word);

if(m.matches()) System.out.println("NO");

In this current test code, every string I use returns false.

Could anyone provide me with some direction on how to modify this regular expression to work for my specifications.


问:
Angular2 Karma test runner not reloading
I'm running through the Angular2 testing tutorial. I'm pretty new to Jasmine/Karma so this may be something basic. I've noticed that once I have the "npm test" running that if I make a change, the test runner tries to reload but gets an error:

ERROR in
  C:/dev/unittest1/src/app/banner-inline/banner-inline.component.spec.ts
  (12,11): Cannot find name 'HTMLElement'.)

Here is the spec code (pretty much just taken from here):

import { ComponentFixture, TestBed, ComponentFixtureAutoDetect } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { DebugElement } from '@angular/core';

```<code>import { BannerInlineComponent } from './banner-inline.component';

describe('BannerInlineComponent (inline template)', () => {

  let comp: BannerInlineComponent;
  let fixture: ComponentFixture<BannerInlineComponent>;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [BannerInlineComponent], // declare the test component
      providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }]
    });

    fixture = TestBed.createComponent(BannerInlineComponent);

    comp = fixture.componentInstance; // BannerInlineComponent test instance

    // query for the title <h1> by CSS element selector
    de = fixture.debugElement.query(By.css('h1'));
    el = de.nativeElement;
  });

  it('should display original title', () => {
    expect(el.textContent).toContain(comp.title);
  });

  it('should still see original title after comp.title change', () => {
    const oldTitle = comp.title;
    comp.title = 'Test Title';
    fixture.detectChanges();
    // Displayed title is old because Angular didn't hear the change :(
    expect(el.textContent).toContain(oldTitle);
  });

  it('should display updated title after detectChanges', () => {
    comp.title = 'Test Title';
    fixture.detectChanges(); // detect changes explicitly
    expect(el.textContent).toContain(comp.title);
  });
});
</code>```

If I stop the test runner and restart it, everything works fine. Why am I getting this error and how can I prevent it?

答:
I guess in your tsconfig.json in your project you should add the dom library to the lib array:</p>

```<code>"lib": ["es6", "dom", "es2015.iterable"],
</code>```

Body:
I'm running through the Angular2 testing tutorial. I'm pretty new to Jasmine/Karma so this may be something basic. I've noticed that once I have the "npm test" running that if I make a change, the test runner tries to reload but gets an error:

ERROR in
  C:/dev/unittest1/src/app/banner-inline/banner-inline.component.spec.ts
  (12,11): Cannot find name 'HTMLElement'.)

Here is the spec code (pretty much just taken from here):

import { ComponentFixture, TestBed, ComponentFixtureAutoDetect } from '@angular/core/testing';
    import { By } from '@angular/platform-browser';
    import { DebugElement } from '@angular/core';

import { BannerInlineComponent } from './banner-inline.component';

describe('BannerInlineComponent (inline template)', () => {

  let comp: BannerInlineComponent;
  let fixture: ComponentFixture<BannerInlineComponent>;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [BannerInlineComponent], // declare the test component
      providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }]
    });

    fixture = TestBed.createComponent(BannerInlineComponent);

    comp = fixture.componentInstance; // BannerInlineComponent test instance

    // query for the title
 by CSS element selector
    de = fixture.debugElement.query(By.css('h1'));
    el = de.nativeElement;
  });

  it('should display original title', () => {
    expect(el.textContent).toContain(comp.title);
  });

  it('should still see original title after comp.title change', () => {
    const oldTitle = comp.title;
    comp.title = 'Test Title';
    fixture.detectChanges();
    // Displayed title is old because Angular didn't hear the change :(
    expect(el.textContent).toContain(oldTitle);
  });

  it('should display updated title after detectChanges', () => {
    comp.title = 'Test Title';
    fixture.detectChanges(); // detect changes explicitly
    expect(el.textContent).toContain(comp.title);
  });
});

If I stop the test runner and restart it, everything works fine. Why am I getting this error and how can I prevent it?

Body:
I guess in your tsconfig.json in your project you should add the dom library to the lib array:

"lib": ["es6", "dom", "es2015.iterable"],


问:
Merge two tabs in Java Swing
Thank you for viewing. I'm a beginner with Java swing. I'm trying to merge two tabs in an application. The tabs are created in this way:

```
  pane=new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
  pane.add(panel1);
  pane.add(panel2);
```

I'd like to have the contents of panel1 and panel2 merged together, with panel2 displayed underneath panel1. I know this may seem like a very simple question, but I am still learning. Thanks guys.

Edit: panel1 and panel2 are both JScrollPane

答:
Create a third JPanel that uses whatever layout would work (BorderLayout or BoxLayout come to mind), and add your two JPanels to the third one. Then add the third one to the tabbed pane.

edit: this is a little confusing: "Edit: panel1 and panel2 are both JScrollPane" So these are in fact JScrollPanes, not JPanels? Regardless, my suggestion above still works. :)

Most important though: study how to use layout managers and components such as JPanels etc on the Oracle Swing Tutorials:  Layout Manager Tutorial

```<code>JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
containerPanel.add(panel1);
containerPanel.add(panel2);
pane.add(containerPanel);
</code>```

Title: Merge two tabs in Java Swing

Body:
Thank you for viewing. I'm a beginner with Java swing. I'm trying to merge two tabs in an application. The tabs are created in this way:

  pane=new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
  pane.add(panel1);
  pane.add(panel2);

I'd like to have the contents of panel1 and panel2 merged together, with panel2 displayed underneath panel1. I know this may seem like a very simple question, but I am still learning. Thanks guys.

Edit: panel1 and panel2 are both JScrollPane

Body:
Create a third JPanel that uses whatever layout would work (BorderLayout or BoxLayout come to mind), and add your two JPanels to the third one. Then add the third one to the tabbed pane.

edit: this is a little confusing: "Edit: panel1 and panel2 are both JScrollPane" So these are in fact JScrollPanes, not JPanels? Regardless, my suggestion above still works. :)

Most important though: study how to use layout managers and components such as JPanels etc on the Oracle Swing Tutorials:  Layout Manager Tutorial

JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS));
containerPanel.add(panel1);
containerPanel.add(panel2);
pane.add(containerPanel);


问:
How to use address function in Excel VBA?
I am trying to use VBA to dynamically add a formula to a few cells using the address function. When I run the following scripts I get a file explorer window that opens. I am not sure why that happens. What am I doing wrong?

Here is one of the solutions I tried:

```<code>Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub
</code>```

I also tried this:

```<code>Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address() & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub
</code>```

答:
I'd go as follows</p>

```<code>With Sheet7
    With .Range("CU2")
        colCount = .Range(.Cells, .End(xlToRight)).Columns.Count
    End With

    startCount = 98

    For i = 1 To colCount

        If IsNumeric(.Cells(2, startCount + i)) Then
            Set bSum = .Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            .Cells(3, i).Formula = "=" & Sheet6.Name & "!" & bSpr.Address() & "*" & .Name & "!" & bSpr.Address()

        Else
            'Do some stuff
        End If
    Next i
End With
</code>```

Body:
I am trying to use VBA to dynamically add a formula to a few cells using the address function. When I run the following scripts I get a file explorer window that opens. I am not sure why that happens. What am I doing wrong?

Here is one of the solutions I tried:

Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub

I also tried this:

Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address() & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub

Body:
I'd go as follows

With Sheet7
    With .Range("CU2")
        colCount = .Range(.Cells, .End(xlToRight)).Columns.Count
    End With

    startCount = 98

    For i = 1 To colCount

        If IsNumeric(.Cells(2, startCount + i)) Then
            Set bSum = .Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            .Cells(3, i).Formula = "=" & Sheet6.Name & "!" & bSpr.Address() & "*" & .Name & "!" & bSpr.Address()

        Else
            'Do some stuff
        End If
    Next i
End With


问:
How can I have tab 1 and 4 selected
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

```<code>        <!DOCTYPE html>
<html>
<head>
<style>
body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}
</style>
</head>
<body>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>
</div>

<div id="1" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="2" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="3" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen1").click();
document.getElementById("defaultOpen2").click();
</script>

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

答:
Not sure if I understood what you meant. But here is a working fiddle.

I would advice you to add a container DIV for your tabs so it becomes easier to get the first element with javascript.

Let me know if you need anything else.

window.openCity = function (evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

document.getElementById("London").style.display='block';
 document.getElementById("1").style.display='block';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover,
div.tab button.active{
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

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

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks active" onclick="openCity(this, 'London');" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

```

Title: How can I have tab 1 and 4 selected

Body:
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

        <!DOCTYPE html>

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Body:
Not sure if I understood what you meant. But here is a working fiddle.

I would advice you to add a container DIV for your tabs so it becomes easier to get the first element with javascript.

Let me know if you need anything else.

window.openCity = function (evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

document.getElementById("London").style.display='block';
 document.getElementById("1").style.display='block';

body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover,
div.tab button.active{
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks active" onclick="openCity(this, 'London');" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>
</div>

<div id="1" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="2" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="3" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>


问:
How to refresh a google map manually?
I have a marker - creating activity, when the user can customise the position. After this activity is closed I want to put the new, and the ealier saved markers on my google map. (so UPDATE the map)

I am using this function:

```<code>onMapReady(GoogleMap googleMap)
</code>```

but it is not working properly. I have to close and reopen the app to see the changes.

答:
If you override onResume in your activity/fragment, you can do work once the marker creation activity closes. In there, you can update your map like you would in onMapReady if you set your GoogleMap object as global. For example:

```<code>GoogleMap mGoogleMap;

...

...onMapReady(GoogleMap googleMap){

    mGoogleMap = googleMap;

    ...

}

@Override
public void onResume(){
    super.onResume();

    if(mGoogleMap != null){ //prevent crashing if the map doesn't exist yet (eg. on starting activity)
        mGoogleMap.clear();

        // add markers from database to the map
    }
}
</code>```

You could consider making your marker adding into a function that gets called in onResume and onMapReady to make your code more maintainable.

Title: How to refresh a google map manually?

Body:
I have a marker - creating activity, when the user can customise the position. After this activity is closed I want to put the new, and the ealier saved markers on my google map. (so UPDATE the map)

I am using this function:

onMapReady(GoogleMap googleMap)

but it is not working properly. I have to close and reopen the app to see the changes.

Body:
If you override onResume in your activity/fragment, you can do work once the marker creation activity closes. In there, you can update your map like you would in onMapReady if you set your GoogleMap object as global. For example:

GoogleMap mGoogleMap;

...

...onMapReady(GoogleMap googleMap){

    mGoogleMap = googleMap;

    ...

}

@Override
public void onResume(){
    super.onResume();

    if(mGoogleMap != null){ //prevent crashing if the map doesn't exist yet (eg. on starting activity)
        mGoogleMap.clear();

        // add markers from database to the map
    }
}

You could consider making your marker adding into a function that gets called in onResume and onMapReady to make your code more maintainable.


问:
how to remove x amount of data between 2 words
how to remove some random words between 2 selected words in notepad++ using regex...
here is an example to my question

```<code>DATA100003165663180:sdhfdsdf

DATA:cuoleL

DATA0004513337081:fsdfsd

DATAjhh07016550687:csd

DATA2369343834:1dsdsdbhz
</code>```

here you can see i need to remove all the words that are between DATA and ":" in such a way that i get DATA:xxx and not DATA006554something:xxx
and as you can see on line 2 there is no extra things that needs to be removed after DATA so the regex should ignore such lines

答:
You could use

```<code>(DATA)[^:]*:(.+)
</code>```

and replace the found matches with $1:$2, see a demo on regex101.com.

Body:
how to remove some random words between 2 selected words in notepad++ using regex...
here is an example to my question

DATA100003165663180:sdhfdsdf

DATA:cuoleL

DATA0004513337081:fsdfsd

DATAjhh07016550687:csd

DATA2369343834:1dsdsdbhz

here you can see i need to remove all the words that are between DATA and ":" in such a way that i get DATA:xxx and not DATA006554something:xxx
and as you can see on line 2 there is no extra things that needs to be removed after DATA so the regex should ignore such lines

Body:
You could use

(DATA)[^:]*:(.+)

and replace the found matches with $1:$2, see a demo on regex101.com.


问:
access individual fields using elastic search dsl in python
Is the below accurate  or should it be something else ?

I am getting the expected results just checking if this is the most efficient way to access individual (nested) fields.

```<code>from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

import json
client = Elasticsearch('my_server')

policy_number = 'POLICY1234'
s = Search(using=client, index = "my_index").query("term",policyNumber=policy_number.lower())
es_response = s.execute()

for hits in es_response:
   print hits['policyNumber']
   print hits.party[0]['fullName']
   print hits.party[0].partyAddress[0]['address1']
   print hits.party[0].partyAddress[0]['city']
   print hits.party[0].phoneList[0]['phoneNumber']
</code>```

答:
You don't need to call execute manually and you don't have to use [] to access fields by name, you can just use the attribute access:

```<code>for hit in s:
   print hit.policyNumber
   print hit.party[0].fullName
   print hit.party[0].partyAddress[0].address1
   print hit.party[0].partyAddress[0].city
   print hit.party[0].phoneList[0].phoneNumber
</code>```

Body:
Is the below accurate  or should it be something else ?

I am getting the expected results just checking if this is the most efficient way to access individual (nested) fields.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

import json
client = Elasticsearch('my_server')

policy_number = 'POLICY1234'
s = Search(using=client, index = "my_index").query("term",policyNumber=policy_number.lower())
es_response = s.execute()

for hits in es_response:
   print hits['policyNumber']
   print hits.party[0]['fullName']
   print hits.party[0].partyAddress[0]['address1']
   print hits.party[0].partyAddress[0]['city']
   print hits.party[0].phoneList[0]['phoneNumber']

Body:
You don't need to call execute manually and you don't have to use [] to access fields by name, you can just use the attribute access:

for hit in s:
   print hit.policyNumber
   print hit.party[0].fullName
   print hit.party[0].partyAddress[0].address1
   print hit.party[0].partyAddress[0].city
   print hit.party[0].phoneList[0].phoneNumber