问:
AngularJs Kendo Grid Detail Template: Updating based on selected row in detail template
I am playing around with the KendoUI AngularJS Grid detail template.
I would like to be able to update a panel based on a selected row in the detail template grid.

I have correctly wired up the on change event to select a value from the detail template grid.  But when I try to update a variable on the $scope object the value remains the same (the default value).

What is causing the variable on the #scope object not to update?

```<code><div id="example">
<div ng-controller="MyCtrl">
    <kendo-grid options="mainGridOptions">
        <div k-detail-template>
            <kendo-tabstrip>
                <ul>
                    <li class="k-state-active">Orders</li>
                    <li>Contact information</li>
                </ul>
                <div>
                    <div kendo-grid k-options="detailGridOptions(dataItem)"></div>
                </div>
                <div>
                    <ul class="contact-info-form">
                        <li><label>Country:</label> <input class="k-textbox" ng-model="dataItem.Country" /></li>
                        <li><label>City:</label> <input class="k-textbox" ng-model="dataItem.City" /></li>
                        <li><label>Address:</label> {{dataItem.Address}}</li>
                        <li><label>Home phone:</label> {{dataItem.HomePhone}}</li>
                    </ul>
                </div>
            </kendo-tabstrip>
        </div>
    </kendo-grid>

    <div class="panel panel-default">
        <div class="panel-heading">Content</div>
        <div class="panel-body">
            {{content}}
        </div>
    </div>
</div>
</code>```

```<code><script>
angular.module("app", [ "kendo.directives" ])
    .controller("MyCtrl", function ($scope) {
        $scope.content = 'test';
        $scope.mainGridOptions = {
            dataSource: {
                type: "odata",
                transport: {
                    read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
                },
                pageSize: 5,
                serverPaging: true,
                serverSorting: true
            },
            sortable: true,
            selectable: true,
            pageable: true,
            dataBound: function() {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "120px"
                },{
                field: "LastName",
                title: "Last Name",
                width: "120px"
                },{
                field: "Country",
                width: "120px"
                },{
                field: "City",
                width: "120px"
                },{
                field: "Title"
            }]
        };

        $scope.detailGridOptions = function(dataItem) {
            return {
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
                    },
                    schema: {
                        model: {
                            id: "OrderID"
                        }
                    },
                    serverPaging: true,
                    serverSorting: true,
                    serverFiltering: true,
                    pageSize: 5,
                    filter: { field: "EmployeeID", operator: "eq", value: dataItem.EmployeeID }
                },
                scrollable: false,
                sortable: true,
                selectable: true,
                change: onChange,
                pageable: true,
                columns: [
                { field: "OrderID", title:"ID", width: "56px" },
                { field: "ShipCountry", title:"Ship Country", width: "110px" },
                { field: "ShipAddress", title:"Ship Address" },
                { field: "ShipName", title: "Ship Name", width: "190px" }
                ]
            };
        };
        function onChange(arg) {
            console.log("The selected product id: [" + this.dataItem($(this.select()[0]).closest("tr")).id + "]");
            $scope.content = this.dataItem($(this.select()[0]).closest("tr")).id;
        }
    })
</code>```

I have tried using an inline Kendo provided on change function like this:

```<code><div kendo-grid k-options="detailGridOptions(dataItem)" k-on-change="handleChange(data, dataItem, columns)"></div>
</code>```

But it doesn't work correctly as the skope of data etc is the parent grid.

答:
I figured out how to fix the issue

I changed selectable: true to selectable: "row".
I also added k-on-change="handleChange(data) to the child and parent grid and handle the change event with the following function on $scope:

```<code> $scope.handleChange = function (data) {
            $scope.data = data;
        };
</code>```

It is much cleaner then the original approach I took and allows me to access the OrderID like this: {{data.OrderID}}

Body:
I am playing around with the KendoUI AngularJS Grid detail template.
I would like to be able to update a panel based on a selected row in the detail template grid.

I have correctly wired up the on change event to select a value from the detail template grid.  But when I try to update a variable on the $scope object the value remains the same (the default value).

What is causing the variable on the #scope object not to update?

    <kendo-grid options="mainGridOptions">

            <kendo-tabstrip>

Orders

Contact information

Country: <input class="k-textbox" ng-model="dataItem.Country" />

City: <input class="k-textbox" ng-model="dataItem.City" />

Address: {{dataItem.Address}}

Home phone: {{dataItem.HomePhone}}

            </kendo-tabstrip>

    </kendo-grid>

Content

            {{content}}

Body:
I figured out how to fix the issue

I changed selectable: true to selectable: "row".
I also added k-on-change="handleChange(data) to the child and parent grid and handle the change event with the following function on $scope:

 $scope.handleChange = function (data) {
            $scope.data = data;
        };

It is much cleaner then the original approach I took and allows me to access the OrderID like this: {{data.OrderID}}


来源: stackexchange

问:
How to iterate a list within a list into columns?
Suppose I have a list of numbers divided into 3 lists:

```<code>numbers = [[0,1,2], [3,4,5], [6,7,8]]
</code>```

And I want to iterate through each 3 lists and divide them into columns:

```<code>0  1  2
3  4  5
6  7  8
</code>```

How would I go about doing this?
So far, I can only print out 1 column:

```<code>for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )
</code>```

答:
I think you can try the following:

```<code>for n in numbers:
    for i in n:
        print(i, end=" ")
    print()
</code>```

The 1st loop goes through your list and the 2nd loop goes through each element in the sub lists. With "end" you specify what you want to print after each element. By default, it’s a new line. And by using print() after going through 2nd loop you print elements from sub lists on separate lines.
Hopefully my explanation is clear enough.

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a list of numbers divided into 3 lists:

numbers = [[0,1,2], [3,4,5], [6,7,8]]

And I want to iterate through each 3 lists and divide them into columns:

0  1  2
3  4  5
6  7  8

How would I go about doing this?
So far, I can only print out 1 column:

for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )

Body:
I think you can try the following:

for n in numbers:
    for i in n:
        print(i, end=" ")
    print()

The 1st loop goes through your list and the 2nd loop goes through each element in the sub lists. With "end" you specify what you want to print after each element. By default, it’s a new line. And by using print() after going through 2nd loop you print elements from sub lists on separate lines.
Hopefully my explanation is clear enough.


问:
How to one way bind the selected text value of a ComboBox to a property of an object
I have a combobox that's set to DropDownStyle=DropDownList (meaning users can't type anything, just select from dropdown).  The combo contains a list of states.

I am trying to bind the selected text value to _model.StateBar, but my code doesn't seem to update the property of the object.

I've tried both of the following:

```<code>cboStates.DataBindings.Add("Text", _model, "StateBar")
cboStates.DataBindings.Add("SelectedItem", _model, "StateBar")
cboStates.DataBindings.Add("SelectedValue", _model, "StateBar")
</code>```

I just need to bind it one way: updates from the control need to end up on the object.

答:
Binding to ComboBox.SelectedValue should work, but only in case when you add items through ComboBox.DataSource.

```<code>public class Model
{
    public string StateBar { get; set; }
}

 // In the form

var states = new List<string> { "Alabama", "California" };

combobox.DataSource = states;
combobox.DataBindings.Add("SelectedValue", _model, "StateBar", true, DataSourceUpdateMode.OnPropertyChanged);
</code>```

Binding to SelectedItem should work in all cases.

Body:
I have a combobox that's set to DropDownStyle=DropDownList (meaning users can't type anything, just select from dropdown).  The combo contains a list of states.

I am trying to bind the selected text value to _model.StateBar, but my code doesn't seem to update the property of the object.

I've tried both of the following:

cboStates.DataBindings.Add("Text", _model, "StateBar")
cboStates.DataBindings.Add("SelectedItem", _model, "StateBar")
cboStates.DataBindings.Add("SelectedValue", _model, "StateBar")

I just need to bind it one way: updates from the control need to end up on the object.

Body:
Binding to ComboBox.SelectedValue should work, but only in case when you add items through ComboBox.DataSource.

public class Model
{
    public string StateBar { get; set; }
}

 // In the form

var states = new List<string> { "Alabama", "California" };

combobox.DataSource = states;
combobox.DataBindings.Add("SelectedValue", _model, "StateBar", true, DataSourceUpdateMode.OnPropertyChanged);

Binding to SelectedItem should work in all cases.


问:
How to store file into inetpub\wwwroot instead of local machine folder on UWP application
I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit

For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.

I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.

Here are my codes for storing on my local desktop:

```<code>private async Task TakePhotoAsync()
    {
        idleTimer.Stop();
        idleTimer.Start();

        var stream = new InMemoryRandomAccessStream();

        //MediaPlayer mediaPlayer = new MediaPlayer();
        //mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
        //mediaPlayer.Play();

        Debug.WriteLine("Taking photo...");
        await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

        try
        {
            var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
            Debug.WriteLine("Photo taken! Saving to " + file.Path);

            var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

            await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
            Debug.WriteLine("Photo saved!");

        }
        catch (Exception ex)
        {
            // File I/O errors are reported as exceptions
            Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
        }

    }
</code>```

