问:
Upload multiple files via AngularJS to Laravel Controller

I have

Browse files button

```<code><input type="file" upload-files multiple />
</code>```

Create Button

```<code><button class="btn btn-link" ng-click="store()" >Create</button>
</code>```

Directive

```<code>myApp.directive('uploadFiles', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            element.bind('change', function (event) {
                var files = event.target.files;
                for (var i = 0; i < files.length; i++) {
                    scope.$emit("seletedFile", { file: files[i] });
                }
            });
        }
    };
});
</code>```

Listen for the file selected

```<code>$scope.files = [];
$scope.$on("seletedFile", function (event, args) {

    console.log("event is ", event);
    console.log("args is ", args);

    $scope.$apply(function () {
        $scope.files.push(args.file);
    });

});
</code>```

Post data and selected files.

```<code>$scope.store = function() {

    $scope.model = {
      name: $scope.name,
      type: $scope.type
    };

    $http({
        method: 'POST',
        url: '/image/store',
        headers: { 'Content-Type': undefined },
        transformRequest: function (data) {
            console.log("data coming into the transform is ", data);
            var formData = new FormData();
            formData.append("model", angular.toJson(data.model));
            for (var i = 0; i < data.files; i++) {
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },

        data: { model: $scope.model, files: $scope.files }

    })

    .then(function successCallback(response) {
        console.log("%cSuccess!", "color: green;");
        console.log(response);
        $scope.refresh();
        $scope.showModal = false;
        }, function errorCallback(response) {
        console.log("%cError", "color: red;");
        console.log(response);
    });
};
</code>```

Result

In my console, I don't see my files got pass on to my controller in the back-end.

```<code>array:1 [
  "model" => "{"type":"wedding"}"
]
</code>```

Questions

What steps did I forget?

How would one go about and debug this further ?

答:
I am not very experienced in Angular, so I'm assuming that your front-end works.

Debugging Tip Create a PHP file called...I dunno...file_dump.php. In that file, put this code:

```<code><?php
    echo "```"
    print_r($_REQUEST)
    echo "```"
?>
</code>```

and submit your form to that. That will show you all your request data. If you do not see your files in the output, it is a problem with your JavaScript. Since I am not that good at Angular, I'm going to point you to this link: link to multiple file upload tutorial using Angular.
These guys seem to know what they're doing.

If you do see your files in the file_dump.php output, it's a problem with your backend - Laravel. This, I can help you with, but I need to see your scripts for me to be helpful in this aspect.

Please do post the results of file_dump.php.

Also, are you using the correct methods for fetching files? Link. If not, then we have found our culprit...

=D

Pranav

Body:
I have

Browse files button

<input type="file" upload-files multiple />

Create Button

<button class="btn btn-link" ng-click="store()" >Create</button>

Directive

myApp.directive('uploadFiles', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            element.bind('change', function (event) {
                var files = event.target.files;
                for (var i = 0; i < files.length; i++) {
                    scope.$emit("seletedFile", { file: files[i] });
                }
            });
        }
    };
});

Listen for the file selected

$scope.files = [];
$scope.$on("seletedFile", function (event, args) {

    console.log("event is ", event);
    console.log("args is ", args);

    $scope.$apply(function () {
        $scope.files.push(args.file);
    });

});

Post data and selected files.

$scope.store = function() {

    $scope.model = {
      name: $scope.name,
      type: $scope.type
    };

    $http({
        method: 'POST',
        url: '/image/store',
        headers: { 'Content-Type': undefined },
        transformRequest: function (data) {
            console.log("data coming into the transform is ", data);
            var formData = new FormData();
            formData.append("model", angular.toJson(data.model));
            for (var i = 0; i < data.files; i++) {
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },

        data: { model: $scope.model, files: $scope.files }

    })

    .then(function successCallback(response) {
        console.log("%cSuccess!", "color: green;");
        console.log(response);
        $scope.refresh();
        $scope.showModal = false;
        }, function errorCallback(response) {
        console.log("%cError", "color: red;");
        console.log(response);
    });
};

Result

In my console, I don't see my files got pass on to my controller in the back-end.

array:1 [
  "model" => "{"type":"wedding"}"
]

Questions

What steps did I forget?

How would one go about and debug this further ?

Body:
I am not very experienced in Angular, so I'm assuming that your front-end works.

Debugging Tip Create a PHP file called...I dunno...file_dump.php. In that file, put this code:

<?php
    echo "<pre>"
    print_r($_REQUEST)
    echo "</pre>"
?>

and submit your form to that. That will show you all your request data. If you do not see your files in the output, it is a problem with your JavaScript. Since I am not that good at Angular, I'm going to point you to this link: link to multiple file upload tutorial using Angular.
These guys seem to know what they're doing.

If you do see your files in the file_dump.php output, it's a problem with your backend - Laravel. This, I can help you with, but I need to see your scripts for me to be helpful in this aspect.

Please do post the results of file_dump.php.

Also, are you using the correct methods for fetching files? Link. If not, then we have found our culprit...

=D

Pranav


来源: stackexchange

问:
Android back button app is not closing
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice</p>

```<code>  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }
</code>```

答:
use this...</p>

```<code>private long lastBackPressTime = 0;

     @Override
    public void onBackPressed() {

        if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {

            //Add Snhackbar or Toast, whatever you want
            this.lastBackPressTime = System.currentTimeMillis();

        } else {
            if (toast != null) {
                toast.cancel();
            }
            moveTaskToBack(true);

        }

    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android back button app is not closing

Body:
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice

  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }

Body:
use this...

private long lastBackPressTime = 0;

     @Override
    public void onBackPressed() {

        if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {

            //Add Snhackbar or Toast, whatever you want
            this.lastBackPressTime = System.currentTimeMillis();

        } else {
            if (toast != null) {
                toast.cancel();
            }
            moveTaskToBack(true);

        }

    }


问:
Page Loading Part in Angularjs
I finished the data loading part in the front-end, and also i'm trying to put the page loading part (Progress bar).But, it is not working in the correct way. I kindly request anyone to help me...

HTML

```<code><div class="w3-col m7" ng-init="init()" ng-show="IsVisibleForm">

    <div class="w3-row-padding">
        <div ng-show="IsVisible" style="text-align:center;">
            <md-progress-circular md-mode="indeterminate"></md-progress-circular>
            <h3>Please wait</h3>
        </div>
        <div class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>

                <br />
                <div>

                    <table class="table defaultTable" ng-show="resultTble">

                        <tr>
                            <th></th>
                            <th>Dog ID</th>
                            <th>Dog Name</th>
                            <th>Sex</th>
                            <th>Sire Name</th>
                            <th>Dam Name</th>
                            <th>Creater</th>
                            <th>Created Date</th>
                            <!--<th></th>-->
                            <!--<th></th>-->
                        </tr>
                        <tr ng-repeat="d in newDogList">
                            <td><a href="#/EditDog/{{d.id}}" target="_blank">$</a></td>
                            <td><a href="#">#</a></td>
                            <td><a href="#/ViewDog/{{d.id}}" target="_blank">{{d.name}}</a></td>
                            <td>{{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}</td>
                            <td>{{d.sireName}}</td>
                            <td>{{d.damName}}</td>
                            <!--<td><a href="#/Mail">&</a></td>-->
                            <td><a href="#/Mail/{{d.createdMailId}}" target="_blank">{{d.createdUserName}}</a></td>
                            <td>{{d.createdDate}}</td>
                            <!--<td>
                                <a href="#/Edit" class="btn btn-success btn-lg" title="Edit">
                                <span style="font-size: 15px" class="glyphicon glyphicon-edit"></span></a>
                            </td>-->
                           <!-- {{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}-->
                            <!--{{d.gender==1 ? 'Male' : 'Female' }}-->
                            <!--<td>
                                <a href="#" class="btn btn-success btn-lg" title="Delete">
                                    <span style="font-size: 15px" class="glyphicon glyphicon-remove"></span>
                                </a>
                            </td>-->
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

controller

```<code>    $scope.init = function () {
            $scope.IsVisible = true;
            $scope.IsVisibleForm = false;
            $scope.resultTble = false;
            //$scope.mail = urls.domain + "#/Mail/?createdMailId=";
    }

    var request = $http({
        method: 'GET',
        url: urls.api + 'Dog/NewDogs'

    }).success(function (data, status) {

        //console.log(data);
        //console.log(JSON.stringify(data));
        //console.log(JSON.parse(JSON.stringify(data)));

        $scope.newDogList = angular.fromJson(data);
        $scope.IsVisible = false;
        $scope.IsVisibleForm = true;
        $scope.resultTble = true;
    })
     .error(function (error) {
         $scope.status = 'Unable to load new dog list: ' + error.message;
         console.log($scope.status);
     });
