问:
WPF Data binding: Changing items in the binded collection does not update binding source?
I have two classes:

```<code>public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}
</code>```

and

```<code>public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}
</code>```

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

```<code><Window.Resources>

    <!-- Window controller -->
    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...
</code>```

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}
</code>```

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}
</code>```

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

答:
Try something like:

```<code>public class Person : INotifyPropertyChanged
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }

    public void AddDetail(AccountDetail detail) {
        details.Add(detail);
        OnPropertyChanged("Phones");
    }

    public IEnumerable<AccountDetail> Phones
    {
        get
        {
            return details.Where(d => d.Type == DetailType.Phone);
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;

    /// <summary>
    /// Called when a property changes.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region INotifyPropertyChanged Members

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

}
</code>```

You could call the AddDetail method from you button event handler:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    windowController.SelectedPerson.AddDetail(new AccountDetail(DetailType.Phone));
}
</code>```

Raising the OnPropertyChanged event for the Phones property will simply cause the WPF binding framework to requery the propery, and the Linq query to be re-evaluated, after you added a Phone detail to the list of Details.

ContentLicense: CC BY-SA 2.5

Body:
I have two classes:

public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}

and

public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

<Window.Resources>

    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

Body:
Try something like:

public class Person : INotifyPropertyChanged
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }

    public void AddDetail(AccountDetail detail) {
        details.Add(detail);
        OnPropertyChanged("Phones");
    }

    public IEnumerable<AccountDetail> Phones
    {
        get
        {
            return details.Where(d => d.Type == DetailType.Phone);
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;

    /// <summary>
    /// Called when a property changes.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region INotifyPropertyChanged Members

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

}

You could call the AddDetail method from you button event handler:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    windowController.SelectedPerson.AddDetail(new AccountDetail(DetailType.Phone));
}

Raising the OnPropertyChanged event for the Phones property will simply cause the WPF binding framework to requery the propery, and the Linq query to be re-evaluated, after you added a Phone detail to the list of Details.


来源: stackexchange

问:
How to hide angular element on click event
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide()" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

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

答:
if you want to hide the product div tag to avoid page reload initially

just get type button without type="submit" ( inside <form></form> )

<button type="submit" > to >>> <button ng-click="hide()">

ContentLicense: CC BY-SA 3.0

Body:
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});

{{x}}


问:
CakePHP 3 & JSON response - Formatting response data linked with other tables
I have two tables with their attributes:

Sessions

id

staff_id

Staff

id

firstname

lastname

By clicking a link, I trigger my JavaScript code to open up a modal, and an AJAX call is sent to retrieve data in JSON format. I then use the JSON response to populate my modal.

The link that triggers the JavaScript is this:

```<code><?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>
</code>```

This is an action from a table on a CakePHP 3 View. $session->id is decided based on which row of data the link is clicked. Popup is an empty CakePHP 3 function that just facilitates the JavaScript working and the modal opening up.

The JavaScript which triggers the modal is as follows:

```<code><script type="text/javascript">
    $(function () {
        $('.view').click(function (ev) {
            ev.preventDefault();
            var sessionId = $(this).attr('data-id');
            $('#viewModal').modal('show');
            $.ajax({
                url:"localhost/project/sessions/details/"+sessionId+".json",
                type:'POST',
                success:function(res) {
                    if(res) {
                        document.getElementById("prstaff").innerHTML = res.staff_id;
                    }
                }
            });
        });
    });
</script>
</code>```

The details function from my CakePHP 3 SessionsController is this, which retrieves the relevant data for the $session->id that was obtained earlier:

```<code>public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }
</code>```

This is my modal in full that then opens up:

```<code><!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h3 class="modal-title" id="viewModalLabel">Session Details</h3>
                <br>
                <table class="vertical table col-sm-2">
                    <tr>
                        <th>Staff Name:</th>
                        <td id="prstaff"></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>
            </div>
        </div>
    </div>
</div>
</code>```

However the end result would just be:

Staff Name: 2 (or whatever foreign key is fetched)

This is not very meaningful. I could do another AJAX call for the Staff table, but I don't know how to link it to the first AJAX call so that when I want to populate the modal, I can actually put in meaningful data (eg. John Smith instead of foreign key 2).

答:
Why are you requesting JS via AJAX, then execute another query to retrieve JSON and then want to put this into the modal? This is weird and not necessary. If I understood this correctly at all.

Call the action and return the whole HTML content for the modal directly and let Cake render the data into the template, server side. This is just one AJAX call.

Have a template , on click do the AJAX call and return JSON and use to replace the placeholders {{somevar}} in your template and put the result in your modal. This is just one AJAX call as well. You can use Mustache for easy template parsing, it's really small.

I personally prefer to work with JSON responses and filling templates.

Body:
I have two tables with their attributes:

Sessions

id

staff_id

Staff

id

firstname

lastname

By clicking a link, I trigger my JavaScript code to open up a modal, and an AJAX call is sent to retrieve data in JSON format. I then use the JSON response to populate my modal.

The link that triggers the JavaScript is this:

<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>

This is an action from a table on a CakePHP 3 View. $session->id is decided based on which row of data the link is clicked. Popup is an empty CakePHP 3 function that just facilitates the JavaScript working and the modal opening up.

The JavaScript which triggers the modal is as follows:

The details function from my CakePHP 3 SessionsController is this, which retrieves the relevant data for the $session->id that was obtained earlier:

public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }

This is my modal in full that then opens up:

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Session Details

                        Staff Name:

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>

However the end result would just be:

Staff Name: 2 (or whatever foreign key is fetched)

This is not very meaningful. I could do another AJAX call for the Staff table, but I don't know how to link it to the first AJAX call so that when I want to populate the modal, I can actually put in meaningful data (eg. John Smith instead of foreign key 2).

Body:
Why are you requesting JS via AJAX, then execute another query to retrieve JSON and then want to put this into the modal? This is weird and not necessary. If I understood this correctly at all.

Call the action and return the whole HTML content for the modal directly and let Cake render the data into the template, server side. This is just one AJAX call.

Have a template <script type="html/template" id="model-template">conten here</script>, on click do the AJAX call and return JSON and use to replace the placeholders {{somevar}} in your template and put the result in your modal. This is just one AJAX call as well. You can use Mustache for easy template parsing, it's really small.

I personally prefer to work with JSON responses and filling templates.


问:
Does the react-redux connect cause rerender?
I have a component in which there is no componentWillRecieveProps and no other function is changing the state, despite that whenever the store is updating, the component(wrapped in connect) is getting rerendered(which is what I want but i dont understand how without state it is happening). I know connect supplies the component with the new props if they have changed but can this cause the component to rerender?</p>

答:
The short answer is that yes, a change in props will cause a component to re-render.  It might be helpful to look at the lifecycle method shouldComponentUpdate.  This function will be called by React every time either props or state change to determine whether the component should re-render.  It looks like this:

```<code>shouldComponentUpdate(nextProps, nextState) {
    // return boolean
}
</code>```

If it returns true, then the component will update, if it returns false, there will not be a re-render.

If we don't add this method to our component, then the default implementation is used, which is simply:

```<code>shouldComponentUpdate(nextProps, nextState) {
    return true;
}
</code>```

I.e. always update on props/state changes.

Occasionally it can be useful for a performance reason to implement some logic in this lifecycle method to only update when necessary, but the majority of the time the default (always return true) works fine.

Body:
The short answer is that yes, a change in props will cause a component to re-render.  It might be helpful to look at the lifecycle method shouldComponentUpdate.  This function will be called by React every time either props or state change to determine whether the component should re-render.  It looks like this:

shouldComponentUpdate(nextProps, nextState) {
    // return boolean
}

If it returns true, then the component will update, if it returns false, there will not be a re-render.

If we don't add this method to our component, then the default implementation is used, which is simply:

shouldComponentUpdate(nextProps, nextState) {
    return true;
}

I.e. always update on props/state changes.

Occasionally it can be useful for a performance reason to implement some logic in this lifecycle method to only update when necessary, but the majority of the time the default (always return true) works fine.


问:
Finding all entries that can be found by recursive selection
I want to select all countries in Countries that can be found by recursively adding all neighbouring countries to the reachable countries already found by looking at the set that starts with just 'Sweden'. Basically, I have the set S which at the very beginning is the set {Sweden}, and select all names from the table borders that are equal to the Country1 attribute while the Country2 attribute is in S, or are equal to the Country2 attribute while the Country1 attribute is in S. I modify S to this selected set. Then I keep doing this selection until I find no new countries that aren't in S.

By performing the selection on the table

```<code>Country1      Country2
----------------------
Sweden        Finland
Norway        Sweden
Norway        Finland
Norway        Russia
Russia        Ukraine
Russia        Finland
Russia        China
Canada        United States
</code>```

I should get the result:

```<code>Name
----------------------
Finland
Norway
Russia
Ukraine
China
</code>```

It's not the best but I hope that you get the idea of what I want to do. I'm using PostgreSQL.

答:
Kind of (edited)</p>

```<code>create table borders(
    Country1 varchar(100),
    Country2 varchar(100)
);
insert into borders(Country1,Country2)
values
('Sweden','Finland'),
('Norway','Sweden'),
('Norway','Finland'),
('Norway','Russia'),
('Russia','Ukraine'),
('Russia','Finland'),
('Russia','China'),
('Canada','United States')
;