For the storing of the files:

```<code>private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
    {
        using (var inputStream = stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(inputStream);

            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };

                await encoder.BitmapProperties.SetPropertiesAsync(properties);
                await encoder.FlushAsync();
            }
        }
    }
</code>```

答:
I would add an answer since there are tricky things about this requirement.

The first is the app can only access a few folders, inetpub is not one of them.

Using brokered Windows runtime component (I would suggest using FullTrustProcessLauncher, which is much simpler to develop and deploy) can enable UWP apps access folders in the same way as the traditional desktop applications do.

While this works for an ordinary folder,  the inetpub folder, however, is different that it requires Administrators Privileges to write to, unless you turn UAC off.

The desktop component launched by the app does not have the adequate privileges to write to that folder, either.

So it think an alternative way would be setting up a virtual directory in IIS manager that maps to a folder in the public Pictures library, and the app saves picture to that folder.

From the website’s perspective, a virtual directory is the same as a real folder under inetpub, what differs is the access permissions.

Body:
I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit

For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.

I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.

Here are my codes for storing on my local desktop:

private async Task TakePhotoAsync()
    {
        idleTimer.Stop();
        idleTimer.Start();

        var stream = new InMemoryRandomAccessStream();

        //MediaPlayer mediaPlayer = new MediaPlayer();
        //mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
        //mediaPlayer.Play();

        Debug.WriteLine("Taking photo...");
        await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

        try
        {
            var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
            Debug.WriteLine("Photo taken! Saving to " + file.Path);

            var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

            await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
            Debug.WriteLine("Photo saved!");

        }
        catch (Exception ex)
        {
            // File I/O errors are reported as exceptions
            Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
        }

    }

For the storing of the files:

private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
    {
        using (var inputStream = stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(inputStream);

            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };

                await encoder.BitmapProperties.SetPropertiesAsync(properties);
                await encoder.FlushAsync();
            }
        }
    }


问:
SQLSTATE[HY000] [2002] No such file or directory (SQL: select count(*) as aggregate from `users` where `email` = ronit5rg@gmail.com)
While trying to register, above (in the title) is the error that I get. The migrations were migrated successfully, so I don't think there is any connection problem with the database, but I don't know why this error is coming?
I have just tried to create an authentication system using

```<code>php artisan make:auth
</code>```

And I have migrated the migrations

Please help...

答:
You need to make some changes in the .env file:

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelfive(DB name)
DB_USERNAME=root (Username must be Root)
DB_PASSWORD='' (Password should be empty)
</code>```

Then change the config -> database file like this:

```<code>'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'laravelfive'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
</code>```

Finally, run Xampp Apache and MySQL like in the following link:

Xampp running picture

Body:
While trying to register, above (in the title) is the error that I get. The migrations were migrated successfully, so I don't think there is any connection problem with the database, but I don't know why this error is coming?
I have just tried to create an authentication system using

php artisan make:auth

And I have migrated the migrations

Please help...

Body:
You need to make some changes in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelfive(DB name)
DB_USERNAME=root (Username must be Root)
DB_PASSWORD='' (Password should be empty)

Then change the config -> database file like this:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'laravelfive'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),

Finally, run Xampp Apache and MySQL like in the following link:

Xampp running picture

ContentLicense: CC BY-SA 4.0


问:
Spring boot - Embedded Tomcat - Connector Customizer - fail to add parseBodyMethods attributes
The original problem is when I sent a http request with method 'DELETE', the body part couldn't be sent to the server.

After googling, I found this article that suggests modifying the server.xml file and adding 'parseBodyMethods' to the Connector part can solve the problem:

```<code><Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           parseBodyMethods="POST,PUT,DELETE"
           redirectPort="8443" />
</code>```

However, because I'm using spring's embedded tomcat, I have to find a way to do the same in spring's way. So, I found this article that seems to allow me to add ConnectorCustomizer and add additional attribute to the Connector. The following is my code:

```<code>    public class MyTomcatConnectorCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer factory) {
        if(factory instanceof TomcatEmbeddedServletContainerFactory) {
            customizeTomcat((TomcatEmbeddedServletContainerFactory) factory);
        }
    }

    public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
        TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) factory;
        tomcat.addConnectorCustomizers(connector -> {
            connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");
        });
    }

}
</code>```

```<code>@Bean
MyTomcatConnectorCustomizer myTomcatConnectorCustomizer() {
    MyTomcatConnectorCustomizer myTomcatConnectorCustomizer = new MyTomcatConnectorCustomizer();
    return myTomcatConnectorCustomizer;
}
</code>```

But still, the same issue exists. the body is still empty when I send a 'DELETE' request to the server. Does anyone have encountered the same issue before? Help appreciated!

答:
change

```<code>connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");
</code>```

to

```<code>connector.setParseBodyMethods("POST,PUT,DELETE")
</code>```

or just

```<code>@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory(){
        @Override
        protected void customizeConnector(Connector connector) {
            super.customizeConnector(connector);
            connector.setParseBodyMethods("POST,PUT,DELETE");
        }
    };
}
</code>```

Body:
The original problem is when I sent a http request with method 'DELETE', the body part couldn't be sent to the server.

After googling, I found this article that suggests modifying the server.xml file and adding 'parseBodyMethods' to the Connector part can solve the problem:

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           parseBodyMethods="POST,PUT,DELETE"
           redirectPort="8443" />

However, because I'm using spring's embedded tomcat, I have to find a way to do the same in spring's way. So, I found this article that seems to allow me to add ConnectorCustomizer and add additional attribute to the Connector. The following is my code:

    public class MyTomcatConnectorCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer factory) {
        if(factory instanceof TomcatEmbeddedServletContainerFactory) {
            customizeTomcat((TomcatEmbeddedServletContainerFactory) factory);
        }
    }

    public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
        TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) factory;
        tomcat.addConnectorCustomizers(connector -> {
            connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");
        });
    }

}

@Bean
MyTomcatConnectorCustomizer myTomcatConnectorCustomizer() {
    MyTomcatConnectorCustomizer myTomcatConnectorCustomizer = new MyTomcatConnectorCustomizer();
    return myTomcatConnectorCustomizer;
}

But still, the same issue exists. the body is still empty when I send a 'DELETE' request to the server. Does anyone have encountered the same issue before? Help appreciated!

Body:
change

connector.setAttribute("parseBodyMethods", "POST,PUT,DELETE");

to

connector.setParseBodyMethods("POST,PUT,DELETE")

or just

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
    return new TomcatEmbeddedServletContainerFactory(){
        @Override
        protected void customizeConnector(Connector connector) {
            super.customizeConnector(connector);
            connector.setParseBodyMethods("POST,PUT,DELETE");
        }
    };
}


问:
How can I one-hot encode data with numpy?
Suppose I have a dataset

```<code>sex    age hours
female 23  900
male   19  304
female 42  222
      ...
</code>```

If I use np.loadtxt or np.genfromtxt I can use a converter as a way to assign values to each of the categorical data in the sex column. Is there a way to instead create a one-hot column during the loading process? If not, where should I look to accomplish this?

答:
Have a look at pandas.get_dummies function.

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

Body:
Suppose I have a dataset

sex    age hours
female 23  900
male   19  304
female 42  222
      ...

If I use np.loadtxt or np.genfromtxt I can use a converter as a way to assign values to each of the categorical data in the sex column. Is there a way to instead create a one-hot column during the loading process? If not, where should I look to accomplish this?


问:
FetchOptions withLimit() does not reduce query execution time (Google App Engine)

Problem

Running a datastore query with or without FetchOptions.Builder.withLimit(100) takes the same execution time! Why is that? Isn't the limit method intended to reduce the time to retrieve results!?

Test setup

I am locally testing the execution time of some datastore queries with Google's App Engine. I am using the Google Cloud SDK Standard Environment with the App Engine SDK 1.9.59.

For the test, I created an example entity with 5 indexed properties and 5 unindexed properties. I filled the datastore with 50.000 entries of a test entity. I run the following method to retrieve 100 of this entities by utilizing the withLimit() method.

public List<Long> getTestIds() {
    List<Long> ids = new ArrayList<>();
    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(100);
    Query q = new Query("test_kind").setKeysOnly();
    for (Entity entity : datastore.prepare(q).asIterable(fetchOptions)) {
        ids.add(entity.getKey().getId());
    }
    return ids;
}
```

<p>I measure the time before and after calling this method:</p>