</code>```

Thankyou

答:
The issue is that, the progress-bar is inside the main hiding div.

Current scenario:

If,

IsVisibleForm -- hides --> progress-bar -- hides

IsVisibleForm -- show --> progress-bar -- show

The above happens because progress-bar is the child of IsVisibleForm

Solution:

Move the progress-bar out of the IsVisibleForm div.

Since you have taken the progress-bar inside the main div the logic which you have used inside the init() function is not working.

```<code><div ng-show="IsVisible" style="text-align:center;" ng-init="init()">
    <md-progress-circular md-mode="indeterminate"></md-progress-circular>
    <h3>Please wait</h3>
</div>

<div class="w3-col m7" ng-init="init()" ng-show="IsVisibleForm">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>

                <br />
                <div>

                    <table class="table defaultTable" ng-show="resultTble">
                        ...
                        ...
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Page Loading Part in Angularjs

Body:
I finished the data loading part in the front-end, and also i'm trying to put the page loading part (Progress bar).But, it is not working in the correct way. I kindly request anyone to help me...

HTML

            <md-progress-circular md-mode="indeterminate"></md-progress-circular>

Please wait

New Dogs

                            Dog ID
                            Dog Name
                            Sex
                            Sire Name
                            Dam Name
                            Creater
                            Created Date

                            $
                            #
                            {{d.name}}
                            {{d.gender==1 ? 'Male' : d.gender==2 ? 'Female' : 'Unknown'}}
                            {{d.sireName}}
                            {{d.damName}}

                            {{d.createdUserName}}
                            {{d.createdDate}}

controller

    $scope.init = function () {
            $scope.IsVisible = true;
            $scope.IsVisibleForm = false;
            $scope.resultTble = false;
            //$scope.mail = urls.domain + "#/Mail/?createdMailId=";
    }

    var request = $http({
        method: 'GET',
        url: urls.api + 'Dog/NewDogs'

    }).success(function (data, status) {

        //console.log(data);
        //console.log(JSON.stringify(data));
        //console.log(JSON.parse(JSON.stringify(data)));

        $scope.newDogList = angular.fromJson(data);
        $scope.IsVisible = false;
        $scope.IsVisibleForm = true;
        $scope.resultTble = true;
    })
     .error(function (error) {
         $scope.status = 'Unable to load new dog list: ' + error.message;
         console.log($scope.status);
     });

Thankyou

Body:
The issue is that, the progress-bar is inside the main hiding div.

Current scenario:

If,

IsVisibleForm -- hides --> progress-bar -- hides

IsVisibleForm -- show --> progress-bar -- show

The above happens because progress-bar is the child of IsVisibleForm

Solution:

Move the progress-bar out of the IsVisibleForm div.

Since you have taken the progress-bar inside the main div the logic which you have used inside the init() function is not working.

<div ng-show="IsVisible" style="text-align:center;" ng-init="init()">
    <md-progress-circular md-mode="indeterminate"></md-progress-circular>
    <h3>Please wait</h3>
</div>

<div class="w3-col m7" ng-init="init()" ng-show="IsVisibleForm">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div>
                <h2><b>New Dogs</b></h2>

                <br />
                <div>

                    <table class="table defaultTable" ng-show="resultTble">
                        ...
                        ...
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


问:
How to add a new value to a list with md-autocomplete?
I want to use md-autocomplete to search for an object in an array. If the object is found I want an edit form to be populated, but if the object is not found, I want the user to be able to add a new one using the same form.

For example, I have an array of contacts: [{name: string, email: string}...].

Then in my template:

```<code><md-autocomplete
  md-selected-item="$ctrl.newContact"
  md-search-text="$ctrl.searchString"
  md-selected-item-change="$ctrl.selectedItemChanged(item)"
  md-items="item in $ctrl.getContactsByFullName($ctrl.searchString)"
  md-floating-label="Contact's Name"
  md-item-text="item.fullName">
</md-autocomplete>
<md-input-container>
  <label>Email</label>
  <input type='email' ng-model='$ctrl.newContact.email/>
</md-input-container>
</code>```

When I enter a new value in Contact's name, tab to email and enter a value in email, the value of  $ctrl.newContact.fullName becomes an object.

What am I doing wrong here? I've fiddled and codepenned but can't seem to get it right. Does anybody have a working example please?

答:
for those who are looking to achieve the same check this fiddle

Approach:
Basically it attach a new model whenever md-search-text-change event occured and also remove the garbage model.

html code

```<code><md-autocomplete
...
md-search-text="searchString"
md-search-text-change="selectedItemChanged(searchString)
...
</md-autocomplete>
</code>```

angular code

```<code>function selectedItemChanged(searchString){
  vm.contactArray.splice(actualLength,currentLength-actualLength)
  vm.newModel = {};
  vm.newModel.name=searchString;
  vm.newModel.email='test'
  vm.contacts.push(vm.newModel)

}
</code>```

Body:
I want to use md-autocomplete to search for an object in an array. If the object is found I want an edit form to be populated, but if the object is not found, I want the user to be able to add a new one using the same form.

For example, I have an array of contacts: [{name: string, email: string}...].

Then in my template:

<md-autocomplete
  md-selected-item="$ctrl.newContact"
  md-search-text="$ctrl.searchString"
  md-selected-item-change="$ctrl.selectedItemChanged(item)"
  md-items="item in $ctrl.getContactsByFullName($ctrl.searchString)"
  md-floating-label="Contact's Name"
  md-item-text="item.fullName">
</md-autocomplete>
<md-input-container>
  Email
  <input type='email' ng-model='$ctrl.newContact.email/>
</md-input-container>

When I enter a new value in Contact's name, tab to email and enter a value in email, the value of  $ctrl.newContact.fullName becomes an object.

What am I doing wrong here? I've fiddled and codepenned but can't seem to get it right. Does anybody have a working example please?

Body:
for those who are looking to achieve the same check this fiddle

Approach:
Basically it attach a new model whenever md-search-text-change event occured and also remove the garbage model.

html code

<md-autocomplete
...
md-search-text="searchString"
md-search-text-change="selectedItemChanged(searchString)
...
</md-autocomplete>

angular code

function selectedItemChanged(searchString){
  vm.contactArray.splice(actualLength,currentLength-actualLength)
  vm.newModel = {};
  vm.newModel.name=searchString;
  vm.newModel.email='test'
  vm.contacts.push(vm.newModel)

}


问:
Find and tag a number between a range
I have two dfs as below

```<code>>codes1

Country       State                       City  Start No    End No
IN          Telangana                Hyderabad    100        200
IN        Maharashtra       Pune (Bund Garden)    300        400
IN            Haryana                  Gurgaon    500        600
IN        Maharashtra                     Pune    700        800
IN            Gujarat    Ahmedabad (Vastrapur)    900        1000
</code>```

Now i want to tag ip address from table 1

```<code>>codes2

ID     No
1      157
2      346
3      389
4      453
5      562
6      9874
7      98745
</code>```

Now i want to tag numbers in codes2 df as per the range given in codes1 df for No column , expected ouput is

```<code>ID     No    Country     State          City
1     157       IN      Telangana     Hyderabad
2     346       IN     Maharashtra   Pune(Bund Garden)
.
.
.
</code>```

Basically want to tag No column in codes 2 with codes1 according to the range (Start No and End No) that No observations falls in.

Also the order could be anything in codes 2 df .

答:
if you're comfortable writing SQL, you might consider using the sqldf package to do something like

```<code>library('sqldf')
result <- sqldf('select * from codes2 left join codes1 on codes2.No between codes1.StartNo and codes1.EndNo')
</code>```

you may have to remove special characters and spaces from the columnnames of your dataframes beforehand.

Title: Find and tag a number between a range

Body:
I have two dfs as below

>codes1

Country       State                       City  Start No    End No
IN          Telangana                Hyderabad    100        200
IN        Maharashtra       Pune (Bund Garden)    300        400
IN            Haryana                  Gurgaon    500        600
IN        Maharashtra                     Pune    700        800
IN            Gujarat    Ahmedabad (Vastrapur)    900        1000

Now i want to tag ip address from table 1

>codes2

ID     No
1      157
2      346
3      389
4      453
5      562
6      9874
7      98745

Now i want to tag numbers in codes2 df as per the range given in codes1 df for No column , expected ouput is

ID     No    Country     State          City
1     157       IN      Telangana     Hyderabad
2     346       IN     Maharashtra   Pune(Bund Garden)
.
.
.

Basically want to tag No column in codes 2 with codes1 according to the range (Start No and End No) that No observations falls in.

Also the order could be anything in codes 2 df .

Body:
if you're comfortable writing SQL, you might consider using the sqldf package to do something like

library('sqldf')
result <- sqldf('select * from codes2 left join codes1 on codes2.No between codes1.StartNo and codes1.EndNo')

you may have to remove special characters and spaces from the columnnames of your dataframes beforehand.


问:
Cassandra 'nodetool repair -pr' taking way too much time
I am running a cluster with 1 datacenter (10 nodes) and Cassandra 2.1.7 installed on each. We are using SimpleStretegy (old mistake).