WITH RECURSIVE neighbours AS (
    -- start with 'Sweden' if any neighbour of it exists
    SELECT DISTINCT 'Sweden' as Name, ARRAY[cast('Sweden' as varchar)] as path
    FROM borders b
    WHERE 'Sweden' IN (b.Country1, b.Country2)
    --
    UNION ALL
    SELECT
      CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END,
      path || CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END
    FROM borders b
    JOIN neighbours nb ON nb.Name IN(b.Country1, b.Country2)
          AND NOT(b.Country1 = ANY(path) AND b.Country2 = ANY(path))
)
SELECT DISTINCT Name
FROM neighbours;
</code>```

Body:
I want to select all countries in Countries that can be found by recursively adding all neighbouring countries to the reachable countries already found by looking at the set that starts with just 'Sweden'. Basically, I have the set S which at the very beginning is the set {Sweden}, and select all names from the table borders that are equal to the Country1 attribute while the Country2 attribute is in S, or are equal to the Country2 attribute while the Country1 attribute is in S. I modify S to this selected set. Then I keep doing this selection until I find no new countries that aren't in S.

By performing the selection on the table

Country1      Country2
----------------------
Sweden        Finland
Norway        Sweden
Norway        Finland
Norway        Russia
Russia        Ukraine
Russia        Finland
Russia        China
Canada        United States

I should get the result:

Name
----------------------
Finland
Norway
Russia
Ukraine
China

It's not the best but I hope that you get the idea of what I want to do. I'm using PostgreSQL.

Body:
Kind of (edited)

create table borders(
    Country1 varchar(100),
    Country2 varchar(100)
);
insert into borders(Country1,Country2)
values
('Sweden','Finland'),
('Norway','Sweden'),
('Norway','Finland'),
('Norway','Russia'),
('Russia','Ukraine'),
('Russia','Finland'),
('Russia','China'),
('Canada','United States')
;

WITH RECURSIVE neighbours AS (
    -- start with 'Sweden' if any neighbour of it exists
    SELECT DISTINCT 'Sweden' as Name, ARRAY[cast('Sweden' as varchar)] as path
    FROM borders b
    WHERE 'Sweden' IN (b.Country1, b.Country2)
    --
    UNION ALL
    SELECT
      CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END,
      path || CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END
    FROM borders b
    JOIN neighbours nb ON nb.Name IN(b.Country1, b.Country2)
          AND NOT(b.Country1 = ANY(path) AND b.Country2 = ANY(path))
)
SELECT DISTINCT Name
FROM neighbours;


问:
GUI design techniques to enhance user experience
What techniques do you know\use to create user-friendly GUI ?

I can name following techniques that I find especially useful:

Non-blocking notifications (floating dialogs like in Firefox3 or Vista's pop-up messages in tray area)

Absence of "Save" button

MS OneNote as an example.

IM clients can save conversation history automatically

Integrated search

Search not only through help files but rather make UI elements searchable.

Vista made a good step toward such GUI.

Scout addin Microsoft Office was a really great idea.

Context oriented UI (Ribbon bar in MS Office 2007)

Do you implement something like listed techniques in your software?

Edit:

As Ryan P mentioned, one of the best way to create usable app is to put yourself in user's place. I totally agree with it, but what I want to see in this topic is specific techniques (like those I mentioned above) rather than general recommendations.

答:
Check out the great book Don't make me think by Steve Krug.

It's web focused but many of the conepts can apply to anything from blenders to car dashboards.

Topics covered:

User patterns

Designing for scanning

Wise use of copy

Navigation design

Home page layout

Usability testing

He also has a blog called Advanced Common Sense

And some random UI related links:

 - User Interface Design for Programmers by Joel Spolsky

 - 10 Usability Nightmares You Should Be Aware Of

OwnerDisplayName: aku

LastEditorDisplayName: unwind

OwnerDisplayName: David H Aust


问:
How to invoke pandas str.split() and not python's built in str.split()
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)
</code>```

I am trying to achieve :

```<code>node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child
</code>```

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res
</code>```

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.

答: You can't invoke str.split() of the pandas library in your particular case because you are using the DataFrame object, and this particular object does not implement str.split(). Only the Series object implements str.split().

Body:
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

I am trying to achieve :

node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.


问:
ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke
I'm getting ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke when executing:

```<code>REVOKE REFERENCES ON dbo.ABC FROM XYZ;
</code>```

How do I address the issue?

答:
try this:

```<code>REVOKE REFERENCES ON dbo.ABC FROM XYZ CASCADE CONSTRAINTS;
</code>```

Body:
I'm getting ORA-01981: CASCADE CONSTRAINTS must be specified to perform this revoke when executing:

REVOKE REFERENCES ON dbo.ABC FROM XYZ;

How do I address the issue?

Body:
try this:

REVOKE REFERENCES ON dbo.ABC FROM XYZ CASCADE CONSTRAINTS;


问:
SQL date comparision in yyyy/mm/dd
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

```<code>d.date_begin >= DATEADD(day,-7, GETDATE())
</code>```

is not working :), i'm TERRIBLE at convert and data type..

答:
```<code>SELECT * FROM tbl_name
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
</code>```

Title: SQL date comparision in yyyy/mm/dd

Body:
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

d.date_begin >= DATEADD(day,-7, GETDATE())

is not working :), i'm TERRIBLE at convert and data type..


问:
Can't set value to data attribute with jQuery
From some reason I can't figure out, the $('element').data('data_attribute_name', 'value'); syntax doesn't work here:

HTML:

```<code><ul class="main_menu__list" data-scheme="light">
...
</ul>
</code>```

JS:

```<code>$('.main_menu__list').data('scheme', 'dark');
$('.main_menu__list').css('border', '10px solid yellow');
</code>```

The second line does work (yellow border applied), the second one does nothing. why?

答:
Use this :

```<code>$('.main_menu__list').attr('data-scheme', 'dark');
</code>```

instead of this :

```<code>$('.main_menu__list').data('scheme', 'dark');
</code>```

Body:
From some reason I can't figure out, the $('element').data('data_attribute_name', 'value'); syntax doesn't work here:

HTML:

...

JS:

$('.main_menu__list').data('scheme', 'dark');
$('.main_menu__list').css('border', '10px solid yellow');

The second line does work (yellow border applied), the second one does nothing. why?

Body:
Use this :

$('.main_menu__list').attr('data-scheme', 'dark');

instead of this :

$('.main_menu__list').data('scheme', 'dark');


问:
Updating .stringsdict localization files over-the-air
I'm looking for a way to update stringsdict localization files over-the-air without having to release a new version in the appStore. So ideally I want my stringdict files on a webserver, and the iOS app should download these files from the website and update the local strings.

After doing some research, I realized that we cannot update files in the bundle it was shipped in however I found some reports saying we could store/load localizations in/from the application support folder.

source #1

source #2

source #3

Can this also be applied to stringsdict files because I'm trying but no success so far.

答:
Basically you need to create a .bundle with your new strings and make your app download it. After that, I think it's possible to create a NSBundle object using your freshly downloaded translations and swizzle a couple of methods from the main NSBundle currently used by the system.

I've tried something similar, but found out that it's much easier to integrate an existing service such as Smartling or Lokalise. They already have an SDK that allows you to update your translation over the air.

Also I found it's much easier to manage all my translations there.


问:
'list' object has no attribute 'timeout'
I am trying to download Pdfs using urllib.request.urlopen from a page but it returns an error: 'list' object has no attribute 'timeout':

```<code>def get_hansard_data(page_url):
    #Read base_url into Beautiful soup Object
    html = urllib.request.urlopen(page_url).read()
    soup = BeautifulSoup(html, "html.parser")
    #grab <div class="itemContainer"> that hold links and dates to all hansard pdfs
    hansard_menu = soup.find_all("div","itemContainer")

    #Get all hansards
    #write to a tsv file
    with open("hansards.tsv","a") as f:
        fieldnames = ("date","hansard_url")
        output = csv.writer(f, delimiter="\t")

        for div in hansard_menu:
            hansard_link = [HANSARD_URL + div.a["href"]]
            hansard_date = div.find("h3", "catItemTitle").string

            #download

            with urllib.request.urlopen(hansard_link) as response:
                data = response.read()
                r = open("/Users/Parliament Hansards/"+hansard_date +".txt","wb")
                r.write(data)
                r.close()

            print(hansard_date)
            print(hansard_link)
            output.writerow([hansard_date,hansard_link])
        print ("Done Writing File")