<pre class="lang-java prettyprint-override"><code>long start = System.currentTimeMillis();
int size = getTestIds().size();
long end = System.currentTimeMillis();
log.info("time: " + (end - start) + " results: " + size);
</code>```

I log the execution time and the number of returned results.

Results

When I do not use the withLimit() FetchOptions for the query, I get the expected 50.000 results in about 1740 ms. Nothing surprising here.

If I run the code as displayed above and use withLimit(100) I get the expected 100 results. However, the query runs about the same 1740 ms!

I tested with different numbers of datastore entries and different limits. Every time the queries with or without withLimit(100) took the same time.

Question

Why is the query still fetching all entities? I am sure the query is not supposed to get all entities even though the limit is set to 100 right? What am I missing? Is there some datastore configuration for that? After testing and searching the web for 4 days I still can't find the problem.

答:
FWIW, you shouldn't expect meaningful results from datastore performance tests performed locally, using either the development server or the datastore emulator - they're just emulators, they don't have the same performance (or even the 100% equivalent functionality) as the real datastore.

See for example Datastore fetch VS fetch(keys_only=True) then get_multi (including comments)

Body:
Problem

Running a datastore query with or without FetchOptions.Builder.withLimit(100) takes the same execution time! Why is that? Isn't the limit method intended to reduce the time to retrieve results!?

Test setup

I am locally testing the execution time of some datastore queries with Google's App Engine. I am using the Google Cloud SDK Standard Environment with the App Engine SDK 1.9.59.

For the test, I created an example entity with 5 indexed properties and 5 unindexed properties. I filled the datastore with 50.000 entries of a test entity. I run the following method to retrieve 100 of this entities by utilizing the withLimit() method.

public List<Long> getTestIds() {
    List<Long> ids = new ArrayList<>();
    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(100);
    Query q = new Query("test_kind").setKeysOnly();
    for (Entity entity : datastore.prepare(q).asIterable(fetchOptions)) {
        ids.add(entity.getKey().getId());
    }
    return ids;
}

I measure the time before and after calling this method:

long start = System.currentTimeMillis();
int size = getTestIds().size();
long end = System.currentTimeMillis();
log.info("time: " + (end - start) + " results: " + size);

I log the execution time and the number of returned results.

Results

When I do not use the withLimit() FetchOptions for the query, I get the expected 50.000 results in about 1740 ms. Nothing surprising here.

If I run the code as displayed above and use withLimit(100) I get the expected 100 results. However, the query runs about the same 1740 ms!

I tested with different numbers of datastore entries and different limits. Every time the queries with or without withLimit(100) took the same time.

Question

Why is the query still fetching all entities? I am sure the query is not supposed to get all entities even though the limit is set to 100 right? What am I missing? Is there some datastore configuration for that? After testing and searching the web for 4 days I still can't find the problem.


问:
How to get images from hidden folder in android
I am able to fetch all the images from any specified non hidden folder from device but how can I get all the images from a hidden specified folder.
As soon as I mention my hidden folder name in the query, cursor return null</p>

```<code>  public static List<MediaData> getAppScannedImages(Context context) {
    Cursor imagecursor = null;
    List<MediaData> gallerydata = new ArrayList<MediaData>();

    try {
        final String orderBy = Images.ImageColumns.DATE_TAKEN + " DESC";
        imagecursor = context.getContentResolver()
                .query(Images.Media.EXTERNAL_CONTENT_URI,
                        projectionImage,
                        Images.Media.BUCKET_DISPLAY_NAME + "='"
                                + ".myHiddenFolder" + "'", null,
                        orderBy);
        if (imagecursor != null) {
            imagecursor.moveToFirst();
            int count = imagecursor.getCount();
            for (int i = 0; i < count; i++) {
                MediaData galData = new MediaData();
                galData.setKey_id(i);
                galData.setId(imagecursor.getString(0));
                galData.setName(imagecursor.getString(1));
                galData.setPath(imagecursor.getString(2));
                galData.setDate(imagecursor.getString(3));
                gallerydata.add(galData);
                imagecursor.moveToNext();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (imagecursor != null) {
            imagecursor.close();
        }
    }
    return gallerydata;
}
</code>```

答:
You can try a different approach.
You have to find out the list of hidden folder from sd card and search all those folders for images.

the follwoing code is displays hidden files:

```<code>public void goTODir(File dir) {

//dir is initail dir like="/mnt/sdcard"
    String imageType = ".jpg";

    File[] listFile = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                goTODir(listFile[i]);
            } else {
              if (listFile[i].isHidden()){
                        if(listFile[i].getName().endsWith(imageType))
                            {
                              //add to your array list
                               }

              }
            }
        }
    }
 }
</code>```

Body:
I am able to fetch all the images from any specified non hidden folder from device but how can I get all the images from a hidden specified folder.
As soon as I mention my hidden folder name in the query, cursor return null

  public static List<MediaData> getAppScannedImages(Context context) {
    Cursor imagecursor = null;
    List<MediaData> gallerydata = new ArrayList<MediaData>();

    try {
        final String orderBy = Images.ImageColumns.DATE_TAKEN + " DESC";
        imagecursor = context.getContentResolver()
                .query(Images.Media.EXTERNAL_CONTENT_URI,
                        projectionImage,
                        Images.Media.BUCKET_DISPLAY_NAME + "='"
                                + ".myHiddenFolder" + "'", null,
                        orderBy);
        if (imagecursor != null) {
            imagecursor.moveToFirst();
            int count = imagecursor.getCount();
            for (int i = 0; i < count; i++) {
                MediaData galData = new MediaData();
                galData.setKey_id(i);
                galData.setId(imagecursor.getString(0));
                galData.setName(imagecursor.getString(1));
                galData.setPath(imagecursor.getString(2));
                galData.setDate(imagecursor.getString(3));
                gallerydata.add(galData);
                imagecursor.moveToNext();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (imagecursor != null) {
            imagecursor.close();
        }
    }
    return gallerydata;
}

Body:
You can try a different approach.
You have to find out the list of hidden folder from sd card and search all those folders for images.

the follwoing code is displays hidden files:

public void goTODir(File dir) {

//dir is initail dir like="/mnt/sdcard"
    String imageType = ".jpg";

    File[] listFile = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                goTODir(listFile[i]);
            } else {
              if (listFile[i].isHidden()){
                        if(listFile[i].getName().endsWith(imageType))
                            {
                              //add to your array list
                               }

              }
            }
        }
    }
 }


问:
RecursionError when python copy.deepcopy
I have a problem in python.

I have a class whis custom __getattr__

```<code>class ChoiceNumToName(object):
    def __init__(self, django_choice_tuple):
        self.ods_choice_tuple = django_choice_tuple
        self.choice_data = {}
        self.choice_point = -1
        for choice_value, choice_name in django_choice_tuple:
            self.choice_data.setdefault(choice_name, choice_value)

    def __getattr__(self, item):
        if item in self.choice_data:
            return self.choice_data[item]
        else:
            raise AttributeError("no attribute %s" % item)

    def __str__(self):
        return str(self.ods_choice_tuple)

    def __iter__(self):
        self.choice_point = -1
        return self

    def __next__(self):
        self.choice_point += 1
        try:
            return self.ods_choice_tuple[self.choice_point]
        except IndexError:
            raise StopIteration()
</code>```

when I execute this

```<code>a = ChoiceNumToName((
    (1, "running"),
    (2, "stopped"),
))
b = copy.deepcopy(a)
</code>```

It raise RecursionError: maximum recursion depth exceeded while calling a Python object

To fix this problem is sample, change __getattr__ function to this

```<code>def __getattr__(self, item):
    if item == "__setstate__":
        raise AttributeError(item)
    if item in self.choice_data:
        return self.choice_data[item]
    else:
        raise AttributeError("no attribute %s" % item)
</code>```

It work well.

I know this solution from here
https://github.com/python-babel/flask-babel/commit/8319a7f44f4a0b97298d20ad702f7618e6bdab6a

But can anyone tell me why?

答:
The methods __getstate__ and __setstate__ are used in pickling operations. Why does this matter? From the Python docs on copying:

Classes can use the same interfaces to control copying that they use to control pickling.

By defining a __setstate__ that refers to itself you've created a recursive object, hence the RecursionError.

Body:
I have a problem in python.

I have a class whis custom __getattr__

class ChoiceNumToName(object):
    def __init__(self, django_choice_tuple):
        self.ods_choice_tuple = django_choice_tuple
        self.choice_data = {}
        self.choice_point = -1
        for choice_value, choice_name in django_choice_tuple:
            self.choice_data.setdefault(choice_name, choice_value)

    def __getattr__(self, item):
        if item in self.choice_data:
            return self.choice_data[item]
        else:
            raise AttributeError("no attribute %s" % item)

    def __str__(self):
        return str(self.ods_choice_tuple)

    def __iter__(self):
        self.choice_point = -1
        return self

    def __next__(self):
        self.choice_point += 1
        try:
            return self.ods_choice_tuple[self.choice_point]
        except IndexError:
            raise StopIteration()

when I execute this

a = ChoiceNumToName((
    (1, "running"),
    (2, "stopped"),
))
b = copy.deepcopy(a)

It raise RecursionError: maximum recursion depth exceeded while calling a Python object

To fix this problem is sample, change __getattr__ function to this

def __getattr__(self, item):
    if item == "__setstate__":
        raise AttributeError(item)
    if item in self.choice_data:
        return self.choice_data[item]
    else:
        raise AttributeError("no attribute %s" % item)

It work well.

I know this solution from here
https://github.com/python-babel/flask-babel/commit/8319a7f44f4a0b97298d20ad702f7618e6bdab6a

But can anyone tell me why?


答:
With pandas, you can pass the category dtype (which loads in the column cheaply):

```<code>In [11]: df = pd.read_csv("my_file.csv", dtype={"sex": "category"})