The situation is, I have not run any nodetool repair since begining, and now there is data of about 200 GB with 3 RF.

As running full repair or incremental repair is same at this point. So I have tried to run full repair. But this result in coordinator node down.

So I end up running full partition ranges repair (nodetool repair -pr) on each node one at a time. But this is taking way too much time (15+ hrs for each node, hence weeks for all nodes).

Am I doing this wrong, or this is supposed to happen? Or this is a version problem?

In future, if I run full repair again after finishing this, would this take weeks as well?

答:
Since full repair is mainly affected by data size, it should take same amount of time.

I suggest moving to incremental repairs, this should save your time and resources.

Here's a article about how to do this in 2.1:
https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/opsRepairNodesMigration.html


问:
Implementing a file based queue
I have an in memory bounded queue in which multiple threads queue objects. Normally the queue should be emptied by a single reader thread that processes the items in the queue.

However, there is a possibility that the queue is filled up. In such a case I would like to persist any additional items on the disk that would be processed by another background reader thread that scans a directory for such files and processes the entries within the files. I am familiar with Active MQ but prefer a more light weight solution. It is ok if the "FIFO" is not strictly followed (since the persisted entries may be processed out of order).

Are there any open source solutions out there? I did not find any but thought I would ping this list for suggestions before I embark on the implementation myself.

Thank you!

答:
The most performant and GC friendly solution I've found by now is Chronicle Queue.
It has extremely low write latency, order of tens of nanoseconds, several grades of magnitude lower than MapDB or SQLite.</p>

ContentLicense: CC BY-SA 2.5

Title: Implementing a file based queue


问:
Chrome --kiosk-printing has 1-2 minute lag/delay
I need print receipt in Chrome running in

```<code>--kiosk
</code>```

mode. Of course I use

```<code>--kiosk-printing
</code>```

to disable print dialog. I have to note this parameter only emulate automatic pressing Print button.

My printer is Rongta RP80 80mm Thermal Receipt Printer connected via USB to laptop with Windows 10, Chrome 57.

Printing mechanism is easy, printing launches by javascript on page.

When I don't use --kiosk-printing parameter printing starts immediately on Print button press in chrome print preview dialog.

I face to big problem with --kiosk-printing: printing starts only after 1-2 minutes since chrome printing dialog appear and disappear (as noticed, parameter only emulate automatic pressing Print button). It is not printer problem, cause new document appear in windows print queue after this lag.

Why there is a so big lag with --kiosk-printing parameter, how to minimize it?

答: I had the same problem. Using Chrome Canary on a Windows 8.1 PC solved it for me. </p>

Body:
I need print receipt in Chrome running in

--kiosk

mode. Of course I use

--kiosk-printing

to disable print dialog. I have to note this parameter only emulate automatic pressing Print button.

My printer is Rongta RP80 80mm Thermal Receipt Printer connected via USB to laptop with Windows 10, Chrome 57.

Printing mechanism is easy, printing launches by javascript on page.

When I don't use --kiosk-printing parameter printing starts immediately on Print button press in chrome print preview dialog.

I face to big problem with --kiosk-printing: printing starts only after 1-2 minutes since chrome printing dialog appear and disappear (as noticed, parameter only emulate automatic pressing Print button). It is not printer problem, cause new document appear in windows print queue after this lag.

Why there is a so big lag with --kiosk-printing parameter, how to minimize it?


问:
Algorithm for finding strings that a specific Regex will match
Given a regex pattern, I'm trying to find a string that matches it. Similar to how Django reverses them, but in C#. Are there any pre-made C# libraries that do this?

Edit: Moving this project to Google code pretty soon.

Current Test Results

```<code>^abc$                     > abc                  : pass
\Aa                       > a                    : pass
z\Z                       > z                    : pass
z\z                       > z                    : pass
z\z                       > z                    : pass
\G\(a\)                   > \(a\)                : pass
ab\b                      > ab                   : pass
a\Bb                      > ab                   : pass
\a                        >                     : pass
[\b]                      >                    : pass
\t                        > \t                   : pass
\r                        > \r                   : pass
\v                        > ♂                    : pass
\f                        > \f                   : pass
\n                        > \n                   : pass
\e                        > ←                    : pass
\141                      > a                    : pass
\x61                      > a                    : pass
\cC                       > ♥                    : pass
\u0061                    > a                    : pass
\\                        > \\                   : pass
[abc]                     > a                    : pass
[^abc]                    > î                    : pass
[a-z]                     > a                    : pass
.                         > p                    : pass
\w                        > W                    : pass
\W                        > ☻                    : pass
\s                        > \n                   : pass
\S                        > b                    : pass
\d                        > 4                    : pass
\D                        > G                    : pass
(a)\1                     > aa                   : pass
(?<n>a)\k<n>              > aa                   : pass
(?<n>a)\1                 > aa                   : pass
(a)(?<n>b)\1\2            > abab                 : pass
(?<n>a)(b)\1\2            > abba                 : pass
(a(b))\1\2                > ababb                : pass
(a(b)(c(d)))\1\2\3\4      > abcdabcdbcdd         : pass
a\0                       > a                    : pass
ab*                       > a                    : pass
ab+                       > abbb                 : pass
ab?                       > a                    : pass
ab{2}                     > abb                  : pass
ab{2,}                    > abbbbbbbbb           : pass
ab{2,3}                   > abb                  : pass
ab*?                      > abb                  : pass
ab+?                      > abbbbb               : pass
ab??                      > a                    : pass
ab{2}?                    > abb                  : pass
ab{2,}?                   > abbbbbbbbb           : pass
ab{2,3}?                  > abbb                 : pass
/users(?:/(?<id>\d+))?    > /users/77            : pass
Passed 52/52 tests.
</code>```

答:
"Are there any pre-made C# libraries that do this?"

NO

(I expect this will be accepted as the answer momentarily)

Body:
Given a regex pattern, I'm trying to find a string that matches it. Similar to how Django reverses them, but in C#. Are there any pre-made C# libraries that do this?

Edit: Moving this project to Google code pretty soon.

Current Test Results

^abc$                     > abc                  : pass
\Aa                       > a                    : pass
z\Z                       > z                    : pass
z\z                       > z                    : pass
z\z                       > z                    : pass
\G\(a\)                   > \(a\)                : pass
ab\b                      > ab                   : pass
a\Bb                      > ab                   : pass
\a                        >                     : pass
[\b]                      >                    : pass
\t                        > \t                   : pass
\r                        > \r                   : pass
\v                        > ♂                    : pass
\f                        > \f                   : pass
\n                        > \n                   : pass
\e                        > ←                    : pass
\141                      > a                    : pass
\x61                      > a                    : pass
\cC                       > ♥                    : pass
\u0061                    > a                    : pass
\\                        > \\                   : pass
[abc]                     > a                    : pass
[^abc]                    > î                    : pass
[a-z]                     > a                    : pass
.                         > p                    : pass
\w                        > W                    : pass
\W                        > ☻                    : pass
\s                        > \n                   : pass
\S                        > b                    : pass
\d                        > 4                    : pass
\D                        > G                    : pass
(a)\1                     > aa                   : pass
(?<n>a)\k<n>              > aa                   : pass
(?<n>a)\1                 > aa                   : pass
(a)(?<n>b)\1\2            > abab                 : pass
(?<n>a)(b)\1\2            > abba                 : pass
(a(b))\1\2                > ababb                : pass
(a(b)(c(d)))\1\2\3\4      > abcdabcdbcdd         : pass
a\0                       > a                    : pass
ab*                       > a                    : pass
ab+                       > abbb                 : pass
ab?                       > a                    : pass
ab{2}                     > abb                  : pass
ab{2,}                    > abbbbbbbbb           : pass
ab{2,3}                   > abb                  : pass
ab*?                      > abb                  : pass
ab+?                      > abbbbb               : pass
ab??                      > a                    : pass
ab{2}?                    > abb                  : pass
ab{2,}?                   > abbbbbbbbb           : pass
ab{2,3}?                  > abbb                 : pass
/users(?:/(?<id>\d+))?    > /users/77            : pass
Passed 52/52 tests.


问:
How to check specific value in JSONArray?
I have a little problem with looping in Swift 3. I have one JSONArray and one JSONObject like below :

dataReqList [Any] :

```<code>[{
bezeich = "MORE SALT";
grpnr = 0;
nr = 1;
}, {
bezeich = "MORE SWEET";
grpnr = 0;
nr = 2;
}, {
bezeich = "MORE PEPPER";
grpnr = 0;
nr = 3;
}, {
bezeich = "MORE CHILLI";
grpnr = 0;
nr = 4;
}, {
bezeich = COLD;
grpnr = 0;
nr = 5;
}, {
bezeich = HOT;
grpnr = 0;
nr = 6;
}, {
bezeich = SMALL;
grpnr = 0;
nr = 7;
}, {
bezeich = LARGE;
grpnr = 0;
nr = 8;
}, {
bezeich = "MEDIUM COOKED";
grpnr = 0;
nr = 9;
}, {
bezeich = "WELL DONE";
grpnr = 0;
nr = 10;
}]
</code>```