</code>```

答:
A bit late, but might still be helpful to someone else (if not for topic starter). I found the solution by solving the same problem.

The problem was that page_url (in your case) was a list, rather than a string. The reason for that is mos likely that page_url comes from argparse.parse_args() (at least it was so in my case).
Doing page_url[0] should work but it is not nice to do that inside the def get_hansard_data(page_url) function. Better would be to check the type of the parameter and return an appropriate error to the function caller, if the type does not match.

The type of an argument could be checked by calling type(page_url) and comparing the result like for example: typen("") == type(page_url). I am sure there might be more elegant way to do that, but it is out of the scope of this particular question.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to download Pdfs using urllib.request.urlopen from a page but it returns an error: 'list' object has no attribute 'timeout':

def get_hansard_data(page_url):
    #Read base_url into Beautiful soup Object
    html = urllib.request.urlopen(page_url).read()
    soup = BeautifulSoup(html, "html.parser")
    #grab
 that hold links and dates to all hansard pdfs
    hansard_menu = soup.find_all("div","itemContainer")

    #Get all hansards
    #write to a tsv file
    with open("hansards.tsv","a") as f:
        fieldnames = ("date","hansard_url")
        output = csv.writer(f, delimiter="\t")

        for div in hansard_menu:
            hansard_link = [HANSARD_URL + div.a["href"]]
            hansard_date = div.find("h3", "catItemTitle").string

            #download

            with urllib.request.urlopen(hansard_link) as response:
                data = response.read()
                r = open("/Users/Parliament Hansards/"+hansard_date +".txt","wb")
                r.write(data)
                r.close()

            print(hansard_date)
            print(hansard_link)
            output.writerow([hansard_date,hansard_link])
        print ("Done Writing File")


答:
This will work if you want records from 7 days ago up to and including today's records</p>

```<code>CAST(d.date_begin AS DATE) >= CAST(DATEADD(day,-7, GETDATE()) AS DATE)
</code>```

Title: SQL date comparision in yyyy/mm/dd

Body:
This will work if you want records from 7 days ago up to and including today's records

CAST(d.date_begin AS DATE) >= CAST(DATEADD(day,-7, GETDATE()) AS DATE)


问:
Why does Emacs complain about void-variable displayed-year in my .emacs file?
I'm trying to implement the solar terms in my .emacs so my "holidays" will display the time when the solar longitude crosses each multiple of 15 degrees.  Here is the relevant snipplet.

```<code>(defun next-solar-term-date (d)
  (solar-date-next-longitude d 15))

(defconst solar-term-names
  ["moderate cold" "severe cold" "spring commerces"
   "rain water" "insects awaken" "vernal equinox"
   "Ching Ming" "corn rain" "summer commerces"
   "corn forms" "corn on ear" "summer solstice"
   "minor heat" "great heat" "autumn commerces"
   "end of heat" "white dew" "autumnal equinox"
   "cold dew" "frost" "winter commerces"
   "light snow" "heavy snow" "winter solstice"])