In [12]: df
Out[12]:
      sex  age  hours
0  female   23    900
1    male   19    304
2  female   42    222

In [13]: df.dtypes
Out[13]:
sex      category
age         int64
hours       int64
dtype: object
</code>```

Once you have a category you can use get_dummies:

```<code>In [21]: pd.get_dummies(df.sex)
Out[21]:
   female  male
0       1     0
1       0     1
2       1     0

In [22]: pd.get_dummies(df.sex.cat.codes)
Out[22]:
   0  1
0  1  0
1  0  1
2  1  0
</code>```

Title: How can I one-hot encode data with numpy?

Body:
With pandas, you can pass the category dtype (which loads in the column cheaply):

In [11]: df = pd.read_csv("my_file.csv", dtype={"sex": "category"})

In [12]: df
Out[12]:
      sex  age  hours
0  female   23    900
1    male   19    304
2  female   42    222

In [13]: df.dtypes
Out[13]:
sex      category
age         int64
hours       int64
dtype: object

Once you have a category you can use get_dummies:

In [21]: pd.get_dummies(df.sex)
Out[21]:
   female  male
0       1     0
1       0     1
2       1     0

In [22]: pd.get_dummies(df.sex.cat.codes)
Out[22]:
   0  1
0  1  0
1  0  1
2  1  0


问:
DDD: Referencing MediatR interface from the domain project
I'm just getting started with DDD. I'm putting domain events into a CQRS application and I'm stumbling on a fundamental task: How to use the MediatR.INotification marker interface within the domain project without creating a domain dependency on infrastructure.

My solution is organized in four projects as follows:

```<code>MyApp.Domain
    - Domain events
    - Aggregates
    - Interfaces (IRepository, etc), etc.
MyApp.ApplicationServices
    - Commands
    - Command Handlers, etc.
MyApp.Infrastructure
    - Repository
    - Emailer, etc.
MyApp.Web
    - Startup
    - MediatR NuGet packages and DI here
    - UI, etc.
</code>```

I currently have the MediatR and MediatR .net Core DI packages installed in the UI project and they are added to DI using .AddMediatR(), with the command

```<code>services.AddMediatR(typeof(MyApp.AppServices.Commands.Command).Assembly);
</code>```

which scans and registers command handlers from the AppServices project.

The problem comes when I want to define an event. For MediatR to work with my domain events, they need to be marked with the MediatR.INotification interface.

```<code>namespace ObApp.Domain.Events
{
    public class NewUserAdded : INotification
    {
        ...
    }
</code>```

What is the proper way to mark my events in this situation so they can be used by MediatR? I can create my own marker interface for events, but MediatR won't recognize those without some way to automatically cast them to MediatR.INotification.

Is this just a shortcoming of using multiple projects? Even if I was using a single project, though, I would be putting an "external" interface in the domain if I used MediatR.INotification from within the domain section.

I've run into the same issue when my User entity inherited from EF's IdentityUser. In that case the web consensus seems to say be pragmatic and go ahead and allow the minor pollution to save a lot of headaches. Is this another similar case? I don't mind sacrificing purity for pragmatism, but not just to be lazy.

This is a fundamental issue that will occur with other packages I use, so I look forward to solving this.

Thank you!

答:
It would be first prize to attempt to first not have an infrastructure dependency in the domain layer.

I don't know MediatR but from what you describe it requires an interface to be implemented on a class that is going to be used in that space.

Is it perhaps an option to create a wrapper class that lives outside your domain?

```<code>public class MediatRNotification<T> : INotification
{
    T Instance { get; }

    public MediatRNotification(T instance)
    {
        Instance = instance;
    }
}
</code>```

Your infrastructure could even use some reflection to create this wrapper from a domain event.

Body:
I'm just getting started with DDD. I'm putting domain events into a CQRS application and I'm stumbling on a fundamental task: How to use the MediatR.INotification marker interface within the domain project without creating a domain dependency on infrastructure.

My solution is organized in four projects as follows:

MyApp.Domain
    - Domain events
    - Aggregates
    - Interfaces (IRepository, etc), etc.
MyApp.ApplicationServices
    - Commands
    - Command Handlers, etc.
MyApp.Infrastructure
    - Repository
    - Emailer, etc.
MyApp.Web
    - Startup
    - MediatR NuGet packages and DI here
    - UI, etc.

I currently have the MediatR and MediatR .net Core DI packages installed in the UI project and they are added to DI using .AddMediatR(), with the command

services.AddMediatR(typeof(MyApp.AppServices.Commands.Command).Assembly);

which scans and registers command handlers from the AppServices project.

The problem comes when I want to define an event. For MediatR to work with my domain events, they need to be marked with the MediatR.INotification interface.

namespace ObApp.Domain.Events
{
    public class NewUserAdded : INotification
    {
        ...
    }

What is the proper way to mark my events in this situation so they can be used by MediatR? I can create my own marker interface for events, but MediatR won't recognize those without some way to automatically cast them to MediatR.INotification.

Is this just a shortcoming of using multiple projects? Even if I was using a single project, though, I would be putting an "external" interface in the domain if I used MediatR.INotification from within the domain section.

I've run into the same issue when my User entity inherited from EF's IdentityUser. In that case the web consensus seems to say be pragmatic and go ahead and allow the minor pollution to save a lot of headaches. Is this another similar case? I don't mind sacrificing purity for pragmatism, but not just to be lazy.

This is a fundamental issue that will occur with other packages I use, so I look forward to solving this.

Thank you!

Body:
It would be first prize to attempt to first not have an infrastructure dependency in the domain layer.

I don't know MediatR but from what you describe it requires an interface to be implemented on a class that is going to be used in that space.

Is it perhaps an option to create a wrapper class that lives outside your domain?

public class MediatRNotification<T> : INotification
{
    T Instance { get; }

    public MediatRNotification(T instance)
    {
        Instance = instance;
    }
}

Your infrastructure could even use some reflection to create this wrapper from a domain event.


问:
Issues in calculating tf-idf in gensim
I am using Gensim to calculate tf-idf scores for my corpus mentioned below.

```<code>corpus=['human interface computer',
 'survey user computer system response time',
 'eps user interface system',
 'system human system eps',
 'user response time']
</code>```

My current code is as follows.

```<code>dictionary = corpora.Dictionary(line.lower().split() for line in corpus)

class MyCorpus(object):
    def __iter__(self):
        for line in corpus:
            yield dictionary.doc2bow(line.lower().split())

corpus = MyCorpus()

tfidf = models.TfidfModel(corpus)

corpus_tfidf = tfidf[corpus]
</code>```

However, I get the error RecursionError: maximum recursion depth exceeded while calling a Python object (PS: if my code is wrong I am happy to have a different code). Please help me to calculate tf-idf values for my current corpus. Moreover, I want to get the 3 terms that has the highest tf-idf score in my corpus.

Please help me!

答: Well you are redefining your original corpus list as a MyCorpus object, so of course this is going into an infinite recursion when trying to iterate over it (since you iterate over corpus in the __iter__ method). Maybe you want to define my_corpus = MyCorpus()? Otherwise explain what you are trying to do...

Title: Issues in calculating tf-idf in gensim

Body:
I am using Gensim to calculate tf-idf scores for my corpus mentioned below.

corpus=['human interface computer',
 'survey user computer system response time',
 'eps user interface system',
 'system human system eps',
 'user response time']

My current code is as follows.

dictionary = corpora.Dictionary(line.lower().split() for line in corpus)

class MyCorpus(object):
    def __iter__(self):
        for line in corpus:
            yield dictionary.doc2bow(line.lower().split())

corpus = MyCorpus()

tfidf = models.TfidfModel(corpus)

corpus_tfidf = tfidf[corpus]

However, I get the error RecursionError: maximum recursion depth exceeded while calling a Python object (PS: if my code is wrong I am happy to have a different code). Please help me to calculate tf-idf values for my current corpus. Moreover, I want to get the 3 terms that has the highest tf-idf score in my corpus.

Please help me!


问:
Do member account need to join Apple Membership Program if added into an Organizations's Account team ?
This may be a silly question, but i read all detail in the link below and still confusing.

https://developer.apple.com/support/enrollment/

Question: I need to create a new (and first) Apple ID for my company (that hasn't experimented in iOS development before) and join Apple Developer Program for Organizations. But i still not understand :

Is it true that my company only need to pay once (99$/year) for the Team Agent account ? If we add another members, do their account need to be a Paid Account or just an Apple ID is enough ?

If 1's answer is YES, is there any limitation for the number of member that Team Agent account can add ?

Please help, and sorry for my bad English.

答:
yes, company needs to pay once per year. But account must be organization account, as mentioned in your link, you should have legal entity status (or name), DUNs number etc. to register as organization account.

For adding new members there is no need for paid account.
check how to manage team at reference: https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ManagingYourTeam/ManagingYourTeam.html

As of my knowledge there is no limit for adding members (or developers)

Hope this helps


问:
Using vector to hold class objects
SOLVED: Used a vector of pointers instead

I have a class named Nurse and I would like a vector of size numNurses of Nurse objects. With each object having unique data.
I first attempted to do this with the code

```<code>std::vector<Nurse> allNurses;
for (int i=0; i<numNurses; i++){
allNurses.push_back (Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1));
}
</code>```

but I found that changing the data of any nurse, referenced by some
index into allNurses (allNurses[0] for example) would affect every
other member of the vector.

I figured that maybe I just needed to call new somewhere since I was probably never creating new objects. Trying something like

```<code>allNurses[i]= new Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);
</code>```

Resulted in an error (that I don't think is too important):

Optimize_Schedule.cpp: In constructor
  'Optimize_Schedule::Optimize_Schedule(int)':

Optimize_Schedule.cpp:38:17: error: no match for 'operator=' (operand
  types are 'Nurse' and 'Nurse*')

```<code> allNurses[i]= new Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);
             ^ In file included from Optimize_Schedule.cpp:5:0:
</code>```

Nurse.h:15:7: note: candidate: Nurse& Nurse::operator=(const Nurse&)
  class Nurse{

```<code>                                                                        ^
</code>```

Nurse.h:15:7: note:   no known conversion for argument 1 from 'Nurse*'
  to 'const Nurse&'

答:
The allNurses declaration is for a vector or Nurse objects, by value:

```<code>std::vector<Nurse> allNurses;
</code>```

So you do NOT want to call "new" which returns a pointer.

The complaint about 'operator=' is because this line tries to assign a Nurse pointer to a Nurse instance.

```<code>allNurses[i]= new Nurse(...);
</code>```

Concerning the original symptom:

There isn't enough information to understand why changing one Nurse object might affect others -- however there may be a different explanation. Since this is a vector of objects (not a vector of object pointers), the default copy constructor is likely being used as the vector gets expanded. If Nurse contains any members that cannot be copied element-by-element, you'd need your own copy constructor. (Move constructor in C++11.)

The alternative might be to use a vector of (smart) pointers. Then "operator=" would work.

(If going down this route, consider using a smart pointer so there's no need to explicitly clean up all the vector elements when the vector needs to be released.)

As an aside, if you have C++11 and are using a vector by value, consider using "emplace_back" instead of "push_back" to append a newly constructed Nurse object in-place, as follows:

```<code>allNurses.emplace_back(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);
</code>```

Title: Using vector to hold class objects

Body:
SOLVED: Used a vector of pointers instead

I have a class named Nurse and I would like a vector of size numNurses of Nurse objects. With each object having unique data.
I first attempted to do this with the code

std::vector<Nurse> allNurses;
for (int i=0; i<numNurses; i++){
allNurses.push_back (Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1));
}

but I found that changing the data of any nurse, referenced by some
index into allNurses (allNurses[0] for example) would affect every
other member of the vector.

I figured that maybe I just needed to call new somewhere since I was probably never creating new objects. Trying something like

allNurses[i]= new Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);

Resulted in an error (that I don't think is too important):

Optimize_Schedule.cpp: In constructor
  'Optimize_Schedule::Optimize_Schedule(int)':

Optimize_Schedule.cpp:38:17: error: no match for 'operator=' (operand
  types are 'Nurse' and 'Nurse*')

 allNurses[i]= new Nurse(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);
             ^ In file included from Optimize_Schedule.cpp:5:0:

Nurse.h:15:7: note: candidate: Nurse& Nurse::operator=(const Nurse&)
  class Nurse{

                                                                        ^

Nurse.h:15:7: note:   no known conversion for argument 1 from 'Nurse*'
  to 'const Nurse&'

Body:
The allNurses declaration is for a vector or Nurse objects, by value:

std::vector<Nurse> allNurses;

So you do NOT want to call "new" which returns a pointer.

The complaint about 'operator=' is because this line tries to assign a Nurse pointer to a Nurse instance.

allNurses[i]= new Nurse(...);

Concerning the original symptom:

There isn't enough information to understand why changing one Nurse object might affect others -- however there may be a different explanation. Since this is a vector of objects (not a vector of object pointers), the default copy constructor is likely being used as the vector gets expanded. If Nurse contains any members that cannot be copied element-by-element, you'd need your own copy constructor. (Move constructor in C++11.)

The alternative might be to use a vector of (smart) pointers. Then "operator=" would work.

(If going down this route, consider using a smart pointer so there's no need to explicitly clean up all the vector elements when the vector needs to be released.)

As an aside, if you have C++11 and are using a vector by value, consider using "emplace_back" instead of "push_back" to append a newly constructed Nurse object in-place, as follows:

allNurses.emplace_back(input,numShifts,numDays,inRow,nurMaxDay,nurMinDay,1);


问:
How do I find the number of common numbers occurring in 2nd array?
commonCount(ar1, ar2)

if arr1 = [1,1,2,3,3] and arr2 = [1,4,3,1,1], the answer is 3

My thought process:

initialize accumulator

iterate through arr1

if arr1[i] is in the arr2, add 1 to the accumulator

remove the arr1[i] from arr2 (because don't want to have duplicate if the number already exist)

return accumulator

1) How do I check if arr1[i] is in the arr2?

2) How do I remove arr1[i] from arr2?

答:
You can store all unique values along with its frequency in an object using array#reduce and then filter result by looking into unique object using array#filter and decrementing the frequency once you find the same value. After that simply return length.

const arr1 = [1,1,2,3,3],
      arr2 = [1,4,3,1,1];

var commonCount = (ar1, ar2) => {
  const uniques = ar1.reduce((res, v) => {
    res[v] = (res[v] || 0) + 1;
    return res;
  },{});
  const common = arr2.filter(v => uniques[v] > 0 && uniques[v]--);
  return common.length;
}

console.log(commonCount(arr1,arr2));```


问:
"Next" and "Previous" button on Django, on posts with Slugs
What I want is to create "Next Post" and "Previous Post" on Django. What I have managed to do until now is to link the button to a page where the primary key is one above or one below the current post:

```<code><a class="btn btn-default" href="{% url 'post_detail' slug=post.slug pk=post.pk|add:'1' %}">Next</a>
</code>```

There are two issues: one is with the Slug and with the URL, and the other is with the showing (or hiding) of the button.

When I click next, I am taken to the next post (if it exists. If it doens't I receive an error telling me that such a page doesn't exist). The URL remains the same as the previous post, correspondingly: If I click it three times, the URL displayed will be the one of the second post. What I would like is to somehow also display the corresponding slug.

The second problem, is that I want to disable the button if there is no post before or after. But the following piece of code:

```<code>  {% if post.pk|add:'1' %}
</code>```

Which is what I have come up with up until now. But apparently it checks if such a number exists, not if the post exists or not.

The view class for this page is the following:

```<code>class PostDetailView(HitCountDetailView):
    model = Post
    slug_field = "title"
    count_hit = True
</code>```

Whereas the model is (removing irrelevant-to-this-issue code):

```<code>@python_2_unicode_compatible
class Post(models.Model, HitCountMixin):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=100, null=False, blank=False)
    text = models.TextField(null=False, blank=False)
    slug = models.SlugField(max_length=100, blank=True)

    # rewrite save method
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    def article_pre_save(signal, instance, sender, **kwargs):
        instance.slug = slugify(instance.title)

    signals.pre_save.connect(article_pre_save, sender="blog.Post")

    # go to post page
    def get_absolute_url(self):
        return reverse("post_detail", kwargs={'slug':self.slug, 'pk':self.pk})

    # retorna o título do post
    def __str__(self):
        return self.title
</code>```

And the related url:

```<code>    url(_(r'^post/(?P<pk>\d+)-(?P<slug>[-\w]+)/$'), views.PostDetailView.as_view(), name='post_detail'),
</code>```

How could I proceed to this? I thought about writing a Raw SQL query (I've been having problems with this too, but that's another matter), but I don't know, up to now, how I could actually link it to the  template. Thank you for your help, if you will, and attention, in advance.

答: django-next-prev refer this. its good package for these kinds of requirements. this package will get you the next and previous object of the current object. after that, you have to build the next and previous URL using reverse or reverze_lazy methods in Django</p>

Body:
What I want is to create "Next Post" and "Previous Post" on Django. What I have managed to do until now is to link the button to a page where the primary key is one above or one below the current post:

Next

There are two issues: one is with the Slug and with the URL, and the other is with the showing (or hiding) of the button.

When I click next, I am taken to the next post (if it exists. If it doens't I receive an error telling me that such a page doesn't exist). The URL remains the same as the previous post, correspondingly: If I click it three times, the URL displayed will be the one of the second post. What I would like is to somehow also display the corresponding slug.

The second problem, is that I want to disable the button if there is no post before or after. But the following piece of code:

  {% if post.pk|add:'1' %}

Which is what I have come up with up until now. But apparently it checks if such a number exists, not if the post exists or not.

The view class for this page is the following:

class PostDetailView(HitCountDetailView):
    model = Post
    slug_field = "title"
    count_hit = True

Whereas the model is (removing irrelevant-to-this-issue code):