currArticle [Anyhashable: Any] :

```<code>Optional([AnyHashable("bezeich"): Fresh and Green Salad,
        AnyHashable("special-request"): ["MORE PEPPER", "COLD", "HOT"]])
</code>```

I want to know, how to print the key bezeich in array , if the JSONArray have same String with special-request in JSONObject. I've try this but its not working :

```<code>for i in 0..<dataReqList.count {
        if ( ((dataReqList[i] as? [AnyHashable: Any])? ["bezeich"] as! String) == (("\(currArticle?["special-request"]!)") as String) ) {
            print (dataReqList[i])
        }
</code>```

Any answer and suggest will help for me. Thanks in advance

EDIT :
I'm new in Swift. I have read THIS before but its still not work.

答:
Key special-request with currArticle Dictionary having Array of String as value so you can not directly compare it with string, you can use filter for that like this.

```<code>var filterArray = [[String:Any]]()
if let dataArray = dataReqList as? [[String:Any]],
   let specialRequestArray = currArticle["special-request"] as? [String] {

     filterArray = dataArray.filter { specialRequestArray.contains($0["bezeich"] as? String ?? "") }
     print(filterArray)
}
</code>```

Body:
I have a little problem with looping in Swift 3. I have one JSONArray and one JSONObject like below :

dataReqList [Any] :

[{
bezeich = "MORE SALT";
grpnr = 0;
nr = 1;
}, {
bezeich = "MORE SWEET";
grpnr = 0;
nr = 2;
}, {
bezeich = "MORE PEPPER";
grpnr = 0;
nr = 3;
}, {
bezeich = "MORE CHILLI";
grpnr = 0;
nr = 4;
}, {
bezeich = COLD;
grpnr = 0;
nr = 5;
}, {
bezeich = HOT;
grpnr = 0;
nr = 6;
}, {
bezeich = SMALL;
grpnr = 0;
nr = 7;
}, {
bezeich = LARGE;
grpnr = 0;
nr = 8;
}, {
bezeich = "MEDIUM COOKED";
grpnr = 0;
nr = 9;
}, {
bezeich = "WELL DONE";
grpnr = 0;
nr = 10;
}]

currArticle [Anyhashable: Any] :

Optional([AnyHashable("bezeich"): Fresh and Green Salad,
        AnyHashable("special-request"): ["MORE PEPPER", "COLD", "HOT"]])

I want to know, how to print the key bezeich in array , if the JSONArray have same String with special-request in JSONObject. I've try this but its not working :

for i in 0..<dataReqList.count {
        if ( ((dataReqList[i] as? [AnyHashable: Any])? ["bezeich"] as! String) == (("\(currArticle?["special-request"]!)") as String) ) {
            print (dataReqList[i])
        }

Any answer and suggest will help for me. Thanks in advance

EDIT :
I'm new in Swift. I have read THIS before but its still not work.

Body:
Key special-request with currArticle Dictionary having Array of String as value so you can not directly compare it with string, you can use filter for that like this.

var filterArray = [[String:Any]]()
if let dataArray = dataReqList as? [[String:Any]],
   let specialRequestArray = currArticle["special-request"] as? [String] {

     filterArray = dataArray.filter { specialRequestArray.contains($0["bezeich"] as? String ?? "") }
     print(filterArray)
}


问:
Function's input appear to be a list
I have a nested list and a header which is the column name.
I want to find maximum in column and print out the maximum's row information.
Here's my code.

```<code>def find_col(v):
    for i in range(1,31):
        if header[i]==v:
            return i

def col_list(col):
    list = []
    for row in linelist:
        list.append(row[int(col)])
    return list

def M(col):
    def max(li):
        inf = -float('inf')
        maxnumber = inf
        for i, value in enumerate(li):
            if value>maxnumber:
                maxnumber = value
        return maxnumber
    return max(col_list(col))
def max_row(col):
    li = col_list(col)
    m = M(col)
    for i, j in enumerate(li):
        if j == m:
            return i

def col_max(name):
    col = find_col(name)
    return M(col)

def pri(name):
    column = find_col(name)
    maxima = M(column)
    li = col_list(column)
    maxrow = max_row(li)
    print(linelist[maxrow][1], linelist[maxrow][4], maxima)

pri('MP')
</code>```

The problem is at function col_list, but I can't figure out how 'col' appear to be a list.

答:
The problem seams to be that in the function pri(name) you call max_row in the statement maxrow = max_row(li) where li is what col_list returns (a list...) so you call max_row(<somelist>). However, max_row then goes ahead and calls col_list with its input parameter (so a list, since it was passed a list...) that's where things go wrong.

How to fix it depends on what exactly you want to do. If I understand your intentions correctly something like:

```<code>li = []
for row in <imputParameter>: ## in your case its called col, but its a list...
  li.append(max(row)) ## or some other way to compute the value you want from that...
##continue function as in your case...
</code>```

hope that helps.

Title: Function's input appear to be a list

Body:
I have a nested list and a header which is the column name.
I want to find maximum in column and print out the maximum's row information.
Here's my code.

def find_col(v):
    for i in range(1,31):
        if header[i]==v:
            return i

def col_list(col):
    list = []
    for row in linelist:
        list.append(row[int(col)])
    return list

def M(col):
    def max(li):
        inf = -float('inf')
        maxnumber = inf
        for i, value in enumerate(li):
            if value>maxnumber:
                maxnumber = value
        return maxnumber
    return max(col_list(col))
def max_row(col):
    li = col_list(col)
    m = M(col)
    for i, j in enumerate(li):
        if j == m:
            return i

def col_max(name):
    col = find_col(name)
    return M(col)

def pri(name):
    column = find_col(name)
    maxima = M(column)
    li = col_list(column)
    maxrow = max_row(li)
    print(linelist[maxrow][1], linelist[maxrow][4], maxima)

pri('MP')

The problem is at function col_list, but I can't figure out how 'col' appear to be a list.

Body:
The problem seams to be that in the function pri(name) you call max_row in the statement maxrow = max_row(li) where li is what col_list returns (a list...) so you call max_row(<somelist>). However, max_row then goes ahead and calls col_list with its input parameter (so a list, since it was passed a list...) that's where things go wrong.

How to fix it depends on what exactly you want to do. If I understand your intentions correctly something like:

li = []
for row in <imputParameter>: ## in your case its called col, but its a list...
  li.append(max(row)) ## or some other way to compute the value you want from that...
##continue function as in your case...

hope that helps.


问:
Javascript replace every 6th colon in array
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

```<code>arrayProducts[i] = arrayProducts[i].join(':');
</code>```

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

```<code>F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3
</code>```

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

答:
What you are looking for is to split over the following expression :[A-Z]
(assuming that your rows always start with this range)

a simple solution could be:

```<code>mystring.split(/:[A-Z]/).join(',')
</code>```

/:[A-Z]/ matches any : followed by a uppercase letter

Body:
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

arrayProducts[i] = arrayProducts[i].join(':');

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

Body:
What you are looking for is to split over the following expression :[A-Z]
(assuming that your rows always start with this range)

a simple solution could be:

mystring.split(/:[A-Z]/).join(',')

/:[A-Z]/ matches any : followed by a uppercase letter


问:
create new file with system calls
Im trying to create a new file / overwrite an existing file using systemcalls
, but  for some reason I have two problems:

1. When I'm first running the program it exits with value 0, so it seems
 like it created the file successfully, but I can't see anything in my project directory.

 then when I secondly running the program the file is created, but an error message is printed on the screen.

 2. Also after the first iteration of the program, I can't see the prinf message at the end of the main function.

Thanks for helping.

```<code>    int readFileDesc = 0, writeFiledesc = 0;
    int sourceFile = 1, destFile = 2, bufferSize = 3, isOverwrite;

    if (argc != 4 && argc != 5) {
        printf("Invalid number of arguments\n");
        printf("Usage:\n");
        printf("     ex1 [-f] SOURCE DEST BUFFER_SIZE");
        exit(EXIT_FAILURE);
    }

    //Checking if -f [OP] is activated.
    isOverwrite = (strcmp(argv[1], "-f") == 0);

    if (isOverwrite) {
        sourceFile++;
        destFile++;
        bufferSize++;
    }

    //Opening the source file
    readFileDesc = open(argv[sourceFile], O_RDONLY);
    if (readFileDesc < 0) {
        perror("Unable to open source file for reading: ");
        exit(EXIT_FAILURE);
    }

    //opening the destination file

    if (!isOverwrite) {
        //Case we dont have the -f [op] so we create the file.
        writeFiledesc = open(argv[destFile],
                O_CREAT | O_EXCL | O_WRONLY ,
                S_IRUSR | S_IWUSR);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for reading: ");
            exit(EXIT_FAILURE);
        }
    } else {
        //Case we have the -f [op] so we override existing file.
        writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for writing: ");
            exit(EXIT_FAILURE);
        }
    }

    //Assume the buffersize is legal.
    bufferSize = atoi(argv[bufferSize]);
    char data[bufferSize];
    int nread, nwrite;
    while ((nread = read(readFileDesc, data, bufferSize)) > 0) {
        if ((nwrite = write(writeFiledesc, data, nread)) != nread) {
            printf("write problem: ");
        }
    }
// cant see this!
    printf("File %s was copied to %s" , argv[sourceFile] , argv[destFile]);
    //handling errors
    close(sourceFile);
    close(destFile);

        return EXIT_SUCCESS;
    }
</code>```

答:
This is wrong:

```<code>    writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
</code>```

Using both O_RDONLY and O_WRONLY is wrong.  You need to use O_RDWR.

Per the POSIX standard for open():

SYNOPSIS

```<code>#include <sys/stat.h> #include <fcntl.h>

int open(const char *path, int oflag, ...);
</code>```

...

Values for oflag are constructed by a bitwise-inclusive OR of flags
  from the following list, defined in . Applications shall
  specify exactly one of the first five values (file access modes)
  below in the value of oflag:

O_EXEC

Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.

O_RDONLY

Open for reading only.

O_RDWR

Open for reading and writing. The result is undefined if this flag is applied to a FIFO.

O_SEARCH

Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.

O_WRONLY

Open for writing only.

Any combination of the following may be used:

...

Also, read() and write() return ssize_t, not int.

Title: create new file with system calls

Body:
Im trying to create a new file / overwrite an existing file using systemcalls
, but  for some reason I have two problems:

1. When I'm first running the program it exits with value 0, so it seems
 like it created the file successfully, but I can't see anything in my project directory.

 then when I secondly running the program the file is created, but an error message is printed on the screen.

 2. Also after the first iteration of the program, I can't see the prinf message at the end of the main function.

Thanks for helping.

    int readFileDesc = 0, writeFiledesc = 0;
    int sourceFile = 1, destFile = 2, bufferSize = 3, isOverwrite;

    if (argc != 4 && argc != 5) {
        printf("Invalid number of arguments\n");
        printf("Usage:\n");
        printf("     ex1 [-f] SOURCE DEST BUFFER_SIZE");
        exit(EXIT_FAILURE);
    }

    //Checking if -f [OP] is activated.
    isOverwrite = (strcmp(argv[1], "-f") == 0);

    if (isOverwrite) {
        sourceFile++;
        destFile++;
        bufferSize++;
    }

    //Opening the source file
    readFileDesc = open(argv[sourceFile], O_RDONLY);
    if (readFileDesc < 0) {
        perror("Unable to open source file for reading: ");
        exit(EXIT_FAILURE);
    }

    //opening the destination file

    if (!isOverwrite) {
        //Case we dont have the -f [op] so we create the file.
        writeFiledesc = open(argv[destFile],
                O_CREAT | O_EXCL | O_WRONLY ,
                S_IRUSR | S_IWUSR);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for reading: ");
            exit(EXIT_FAILURE);
        }
    } else {
        //Case we have the -f [op] so we override existing file.
        writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for writing: ");
            exit(EXIT_FAILURE);
        }
    }

    //Assume the buffersize is legal.
    bufferSize = atoi(argv[bufferSize]);
    char data[bufferSize];
    int nread, nwrite;
    while ((nread = read(readFileDesc, data, bufferSize)) > 0) {
        if ((nwrite = write(writeFiledesc, data, nread)) != nread) {
            printf("write problem: ");
        }
    }