(setq solar-terms-holidays
      (let* ((k 0) (mylist nil))
        (dotimes (k 4);k=season
          (let* ((j 0))
            (dotimes (j 5);no equinoxes/solstices --- use solar for them
              (let* ((i (+ j (* 6 k)))
                     (month (+ 1 (/ i 2)))
                     (astronextdate (next-solar-term-date
                                     (calendar-astro-from-absolute
                                      (+ (* 15 i)
                                         (calendar-absolute-from-gregorian
                                          (list 1 1 displayed-year))))))
                     (s (aref solar-term-names i))
                     (absnextdate (calendar-absolute-from-astro
                                   astronextdate))
                     (gregnextdate (calendar-gregorian-from-absolute
                                    (floor absnextdate)))
                     (compt (* 24 (- absnextdate (floor absnextdate))))
                     (str (concat s " "
                                  (solar-time-string
                                   compt (if (dst-in-effect absnextdate)
                                             calendar-daylight-time-zone-name
                                           calendar-standard-time-zone-name))))
                     (d (extract-calendar-day gregnextdate)))
                (setq mylist (append mylist
                                     (list
                                      (list 'holiday-fixed month d str))))))))
        mylist))
</code>```

However, emacs (version 23.2-r2 on Gentoo) complains about displayed-year being a void-variable at start-up, and trying to generate the calendar with M-x calendar RET doesn't help either.  Any idea how I can fix that?  (Certainly not with defining displayed-year in my .emacs since this definitely screws up everything else...)

答:
The calculation needs to be deferred until displayed-year is available, which may be achieved by replacing the last expression in your paste with these two:

```<code>(defun solar-term (i month)
  (let* ((astronextdate (next-solar-term-date
                         (calendar-astro-from-absolute
                          (+ (* 15 i)
                             (calendar-absolute-from-gregorian
                              (list 1 1 displayed-year))))))
         (s (aref solar-term-names i))
         (absnextdate (calendar-absolute-from-astro
                       astronextdate))
         (gregnextdate (calendar-gregorian-from-absolute
                        (floor absnextdate)))
         (compt (* 24 (- absnextdate (floor absnextdate))))
         (str (concat s " "
                      (solar-time-string
                       compt (if (dst-in-effect absnextdate)
                                 calendar-daylight-time-zone-name
                               calendar-standard-time-zone-name))))
         (d (extract-calendar-day gregnextdate)))
    (holiday-fixed month d str)))

(setq solar-terms-holidays
      (let* ((mylist nil))
        (dotimes (k 4)    ;k=season
          (dotimes (j 5)  ;no equinoxes/solstices --- use solar for them
            (let* ((i (+ j (* 6 k)))
                   (month (+ 1 (/ i 2))))
              (push `(solar-term ,i ,month) mylist))))
        mylist))
</code>```

Body:
I'm trying to implement the solar terms in my .emacs so my "holidays" will display the time when the solar longitude crosses each multiple of 15 degrees.  Here is the relevant snipplet.

(defun next-solar-term-date (d)
  (solar-date-next-longitude d 15))

(defconst solar-term-names
  ["moderate cold" "severe cold" "spring commerces"
   "rain water" "insects awaken" "vernal equinox"
   "Ching Ming" "corn rain" "summer commerces"
   "corn forms" "corn on ear" "summer solstice"
   "minor heat" "great heat" "autumn commerces"
   "end of heat" "white dew" "autumnal equinox"
   "cold dew" "frost" "winter commerces"
   "light snow" "heavy snow" "winter solstice"])

(setq solar-terms-holidays
      (let* ((k 0) (mylist nil))
        (dotimes (k 4);k=season
          (let* ((j 0))
            (dotimes (j 5);no equinoxes/solstices --- use solar for them
              (let* ((i (+ j (* 6 k)))
                     (month (+ 1 (/ i 2)))
                     (astronextdate (next-solar-term-date
                                     (calendar-astro-from-absolute
                                      (+ (* 15 i)
                                         (calendar-absolute-from-gregorian
                                          (list 1 1 displayed-year))))))
                     (s (aref solar-term-names i))
                     (absnextdate (calendar-absolute-from-astro
                                   astronextdate))
                     (gregnextdate (calendar-gregorian-from-absolute
                                    (floor absnextdate)))
                     (compt (* 24 (- absnextdate (floor absnextdate))))
                     (str (concat s " "
                                  (solar-time-string
                                   compt (if (dst-in-effect absnextdate)
                                             calendar-daylight-time-zone-name
                                           calendar-standard-time-zone-name))))
                     (d (extract-calendar-day gregnextdate)))
                (setq mylist (append mylist
                                     (list
                                      (list 'holiday-fixed month d str))))))))
        mylist))

However, emacs (version 23.2-r2 on Gentoo) complains about displayed-year being a void-variable at start-up, and trying to generate the calendar with M-x calendar RET doesn't help either.  Any idea how I can fix that?  (Certainly not with defining displayed-year in my .emacs since this definitely screws up everything else...)

Body:
The calculation needs to be deferred until displayed-year is available, which may be achieved by replacing the last expression in your paste with these two:

(defun solar-term (i month)
  (let* ((astronextdate (next-solar-term-date
                         (calendar-astro-from-absolute
                          (+ (* 15 i)
                             (calendar-absolute-from-gregorian
                              (list 1 1 displayed-year))))))
         (s (aref solar-term-names i))
         (absnextdate (calendar-absolute-from-astro
                       astronextdate))
         (gregnextdate (calendar-gregorian-from-absolute
                        (floor absnextdate)))
         (compt (* 24 (- absnextdate (floor absnextdate))))
         (str (concat s " "
                      (solar-time-string
                       compt (if (dst-in-effect absnextdate)
                                 calendar-daylight-time-zone-name
                               calendar-standard-time-zone-name))))
         (d (extract-calendar-day gregnextdate)))
    (holiday-fixed month d str)))

(setq solar-terms-holidays
      (let* ((mylist nil))
        (dotimes (k 4)    ;k=season
          (dotimes (j 5)  ;no equinoxes/solstices --- use solar for them
            (let* ((i (+ j (* 6 k)))
                   (month (+ 1 (/ i 2))))
              (push `(solar-term ,i ,month) mylist))))
        mylist))


问:
What is the right configuration for Java 8 Stream
I have the following code (just an example that i wrote for this question) which simply calculates sum of a range
I implemented it in three ways:

Serial

Parallel Stream

With ForkJoinPool

Surprisingly the Serial method was the fastest one. In fact it takes %10 of the time of the other two.

What is the right configurations for Java Stream in order to make it faster?
What wrong i am doing ?

```<code>package ned.main;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class TestParallelStream {

    static private void testParallelStream() {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1000000");

        ForkJoinPool forkJoinPool = new ForkJoinPool(10000);

        Date start = new Date();

        long sum1 = 0;
        for (int i = 0; i < 1_000_000; ++i) {
            sum1 += i * 10;
        }

        Date start1 = new Date();

        long sum2 = IntStream.range(1, 1_000_000)
                        .parallel()
                        .map(x -> x * 10)
                        .sum();

        Date start2 = new Date();

        try {
            long sum3 = forkJoinPool.submit(() ->
                IntStream
                    .range(1, 1_000_000)
                    .parallel()
                    .map(x -> x * 10)
                    .sum())
                        .get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        long serial = start1.getTime() - start.getTime();
        long parallelstream = start2.getTime() - start1.getTime();
        long withfork = start2.getTime() - start1.getTime();

        System.out.println(serial + "," + parallelstream + "," + withfork);

    }

    public static void main(String[] args) {
        testParallelStream();
    }
}
</code>```

Thanks

答:
It seems to have a fundamentally wrong understanding of the parallelism property. To utilize all CPU cores for a computation, the parallelism should match the number of cores, which is already the default.

Setting the parallelism to 1000000 makes no sense—even in the unlikely case that you really have 1000000 processors, as in that case, it’s still obsolete to set what is already the default. As a side note, if you had 1000000 processing units, a job consisting of 1000000 multiplications would be way too small to benefit from this hardware. You start one thread for each int multiplication, which is insane.

If in doubt, don’t mess with that setting and leave the parallelism at its default.

It still depends on the actual operation, whether it will benefit from parallel processing. The JVM’s optimizer will process small chunks of sequential code only, so splitting an operation into chunks to be processed in parallel may reduce the code optimization benefit.

In the most extreme variant, a loop of the form

```<code>long sum1 = 0;
for(int i=from; i<to; ++i) sum1 += i * constant;
</code>```

can be optimized to

```<code>long sum1=((long)from+to-1)*(to-from)/2  * constant;
</code>```

which would result in a constant calculation time for arbitrary ranges, so splitting the range into subranges, to be calculated in parallel, couldn’t shorten the required time in general. But that’s, of course, JVM specific.

In case of HotSpot, which has some very restrictive inlining thresholds, it can happen that performing the operation with stream code exceeds them, reducing the JVM’s optimization potential. Whether this happens, can be tested by also benchmarking an equivalent sequential stream operation. In the best case, it should perform exactly like the loop. If not, you know that the stream operation will carry a disadvantage over the loop that will apply to parallel streams as well. Tuning the JVM options may help (hopefully, the defaults will become more “stream friendly” in the future).

Body:
I have the following code (just an example that i wrote for this question) which simply calculates sum of a range
I implemented it in three ways:

Serial

Parallel Stream

With ForkJoinPool

Surprisingly the Serial method was the fastest one. In fact it takes %10 of the time of the other two.

What is the right configurations for Java Stream in order to make it faster?
What wrong i am doing ?

package ned.main;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class TestParallelStream {

    static private void testParallelStream() {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1000000");

        ForkJoinPool forkJoinPool = new ForkJoinPool(10000);

        Date start = new Date();

        long sum1 = 0;
        for (int i = 0; i < 1_000_000; ++i) {
            sum1 += i * 10;
        }

        Date start1 = new Date();

        long sum2 = IntStream.range(1, 1_000_000)
                        .parallel()
                        .map(x -> x * 10)
                        .sum();

        Date start2 = new Date();

        try {
            long sum3 = forkJoinPool.submit(() ->
                IntStream
                    .range(1, 1_000_000)
                    .parallel()
                    .map(x -> x * 10)
                    .sum())
                        .get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        long serial = start1.getTime() - start.getTime();
        long parallelstream = start2.getTime() - start1.getTime();
        long withfork = start2.getTime() - start1.getTime();

        System.out.println(serial + "," + parallelstream + "," + withfork);

    }

    public static void main(String[] args) {
        testParallelStream();
    }
}

Thanks

Body:
It seems to have a fundamentally wrong understanding of the parallelism property. To utilize all CPU cores for a computation, the parallelism should match the number of cores, which is already the default.

Setting the parallelism to 1000000 makes no sense—even in the unlikely case that you really have 1000000 processors, as in that case, it’s still obsolete to set what is already the default. As a side note, if you had 1000000 processing units, a job consisting of 1000000 multiplications would be way too small to benefit from this hardware. You start one thread for each int multiplication, which is insane.

If in doubt, don’t mess with that setting and leave the parallelism at its default.

It still depends on the actual operation, whether it will benefit from parallel processing. The JVM’s optimizer will process small chunks of sequential code only, so splitting an operation into chunks to be processed in parallel may reduce the code optimization benefit.

In the most extreme variant, a loop of the form

long sum1 = 0;
for(int i=from; i<to; ++i) sum1 += i * constant;

can be optimized to

long sum1=((long)from+to-1)*(to-from)/2  * constant;

which would result in a constant calculation time for arbitrary ranges, so splitting the range into subranges, to be calculated in parallel, couldn’t shorten the required time in general. But that’s, of course, JVM specific.

In case of HotSpot, which has some very restrictive inlining thresholds, it can happen that performing the operation with stream code exceeds them, reducing the JVM’s optimization potential. Whether this happens, can be tested by also benchmarking an equivalent sequential stream operation. In the best case, it should perform exactly like the loop. If not, you know that the stream operation will carry a disadvantage over the loop that will apply to parallel streams as well. Tuning the JVM options may help (hopefully, the defaults will become more “stream friendly” in the future).


答:
Use json_decode() to convert JSON data to multidimensional array.
When TRUE is passed as a second argument, returned objects will be converted into associative arrays.

```<code>print_r(json_decode(json_array, true));
</code>```

After that use the array_chunk() function to split the multidimensional array into smaller chunks.

Example:

```<code>$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
</code>```

Title: How to divide array into small size chunks?

Body:
I am fetching this array in JavaScript program by ajax in every second, the response from the request takes about 3 to 4 second to be completed. Therefore I want to this array to be split in chunks but failed to complete the array was

{"m":true,
"s":true,
"q":{
"eur":{"b":"1.06783","a":"1.06790","h":"1.06978","l":"1.06729"},
"gbp":{"b":"1.24407","a":"1.24416","h":"1.25093","l":"1.24397"},
"aud":{"b":"0.76456","a":"0.76464","h":"0.76630","l":"0.76387"},
"cad":{"b":"1.33550","a":"1.33557","h":"1.33583","l":"1.33251"},
"jpy":{"b":"111.996","a":"112.002","h":"112.204","l":"111.700"},
"chf":{"b":"1.00110","a":"1.00117","h":"1.00188","l":"0.99850"},
"xau":{"b":"1241.75","a":"1242.1","h":"1244.69","l":"1239.53"},
"xag":{"b":"18.056","a":"18.098","h":"18.175","l":"18.02"},
"nok":{"b":"8.58853","a":"8.5901","h":"8.59342","l":"8.55128"},
"sek":{"b":"8.9308","a":"8.9323","h":"8.9515","l":"8.92151"},
"sgd":{"b":"1.3975","a":"1.3977","h":"1.3959","l":"1.3987"},
"pkr":{"b":"104.8300","a":"105.8300","h":"104.8300","l":"104.620"},
"dkk":{"b":"6.9645","a":"6.9648","h":"6.9500","l":"6.9691"},
"nzd":{"b":"0.69835","a":"0.69859","h":"0.70084","l":"0.69794"},
"zar":{"b":"13.3688","a":"13.37396","h":"13.6475","l":"13.232"},
"hkd":{"b":"7.77017","a":"7.77098","h":"7.77244","l":"7.76847"},
"inr":{"b":"64.8500","a":"64.8600","h":"64.925","l":"64.7800"},
"try":{"b":"3.63447","a":"3.63558","h":"3.65941","l":"3.63076"},
"pln":{"b":"3.9514","a":"3.9520","h":"3.9361","l":"3.9520"},
"cnh":{"b":"6.88261","a":"6.88352","h":"6.89029","l":"6.8706"},
"myr":{"b":"0.2255","a":"0.2265","h":"0.2253","l":"0.2257"},
"sar":{"b":"0.2662","a":"0.2672","h":"0.2662","l":"0.2662"}
}}

Please help me, I am getting stuck on this...

Body:
Use json_decode() to convert JSON data to multidimensional array.
When TRUE is passed as a second argument, returned objects will be converted into associative arrays.

print_r(json_decode(json_array, true));

After that use the array_chunk() function to split the multidimensional array into smaller chunks.

Example:

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));


问:
How to change the primary key value in sql server?
I am using SQL server 2014.

In my table, I set primary key for the column.The primary key value starts from 1. I want to change it to start from 0. How can I achieve this?

答:
You may be able to reseed it;</p>

```<code>DBCC CHECKIDENT ('TableName', RESEED, 0);
GO
</code>```

Body:
You may be able to reseed it;

DBCC CHECKIDENT ('TableName', RESEED, 0);
GO


问:
How WCF request is handled in IIS
I am working on a project to improve the performance of WCF service. We have WCF service hosted on IIS server.
I went through various articles to understand the End to End flow from WCF client to request processing by WCF service.

Kindly clarify the below questions:

What happens in IIS when the WCF request comes from the client?

How the IIS identifies the request is for particular WCF service (assume that there are multiple WCF services hosted in the IIS)?

How IIS is delegating the request processing to WCF service?

Who is responsible for creating the WCF service instance?

How the ASP.Net worker threads come into WCF service processing request?

What is the role of Application pool settings in WCF service request processing?

答:
The requests to the WCF service that is hosted on IIS are handled by WAS (Windows Activation Service) which decouples the activation architecture from IIS.
WAS is responsible for processing the requests / response for WCF service.

Here is the high level of what goes on when a http request arrives for a WCF Service hosted on WAS

Requests are first received by the http.sys kernel.

A new WAS service is responsible for configuring application pools,
among other things.

The WWW Service is responsible for activating application pools and
requests queues to process incoming requests. In addition, this
service has a new HTTP Listener Adapter that forwards requests to the
HttpHandler to process the request (without the need for
aspnet_isapi.dll).

Keeping above points in mind, here are the best answers that I can come up with.

Assuming your WCF service is listening on HTTP protocol

1.   What happens in IIS when the WCF request comes from the client?

Everything happens in WAS not IIS.

When a protocol listener ( HTTP.sys) picks up a client request, WAS determines if a worker process is running or not. If an application pool already has a worker process that is servicing requests, the listener adapter passes the request onto the worker process for processing. If there is no worker process in the application pool, WAS will start a worker process so that the listener adapter can pass the request to it for processing.

The listener adapter is part of WAS. The request then flows into the worker process’ (w3wp.exe activated by WAS) app domain that has HTTP module and HTTP handler (without the need for aspnet_isapi.dll) that process this request.

2.   How the IIS identifies the request is for particular WCF service (assume that there are multiple WCF services hosted in the IIS)?

Its not IIS its WAS that creates a worker process instance (w3wp.exe) and loads application’s code along with other components / network protocols in that worker process. The incomming request has an endpoint address that contains the WCF service name. Also the SOAP message contains the method and the service (class) name which is called by the client. The Channel Dispatchers and Endpoint Dispatchers use this information to activate the class instance and call the target method.

Channel and Endpoint Dispatchers

3.   How IIS is delegating the request processing to WCF service?

Again its WAS that delegates the request to particular WCF service which it identifies when the request comes in.

4.   Who is responsible for creating the WCF service instance?

Dispatchers are responsible for accepting new channels, receiving messages, operation dispatch and invocation, and response processing. The answer for question # 2 describes this.

5.   How the ASP.Net worker threads come into WCF service processing request?

In IIS 7 and later, Windows Process Activation Service (WAS) manages application pool configuration and worker processes instead of the WWW Service.It manages application pools and worker processes for both HTTP and non-HTTP requests.

HTTP Listener adapter is responsible for bridging requests between WAS and  ASP.Net worker process. For HTTP requests the adapter is provided by www services (w3svc).

6.   What is the role of Application pool settings in WCF service request processing?

All of the applications inside an application pool share a common set of run-time characteristics. For example, they all run under the same version of the common language runtime (CLR) and they all share a common process identity. Each application pool corresponds to an instance of a worker process (w3wp.exe). Each managed application running inside of a shared application pool is isolated from other applications by means of a CLR AppDomain.

Once the request arrives at the ServiceHost process, WCF channel dispatchers picks it up and forward to the particular endpoint dispatchers which intern call the method (endpoint) that is responsible to processes the request.

References:

Learning WCF: A Hands-on Guide By Michele Leroux Bustamante

http://devproconnections.com/net-framework/iis-and-was-hosting-architecture

https://msdn.microsoft.com/en-us/library/ms734677(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/ms789006(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/ms734665.aspx

https://www.iis.net/learn/get-started/introduction-to-iis/introduction-to-iis-architecture#WAS

Title: How WCF request is handled in IIS


问:
ngRepeat - Sort object by specific keys first
I'm writing an AngularJS application (Angular 1) which requires a list of tables to be displayed on the page. However certain keys need to be displayed first like so:

```<code><div>baz (data)</div>
<div>bar (data)</div>
<div>foo (data)</div>
<div>baa (data)</div>
</code>```

I figured out I need to use the orderBy filter, however I can't seem to get that working. Does anyone know how I could achieve this?

JS:

```<code>angular.module("MyModule").controller("Test", function() {

    this.sort = ["baz", "bar"];

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

});
</code>```

HTML:

```<code><div ng-controller="Test as T">
    <div ng-repeat="(title, row) in T.data"> <!-- Not sure how I would go about sorting these keys by certain ones first -->
        {{ title }} ({{ row }})
    </div>
</div>
</code>```

答:
You'll need to use orderBy which unfortunately doesn't work with objects so you will have to write a custom toArray filter.

```<code>angular.module("MyModule").controller("Test", function() {

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

    this.customSort = function(a, b){
        /* Whatever way you need to do this */
        var sort = ["baz", "bar"];
        return sort.indexOf(a) < sort.indexOf(b) ? 1 : -1;
    }

}).filter('toArray', function () {

    return function (obj) {
        if (!(obj instanceof Object)) {
            return obj;
        }

        return Object.keys(obj).map(function (key) {
            return Object.defineProperty(obj[key], '$key', {__proto__: null, value: key});
        });
    }
});
</code>```

HTML

```<code><div ng-controller="Test as T">
  <div ng-repeat="item in T.data | toArray | orderBy: $key : false : T.customSort">
    {{ item.$key }} ({{ item.value }})
  </div>
</div>
</code>```

Angular orderBy docs and
Discussion on orderBy for objects

Body:
I'm writing an AngularJS application (Angular 1) which requires a list of tables to be displayed on the page. However certain keys need to be displayed first like so:

baz (data)

bar (data)

foo (data)

baa (data)

I figured out I need to use the orderBy filter, however I can't seem to get that working. Does anyone know how I could achieve this?

JS:

angular.module("MyModule").controller("Test", function() {

    this.sort = ["baz", "bar"];

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

});

HTML:

        {{ title }} ({{ row }})

Body:
You'll need to use orderBy which unfortunately doesn't work with objects so you will have to write a custom toArray filter.

angular.module("MyModule").controller("Test", function() {

    this.data = {
        "foo": { /* snip */ },
        "bar": { /* snip */ },
        "baz": { /* snip */ },
        "baa": { /* snip */ }
    };

    this.customSort = function(a, b){
        /* Whatever way you need to do this */
        var sort = ["baz", "bar"];
        return sort.indexOf(a) < sort.indexOf(b) ? 1 : -1;
    }

}).filter('toArray', function () {

    return function (obj) {
        if (!(obj instanceof Object)) {
            return obj;
        }

        return Object.keys(obj).map(function (key) {
            return Object.defineProperty(obj[key], '$key', {__proto__: null, value: key});
        });
    }
});

HTML

<div ng-controller="Test as T">
  <div ng-repeat="item in T.data | toArray | orderBy: $key : false : T.customSort">
    {{ item.$key }} ({{ item.value }})
  </div>
</div>

Angular orderBy docs and
Discussion on orderBy for objects


问:
Ask user to turn on Location
How can I prompt the user to turn on Location?

The app is supposed to filter a list of locations with the current location of the user. If the user has the Location service turned off, the app should prompt the user asking for the Location to be turned on.

For instance Trip Advisor app does this:

( Not sure if I can post other apps screenshots here, but if I shouldn't be doing it, please say so. And apologize for the full sized images, tried to make them smaller, but SO didn't liked it... )

In the first image, you can see I have the Location service turned off. The, after opening the Trip Advisor app, and tapping the Near me now option, I'm prompted with the second image, where I'm asked to Turn on Location services. After I tap the button, a dialog shows up so I can allow, or disallow, the Location service to be turned on. If I tap OK, the Location service is turned on on the device, and the app consumes it.

How can I achieve this?

答:
Try</p>

```<code>private void turnGPSOn(){
   String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

   if(!provider.contains("gps")){ //if gps is disabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3"));
    sendBroadcast(poke);
 }
}

private void turnGPSOff(){
   String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

   if(provider.contains("gps")){ //if gps is enabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3"));
    sendBroadcast(poke);
}
}

private boolean canToggleGPS() {
   PackageManager pacman = getPackageManager();
PackageInfo pacInfo = null;

   try {
    pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
   } catch (NameNotFoundException e) {
    return false; //package not found
   }

   if(pacInfo != null){
    for(ActivityInfo actInfo : pacInfo.receivers){
        //test if recevier is exported. if so, we can toggle GPS.
        if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
            return true;
        }
    }
 }

 return false; //default
}
</code>```

Title: Ask user to turn on Location

Body:
Try

private void turnGPSOn(){
   String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

   if(!provider.contains("gps")){ //if gps is disabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3"));
    sendBroadcast(poke);
 }
}

private void turnGPSOff(){
   String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

   if(provider.contains("gps")){ //if gps is enabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3"));
    sendBroadcast(poke);
}
}

private boolean canToggleGPS() {
   PackageManager pacman = getPackageManager();
PackageInfo pacInfo = null;

   try {
    pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
   } catch (NameNotFoundException e) {
    return false; //package not found
   }

   if(pacInfo != null){
    for(ActivityInfo actInfo : pacInfo.receivers){
        //test if recevier is exported. if so, we can toggle GPS.
        if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
            return true;
        }
    }
 }

 return false; //default
}


问:
Finding inactive session files in Django
I use django sessions with file system backend. I have set SESSION_EXPIRE_AT_BROWSER_CLOSE to True. So my current session becomes invalid when the browser closes. But the session file created remains.

I want to delete all inactive/invalid files. How can I find these files?

答:
Note that this setting means that the cookie (on the client side!) is deleted after the browser is closed. The session on the server remains until it has expired.

Sessions are stored in the database backend of the Django site. If you want to clear all open sessions, check out Clearing the session table.


问:
how to define an array of IPs in Elasticsearch?
I am using Elasticsearch 5.3. In an index, I want to define a field as an array of ip fields. How do I define this in a mapping?

答:
The mapping for IPs can also be used for arrays of IPs.

```<code>PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "ip_addr": {
          "type": "ip"
        }
      }
    }
  }
}
</code>```

Here you just index the IPs as an array.

```<code>PUT my_index/my_type/1
{
  "ip_addr": ["192.168.1.1", "192.168.1.2"]
}
</code>```

And then you can search them as usual.

```<code>GET my_index/_search
{
  "query": {
    "term": {
      "ip_addr": "192.168.0.0/16"
    }
  }
}
</code>```

The mapping for single entries and arrays is actually always the same in Elasticsearch (for primitive datatypes).

Body:
The mapping for IPs can also be used for arrays of IPs.

PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "ip_addr": {
          "type": "ip"
        }
      }
    }
  }
}

Here you just index the IPs as an array.

PUT my_index/my_type/1
{
  "ip_addr": ["192.168.1.1", "192.168.1.2"]
}

And then you can search them as usual.

GET my_index/_search
{
  "query": {
    "term": {
      "ip_addr": "192.168.0.0/16"
    }
  }
}

The mapping for single entries and arrays is actually always the same in Elasticsearch (for primitive datatypes).


问:
Arguments of functions
Tell me how to determine the amount of function's arguments.

For example:

```<code>var func1 = function(arg1, arg2){};
var func2 = function(agr1, arg2, arg3){};

var i1 = myargscounter(func1); // = 2
var i2 = myargscounter(func1); // = 3
</code>```

myargscounter - unknown algorithm that I need

答:
You can use Function.length for this:</p>

```<code>var func1 = function(arg1, arg2){};
var func2 = function(agr1, arg2, arg3){};

function myargscounter(func) {
  return func.length;
}

var i1 = myargscounter(func1); // = 2
var i2 = myargscounter(func2); // = 3

console.log(i1);
console.log(i2);
</code>```

Title: Arguments of functions

Body:
Tell me how to determine the amount of function's arguments.

For example:

var func1 = function(arg1, arg2){};
var func2 = function(agr1, arg2, arg3){};

var i1 = myargscounter(func1); // = 2
var i2 = myargscounter(func1); // = 3

myargscounter - unknown algorithm that I need

Body:
You can use Function.length for this:

var func1 = function(arg1, arg2){};
var func2 = function(agr1, arg2, arg3){};

function myargscounter(func) {
  return func.length;
}

var i1 = myargscounter(func1); // = 2
var i2 = myargscounter(func2); // = 3

console.log(i1);
console.log(i2);


问:
Using jQuery (window).resize but element dissapears
I have a submenu that is scrolls with the site using position:fixed; I am using jQuery to calculate where it should sit as it's outside of the main content of the site.
It's working fine except for when I resize the browser window; it then disappears from view. Looking at the code in dev tools, it's still there and should be visible.

Perhaps there is something wrong with my script? Your help would be very much appreciated.

```<code>jQuery(document).ready(function() {

    // Sub Menu Placement
  calculation();
  jQuery(window).resize(calculation);

  function calculation() {
      var location = jQuery(".page-content-section .page-content-section-inner").offset();
            var locationTop = jQuery(".header").offset();

      var left = location.left;
      left = left - 0;

      var top = locationTop.top;
      top = top + jQuery('.header').height();

      jQuery("#submenu").css({
        //'position': 'absolute',
        'position' : 'fixed',
        'top': top + 'px',
        'left': left + 'px'
      });
  }

});
</code>```

答:
I figured out the issue:

I changed this line:

```<code>top = top + jQuery('.header').height();
</code>```

to this:

```<code>top = jQuery('.header').height();
</code>```

Body:
I have a submenu that is scrolls with the site using position:fixed; I am using jQuery to calculate where it should sit as it's outside of the main content of the site.
It's working fine except for when I resize the browser window; it then disappears from view. Looking at the code in dev tools, it's still there and should be visible.

Perhaps there is something wrong with my script? Your help would be very much appreciated.

jQuery(document).ready(function() {

    // Sub Menu Placement
  calculation();
  jQuery(window).resize(calculation);

  function calculation() {
      var location = jQuery(".page-content-section .page-content-section-inner").offset();
            var locationTop = jQuery(".header").offset();

      var left = location.left;
      left = left - 0;

      var top = locationTop.top;
      top = top + jQuery('.header').height();

      jQuery("#submenu").css({
        //'position': 'absolute',
        'position' : 'fixed',
        'top': top + 'px',
        'left': left + 'px'
      });
  }

});

Body:
I figured out the issue:

I changed this line:

top = top + jQuery('.header').height();

to this:

top = jQuery('.header').height();


问:
Android Gradle build error while running the project
I have mentioned my gradle below please let me know what is the solution for that question and have used the api level 25 in my project

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            keyAlias 'yaksha'
            keyPassword '123456'
            storeFile file('/home/abhinav/Downloads/yaksha.jks')
            storePassword '123456'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.tene.yaksha"
        minSdkVersion 17
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testApplicationId "com.tene.yaksha1"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
        testHandleProfiling true
        testFunctionalTest true

    }
    testOptions {
        reportDir "$rootDir/test-reports"
        resultsDir "$rootDir/test-results"
    }

    dataBinding {
        enabled = true
    }
    dexOptions {
        //incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "4g"

    }
    lintOptions {
//        lintConfig file("$project.rootDir/tools/rules-lint.xml")
        abortOnError false
        htmlOutput file("$project.buildDir/outputs/lint/lint.html")
        warningsAsErrors false
        xmlReport true
    }

    buildTypes {
        release {
            minifyEnabled true
            debuggable false
            jniDebuggable true
            signingConfig signingConfigs.config
            renderscriptDebuggable true
            shrinkResources true
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
        }
        debug {
            minifyEnabled false
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
            multiDexKeepFile file('multidex-config.txt')
        }

    }

    packagingOptions
            {
                exclude 'META-INF/DEPENDENCIES.txt'
                exclude 'META-INF/LICENSE.txt'
                exclude 'META-INF/NOTICE.txt'
                exclude 'META-INF/NOTICE'
                exclude 'META-INF/LICENSE'
                exclude 'META-INF/DEPENDENCIES'
                exclude 'META-INF/notice.txt'
                exclude 'META-INF/license.txt'
                exclude 'META-INF/dependencies.txt'
                exclude 'META-INF/LGPL2.1'
            }
    testOptions {
        unitTests.returnDefaultValues = true
        unitTests {

            all {
                jvmArgs '-XX:MaxPermSize=256m'
                if (it.name == 'testDebug') {
                    systemProperty 'debug', 'true'
                }
                if (it.name == 'connectedDebugAndroidTest') {

                }
            }
        }
    }
    configurations {
    }
}

dependencies {

    //    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.google.android.gms:play-services:10.2.1'
    compile project(':realmtenedbservice')
    compile project(':tenewsrestlib')
    compile project(':TeneLocationLib')
    compile project(':SecurityYsc')
    compile project(':library')
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:recyclerview-v7:25.3.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.birbit:android-priority-jobqueue:2.0.1'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.maps.android:android-maps-utils:0.4+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'io.realm:android-adapters:1.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.sromku:simple-storage:1.2.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'joda-time:joda-time:2.9.7'
    compile 'id.zelory:compressor:1.0.4'
    compile 'io.reactivex:rxandroid:1.2.1'
}```
</div>
</div>
</p>

<p>I'm getting this error while running the project,can you anybody give suggesions why this is coming </p>

```Information:Gradle tasks [:app:assembleDebug]
Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
Information:BUILD FAILED
Information:Total time: 18.768 secs
Information:1 error
Information:1 warning
Information:See complete output in console
```

答:
I thik this is duplicate</p>

```<code>compile 'com.android.support:multidex:1.0.1'
</code>```

Body:
I have mentioned my gradle below please let me know what is the solution for that question and have used the api level 25 in my project

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    signingConfigs {
        config {
            keyAlias 'yaksha'
            keyPassword '123456'
            storeFile file('/home/abhinav/Downloads/yaksha.jks')
            storePassword '123456'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.tene.yaksha"
        minSdkVersion 17
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testApplicationId "com.tene.yaksha1"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
        testHandleProfiling true
        testFunctionalTest true

    }
    testOptions {
        reportDir "$rootDir/test-reports"
        resultsDir "$rootDir/test-results"
    }

    dataBinding {
        enabled = true
    }
    dexOptions {
        //incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "4g"

    }
    lintOptions {
//        lintConfig file("$project.rootDir/tools/rules-lint.xml")
        abortOnError false
        htmlOutput file("$project.buildDir/outputs/lint/lint.html")
        warningsAsErrors false
        xmlReport true
    }

    buildTypes {
        release {
            minifyEnabled true
            debuggable false
            jniDebuggable true
            signingConfig signingConfigs.config
            renderscriptDebuggable true
            shrinkResources true
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
        }
        debug {
            minifyEnabled false
            proguardFile '/home/abhinav/Android/Sdk/tools/proguard/yakshaproguard.txt'
            multiDexKeepFile file('multidex-config.txt')
        }

    }

    packagingOptions
            {
                exclude 'META-INF/DEPENDENCIES.txt'
                exclude 'META-INF/LICENSE.txt'
                exclude 'META-INF/NOTICE.txt'
                exclude 'META-INF/NOTICE'
                exclude 'META-INF/LICENSE'
                exclude 'META-INF/DEPENDENCIES'
                exclude 'META-INF/notice.txt'
                exclude 'META-INF/license.txt'
                exclude 'META-INF/dependencies.txt'
                exclude 'META-INF/LGPL2.1'
            }
    testOptions {
        unitTests.returnDefaultValues = true
        unitTests {

            all {
                jvmArgs '-XX:MaxPermSize=256m'
                if (it.name == 'testDebug') {
                    systemProperty 'debug', 'true'
                }
                if (it.name == 'connectedDebugAndroidTest') {

                }
            }
        }
    }
    configurations {
    }
}

dependencies {

    //    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.3.0'
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.google.android.gms:play-services:10.2.1'
    compile project(':realmtenedbservice')
    compile project(':tenewsrestlib')
    compile project(':TeneLocationLib')
    compile project(':SecurityYsc')
    compile project(':library')
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:recyclerview-v7:25.3.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.birbit:android-priority-jobqueue:2.0.1'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.maps.android:android-maps-utils:0.4+'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'io.realm:android-adapters:1.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.sromku:simple-storage:1.2.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'joda-time:joda-time:2.9.7'
    compile 'id.zelory:compressor:1.0.4'
    compile 'io.reactivex:rxandroid:1.2.1'
}

I'm getting this error while running the project,can you anybody give suggesions why this is coming

Information:Gradle tasks [:app:assembleDebug]
Warning:Using incompatible plugins for the annotation processing: android-apt. This may result in an unexpected behavior.
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class
Information:BUILD FAILED
Information:Total time: 18.768 secs
Information:1 error
Information:1 warning
Information:See complete output in console

Body:
I thik this is duplicate

compile 'com.android.support:multidex:1.0.1'


问:
Unicorn restart/upgrade doesn't work
Following is link to my init script for unicorn.
https://gist.github.com/1466775

Restart command has never worked for me. I am using upgrade to restart unicorn after each deploy. But whenever there is major changes like new gems being added, upgrade won't work. Recently, i replaced hoptoad gem with airbrake and it errors out saying 'uninitialized constant Airbrake (NameError)'. But when i stopped and started unicorn again, it worked fine. Does the problem lies in init script or its different problem?

Thanks.

答:
I fixed this issue by changing my unicorn init.d script from

```<code>CMD="cd $APP_ROOT; bundle exec unicorn -D -c $APP_ROOT/config/unicorn.rb -E staging"
</code>```

to this:

```<code>CMD="cd $APP_ROOT; BUNDLE_GEMFILE=$APP_ROOT/Gemfile bundle exec unicorn -D -c $APP_ROOT/config/unicorn.rb -E staging"
</code>```

Which seems to point to the new bundle gemfile on every new release.
Taking inspiration from this merge request

Title: Unicorn restart/upgrade doesn't work

Body:
I fixed this issue by changing my unicorn init.d script from

CMD="cd $APP_ROOT; bundle exec unicorn -D -c $APP_ROOT/config/unicorn.rb -E staging"

to this:

CMD="cd $APP_ROOT; BUNDLE_GEMFILE=$APP_ROOT/Gemfile bundle exec unicorn -D -c $APP_ROOT/config/unicorn.rb -E staging"

Which seems to point to the new bundle gemfile on every new release.
Taking inspiration from this merge request


问:
Use django text plugin for model fields in custom plugin
Hi this is a long shot i think but here goes.....

Basically i have a few custom plugins and apps being used in my django /django-cms site.  I have set tinymce up which is working fairly ok however what im wondering is it possible to use the built in text plugin for the TextField model fields in my custom plugins and apps?

so in effect the info text field for my main content plugin would actually render in the admin site as the text plugin

Like i said i think this is a long shot...

答:
I also had this requirement (formatted text on a django-cms plugin configuration) and ended up with the following workaround:
I installed django-tinymce and changed my TextField to an HTMLField in the CMS plugin configuration model. This will render a tinymce text editor in the plugin configuration form. You can then use the input from the HTMLField in your plugin template with the ...|safe filter.


问:
sort array according to date
Sort array according to date,
problem is date saved in string format can this is possible to sort array without change date in NSDate object.(Core Data).

string format is mm/dd/yyyy

答:
If the date is stored in a format where an alphabetic sort is equivalent to a date sort, then it can't be done with core data. In that case you have two options:

Add a new NSDate attribute to your database and convert each textual date to a real date and update the record. Then you can sort with core data

Extract all the data into an in-memory array, then sort that with a custom compare method.

Title: sort array according to date


问:
Scala Generic MongoDB collection
The mongo-scala-driver has been updated recently, and I wanted to update my app (link) to support the newly added case classes.

I'm currently having an issue with those case classes and do not find a way to solve it (proper way at least).

I have a trait named Collection in which I defined some generic queries than can be applied to any of my collections:

```<code>import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{MongoCollection, _}

import scala.concurrent.Future

trait Collection[T] {
  protected val DEFAULT_LIMIT_SIZE = 50
  protected val collection: MongoCollection[T]

  def insert(obj: String): Future[_]

  def get(id: Int) = collection.find(equal("_id", id)).first().head()

}
</code>```

I also implemented in subclasses some collection specific queries, for instance

```<code>import org.mongodb.scala.MongoCollection

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object Groups extends Collection[Group] with Database {

  override val collection : MongoCollection[Group] =   database.withCodecRegistry(Group.codecRegistry).getCollection("groups")

  override def insert(groupId: String) : Future[Group] = {
    val group = Group(groupId.toLong)
    collection
      .insertOne(group)
      .head()
      .map(_ => group)
  }

  def all =
    collection
      .find()
      .toFuture()

}
</code>```

The issue comes from the get method of the Collection trait:

```<code>[error] Collection.scala:13: No ClassTag available for C
[error]   def get(id: Int) = collection.find(equal("_id", id)).first().head()
</code>```

I'm pretty sure it comes from the fact that I use the trait type parameter as type for a MongoCollection, but I can't think of an other way to implement this.

How could I achieve this ?

Thanks

EDIT: By adding (implicit ct: ClassTag[T]) to each method of the Collection trait, it seems to work, but I don't really like doing that...

EDIT2: It's also possible to put this implicit ct in the trait, and override it from subclasses:

```<code>trait Collection[T] {
    implicit def ct: ClassTag[T]
    ...
}
</code>```

And in subclasses:

```<code>object Groups extends Collection[Group] with Database {
    override def ct = implicitly
    ...
}
</code>```

答:
Update: You need to implicitly pass ClassTag for T in get method of your collection trait.

```<code>def get[T : scala.reflect.ClassTag] {
    //...........
}
</code>```

Title: Scala Generic MongoDB collection

Body:
The mongo-scala-driver has been updated recently, and I wanted to update my app (link) to support the newly added case classes.

I'm currently having an issue with those case classes and do not find a way to solve it (proper way at least).

I have a trait named Collection in which I defined some generic queries than can be applied to any of my collections:

import org.mongodb.scala.model.Filters._
import org.mongodb.scala.{MongoCollection, _}

import scala.concurrent.Future

trait Collection[T] {
  protected val DEFAULT_LIMIT_SIZE = 50
  protected val collection: MongoCollection[T]

  def insert(obj: String): Future[_]

  def get(id: Int) = collection.find(equal("_id", id)).first().head()

}

I also implemented in subclasses some collection specific queries, for instance

import org.mongodb.scala.MongoCollection

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object Groups extends Collection[Group] with Database {

  override val collection : MongoCollection[Group] =   database.withCodecRegistry(Group.codecRegistry).getCollection("groups")

  override def insert(groupId: String) : Future[Group] = {
    val group = Group(groupId.toLong)
    collection
      .insertOne(group)
      .head()
      .map(_ => group)
  }

  def all =
    collection
      .find()
      .toFuture()

}

The issue comes from the get method of the Collection trait:

[error] Collection.scala:13: No ClassTag available for C
[error]   def get(id: Int) = collection.find(equal("_id", id)).first().head()

I'm pretty sure it comes from the fact that I use the trait type parameter as type for a MongoCollection, but I can't think of an other way to implement this.

How could I achieve this ?

Thanks

EDIT: By adding (implicit ct: ClassTag[T]) to each method of the Collection trait, it seems to work, but I don't really like doing that...

EDIT2: It's also possible to put this implicit ct in the trait, and override it from subclasses:

trait Collection[T] {
    implicit def ct: ClassTag[T]
    ...
}

And in subclasses:

object Groups extends Collection[Group] with Database {
    override def ct = implicitly
    ...
}

Body:
Update: You need to implicitly pass ClassTag for T in get method of your collection trait.

def get[T : scala.reflect.ClassTag] {
    //...........
}


问:
Show popover on button click using jquery
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

```<code><button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>
</code>```

Jquery

```<code>$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});
</code>```

答:
Just check your condition inside</p>
```<code>$(document).ready(function(){
     //Your condition here
});

</code>```

Body:
I am trying to display notification message by using popover, it is working but after loading a page if i click button first time it doesn't show the popover after that it works fine here is my code-

<button type="button" id="bulk_actions_btn" class="btn btn-default has-spinner-two" data-toggle="popover" data-placement="bottom" data-original-title="" data-content="Click any question mark icon to get help and tips with specific tasks"> Apply </button>

Jquery

$(document).on('click','#bulk_actions_btn',function(){

   if(condition){
        $('[data-toggle="popover"]').popover(); //here if the condition is true then popover should be display.
    }else{
       //ajax
    }
});

Body:
Just check your condition inside

$(document).ready(function(){
     //Your condition here
});