@python_2_unicode_compatible
class Post(models.Model, HitCountMixin):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=100, null=False, blank=False)
    text = models.TextField(null=False, blank=False)
    slug = models.SlugField(max_length=100, blank=True)

    # rewrite save method
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    def article_pre_save(signal, instance, sender, **kwargs):
        instance.slug = slugify(instance.title)

    signals.pre_save.connect(article_pre_save, sender="blog.Post")

    # go to post page
    def get_absolute_url(self):
        return reverse("post_detail", kwargs={'slug':self.slug, 'pk':self.pk})

    # retorna o título do post
    def __str__(self):
        return self.title

And the related url:

    url(_(r'^post/(?P<pk>\d+)-(?P<slug>[-\w]+)/$'), views.PostDetailView.as_view(), name='post_detail'),

How could I proceed to this? I thought about writing a Raw SQL query (I've been having problems with this too, but that's another matter), but I don't know, up to now, how I could actually link it to the  template. Thank you for your help, if you will, and attention, in advance.


问:
Haskell Yesod problems
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

```<code> $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
</code>```

Seriously, I tried a bunch of things to fix it, but nothing is working =S

答: Thank you, guys! It was a problem on how I was starting the project, some files weren't installed on my workspace, so I delete the files, reinstall Yesod and cabal, create another new version after following this steps: https://www.yesodweb.com/page/quickstart</p>

Title: Haskell Yesod problems

Body:
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

 $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1

Seriously, I tried a bunch of things to fix it, but nothing is working =S


问:
JasperReport - taking too much resources
so, problem is when we are showing to user created document in JasperReport Dialog. User can press print icon and sent it to printer.

It seems to take too much resources on client's computer on all three levels: creating report, showing report on screen and sending it to printer. One example PC is AMD Duron 800MHz with 256MB of RAM so we need to see if we can do some optimizations for better user experience.

It also takes significant resources on 'normal' computer with 2GHz processor and 1GB RAM so I need to see if there is an option to tune JasperReport to behave less gready on resources.

答:
Excessive use of subreports can increase resource demands for a report. Each subreport spawns its own thread during fill time. Also if you are using scriptlets or helpers classes ensure all resources they create are being properly cleaned up. Also ensure you are using the latest JR package.

One note. The JR api includes a set of virtualizers. When the report is filling, the entire filled report is created as an object (JasperPrint). Depending on the numbers of pages in the report, this object can get pretty large. The virtualizers can be configured to write to the file system when a set page-threshold has been reached.

Typically this reduces overall memory usage but increases fill time. A comprise might be the gzip virtualizer which rather than writing to the file system, compresses the generated objects using gzip.

Here is an FAQ on the subject:
http://community.jaspersoft.com/wiki/support-large-reports

The example it refers to can be obtained by downloading the JR source.

http://sourceforge.net/project/showfiles.php?group_id=36382&package_id=28579

From a high level view, if you are running this report in an application you can instantiate the virtualizer (here is the interface listing the known implementing classes):
http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JRVirtualizer.html

Then the reference is used at fill time:

```<code>        JRDataSource ds = new JREmptyDataSource(10);
        JRFileVirtualizer virtualizer = new JRFileVirtualizer(2, "tmp");
        JasperPrint jasperPrint = fillReport(fileName, ds, virtualizer);
</code>```

If you are in iReport a virtualizer can be configured in Options -> Settings.

I hope this is helpful.

Luke

OwnerDisplayName: asabo

ContentLicense: CC BY-SA 2.5

Body:
Excessive use of subreports can increase resource demands for a report. Each subreport spawns its own thread during fill time. Also if you are using scriptlets or helpers classes ensure all resources they create are being properly cleaned up. Also ensure you are using the latest JR package.

One note. The JR api includes a set of virtualizers. When the report is filling, the entire filled report is created as an object (JasperPrint). Depending on the numbers of pages in the report, this object can get pretty large. The virtualizers can be configured to write to the file system when a set page-threshold has been reached.

Typically this reduces overall memory usage but increases fill time. A comprise might be the gzip virtualizer which rather than writing to the file system, compresses the generated objects using gzip.

Here is an FAQ on the subject:
http://community.jaspersoft.com/wiki/support-large-reports

The example it refers to can be obtained by downloading the JR source.

http://sourceforge.net/project/showfiles.php?group_id=36382&package_id=28579

From a high level view, if you are running this report in an application you can instantiate the virtualizer (here is the interface listing the known implementing classes):
http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JRVirtualizer.html

Then the reference is used at fill time:

        JRDataSource ds = new JREmptyDataSource(10);
        JRFileVirtualizer virtualizer = new JRFileVirtualizer(2, "tmp");
        JasperPrint jasperPrint = fillReport(fileName, ds, virtualizer);

If you are in iReport a virtualizer can be configured in Options -> Settings.

I hope this is helpful.

Luke


问:
how to copy lines 10 to 15 of a file into another file, in unix?
I want to copy lines 10 to 15 of a file into another file in Unix.

I am having files file1.txt and file2.txt.

I want to copy lines 10 to 15 from file1.txt to file2.txt.

答:
In complement to the previous answer, you can use one of the following 3 solutions.

sed

Print only the lines in the range and redirect it to the output file

```<code>sed -n '10,15p' file1.txt > file2.txt
</code>```

head/tail combination

Use head and tail to cut the file and to get only the range you need before redirecting the output to a file

```<code>head -n 15 file1.txt | tail -n 6 > file2.txt
</code>```

awk

Print only the lines in the range and redirect it to the output file

```<code>awk 'NR>=10 && NR<=15' file1.txt > file2.txt
</code>```

Body:
In complement to the previous answer, you can use one of the following 3 solutions.

sed

Print only the lines in the range and redirect it to the output file

sed -n '10,15p' file1.txt > file2.txt

head/tail combination

Use head and tail to cut the file and to get only the range you need before redirecting the output to a file

head -n 15 file1.txt | tail -n 6 > file2.txt

awk

Print only the lines in the range and redirect it to the output file

awk 'NR>=10 && NR<=15' file1.txt > file2.txt


问:
How can I do java regex? Match 2-3 letters?
I have problem with my java project, I did not add match combination, I have a dictionary and mixed, dictionary is havenormal word, in mixed changed from dictionary like; in dic. = "mouse" mixed= "usemo" those are the same word, I want to do If I write on mixed "usmo" program go to the dictionary and 4 letters are the same at dictionary so word is mouse, or mixed = "usem" dictionary can change "mouse", I search this can be possible with regex, but I do not any idea about how to do this, can anybody help me??</p>

答:
Here is the running code which will match with the pattern that you search using regex and print the matching result from the dictionary.  </p>

```<code>   public class RegexTestStrings {

    private static HashSet<String> dictionarySet = new HashSet<String>();
    private static HashSet<String> regExSetSet = new HashSet<String>();
    public static void main(String[] args) {
        dictionarySet.add("mouse");
        dictionarySet.add("tiger");
        dictionarySet.add("monkey");
        RegexTestStrings regexTestStrings=new RegexTestStrings();
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usemo"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usem"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usmo"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"kmoy"));
    }

    private String fidMatchingWord(HashSet<String> dictionarySet2, String searchWord) {
        String result=null;
        Iterator<String> dictionarIterator=dictionarySet.iterator();
        while(dictionarIterator.hasNext()){
            regExSetSet.clear();
            String inputString=dictionarIterator.next();
            findAllRegEx(inputString.toCharArray(), 0, inputString.length()-1);
            Iterator<String> resultIterator=regExSetSet.iterator();
            // Regular expression to match the pattern of search string
            String pattern = "(?s)^(" + Pattern.quote(searchWord) + ".*$|.*" + Pattern.quote(searchWord) + ")$";
            while(resultIterator.hasNext()){
                String str=resultIterator.next();
                Pattern p = Pattern.compile(pattern);
                Matcher m = p.matcher(str);
                boolean b = m.matches();
                if(b){
                    result=inputString;
                    break;
                }
            }
        }
        return result;
    }

    public static void findAllRegEx(char[] ary, int startIndex, int endIndex) {
        if(startIndex == endIndex){
            regExSetSet.add(String.valueOf(ary));
        }else{
            for(int i=startIndex;i<=endIndex;i++) {
                 swap(ary, startIndex, i );
                 findAllRegEx(ary, startIndex+1, endIndex);
                 swap(ary, startIndex, i );
            }
        }
    }

    public static void swap(char[] arr, int x, int y) {
        char temp = ary[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }
}
Output
______________
mouse
mouse
mouse
monkey
</code>```