// cant see this!
    printf("File %s was copied to %s" , argv[sourceFile] , argv[destFile]);
    //handling errors
    close(sourceFile);
    close(destFile);

        return EXIT_SUCCESS;
    }

Body:
This is wrong:

    writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);

Using both O_RDONLY and O_WRONLY is wrong.  You need to use O_RDWR.

Per the POSIX standard for open():

SYNOPSIS

#include <sys/stat.h> #include <fcntl.h>

int open(const char *path, int oflag, ...);

...

Values for oflag are constructed by a bitwise-inclusive OR of flags
  from the following list, defined in . Applications shall
  specify exactly one of the first five values (file access modes)
  below in the value of oflag:

O_EXEC

Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.

O_RDONLY

Open for reading only.

O_RDWR

Open for reading and writing. The result is undefined if this flag is applied to a FIFO.

O_SEARCH

Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.

O_WRONLY

Open for writing only.

Any combination of the following may be used:

...

Also, read() and write() return ssize_t, not int.


答:
$http request is asynchronous you should use like this

```<code>$scope.$apply(function(){
    $scope.isLoading = false;
});
</code>```

And as whole like this

```<code><md-progress-circular md-mode="indeterminate" ng-show="isLoading"></md-progress-circular>
</code>```

And in your JS

```<code>$scope.isLoading = true;

$http.get("/posts")
   .success(function (data) {
         $scope.$apply(function(){
           $scope.isLoading = false;
         });
   });
</code>```

Title: Page Loading Part in Angularjs

Body:
$http request is asynchronous you should use like this

$scope.$apply(function(){
    $scope.isLoading = false;
});

And as whole like this

<md-progress-circular md-mode="indeterminate" ng-show="isLoading"></md-progress-circular>

And in your JS

$scope.isLoading = true;

$http.get("/posts")
   .success(function (data) {
         $scope.$apply(function(){
           $scope.isLoading = false;
         });
   });


答:
A regex solution is viable. You can use a function as the second parameter of the .replace method to make full use of backreferences.

var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3';

str = str.replace(/((?:[^:]*:){6}(?:[^:]*)):/g, function() {
    var matches = arguments;
    return matches[1] + ',';
});

console.log(str);```

Title: Javascript replace every 6th colon in array


问:
how to simulate keypress for unit testing in jasmine
I need to unit test function that is triggered when key pressed.

```<code>public onKeyDown(event: KeyboardEvent): void {
    if (event.ctrlKey && event.keyCode === 38) {
      console.log('increase');
    }
    if (event.ctrlKey && event.keyCode === 40) {
      console.log('decrease');
    }

    /* Prevent entering characters */
    if (event.keyCode >= 65 && event.keyCode <= 90) {
      return;
    }
  }
</code>```

How can I simulate keypress to satisfy the fist condition, for example?

答:
The example code below shows how an event is created, triggered, and intercepted. </p>

```<code>var keyPressed = null;

function keyPress(key) {
  var event = document.createEvent('Event');
  event.keyCode = key;
  event.initEvent('keydown');
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function(e){
   keyPressed = e.keyCode;
});

keyPress(37)
alert(keyPressed);
</code>```

Body:
I need to unit test function that is triggered when key pressed.

public onKeyDown(event: KeyboardEvent): void {
    if (event.ctrlKey && event.keyCode === 38) {
      console.log('increase');
    }
    if (event.ctrlKey && event.keyCode === 40) {
      console.log('decrease');
    }

    /* Prevent entering characters */
    if (event.keyCode >= 65 && event.keyCode <= 90) {
      return;
    }
  }

How can I simulate keypress to satisfy the fist condition, for example?

Body:
The example code below shows how an event is created, triggered, and intercepted.

var keyPressed = null;

function keyPress(key) {
  var event = document.createEvent('Event');
  event.keyCode = key;
  event.initEvent('keydown');
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function(e){
   keyPressed = e.keyCode;
});

keyPress(37)
alert(keyPressed);


问:
Is it possible to change the size of the text in an HTML input tag?
I have a client who wants bigger text in an <input> box.  I would prefer to not have to make custom graphic button for this as it's on a really resource-constrained embedded system.

答: not only should you increase the font-size, you may also have to increase the height and line-height properties if the input element doesn't scale with the text (depending on how your styles were set).  Also, be sure to check across all browsers, as forms can be very finicky.


问:
Continuous Integration with VSTS
I am trying  to do a PoC on how to achieve continuous integration and deployment using VSTS.
I have been successful in the build process i.e. from VSTS it will pull the code (asp.net based application) and build. The build process is also getting successful.
Now after the build is done I want to deploy the application and run my maven based selenium test cases written in java on the application. This is the part where I am struck. As in the deployment step it is not able to put the artifacts to the remote path that I am mentioning.
Can anyone please provide me some pointers on how to achieve the deployment on a remote machine and then run the java based test cases on this application?

Any pointers would be greatly appreciated.

Ok..here is the complete scenario...
1. I have the asp.net code on cloud in my vsts
2. I have been able to add a build step and create the artifacts successfully
3. Now I have a IIS server where i want to deploy these artifacts, and the server is not accessible from the public network and is behind a firewall.

Hence I am looking for any task that would help me achieve this. I am not sure of the complications that might arise due to the firewall and hence am trying out different methods to understand the complete big picture.
I received a reply here to use the Win RM tasks. I used that but it is giving a 53 error and not able to connect to the server that I am trying to deploy the code on.

答:
To deploy asp.net based application, you can use IIS Web App Deployment step/task to deploy to your server or deploy to azure web site by using Azure App Service Deploy step/task.

To do Java test, there is a Maven step/task.

Title: Continuous Integration with VSTS


问:
indexing server in google chrome browser extension
Is it possible to start an indexing server (like SOLR) within a google chrome extension, so that the user can index files to the local server via the extension?</p>

答:
Disclaimer I'm the author of the Google Chrome Extension Solr Query Debugger

A Google Chrome extension is a Javascript program where you can make HTTP requests to your Solr server so that you can update and query Solr documents.

You can even upload your documents (files like MS Word, MS Excel, pdf, etc.) with Solr Cell using Apache Tika

Solr's ExtractingRequestHandler can use Tika to support uploading
  binary files, including files in popular formats such as Word and PDF,
  for data extraction and indexing.

So you have to configure  first ExtractingRequestHandler in order to upload your documents and then leave to Apache Tika the task to parse them.


问:
How to fetch class instance from class variable (from outside the class)?
Let's say I have this:

```<code>from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?
</code>```

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

答:
One way would we to define foo as a custom property that returns both its value and the related instance when its value is fetched:

```<code>from collections import namedtuple

class Prop(object):
    def __init__(self, val):
        self.val = val

    def __get__(self, instance, type):
        return namedtuple('Prop', ('value', 'instance'))(self.val, instance)

    def __set__(self, instance, val):
        self.val = val

class MyClass(object):
    foo = Prop('bar')
</code>```

Now in your program you can explicitly use its value and the related instance using foo's value and instance attributes respectively.

Demo:

```<code>>>> instance = MyClass()
>>> instance.foo
Prop(value='bar', instance=<__main__.MyClass object at 0x10effbcd0>)
>>> instance.foo.value
'bar'
>>> instance.foo.instance
<__main__.MyClass object at 0x10effbcd0>
</code>```

Body:
Let's say I have this:

from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

Body:
One way would we to define foo as a custom property that returns both its value and the related instance when its value is fetched:

from collections import namedtuple

class Prop(object):
    def __init__(self, val):
        self.val = val

    def __get__(self, instance, type):
        return namedtuple('Prop', ('value', 'instance'))(self.val, instance)

    def __set__(self, instance, val):
        self.val = val

class MyClass(object):
    foo = Prop('bar')

Now in your program you can explicitly use its value and the related instance using foo's value and instance attributes respectively.

Demo:

>>> instance = MyClass()
>>> instance.foo
Prop(value='bar', instance=<__main__.MyClass object at 0x10effbcd0>)
>>> instance.foo.value
'bar'
>>> instance.foo.instance
<__main__.MyClass object at 0x10effbcd0>


问:
Trouble adding second reCAPTCHA. Have Contact Form 7 w/ reCAPTCHA
I have a Wordpress site, that uses the Contact Form 7 plugin and the reCAPTCHA functionality that comes with that, and that works great. I just put that part in place, everything is automatic. But now I'm trying to add a reCAPTCHA to another form (on page form1.php) that isn't set up with Contact Form 7. This is on a PHP page that basically includes the Wordpress header and footer, but does its own thing in the middle. One key point is that the footer includes one of the forms from Contact Form 7, so it's on every page on the site.

I followed Google's instructions, forgetting I had the footer form. Then I saw an error in Firebug Error: ReCAPTCHA placeholder element must be empty

That brought me to this StackOverflow topic here. The only answer there by user easy going says that they had the same error when they realized they had imported the library twice.

Ok, that's what I did too I realized. So, I can remove the script inclusion of https://www.google.com/recaptcha/api.js in my code since it's already included by Contact Form 7 (I see it in the source). I noticed Google had instructions for rendering multiple widgets, I checked it out. But the problem is that the script include line specifies the onload callback function. Big problem. I can't change that because Contact Form 7 puts that in, and I can't make a callback function of the same name since it's already used. Of course I don't want to mess with anything that Contact Form 7 does. But as a result, I don't know how to get it to call my callback function in form1.php which is where my HTML element is specified to render the captcha.

Do you see any way around this issue? Any help is greatly appreciated!

答:
Here is the resolution:

Contact Form 7 supports multiple reCaptcha, just need the right HTML markup to use it.

As you can see in the wp-content\plugins\contact-form-7\modules\recaptcha.php, and also in the HTML, the trick is:

Your non-CF7 reCaptcha must be just inside a form element, like this:

var verifyCallbackY = function(response) {
    /** your stuff... */
    alert(response);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="recaptcha-cf7-migr"> <!-- the form element is important! This is what CF7 fetch one by one to find recaptchas... -->
    <div
        id='yRecaptcha'
        class="wpcf7-form-control g-recaptcha wpcf7-recaptcha captcha-hfs"
        data-sitekey="*********************************qkuila"
        data-callback="verifyCallbackY"></div>
</form></code>```

Body:
Here is the resolution:

Contact Form 7 supports multiple reCaptcha, just need the right HTML markup to use it.

As you can see in the wp-content\plugins\contact-form-7\modules\recaptcha.php, and also in the HTML, the trick is:

Your non-CF7 reCaptcha must be just inside a form element, like this:

var verifyCallbackY = function(response) {
    /** your stuff... */
    alert(response);
};

<form id="recaptcha-cf7-migr"> <!-- the form element is important! This is what CF7 fetch one by one to find recaptchas... -->
    <div
        id='yRecaptcha'
        class="wpcf7-form-control g-recaptcha wpcf7-recaptcha captcha-hfs"
        data-sitekey="*********************************qkuila"
        data-callback="verifyCallbackY"></div>
</form>


问:
How to use openpyxl to insert one sheet to a template?
I want to generate excel spreadsheets by python, the first few tabs are exactly same, all are refer to the last page, so how to insert the last page by openpyxl? because the first few tabs are too complex so load_workbook is always failed, is there have any other way to insert tabs without loading? </p>

答: As far as i know, openpyxl does not allow you to access only one cell, or a limited number of cells for that matter. In order to access any information in a given worksheet, openpyxl will create one in the memory. This is the reason for which you will be unable to add a Sheet without opening the entire document in memory and overwriting it at the end. </p>


问:
How to set dynamic route in codeigniter from database?
In my routes.php file I have added the following code for routing:

```<code>$route['report/:num'] = "home/reportcard/$1";
</code>```

Here is my controller code:

```<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }
</code>```

Here is my model code:

```<code><?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>
</code>```

this is the code of view. I just print the array in my report_view for testing purpose:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>
</code>```

this is my home_view code:

```<code><div class="row">
                <ul class="home-grid">
                    <?php foreach ($query->result() as $row): ?>
                    <li>
                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report"><span class="glyphicon glyphicon-list-alt"></span> <br/>
                        <?=$row->item ?><br/>
                         <small>Click here for see report</small>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