Body:
Here is the running code which will match with the pattern that you search using regex and print the matching result from the dictionary.

   public class RegexTestStrings {

    private static HashSet<String> dictionarySet = new HashSet<String>();
    private static HashSet<String> regExSetSet = new HashSet<String>();
    public static void main(String[] args) {
        dictionarySet.add("mouse");
        dictionarySet.add("tiger");
        dictionarySet.add("monkey");
        RegexTestStrings regexTestStrings=new RegexTestStrings();
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usemo"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usem"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usmo"));
        System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"kmoy"));
    }

    private String fidMatchingWord(HashSet<String> dictionarySet2, String searchWord) {
        String result=null;
        Iterator<String> dictionarIterator=dictionarySet.iterator();
        while(dictionarIterator.hasNext()){
            regExSetSet.clear();
            String inputString=dictionarIterator.next();
            findAllRegEx(inputString.toCharArray(), 0, inputString.length()-1);
            Iterator<String> resultIterator=regExSetSet.iterator();
            // Regular expression to match the pattern of search string
            String pattern = "(?s)^(" + Pattern.quote(searchWord) + ".*$|.*" + Pattern.quote(searchWord) + ")$";
            while(resultIterator.hasNext()){
                String str=resultIterator.next();
                Pattern p = Pattern.compile(pattern);
                Matcher m = p.matcher(str);
                boolean b = m.matches();
                if(b){
                    result=inputString;
                    break;
                }
            }
        }
        return result;
    }

    public static void findAllRegEx(char[] ary, int startIndex, int endIndex) {
        if(startIndex == endIndex){
            regExSetSet.add(String.valueOf(ary));
        }else{
            for(int i=startIndex;i<=endIndex;i++) {
                 swap(ary, startIndex, i );
                 findAllRegEx(ary, startIndex+1, endIndex);
                 swap(ary, startIndex, i );
            }
        }
    }

    public static void swap(char[] arr, int x, int y) {
        char temp = ary[x];
        arr[x] = arr[y];
        arr[y] = temp;
    }
}
Output
______________
mouse
mouse
mouse
monkey


问:
git tree has two "toplevel" branches
I have an old project that I was trying to clean up, and somehow I endedup with two separate commits that think they're the "initial commit" and don't have a parent branch, as seen below:

```<code>% git log --all --date-order --pretty="%h  %p  %d"
    0fb2623  81d3553   (HEAD -> master, tag: v6.2.5, origin/master,
origin/HEAD)
    81d3553  d7d7578   (tag: v6.2.4)
    d7d7578  eae8973   (tag: v6.2.3)
    eae8973  ded0fe9   (tag: v6.2.1)
    ded0fe9  efb33b0   (tag: v6.2.0)
    efb33b0
    13a5b0e  45ab2ba   (tag: v6.0.1)
    45ab2ba  2d60f30
    2d60f30  2185112
    2185112  872f408
    872f408
</code>```

Is there a way that I can re-link that in so that efb33b0 has a parent of 13a5b0e?

答:
I just removed the v6.0.1 tag from my local repository and that whole second tree disappeared

You can still make a new branch on 13a5b0e

Is there a way that I can re-link that in so that efb33b0 has a parent of 13a5b0e?

Create a graft file, and then filter-branch (better in this instance as git replace, as I mention here)

```<code>echo "efb33b0 13a5b0e  >> .git/info/grafts
git filter-branch 13a5b0e ..HEAD
</code>```

Title: git tree has two "toplevel" branches

Body:
I have an old project that I was trying to clean up, and somehow I endedup with two separate commits that think they're the "initial commit" and don't have a parent branch, as seen below:

% git log --all --date-order --pretty="%h  %p  %d"
    0fb2623  81d3553   (HEAD -> master, tag: v6.2.5, origin/master,
origin/HEAD)
    81d3553  d7d7578   (tag: v6.2.4)
    d7d7578  eae8973   (tag: v6.2.3)
    eae8973  ded0fe9   (tag: v6.2.1)
    ded0fe9  efb33b0   (tag: v6.2.0)
    efb33b0
    13a5b0e  45ab2ba   (tag: v6.0.1)
    45ab2ba  2d60f30
    2d60f30  2185112
    2185112  872f408
    872f408

Is there a way that I can re-link that in so that efb33b0 has a parent of 13a5b0e?

Body:
I just removed the v6.0.1 tag from my local repository and that whole second tree disappeared

You can still make a new branch on 13a5b0e

Is there a way that I can re-link that in so that efb33b0 has a parent of 13a5b0e?

Create a graft file, and then filter-branch (better in this instance as git replace, as I mention here)

echo "efb33b0 13a5b0e  >> .git/info/grafts
git filter-branch 13a5b0e ..HEAD


答:
Yes 0099 also should be quoted. I forgot by mistake.

```<code>$ awk -v q='"' '{for(i=1; i<=NF; i++)if($i ~/^0[[:alnum:]][^.\/]/)$i=q $i q}1' infile
1234 "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000" "000012"
1800.000000
"099000"
"0123456789"
</code>```

Input:

```<code>$ cat infile
1234      012345
0.000
01/02/03
01234
05554567
0qwertyu
0099
0000           000012
1800.000000
099000
0123456789
</code>```

Explanation:

/^0[[:alnum:]][^.\/]/

^ asserts position at start of the string

0 matches the character 0 literally

Match a single character present in the list below [[:alnum:]]
[:alnum:] matches a alphanumeric character [a-zA-Z0-9]

Match a single character not present in the list below [^.\/]
. matches the character . literally
\/ matches the character / literally

Title: Need to replace all the strings staring with 0 (except having / and .) in a text file with same string in double quotes

Body:
    awk '{for(i=1;i<=NF;i++){if($i~/^0[a-z,0-9][a-z,0-9]/){print $i}}}' test1 > test3

 doWork()

 { rm /tmp/test1 && awk '{sub(/'$I'/, "\"'$I'\"", $0); print}' >test1;} < test1

 for I in `cat /tmp/test3`
 do doWork;
 done;

Input text file:

/tmp # cat test1 1234      012345
  0.000 01/02/03 01234 05554567 0qwertyu 0099 0000           000012
  1800.000000 099000 0123456789

Current Output:

1234      ""01234"5"
  0.000 01/02/03 "01234" "05554567" "0qwertyu" "0099" "0000"           "000012"
  1800."0000"00 "099000" ""01234"5"6789

Expected output:

1234      "012345"
  0.000 01/02/03 "01234" "05554567" "0qwertyu" 0099 "0000"           "000012"
  1800.000000 "099000" "0123456789"

Body:
Yes 0099 also should be quoted. I forgot by mistake.

$ awk -v q='"' '{for(i=1; i<=NF; i++)if($i ~/^0[[:alnum:]][^.\/]/)$i=q $i q}1' infile
1234 "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000" "000012"
1800.000000
"099000"
"0123456789"

Input:

$ cat infile
1234      012345
0.000
01/02/03
01234
05554567
0qwertyu
0099
0000           000012
1800.000000
099000
0123456789

Explanation:

/^0[[:alnum:]][^.\/]/

^ asserts position at start of the string

0 matches the character 0 literally

Match a single character present in the list below [[:alnum:]]
[:alnum:] matches a alphanumeric character [a-zA-Z0-9]

Match a single character not present in the list below [^.\/]
. matches the character . literally
\/ matches the character / literally


问:
Drop down menu with input box
How can I make a drop down option with a input box using css and html like the picture below?

答:
Modify as your need</p>

```<code><!DOCTYPE html>
    <html lang="en">
    <body>
     <h2>This is what you want </h2>
      <center>
    <select style="height: 36px; border-right: 4px solid; width: 55px; background: transparent;">
    <option value="India">+91</option>
    <option value="India">+92</option>
    <option value="India">+93</option>
    <option value="India">+94</option>
    <option value="India">+01</option>
    </select>
    <input type="text" style="height: 30px; margin-left: -4px; padding-left: 5px;">
    </center>

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

Title: Drop down menu with input box

Body:
Modify as your need

<!DOCTYPE html>
    <html lang="en">
    <body>
     <h2>This is what you want </h2>
      <center>
    <select style="height: 36px; border-right: 4px solid; width: 55px; background: transparent;">
    <option value="India">+91</option>
    <option value="India">+92</option>
    <option value="India">+93</option>
    <option value="India">+94</option>
    <option value="India">+01</option>
    </select>
    <input type="text" style="height: 30px; margin-left: -4px; padding-left: 5px;">
    </center>

    </body>
    </html>


问:
Select one component on click from a list of components in Vue.js
Hello I am trying to implement a comment system using Vue.Js

https://jsfiddle.net/jahid93/597vtcoz/

```<code>[<div id='app'>
<cmt-component :type="comment"></cmt-component>
<div class="comments" v-for="comment in commentList">
<div>
  <span>{{comment.id}}</span>
   <span>{{comment.comment}}</span>
</div>

<span class="reply-spa" @click="actionReply(comment.id)">Reply </span>
<div>
<cmt-component v-if="(selected_comment == comment.id) && replypart" :type="reply"></cmt-component>
</div>
</div>
</div>][1]
</code>```

in the reply part when i click on reply it shows the reply box and then if i click on another reply it hides the first reply box first then i have to click on reply box again for that reply box
But I want to implement when I click on second reply box it hides first one and also show the current one.

答:
You're toggling replypart off when you click on another 'Reply' button; you'd want to change your actionReply method to something like this:

```<code>actionReply: function (id) {
    // if this is the reply box for the selected comment, or if there are no reply boxes open
    if (id === this.selected_comment || this.replypart === false) {
        this.replypart = !this.replypart
    }
    this.selected_comment = id
}
</code>```

Body:
Hello I am trying to implement a comment system using Vue.Js

https://jsfiddle.net/jahid93/597vtcoz/

[

<cmt-component :type="comment"></cmt-component>

  {{comment.id}}
   {{comment.comment}}

Reply

<cmt-component v-if="(selected_comment == comment.id) && replypart" :type="reply"></cmt-component>

][1]

in the reply part when i click on reply it shows the reply box and then if i click on another reply it hides the first reply box first then i have to click on reply box again for that reply box
But I want to implement when I click on second reply box it hides first one and also show the current one.

Body:
You're toggling replypart off when you click on another 'Reply' button; you'd want to change your actionReply method to something like this:

actionReply: function (id) {
    // if this is the reply box for the selected comment, or if there are no reply boxes open
    if (id === this.selected_comment || this.replypart === false) {
        this.replypart = !this.replypart
    }
    this.selected_comment = id
}


问:
Forking multiple process in twisted with shared object
I want to fork multiple processes with twisted. I know from the discussion here that Twisted and multiprocessing are not compatible with each other. Its true that I can launch separate processes from different terminals to achieve the same effect, but I cannot do so.

There is a big object (size in GBs) which I want to share among different python processes (cannot load the same object multiple times on RAM, due to RAM limitation on my computer)

What I am trying to do is

Start multiple rabbit-mq consumers asynchronously in a single process.

Fork multiple such processes with a common shared object to leverage all CPUs in my system.

I am able to achieve step one. Here is what I come up with -

```<code>import pika