</code>```

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

答:
In your model this is wrong return $data->result(); actually $query->result(); is right.

```<code><?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>
</code>```

Body:
In my routes.php file I have added the following code for routing:

$route['report/:num'] = "home/reportcard/$1";

Here is my controller code:

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Home extends CI_Controller
    {

        function __construct() {
            parent::__construct();

        if(empty($this->session->userdata('id_user'))){
            $this->session->set_flashdata('flash_data', 'You cannot access');
                    redirect('login');
        }
        }
        public function index(){
            $this->load->model("item_model");
            $data['records'] = $this->item_model->getAllItems();
            $this->load->view('home',$data);
        }

       function reportcard($id){
            $this->load->model("item_model");
            $data['report'] = $this->item_model->getReport($id);
            $this->load->view('report', $data);
        }

        function logout(){
            $data=['id_user','username'];
            $this->session->unset_userdata($data);
            redirect('login');

        }
    }

Here is my model code:

<?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>

this is the code of view. I just print the array in my report_view for testing purpose:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
print_r($report);
?>

this is my home_view code:

                    <?php foreach ($query->result() as $row): ?>

                        <a  href="<?php echo base_url() ?>report/<?=$row->item ?>/<?=$row->id ?>" class="btn btn-lg btn-warning view-report">

                        <?=$row->item ?>

                         Click here for see report

                    <?php endforeach; ?>

I have tried multiple times to view the array. But failed to get array. How can I load the view? When I click my items from home, it will create a url like http://localhost/super_shop_register/report/1

But didn't show any data. Show "Object not found!". Here is the image of my view:
After Clicking item, it will show like this:

How can I solve this?

Body:
In your model this is wrong return $data->result(); actually $query->result(); is right.

<?php
    class Item_model extends CI_Model
    {
        function getAllItems()
        {
            $this->load->database();
            $q = $this->db->get("item");
            if($q->num_rows() > 0)
            {
                return $q->result();
            }
            return array();
        }

        public function getReport($id){
            $this->db->select('*');
            $this->db->from('item');
            $this->db->where('item.id', $id);
            $query = $this->db->get();
            if($query->num_rows() > 0)
                return $data->result();
        }

}
?>


问:
React do I have to rerender parent in order to rerender children?
I have a table component, with list of items.
By changing an item in the list, I see that whole table is rerender.
I tried to put shouldComponentUpdate, and by returning false I see that the Row components are not rerendered.
Do I have to rerender the parent in order to rerender child components?</p>

答:
https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

Returning false does not prevent child components from re-rendering when their state changes.

If the data in the child is passed as a property from the parent, then yes, you will have to rerender the parent to rerender the child. The reason for this is that if your child is reliant on props, and the parent does not render, then those props are never changed for the child as it only receives changed props when the parent renders and gives it new ones based on its own state or props. I suspect this is your problem. Rerendering the parent is not usually a performance problem in React.

If the children had their own state that was changing then not rerendering the parent would be ok. Another option if you are using a state container is to connect the children directly to the state and then their props get updated when the state container updates the relevant state, but that is somewhat beyond the scope of this question.

In general, it is best not to use shouldComponentUpdate unless performance demands it and then only with very careful consideration.


问:
How do I improve ASP.NET MVC application performance?
How do you improve your ASP.NET MVC application performance?

答:
Following are things to do

Kernel mode Cache

Pipeline mode

Remove unused modules

runAllManagedModulesForAllRequests

Don't write in wwwroot

Remove unused view engines and language


问:
Are there any free parser generators that generate C++ code and handle Unicode correctly?
After asking this question, I'm now sold on trying to use a parser generator, where before I was going to write things manually.

However, I can't seem to find any such parser that generates C++ code, nor can I find a parser that correctly handles Unicode. (note that my input is in UCS-2 -- I don't care about supporting bits outside of the Basic Multilingual Plane if that makes building the parser more difficult)

There are some parsers which can generate C, but such parsers all seem to throw exception safety out the window, which would prevent me from using C++ inside any semantic actions.

Does a parser generator exist which meets these two tenets, or am I stuck doing everything by hand?

EDIT: Oh, and my project is BSL licensed, so there can't be many restrictions on use of the output of the parser generator itself.

答: There appears to be preliminary support for unicode in boost::spirit


问:
Why it is showing time limit exceeded?
In the following question I am getting time limit exceeded message on whichever compiler I tried(though they were all online compilers).What should be the problem?</p>

```<code>#include <stdio.h>
int fact(int);
int main(void)
{
    int num,res;
    printf("enter any number");
    scanf("%d",&num);
    res=fact(num);
    printf("%d",res);
    return 0;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}
</code>```

答:
It is because your fact function goes into infinite loop.

Assuming you are calculating factorial of a number x, this should be the correct fact function.

```<code>int fact(int x)
{
    if(x!=1)
        return x*fact(x-1);
    return 1;
}
</code>```

Title: Why it is showing time limit exceeded?

Body:
In the following question I am getting time limit exceeded message on whichever compiler I tried(though they were all online compilers).What should be the problem?

#include <stdio.h>
int fact(int);
int main(void)
{
    int num,res;
    printf("enter any number");
    scanf("%d",&num);
    res=fact(num);
    printf("%d",res);
    return 0;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}

Body:
It is because your fact function goes into infinite loop.

Assuming you are calculating factorial of a number x, this should be the correct fact function.

int fact(int x)
{
    if(x!=1)
        return x*fact(x-1);
    return 1;
}


问:
Initialize the values into Mat object in OpenCV
I need to initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java

```<code>data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7,
           4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11,
           1.332451366923E12}
</code>```

Can explain to me me how to initialize a new Mat object where I directly insert the array data?

答:
Try inline initialization if you want to hardcode those values.:

```<code>    // For small matrices you may use comma separated initializers:

    Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    cout << "C = " << endl << " " << C << endl << endl;
</code>```

stolen from

http://opencvexamples.blogspot.de/2013/09/creating-matrix-in-different-ways.html?m=1

use data array as source as shown in some else's answer if you want to use a (maybe dynamic) array as input.

Body:
I need to initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java

data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7,
           4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11,
           1.332451366923E12}

Can explain to me me how to initialize a new Mat object where I directly insert the array data?

Body:
Try inline initialization if you want to hardcode those values.:

    // For small matrices you may use comma separated initializers:

    Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    cout << "C = " << endl << " " << C << endl << endl;

stolen from

http://opencvexamples.blogspot.de/2013/09/creating-matrix-in-different-ways.html?m=1

use data array as source as shown in some else's answer if you want to use a (maybe dynamic) array as input.


问:
Ruby on rails rake db error
I have cloned a project and ran it locally on my machine. I'm getting an error when i run rake db:migrate.

Can anyone please explain this to me? I have attached an image showing the error I am receiving.

Error Received

答:
You need to update your rails gem, from 3.2.19 to 3.2.22.
You can edit your gemfile to look like this:

```<code>gem 'rails', '3.2.22'
</code>```

and then run

```<code>bundle update rails
</code>```

Title: Ruby on rails rake db error

Body:
You need to update your rails gem, from 3.2.19 to 3.2.22.
You can edit your gemfile to look like this:

gem 'rails', '3.2.22'

and then run

bundle update rails


问:
listview to string exception thrown
What I have going on is i am using

```<code>string proj = listView2.SelectedItems[0].ToString();
</code>```

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

```<code>    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }
</code>```

working:

```<code>        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }
</code>```

答:
The SelectedIndexChanged event is raised whenever the Selected property of a ListViewItem changes.  This means the event is raised twice:  once when the first item is deselected, and a second time when the item you clicked on is selected.  Since you are not checking whether SelectedItems has any items, you get the exception the first time the event is raised.

As @Jeffrey L Whitledge shows in his answer, you can use SelectedItems.Count to determine whether any items are selected.

Title: listview to string exception thrown

Body:
What I have going on is i am using

string proj = listView2.SelectedItems[0].ToString();

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

InvalidArgument=Value of '0' is not valid for 'index'.
  Parameter name: index

Any thoughts?

    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }

working:

        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }


问:
sbt deprecation warning <<= replaced with := results in no main class found
When using sbt 0.13.13. I could observe that when using := no main class is found (but no deprecation warning is shown), and for <<= I get the warning, but the main class is found. What is wrong here?

```<code>run in Compile := Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))
run in Compile <<= Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))
</code>```

答:
run is an InputTask[Unit] and the type of runTask is Def.Initialize[InputTask[Unit]] and the right side of := needs to be a Unit.

What you did compiles because any value can be discarded in favor of a return value of type Unit, but it doesn't have the same semantics as before.

For input tasks, you need to "evaluate" the task:

```<code>run in Compile := Defaults.runTask(
  fullClasspath in Compile,
  mainClass.in(Compile, run),
  runner.in(Compile, run)).evaluated
</code>```

Body:
When using sbt 0.13.13. I could observe that when using := no main class is found (but no deprecation warning is shown), and for <<= I get the warning, but the main class is found. What is wrong here?

run in Compile := Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))
run in Compile <<= Defaults.runTask(fullClasspath in Compile, mainClass in(Compile, run), runner in(Compile, run))

Body:
run is an InputTask[Unit] and the type of runTask is Def.Initialize[InputTask[Unit]] and the right side of := needs to be a Unit.

What you did compiles because any value can be discarded in favor of a return value of type Unit, but it doesn't have the same semantics as before.

For input tasks, you need to "evaluate" the task:

run in Compile := Defaults.runTask(
  fullClasspath in Compile,
  mainClass.in(Compile, run),
  runner.in(Compile, run)).evaluated


问:
How to get array format in javascript?
I am getting an array in AngularJs with factory function. This is the console

```<code>Array[0]
  0: "value1"
  1: "value2"
  length:2
</code>```

But when i want to get the length of the array

```<code>console.log(array.length)
</code>```

getting data from mysql in loopback

```<code> app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});
</code>```

The controller look like:

```<code>app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])
</code>```

I get that the length is 0. Why is that?

答:
This is a timing issue. The first time you ask for the length it is indeed 0, but when you inspect the object a few seconds later with Chrome Dev Tools you are inspecting the live object which has now been filled.

You can confirm this by using setTimeout

```<code>setTimeout(function(){
   console.log(array);
}, 0)
</code>```

You can checkout this link for further explanation

UPDATE

In angular, use $timeout instead of setTimeout. Like this:

```<code>$timeout(function(){
   console.log(array);
}, 0)
</code>```

Title: How to get array format in javascript?

Body:
I am getting an array in AngularJs with factory function. This is the console

Array[0]
  0: "value1"
  1: "value2"
  length:2

But when i want to get the length of the array

console.log(array.length)

getting data from mysql in loopback

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

The controller look like:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

I get that the length is 0. Why is that?

Body:
This is a timing issue. The first time you ask for the length it is indeed 0, but when you inspect the object a few seconds later with Chrome Dev Tools you are inspecting the live object which has now been filled.

You can confirm this by using setTimeout

setTimeout(function(){
   console.log(array);
}, 0)

You can checkout this link for further explanation

UPDATE

In angular, use $timeout instead of setTimeout. Like this:

$timeout(function(){
   console.log(array);
}, 0)


问:
Dynamically updating overlay icon to Command usning IElementUpdater is not working in eclipse Compitability mode
Recently we have migrated from Eclipse 3.x to Eclipse 4.x and now were are running our Eclipse 3.x code in compatibility mode

I have a handler implementing IElementUpdater and overrided updateElement as shown below:

@SuppressWarnings("rawtypes")
@Override
public void updateElement(final UIElement element, final Map parameters) {
    Image filterImage = PlatformUI.getWorkbench().getSharedImages().getImage(ICECImageConstants.FILTER_CO);
    ImageDescriptor addcoDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin("com.myCompany.ui.common",
                                                                                "icons/decorator_ovr.png");
    if (null != filterImage && null != addcoDescriptor) {
        DecorationOverlayIcon decorationOverlayIcon = new DecorationOverlayIcon(filterImage,
                                                                                addcoDescriptor,
                                                                                IDecoration.BOTTOM_RIGHT);
        element.setIcon(decorationOverlayIcon);

    }

}
```

<p>plugin.xml</p>

<pre class="lang-xml prettyprint-override"><code><extension
     point="org.eclipse.ui.menus">
  <menuContribution
        locationURI="toolbar:com.myCompany.ui.common.bauteilView">
     <command
           commandId="com.myCompany.ui.common.filter.project"
           icon="icons/filter_co.gif "
           id="%command.name.project.filter"
           label="%command.name.project.filter"
           style="push">
     </command>
</code>```

This code is working in Eclipse 3.x but not in Eclipse 4.x, anybody has any idea how to go with this.

答:
It looks like the UIElement.setIcon method will only work when it is possible to determine a URL for the image. Since this isn't possible for DecorationOverlayIcon your code doesn't work.

Using a prebuilt image with the base image and overlay obtained using AbstractUIPlugin.imageDescriptorFromPlugin should work since this will have a URL.

Body:
Recently we have migrated from Eclipse 3.x to Eclipse 4.x and now were are running our Eclipse 3.x code in compatibility mode

I have a handler implementing IElementUpdater and overrided updateElement as shown below:

@SuppressWarnings("rawtypes")
@Override
public void updateElement(final UIElement element, final Map parameters) {
    Image filterImage = PlatformUI.getWorkbench().getSharedImages().getImage(ICECImageConstants.FILTER_CO);
    ImageDescriptor addcoDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin("com.myCompany.ui.common",
                                                                                "icons/decorator_ovr.png");
    if (null != filterImage && null != addcoDescriptor) {
        DecorationOverlayIcon decorationOverlayIcon = new DecorationOverlayIcon(filterImage,
                                                                                addcoDescriptor,
                                                                                IDecoration.BOTTOM_RIGHT);
        element.setIcon(decorationOverlayIcon);

    }

}

plugin.xml

<extension
     point="org.eclipse.ui.menus">
  <menuContribution
        locationURI="toolbar:com.myCompany.ui.common.bauteilView">
     <command
           commandId="com.myCompany.ui.common.filter.project"
           icon="icons/filter_co.gif "
           id="%command.name.project.filter"
           label="%command.name.project.filter"
           style="push">
     </command>

This code is working in Eclipse 3.x but not in Eclipse 4.x, anybody has any idea how to go with this.


问:
Android Studio Mac OSX: JSON File Size exceeds configured limit (2560000). Code insight features not Available
I'm working on an android app where I parse a 4.8 mb JSON file into an sqlite database which I then access to display data in list view. The listview due to the error/flag mentioned in question title I think is preventing all the items from showing in list view. Is there a way to configure the max file size?</p>

答:
Code insights for json file is not necessary. Anyway, follow these steps:

Open the IntelliJ IDEA Platform Properties file:

```<code>cd /Applications/Android Studio.app/Contents/bin
open idea.properties
</code>```

Now, Add the line:

```<code>#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#---------------------------------------------------------------------
idea.max.intellisense.filesize=2500
</code>```

Body:
Code insights for json file is not necessary. Anyway, follow these steps:

Open the IntelliJ IDEA Platform Properties file:

cd /Applications/Android Studio.app/Contents/bin
open idea.properties

Now, Add the line:

#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#---------------------------------------------------------------------
idea.max.intellisense.filesize=2500


问:
How to create a page url from page uid
I am working on a typo3 extension and I want to generate an url from the page id. Currently I create the url by appending index.php?id=ID to $GLOBALS['TSFE']->baseURL.

Is there any other way to create a readable url from the page id, and if yes, how it can be done?

答:
In case that you don't have initialized $GLOBALS['TSFE'] and would you like to avoid this bug https://forge.typo3.org/issues/71361 you have to initialize $GLOBALS['TSFE'] in this way:

```<code>if (!isset($GLOBALS['TSFE'])) {

            $pid = (int)GeneralUtility::_POST('pid');
            $rootline =
                \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($pid);

            foreach ($rootline as $page) {
                if ($page['is_siteroot']) {
                    $id = (int)$page['uid'];
                    break;
                }
            }

            $type = 0;

            if (!is_object($GLOBALS['TT'])) {
                $GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker;
                $GLOBALS['TT']->start();
            }

            $GLOBALS['TSFE'] =
                GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',
                                             $GLOBALS['TYPO3_CONF_VARS'], $id, $type);
            $GLOBALS['TSFE']->connectToDB();
            $GLOBALS['TSFE']->initFEuser();
            $GLOBALS['TSFE']->determineId();
            $GLOBALS['TSFE']->initTemplate();
            $GLOBALS['TSFE']->getConfigArray();

            if
            (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('realurl')
            ) {
                $host =
                    \TYPO3\CMS\Backend\Utility\BackendUtility::firstDomainRecord($rootline);
                $_SERVER['HTTP_HOST'] = $host;
            }
        }
</code>```

Title: How to create a page url from page uid

Body:
In case that you don't have initialized $GLOBALS['TSFE'] and would you like to avoid this bug https://forge.typo3.org/issues/71361 you have to initialize $GLOBALS['TSFE'] in this way:

if (!isset($GLOBALS['TSFE'])) {

            $pid = (int)GeneralUtility::_POST('pid');
            $rootline =
                \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($pid);

            foreach ($rootline as $page) {
                if ($page['is_siteroot']) {
                    $id = (int)$page['uid'];
                    break;
                }
            }

            $type = 0;

            if (!is_object($GLOBALS['TT'])) {
                $GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker;
                $GLOBALS['TT']->start();
            }

            $GLOBALS['TSFE'] =
                GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',
                                             $GLOBALS['TYPO3_CONF_VARS'], $id, $type);
            $GLOBALS['TSFE']->connectToDB();
            $GLOBALS['TSFE']->initFEuser();
            $GLOBALS['TSFE']->determineId();
            $GLOBALS['TSFE']->initTemplate();
            $GLOBALS['TSFE']->getConfigArray();

            if
            (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('realurl')
            ) {
                $host =
                    \TYPO3\CMS\Backend\Utility\BackendUtility::firstDomainRecord($rootline);
                $_SERVER['HTTP_HOST'] = $host;
            }
        }


问:
Organizing script files
I usually have jQuery code that is page specific along with a handful of functions that many pages share. One approach is to make seperate files for organizing, but i'm thinking that putting all the script in one file and making comments in the file for readability would also work. Then when the site goes live I can minify and obfuscate if needed.

I think the question comes down to limiting http requests or limiting file size. Is one of these a bad habit?

答:
If you can put all the scripts in one file which is minified then that's what you should do first.

Also if your webserver sends out gzipped content the actual script transfer would be small, and the script will be cached on client. Since tcp transfers starts out slow and increase in speed, limiting the number of requests is the best way to speed up the overall loading of a page.

This is the same reason you see sites concatenating images into one larger image, and using CSS to display the correct part of it.

Title: Organizing script files


问:
Android back button app is not closing
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice</p>

```<code>  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }
</code>```

答:
This may work. Use finishAffinity() instead.

```<code>  boolean doubleBackToExitPressedOnce = false;

  public void onBackPressed(){
        if(doubleBackToExitPressedOnce)
        {
            finishAffinity();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click back again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;

            }
        },3500);
    }
</code>```

Title: Android back button app is not closing

Body:
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice

  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }

Body:
This may work. Use finishAffinity() instead.

  boolean doubleBackToExitPressedOnce = false;

  public void onBackPressed(){
        if(doubleBackToExitPressedOnce)
        {
            finishAffinity();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click back again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;

            }
        },3500);
    }