class PikaFactory(protocol.ReconnectingClientFactory):
    def __init__(self, parameters, task_number=0, shared_obj=None):
        self.parameters = parameters
        self.task_count = total_tasks
        self.task_number = task_number
        self.shared_obj= shared_obj

    def buildProtocol(self, addr):
        self.resetDelay()
        logger.info('Task: %s, Connected' % self.task_number)
        proto = twisted_connection.TwistedProtocolConnection(self.parameters)
        # run is a async function that consumes the rabbit-queue
        proto.ready.addCallback(run, self.task_number, self.shared_obj)
        return proto

    # Rest of the implementation ...........

def run_tasks(shared_obj):
    from twisted.internet import reactor
    try:
        parameters = pika.ConnectionParameters(**CONNECTION_PARAMETERS)
        factory = PikaFactory(parameters, 0, shared_obj)

        for i in range(total_tasks):
            # Launch multiple async-tasks in the same process
            reactor.connectTCP(parameters.host, parameters.port, factory)

        logger.info(' [*] Waiting for messages. To exit press CTRL+C')
        reactor.run()
    except:
        logger.exception("Error")
        reactor.stop()

if __name__ == '__main__':
    obj = Fibonacci()
    run_tasks(obj)
</code>```

Now to fork multiple processes I have written this code.

```<code>from multiprocessing.managers import BaseManager
class MyManager(BaseManager):
    """
    This Manager is responsible for coordinating shared
    information state between all processes
    """
    pass

# Register your custom "Fibonacci" class with the manager
# This is the class I want to share among multiple processes
MyManager.register('Fibonacci', Fibonacci)

def Manager():
    m = MyManager()
    m.start()
    return m

def run_multiple_processes():
    manager = Manager()
    # object I want to share among multiple processes
    fibonacci = manager.Fibonacci()
    pool = multiprocessing.Pool(processes=workers)
    for i in range(0, workers):
        pool.apply_async(run_tasks, (fibonacci, ))

    # Stay alive
    try:
        while True:
            continue
    except KeyboardInterrupt:
        logger.error(' [*] Exiting...')
        pool.terminate()
        pool.join()
</code>```

I am getting some random errors while running the above code like -

```<code>builtins.AttributeError: '_SIGCHLDWaker' object has no attribute 'doWrite'
</code>```

What would be the twisted way to launch multiple process and share a custom object between them. No writes will be performed on the object, the object is used to only read from its attributes.

Thanks in advance.

答:
While searching I encountered this post - twisted incompatible with python multiprocessing. The answer exists in this post only quoting his words -

"not loading any of Twisted until you've already created the child processes.  This means not even importing Twisted until after you've created the child processes."

Thanks @Jean-Paul Calderone for this useful comment.

Body:
I want to fork multiple processes with twisted. I know from the discussion here that Twisted and multiprocessing are not compatible with each other. Its true that I can launch separate processes from different terminals to achieve the same effect, but I cannot do so.

There is a big object (size in GBs) which I want to share among different python processes (cannot load the same object multiple times on RAM, due to RAM limitation on my computer)

What I am trying to do is

Start multiple rabbit-mq consumers asynchronously in a single process.

Fork multiple such processes with a common shared object to leverage all CPUs in my system.

I am able to achieve step one. Here is what I come up with -

import pika

class PikaFactory(protocol.ReconnectingClientFactory):
    def __init__(self, parameters, task_number=0, shared_obj=None):
        self.parameters = parameters
        self.task_count = total_tasks
        self.task_number = task_number
        self.shared_obj= shared_obj

    def buildProtocol(self, addr):
        self.resetDelay()
        logger.info('Task: %s, Connected' % self.task_number)
        proto = twisted_connection.TwistedProtocolConnection(self.parameters)
        # run is a async function that consumes the rabbit-queue
        proto.ready.addCallback(run, self.task_number, self.shared_obj)
        return proto

    # Rest of the implementation ...........

def run_tasks(shared_obj):
    from twisted.internet import reactor
    try:
        parameters = pika.ConnectionParameters(**CONNECTION_PARAMETERS)
        factory = PikaFactory(parameters, 0, shared_obj)

        for i in range(total_tasks):
            # Launch multiple async-tasks in the same process
            reactor.connectTCP(parameters.host, parameters.port, factory)

        logger.info(' [*] Waiting for messages. To exit press CTRL+C')
        reactor.run()
    except:
        logger.exception("Error")
        reactor.stop()

if __name__ == '__main__':
    obj = Fibonacci()
    run_tasks(obj)

Now to fork multiple processes I have written this code.

from multiprocessing.managers import BaseManager
class MyManager(BaseManager):
    """
    This Manager is responsible for coordinating shared
    information state between all processes
    """
    pass

# Register your custom "Fibonacci" class with the manager
# This is the class I want to share among multiple processes
MyManager.register('Fibonacci', Fibonacci)

def Manager():
    m = MyManager()
    m.start()
    return m

def run_multiple_processes():
    manager = Manager()
    # object I want to share among multiple processes
    fibonacci = manager.Fibonacci()
    pool = multiprocessing.Pool(processes=workers)
    for i in range(0, workers):
        pool.apply_async(run_tasks, (fibonacci, ))

    # Stay alive
    try:
        while True:
            continue
    except KeyboardInterrupt:
        logger.error(' [*] Exiting...')
        pool.terminate()
        pool.join()

I am getting some random errors while running the above code like -

builtins.AttributeError: '_SIGCHLDWaker' object has no attribute 'doWrite'

What would be the twisted way to launch multiple process and share a custom object between them. No writes will be performed on the object, the object is used to only read from its attributes.

Thanks in advance.


问:
com.android.builder.packaging.DuplicateFileException in android studio
I am not getting how to resolve this? Can anyone suggest me some solutions

My Application Gradle.

```<code>   apply plugin: 'com.android.application'

    android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.admin.bigquerytutorials"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
 }

   dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.cloud:google-cloud-bigquery:0.26.0-beta'
    }
</code>```

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK project.properties
      File1: C:\Users\Admin.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-bigquery\0.26.0-beta\69de62300e43f068fee504fbc055fce5d2e64b94\google-cloud-bigquery-0.26.0-beta.jar
      File2: C:\Users\Admin.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.8.0\98ede50a9dfdf818204cfc65e494936feb8c5078\google-cloud-core-1.8.0.jar

答:
In Your app level gradle. Whatever you get duplicate put it here. I was getting in project.properties. I did that and it worked</p>

```<code>android{
   ......
   ......
   ......

packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/io.netty.versions.properties'
    exclude 'META-INF/INDEX.LIST'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'project.properties' <<<<<-------This line worked for me
}
}
</code>```

Body:
I am not getting how to resolve this? Can anyone suggest me some solutions

My Application Gradle.

   apply plugin: 'com.android.application'

    android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.admin.bigquerytutorials"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
 }

   dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.cloud:google-cloud-bigquery:0.26.0-beta'
    }

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK project.properties
      File1: C:\Users\Admin.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-bigquery\0.26.0-beta\69de62300e43f068fee504fbc055fce5d2e64b94\google-cloud-bigquery-0.26.0-beta.jar
      File2: C:\Users\Admin.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.8.0\98ede50a9dfdf818204cfc65e494936feb8c5078\google-cloud-core-1.8.0.jar

Body:
In Your app level gradle. Whatever you get duplicate put it here. I was getting in project.properties. I did that and it worked

android{
   ......
   ......
   ......

packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/io.netty.versions.properties'
    exclude 'META-INF/INDEX.LIST'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'project.properties' <<<<<-------This line worked for me
}
}