问:
UnitTesting (Visual Studio) code isolations in same .net assembly - Recommendation
I would like to know the right recommendation on below case

My application's business module (single assembly) has below folder structure

-Service (folder)

```<code>  - MyService.cs - Implements IMyService deals with service to be performed
</code>```

-DomainModel (folder)

```<code>  - MyDomainModel.cs - only deals with pure business rules and completely isolated from any infrastructure code. (its a normal class and is not decoupled via any interface)
</code>```

Scenario is I need to test MethodA in MyService.cs, internally it  calls  DomainMethodA in MyDomainModel.cs

So here,  do I need to Shim DomainMethodA?

Thanks

答:
Basically when we talk about unit testing we are testing the unit. The unit in this case is small piece of functionality, for example, a method. And in case of unit testing we don't want to go away from this method (at least not to another module/class), thus all other parties should be mocked. So, in your case MyDomainModel should be mocked.

Another case is when we talk about integration testing. In this case we don't want to mock anything, but want the test how application goes through the long sequence of several different modules and classes. Sometimes/quite often it is complicated to check and verify all the results of the middle parts of the sequence, thus in this case it is better to create unit tests for this parties.

I would advice to combine both of this testing types/styles.

Body:
I would like to know the right recommendation on below case

My application's business module (single assembly) has below folder structure

-Service (folder)

  - MyService.cs - Implements IMyService deals with service to be performed

-DomainModel (folder)

  - MyDomainModel.cs - only deals with pure business rules and completely isolated from any infrastructure code. (its a normal class and is not decoupled via any interface)

Scenario is I need to test MethodA in MyService.cs, internally it  calls  DomainMethodA in MyDomainModel.cs

So here,  do I need to Shim DomainMethodA?

Thanks


来源: stackexchange

问:
How to set Animation Slide Down to card view when click on arrow down in ViewHolder?
I tried to set slide down animation to card when the user click on the arrow down icon but it not work when I setAnimationListener(this). it error at "this" keyword.
Note I use recycler view and card in the fragment.
here my code below

```<code>class ListViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle, tvDescription;
        ImageView ivDropDown;
        LinearLayout ll_footer;
        Button btnClose;
        Animation slideDown;

        public ListViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
            ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
            ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
            btnClose = (Button) itemView.findViewById(R.id.btn_close);

            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                    ll_footer.setVisibility(View.GONE);
                }
            });

            ivDropDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callBack.onImageClick(getAdapterPosition());
                    slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                    ll_footer.setAnimation(slideDown);
                    slideDown.setAnimationListener();
                    ll_footer.setVisibility(View.VISIBLE);
                }
            });
        }
    }
</code>```

答:
First of all, create the following anim file named slide_down.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">

    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="-100%"
        android:toYDelta="0" />
</set>
</code>```

Thereafter, use the above anim file as follows :

```<code>ivDropDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callBack.onImageClick(getAdapterPosition());
                Animation slideDown = AnimationUtils.loadAnimation(mContext,
                R.anim.slide_down);
        slideDown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // show the footer
                ll_footer.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
                ll_footer.startAnimation(slideDown);
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried to set slide down animation to card when the user click on the arrow down icon but it not work when I setAnimationListener(this). it error at "this" keyword.
Note I use recycler view and card in the fragment.
here my code below

class ListViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle, tvDescription;
        ImageView ivDropDown;
        LinearLayout ll_footer;
        Button btnClose;
        Animation slideDown;

        public ListViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
            ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
            ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
            btnClose = (Button) itemView.findViewById(R.id.btn_close);

            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                    ll_footer.setVisibility(View.GONE);
                }
            });

            ivDropDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callBack.onImageClick(getAdapterPosition());
                    slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                    ll_footer.setAnimation(slideDown);
                    slideDown.setAnimationListener();
                    ll_footer.setVisibility(View.VISIBLE);
                }
            });
        }
    }

Body:
First of all, create the following anim file named slide_down.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">

    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="-100%"
        android:toYDelta="0" />
</set>

Thereafter, use the above anim file as follows :

ivDropDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callBack.onImageClick(getAdapterPosition());
                Animation slideDown = AnimationUtils.loadAnimation(mContext,
                R.anim.slide_down);
        slideDown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // show the footer
                ll_footer.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
                ll_footer.startAnimation(slideDown);
            }
        });


问:
how to Show/Hide button C# ASP.Net <No Panel>
I have below code

```<code><div class="modal‐footer">
<div class="row">
  <div class="col-md-6" runat="server" id="d1">
    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
  </div>
  <div class="col-md-6" runat="server" id="d2">
    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />
  </div>
  <div class="col-md-6" runat="server" id="d3">
    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />
  </div>
  <div class="col-md-6" runat="server" id="d4">
    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />
  </div>
</div>
</div>
</code>```

I need to show only Update Button, under condition. Example,

```<code>if a=="Pending"; only UpdateBtn will be shown.
</code>```

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

```<code>namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }
</code>```

答:
Try this Javascript code

```<code><script type="text/javascript">
$(function hideButton() {
document.getElementById('<%=Button1.ClientID %>').style.visibility = "hidden";
});
<script>
</code>```

You can call this function in C# code using the RegisterClientScriptBlock

Body:
I have below code

    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />

    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />

    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />

    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />

I need to show only Update Button, under condition. Example,

if a=="Pending"; only UpdateBtn will be shown.

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }

Body:
Try this Javascript code

<script type="text/javascript">
$(function hideButton() {
document.getElementById('<%=Button1.ClientID %>').style.visibility = "hidden";
});
<script>

You can call this function in C# code using the RegisterClientScriptBlock


问:
Handling M/chip fast transactions
i'm doing m-tip transactions and I stuck on M-TIP05-USM.Test.01.Scenario.01f.
According to M-TIP 2.0 Build 225 Test Definition Reference after offline pin verification next should be "The Issuer Script command is sent after First GEN AC - [RA120]".
I'm getting "In Second GEN AC, the terminal requests an AAC - [R3]"             Property: CONTACT.APDU(CLA=80,INS=AE)[2].COMMAND:BYTE.3.BIT.7-8
            Expected: '00'
            Received: '01'

and transaction is approved. Any advices?

答:
On I'm getting "In Second GEN AC, the terminal requests an AAC - [R3]"

When you do GEN AC, in reference control parameter, terminal will
tell the chip what kind of cryptogram it expects. In your case it
says terminal requests an  AAC(reference control parameter is 0x00.
If you were expecting an ARQC, it should have been 0x80 or if a TC
0x40( In case a CDA card, bit 5 also to be considered. Check the below picture from EMV Book 3). In your case
you need to identify what caused your terminal to request an AAC(
which mean terminal did not want to go ahead with the transaction).

May be you can get something from TVR, match the TVR against TAC - Decline (Terminal action code).

On and transaction is approved. Any advices?

An AAC returned transaction should not be approved. How did you
terminal consider the transaction approved.

Title: Handling M/chip fast transactions


问:
Adding string Array in Angular
I have created this app in Angular as a practice can't seem to add the amount to a total value... Here is the Code I need to put the total value of the amount.

```<code><body>
<div class="container" ng-app="myApp" ng-controller="namesCtrl">
<div class="col-sm-6"><br>
<button  class="btn btn-default" ng-click="myFunc()">Show me the Table</button><br>
<div ng-show="showMe">
<table  class="table"  width="80%" border="2px">

    <tr class="panel panel-default">
        <th> Names</th>
        <th>Country</th>
        <th>Amount</th>
    </tr>
    <tr ng-repeat= "x in names">
        <td class="info"> {{x.name}}</td>
        <td class="danger">{{x.country}}</td>
        <td class="default">{{x.amount}}</td>
    </tr>

</table>
</div>
</div>
</div>
<script>
    var app=angular.module("myApp", []);
    app.controller("namesCtrl", function($scope){

$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
    ];

        $scope.showMe=false;
        $scope.myFunc=function(){
        $scope.showMe=!$scope.showMe;

    }

    });

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

it would be help ful for me to Know how to add the amount to a total value.

答:
Using Array.prototype.reduce():

```<code>$scope.total = $scope.names.reduce((a, v) => a + parseInt(v.amount));
</code>```

Note that you would need to use parseFloat() instead of parseInt() if your amounts contain decimal values.

Here's a complete snippet:

var $scope = {};

$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
];

$scope.total = $scope.names.reduce((a, v) => a + parseInt(v.amount), 0);

console.log($scope.total);```

Title: Adding string Array in Angular

Body:
I have created this app in Angular as a practice can't seem to add the amount to a total value... Here is the Code I need to put the total value of the amount.

<button  class="btn btn-default" ng-click="myFunc()">Show me the Table</button>

         Names
        Country
        Amount

         {{x.name}}
        {{x.country}}
        {{x.amount}}

it would be help ful for me to Know how to add the amount to a total value.

Body:
Using Array.prototype.reduce():

$scope.total = $scope.names.reduce((a, v) => a + parseInt(v.amount));

Note that you would need to use parseFloat() instead of parseInt() if your amounts contain decimal values.

Here's a complete snippet:

var $scope = {};

$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
];

$scope.total = $scope.names.reduce((a, v) => a + parseInt(v.amount), 0);

console.log($scope.total);


问:
use data from multiple tables in SQL
need some quick help.. i think i'm supposed to use INNER JOIN, but i'm not really sure.

```<code>List  the employee ID and the full name of the employee who sold or packaged the
transactions placed by customer Benjamin Jones. Each employee should only show up
once in your results
</code>```

employeeID, first and last are in the EMPLOYEES table

benjamin jones' memberID is 101 and in the MEMBERS table

memberID and transactionID and soldorpackagedby are in the TRANSACTIONS table

this is what I have to start it off but don't know how to finish it.

```<code> SELECT EmployeeID, First, Last
 FROM Employees
 WHERE MemberID = '101'
</code>```

thanks!

答:
Try this one</p>

```<code>SELECT employees.EmployeeID,
       employees.First,
       employees.Last
FROM employees
JOIN transactions ON employees.EmployeeID = transactions.EmployeeID
WHERE transactions.memberID = 101
GROUP BY employees.EmployeeID, employees.First,  employees.Last ;
</code>```

Title: use data from multiple tables in SQL

Body:
need some quick help.. i think i'm supposed to use INNER JOIN, but i'm not really sure.

List  the employee ID and the full name of the employee who sold or packaged the
transactions placed by customer Benjamin Jones. Each employee should only show up
once in your results

employeeID, first and last are in the EMPLOYEES table

benjamin jones' memberID is 101 and in the MEMBERS table

memberID and transactionID and soldorpackagedby are in the TRANSACTIONS table

this is what I have to start it off but don't know how to finish it.

 SELECT EmployeeID, First, Last
 FROM Employees
 WHERE MemberID = '101'

thanks!

Body:
Try this one

SELECT employees.EmployeeID,
       employees.First,
       employees.Last
FROM employees
JOIN transactions ON employees.EmployeeID = transactions.EmployeeID
WHERE transactions.memberID = 101
GROUP BY employees.EmployeeID, employees.First,  employees.Last ;


问:
Working on a Git feature branch and use(?) branch at the same time
I'm new to Git, and sometimes I find myself working on a feature branch(say adding library A) while also working on program B that uses it(which I call the use branch, maybe there is a better word). So what I've done in the past is have two separate branches, work on the feature branch 'til it seems like it might work, then start using the API in the use branch, merge the feature branch in and see if it works. If it doesn't work, I go back to the feature branch, fix the issue, merge and repeat. Is this the best way to do this?

My goal is to keep the feature branch separate from any implementation that uses it(though I suppose even that is up for debate). What I also thought of later is presuming I'm editing a limited number of files I could just do the 'fixing' changes in the use branch and use 'git checkout' in the feature branch to bring just the library changes back in.

What I guess I really want is to be working in a single workspace, but specify that these files belong to branch A and these files belong to branch B and be able to commit them separately. (I can imagine an implementation where you specify 2(or n) branches to combine into a pseudo branch, presuming that you don't alter the same files. Then when you change files that are in one branch you can commit just those files to that branch(and if you modify new files, you have to specify which branch this file 'belongs' to)). For all I know this may be in opposition to how Git works, but I don't know it enough to tell. :)

Thoughts?

Clarifications/Addendums:

This is a single program in one repository(though two repositories may be the solution)

There are two branches I'm currently working with

Example(not actually what I'm doing :)):
I'm writing a program to generate a random number and then write it to a file. So my main program is in its own branch(what I refer to as my 'use' branch). My main program is simply:

MyFileApi::Write("myfile", random());

where random() is some system API that already exists, but MyFileApi::Write is a new feature I'm developing(so my program is using this new feature). In my 'feature branch' I have say a header file and implementation for MyFileApi::Write. So I've written some implementation of MyFileApi::Write, but I want to test it using my new random-number-file-writer program(it would probably be best to write tests specifically for this API, but I'm being lazy and testing it in my program that uses the code). So what I've been doing is merging in my MyFileApi::Write changes into my 'use' branch, testing it, seeing it fail, going back to my feature branch, fixing the issue, merging again, repeat etc...

答:
I'm no git guru, but you can theoretically have as many branches as you want. What I would suggest, assuming you have library A in its own git repo and program B (which uses A) in its own git repo would be:

create a branch (for example, "new_features") in A

modify your code, try to compile/link, fix errors

create a branch (use the same name to show what will be tested - "new_features") in B

modify code in B to use the new/modified features that you added/changed in A

compile/link/test B

You really need to have the branch in your program B if the changes you are making to library A change its exposed set of functions/variables. If all you are doing is making changes to the "background" code (that is, leave the exposed functions/vars as they are while improving algorithms, memory usage, etc in those functions), you would not necessarily need a branch for your B program.

Regardless, if you branched both projects, first go to your A library and merge your branch back into the trunk. Compile/link/fix errors. Then go to B and merge its respective branch onto the trunk of that project. Again, compile/link/fix errors.

I'm actually having to do something like this with one of the projects I'm currently developing; has a main application that makes use of various shared libraries. We use SVN, but the concepts are essentially the same.

ContentLicense: CC BY-SA 2.5


问:
Unable to locate json data file while making http get request in angular cli project
Repo: https://github.com/avalokkumar/gametrackers

I'm unable to make http request to src/games-data.json from app/games/shared/GamesService as it is not able to locate the file path correctly.
Please suggest any solution.
Thanks.

答: Changing the path src/games-data.json to src/data/games-data.json in app/games/shared/GamesService did the work.


问:
Alternate Icon in iOS 10.3
I have the info on how to set up alternate icons in iOS 10.3 adding the key in the Info.plist.  However, what I am not sure of is which sizes are needed for each alternate.  I use assets folders right now, and have to put in about 12 different sized icons for spotlight, different iphone and ipad sizes, etc.  What's the rule on the alternate ones?</p>

答:
Since the biggest problem is how to configure the icon image source and info.plist, here is a sample to tell you how to set alternate icons in iOS 10.3, implemented in Swift 3.

If your app doesn't support iPad, the icon image source can be 60pt@2x and 60pt@3x (120x120 180x180), and the 20pt 29pt and 40pt all can be generated from the 60pt image. So, your alternate icon image source should also be 60pt@2x and 60pt@3x, if it is a iPhone-only app. And it should be 83.5pt, if your app supports iPad Pro.

Like what you saw in the picture, the alternate icon image should be added to the project as a png file (the blackBgColor image in my sample), but not added to Assets.xcassets.

The configuration for alternate icons in info.plist is kinda complicated, so if this is your first time doing this, I suggest you copy my code in plist. And, notice my alternate icon's name (blackBgColor) has beed used TWICE in plist, if you are gonna change the icon's name based on my version, make sure you changed the name in both of the two places.

```<code><key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>blackBgColor</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>blackBgColor</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon60x60</string>
        </array>
    </dict>
</dict>
</code>```

Now, code in ViewController will be simple.

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func changeAppIcon(_ sender: Any) {

        if UIApplication.shared.supportsAlternateIcons {
            print("you can change this app's icon")
        }else {
            print("you cannot change this app's icon")
            return
        }

        if let name = UIApplication.shared.alternateIconName {
            // CHANGE TO PRIMARY ICON
            UIApplication.shared.setAlternateIconName(nil) { (err:Error?) in
                print("set icon error：\(String(describing: err))")
            }
            print("the alternate icon's name is \(name)")
        }else {
            // CHANGE TO ALTERNATE ICON
            UIApplication.shared.setAlternateIconName("blackBgColor") { (err:Error?) in
                print("set icon error：\(String(describing: err))")
            }
        }
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Alternate Icon in iOS 10.3

Body:
Since the biggest problem is how to configure the icon image source and info.plist, here is a sample to tell you how to set alternate icons in iOS 10.3, implemented in Swift 3.

If your app doesn't support iPad, the icon image source can be 60pt@2x and 60pt@3x (120x120 180x180), and the 20pt 29pt and 40pt all can be generated from the 60pt image. So, your alternate icon image source should also be 60pt@2x and 60pt@3x, if it is a iPhone-only app. And it should be 83.5pt, if your app supports iPad Pro.

Like what you saw in the picture, the alternate icon image should be added to the project as a png file (the blackBgColor image in my sample), but not added to Assets.xcassets.

The configuration for alternate icons in info.plist is kinda complicated, so if this is your first time doing this, I suggest you copy my code in plist. And, notice my alternate icon's name (blackBgColor) has beed used TWICE in plist, if you are gonna change the icon's name based on my version, make sure you changed the name in both of the two places.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>blackBgColor</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>blackBgColor</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon60x60</string>
        </array>
    </dict>
</dict>

Now, code in ViewController will be simple.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func changeAppIcon(_ sender: Any) {

        if UIApplication.shared.supportsAlternateIcons {
            print("you can change this app's icon")
        }else {
            print("you cannot change this app's icon")
            return
        }

        if let name = UIApplication.shared.alternateIconName {
            // CHANGE TO PRIMARY ICON
            UIApplication.shared.setAlternateIconName(nil) { (err:Error?) in
                print("set icon error：\(String(describing: err))")
            }
            print("the alternate icon's name is \(name)")
        }else {
            // CHANGE TO ALTERNATE ICON
            UIApplication.shared.setAlternateIconName("blackBgColor") { (err:Error?) in
                print("set icon error：\(String(describing: err))")
            }
        }
    }

}


问:
Converting date and time into float in python
Below is my data set

```<code>  Date         Time
  2015-05-13   23:53:00
</code>```

I want to convert date and time into floats as separate columns in a python script.

The output should be like date as 20150513 and time as 235300

答:
If all you need is to strip the hyphens and colons, str.replace() should do the job:

```<code>>>> s = '2015-05-13 23:53:00'
>>> s.replace('-', '').replace(':', '')
'20150513 235300'
</code>```

For mort sophisticated reformatting, parse the input with time.strptime() and then reformat with time.strftime():

```<code>>>> import time
>>> t = time.strptime('2015-05-13 23:53:00', '%Y-%m-%d %H:%M:%S')
>>> time.strftime('%Y%m%d %H%M%S', t)
'20150513 235300'
</code>```

Body:
Below is my data set

  Date         Time
  2015-05-13   23:53:00

I want to convert date and time into floats as separate columns in a python script.

The output should be like date as 20150513 and time as 235300

Body:
If all you need is to strip the hyphens and colons, str.replace() should do the job:

>>> s = '2015-05-13 23:53:00'
>>> s.replace('-', '').replace(':', '')
'20150513 235300'

For mort sophisticated reformatting, parse the input with time.strptime() and then reformat with time.strftime():

>>> import time
>>> t = time.strptime('2015-05-13 23:53:00', '%Y-%m-%d %H:%M:%S')
>>> time.strftime('%Y%m%d %H%M%S', t)
'20150513 235300'


问:
How to know from context values which activity is currently running foreground?
I have a tricky situation. I will try to fully explain it in the best possible way.

My app has few activities, say A, B, C. A is the Main Activity and B & C gets called from A. So basically when B or C is running, A will be stopped(onStop()).

I am using an android library(created by me) in my App. My library saves the contexts of the activities. For example, when we open the app with activity A, my library will save A's context and will create a handler using that context and save them in a Map(Map<Context, Handler>). Now if we navigate to activity B, my library will get B's context and then make a new entry for this in the Map.

At some point in time, I will use the handlers present in the Map to post some runnables. Obviously, both A and B will receive as both are running(one in background and foreground).

But how can I check and send only to the one running in the foreground? Is it possible to check from a context value, whether the activity is currently running or stopped?

Does this.getMainLooper when called from A and B return the same thing?

UPDATE: I am sorry, I missed this point. The App is a demo application on how to use my library. So I will release my library in future and developers will be using it. Hence I don't want the developers to do this and it would be the best if I can do it in my library itself.

答:
But how can I check and send only to the one running in the foreground? Is it possible to check from a context value, whether the
  activity is currently running or stopped?

The easiest and recommended way will be to hand a reference to the Application object to your library, with it you can register to Activity Lifecycle callbacks using Application.registerActivityLifecycleCallbacks, and monitor the state of the Activities and determine when activity is foreground (using onActivityResumed() callback).

Another less preferable option, is that each activity will notify your library code about it's events, but it's of course more tedious and error prone.

Third 'do not do it' way is to use ActivityManager that has getRunningTasks(), and from their you can get top activity, but again it's documented as for 'debug purposes only' and is more error prone then all the above.

Does this.getMainLooper when called from A and B return the same thing?

Yep, A and B sitting on the same process, Main Looper is the looper of the main UI thread, which is singular per Process.


答:
We're going to operate under the assumption that you want IN-OUT-IN-OUT... in the order of the time. I manually created data from your prev screenshot BTW:

```<code>--What your sample data should look like next time
-------------------------------------------------------
DECLARE @yourtable TABLE
(
  employeeCode int,
  [shift]      varchar(40),
  [Date]       date,
  [time]       time,
  [Event]      varchar(3),
  [Site]       varchar(10)
);

DECLARE
  @empcode int         = 561,
  @shift   varchar(40) = '1PM - 10PM',
  @date    date        = '3/28/2017',
  @site    varchar(10) = 'Old Site';

INSERT @yourtable
VALUES
(@empcode, @shift, @date, '00:04:47.0', 'IN',  @site),
(@empcode, @shift, @date, '00:08:38.0', 'OUT', @site),
(@empcode, @shift, @date, '00:08:41.0', 'OUT', @site),
(@empcode, @shift, @date, '00:19:44.0', 'IN',  @site),
(@empcode, @shift, @date, '00:20:25.0', 'OUT', @site),
(@empcode, @shift, @date, '00:20:50.0', 'IN',  @site),
(@empcode, @shift, @date, '00:21:21.0', 'OUT', @site),
(@empcode, @shift, @date, '00:29:47.0', 'IN',  @site),
(@empcode, @shift, @date, '00:29:53.0', 'IN',  @site),
(@empcode, @shift, @date, '00:36:52.0', 'OUT', @site);

-- A solution:
-------------------------------------------------------
WITH prep AS
(
  SELECT *,
    lag1 = LAG([Event], 1)
          OVER (PARTITION BY employeeCode, [shift], [Date], [site] ORDER BY [time])
  FROM @yourtable
)
SELECT
    employeeCode
    [shift],
    [Date],
    [time],
    [Event],
    [Site]
FROM prep
WHERE [Event] <> lag1;
</code>```

Results:

```<code>shift       Date       time             Event Site
----------- ---------- ---------------- ----- ----------
561         2017-03-28 00:08:38.0000000 OUT   Old Site
561         2017-03-28 00:19:44.0000000 IN    Old Site
561         2017-03-28 00:20:25.0000000 OUT   Old Site
561         2017-03-28 00:20:50.0000000 IN    Old Site
561         2017-03-28 00:21:21.0000000 OUT   Old Site
561         2017-03-28 00:29:47.0000000 IN    Old Site
561         2017-03-28 00:36:52.0000000 OUT   Old Site
</code>```

Title: Remove Duplicate Occurance of Values in SQL Server Select Record

Body:
Date    Time    Event   site
2017-03-29  13:09:31.0000000    IN  Old Site
2017-03-29  14:26:32.0000000    OUT Old Site
2017-03-29  14:41:02.0000000    IN  Old Site
2017-03-29  16:21:17.0000000    OUT Old Site
2017-03-29  16:54:18.0000000    IN  Old Site
2017-03-29  16:54:24.0000000    IN  Old Site
2017-03-29  17:45:05.0000000    OUT Old Site
2017-03-29  19:30:03.0000000    IN  Old Site

DECLARE @empTime TABLE ([Date] DATE,[Time] TIME,[Event] VARCHAR(30),[Site] VARCHAR(30))

INSERT INTO @empTime ([Date],[Time],[Event],[Site])
VALUES
('2017-03-29', '13:09:31.0000000', 'IN', 'Old Site'),
('2017-03-29', '14:26:32.0000000', 'OUT', 'Old Site'),
('2017-03-29', '14:41:02.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:21:17.0000000', 'OUT', 'Old Site'),
('2017-03-29', '16:54:18.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:54:24.0000000', 'IN', 'Old Site'),
('2017-03-29', '17:45:05.0000000', 'OUT', 'Old Site'),
('2017-03-29', '19:30:03.0000000', 'IN', 'Old Site')

SELECT *
FROM @empTime

As per above code and output, I want to remove one of the Record for 'IN' '16:54:24.0000000' because I want record in form of continuous IN-OUT-IN-OUT.

I want to remove duplicate occurrence of value in below record. I want record should be in continuous form i.e. In-Out-In-Out.

Body:
We're going to operate under the assumption that you want IN-OUT-IN-OUT... in the order of the time. I manually created data from your prev screenshot BTW:

--What your sample data should look like next time
-------------------------------------------------------
DECLARE @yourtable TABLE
(
  employeeCode int,
  [shift]      varchar(40),
  [Date]       date,
  [time]       time,
  [Event]      varchar(3),
  [Site]       varchar(10)
);

DECLARE
  @empcode int         = 561,
  @shift   varchar(40) = '1PM - 10PM',
  @date    date        = '3/28/2017',
  @site    varchar(10) = 'Old Site';

INSERT @yourtable
VALUES
(@empcode, @shift, @date, '00:04:47.0', 'IN',  @site),
(@empcode, @shift, @date, '00:08:38.0', 'OUT', @site),
(@empcode, @shift, @date, '00:08:41.0', 'OUT', @site),
(@empcode, @shift, @date, '00:19:44.0', 'IN',  @site),
(@empcode, @shift, @date, '00:20:25.0', 'OUT', @site),
(@empcode, @shift, @date, '00:20:50.0', 'IN',  @site),
(@empcode, @shift, @date, '00:21:21.0', 'OUT', @site),
(@empcode, @shift, @date, '00:29:47.0', 'IN',  @site),
(@empcode, @shift, @date, '00:29:53.0', 'IN',  @site),
(@empcode, @shift, @date, '00:36:52.0', 'OUT', @site);

-- A solution:
-------------------------------------------------------
WITH prep AS
(
  SELECT *,
    lag1 = LAG([Event], 1)
          OVER (PARTITION BY employeeCode, [shift], [Date], [site] ORDER BY [time])
  FROM @yourtable
)
SELECT
    employeeCode
    [shift],
    [Date],
    [time],
    [Event],
    [Site]
FROM prep
WHERE [Event] <> lag1;

Results:

shift       Date       time             Event Site
----------- ---------- ---------------- ----- ----------
561         2017-03-28 00:08:38.0000000 OUT   Old Site
561         2017-03-28 00:19:44.0000000 IN    Old Site
561         2017-03-28 00:20:25.0000000 OUT   Old Site
561         2017-03-28 00:20:50.0000000 IN    Old Site
561         2017-03-28 00:21:21.0000000 OUT   Old Site
561         2017-03-28 00:29:47.0000000 IN    Old Site
561         2017-03-28 00:36:52.0000000 OUT   Old Site


问:
How do you debug React Native?
How does one debug their React code with React Native while the app is running in app simulator? </p>

答:
Very simple just two commands</p>

```<code>For IOS $ react-native log-ios
For Android $ react-native log-android
</code>```

Title: How do you debug React Native?

Body:
Very simple just two commands

For IOS $ react-native log-ios
For Android $ react-native log-android


问:
Using Go and Revel, getting error c.RenderArgs is Undefined (possibly outdated?)
I have a script that has some Go code with outdated revel. I ran into an issue that says:

```<code> c.RenderArgs undefined (type *revel.Controller has no field or method RenderArgs)
</code>```

And ive tried to search around, but can't figure out what to replace it with to fix the error. I'm not familiar with revel so its making things that much more difficult.

If someone could help, or simply link me to a space that could help(if i missed it, and i am sorry) i would be greatful!

答:
Without posting more of your code, your question cannot be accurately answered, but here is what I found in the Godocs for Revel.

func (c *Controller) Render(extraRenderArgs ...interface{}) Result

Render a template corresponding to the calling Controller method. Arguments will be added to c.RenderArgs prior to rendering the template. They are keyed on their local identifier.

I believe your code is either trying to modify a field that was changed to be no longer exported, or calling a method that has been changed to the one above.

Body:
I have a script that has some Go code with outdated revel. I ran into an issue that says:

 c.RenderArgs undefined (type *revel.Controller has no field or method RenderArgs)

And ive tried to search around, but can't figure out what to replace it with to fix the error. I'm not familiar with revel so its making things that much more difficult.

If someone could help, or simply link me to a space that could help(if i missed it, and i am sorry) i would be greatful!


问:
Get the user ID in WooCommerce Subscriptions
I am using WooCommerce Subscriptions plugin and I am trying to get the customer or userid of a given wc_subscription.

Here is the code I have been using but fails:

```<code>add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
...
}
</code>```

I thought $wc_subscription->customer_user will have the userid but it is empty. In fact stops the code from continuing.

How can I get the user ID with $wc_subscription?

答:
As class WC_Subscription methods are inherited from WC_Abstract_Order and WC_Order classes, you can use get_user_id() method this way:

```<code>$userid = $wc_subscription->get_user_id();
</code>```

This code is tested and works with WC_Subscription instance object

So your code will be:

```<code>add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->get_user_id(); // <= HERE
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
    // ...
}
</code>```

Update (on OP's comment)

As the argument $wc_subscription was the subscription ID (and not the Subscription object).

So I have changed the code to:

```<code>add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $subscription_id ) {

    // Get an occurrence of the WC_Subscription object
    $subscription = wcs_get_subscription( $subscription_id );

    // Get the user ID (or customer ID)
    $user_id = $subscription->get_user_id();

    // The email adress
    $email = 'example@gmail.com';

    // The theme domain (replace with your theme domain for localisable strings)
    $domain = 'woocommerce';

    mail( $email, 'Expired', __("Someone’s order has expired", $domain);
    mail( $email, 'Expired', __("Someone’s order has expired with customer", $domain) . $user_id );

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

Body:
I am using WooCommerce Subscriptions plugin and I am trying to get the customer or userid of a given wc_subscription.

Here is the code I have been using but fails:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
...
}

I thought $wc_subscription->customer_user will have the userid but it is empty. In fact stops the code from continuing.

How can I get the user ID with $wc_subscription?

Body:
As class WC_Subscription methods are inherited from WC_Abstract_Order and WC_Order classes, you can use get_user_id() method this way:

$userid = $wc_subscription->get_user_id();

This code is tested and works with WC_Subscription instance object

So your code will be:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->get_user_id(); // <= HERE
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
    // ...
}

Update (on OP's comment)

As the argument $wc_subscription was the subscription ID (and not the Subscription object).

So I have changed the code to:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $subscription_id ) {

    // Get an occurrence of the WC_Subscription object
    $subscription = wcs_get_subscription( $subscription_id );

    // Get the user ID (or customer ID)
    $user_id = $subscription->get_user_id();

    // The email adress
    $email = 'example@gmail.com';

    // The theme domain (replace with your theme domain for localisable strings)
    $domain = 'woocommerce';

    mail( $email, 'Expired', __("Someone’s order has expired", $domain);
    mail( $email, 'Expired', __("Someone’s order has expired with customer", $domain) . $user_id );

    // ...
}


问:
How to use sqlite3 in XCode
I imported the libsqlite3.0.dylib framework but this code

```<code>sqlite3 *database;
</code>```

generates an error saying that sqlite3 is undeclared.

答:
Download Sqlite3 source from https://www.sqlite.org/download.html

Add Library(libsqlite3.0.dylib or libsqlite3.0.tbd) to project.

Add headers from downloaded source.(sqlite3.h,sqlite3ext.h).

Just #import "sqlite3.h" where you are creating sqlite3 object.

Title: How to use sqlite3 in XCode

Body:
I imported the libsqlite3.0.dylib framework but this code

sqlite3 *database;

generates an error saying that sqlite3 is undeclared.


问:
Pass additional props to a react component
I would like to know how to pass additional props to an already defined React component, or if it is possible at all.

For instance, given,

```<code>const foo = (
  <Foo
    bar={bar}
  />
);
</code>```

Having defined foo like above, Can I later expand the prop list of foo programmatically to include baz? i.e. as if I did the following to begin with?

```<code>const foo = (
  <Foo
    bar={bar}
    baz={baz}
  />
);
</code>```

答:
In that case you can do one this, instead of passing the values, pass some state object, latter if you want to pass more data just update the state value, automatically that value will get passed to child component.

```<code>data = {bar: bar};

const foo = (
  <Foo
    bar = {this.state.data}
  />
);
</code>```

Latter change the data to:

```<code>data = {bar: bar, a: a};
</code>```

Note: If you want to pass hug data then use some architecture like redux, don't store that data in state variable.

Check this example:

var Foo = (props) => {
   return(

         {props.data.a}

         {props.data.b ? props.data.b : null}

   )
}

class App extends React.Component{

   constructor(){
      super();
      this.state = {
          propsData: {a: 1}
      }
      this.click = this.click.bind(this);
   }

   click(){
      let propsData = Object.assign({},this.state.propsData);
      propsData.b = 2;
      this.setState({propsData});
   }

   render(){
      return(

            <Foo data={this.state.propsData}/>

                Click me pass more data to child

      )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I would like to know how to pass additional props to an already defined React component, or if it is possible at all.

For instance, given,

const foo = (
  <Foo
    bar={bar}
  />
);

Having defined foo like above, Can I later expand the prop list of foo programmatically to include baz? i.e. as if I did the following to begin with?

const foo = (
  <Foo
    bar={bar}
    baz={baz}
  />
);

Body:
In that case you can do one this, instead of passing the values, pass some state object, latter if you want to pass more data just update the state value, automatically that value will get passed to child component.

data = {bar: bar};

const foo = (
  <Foo
    bar = {this.state.data}
  />
);

Latter change the data to:

data = {bar: bar, a: a};

Note: If you want to pass hug data then use some architecture like redux, don't store that data in state variable.

Check this example:

var Foo = (props) => {
   return(
      <div>
         {props.data.a}
         <br/>
         {props.data.b ? props.data.b : null}
      </div>
   )
}

class App extends React.Component{

   constructor(){
      super();
      this.state = {
          propsData: {a: 1}
      }
      this.click = this.click.bind(this);
   }

   click(){
      let propsData = Object.assign({},this.state.propsData);
      propsData.b = 2;
      this.setState({propsData});
   }

   render(){
      return(
         <div>
            <Foo data={this.state.propsData}/>
            <p onClick={this.click} style={{marginTop: 100}}>
                Click me pass more data to child
            </p>
         </div>
      )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
Django: prevent saving empty form in formset
this should be a fairly easy one, but I am really struggling to figure it out by my self.

I am doing a real estate app and I need my users to be able to upload their images of houses. Each image is related to a House and each House is related to a User.

The way it is it works, but if the user submits an empty form with my formset the whole thing breaks, because it registers a non existent image to a User and a House. How can I prevent that?

Heres my View:

```<code>def photos_formset(request, *args, **kwargs):
    pk = kwargs['pk']
    ImovelPhotosModelFormset = modelformset_factory(ImovelPhotos, form=ImovelPhotosForm)
    formset = ImovelPhotosModelFormset(
            request.POST or None, request.FILES or None,
            queryset = Imovel.objects.get(pk=pk).imovelphotos_set.all(),
        )
    if formset.is_valid():
        for form in formset:
            if not request.FILES:
                break
            if form.is_valid():
                obj = form.save(commit=False)
                obj.user = request.user
                obj.imovel = Imovel.objects.get(pk=pk)
                obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))

    context = {
        "formset": formset,
    }
    return render(request, "imovel_photos.html", context)
</code>```

The thing that looked more like a potential answer was this, but it didn't work, if I do this nothing happens:

```<code>if form.is_valid() and not form.empty_permitted:
</code>```

答:
I had to identify which forms were coming with with an empty cleaned_data.
The following code did the trick.</p>

```<code>if formset.is_valid():
        if request.FILES:
            for form in formset:
                if form.is_valid():
                    if form.cleaned_data != {}:
                        obj = form.save(commit=False)
                        obj.user = request.user
                        obj.imovel = Imovel.objects.get(pk=pk)
                        obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))
</code>```

Body:
this should be a fairly easy one, but I am really struggling to figure it out by my self.

I am doing a real estate app and I need my users to be able to upload their images of houses. Each image is related to a House and each House is related to a User.

The way it is it works, but if the user submits an empty form with my formset the whole thing breaks, because it registers a non existent image to a User and a House. How can I prevent that?

Heres my View:

def photos_formset(request, *args, **kwargs):
    pk = kwargs['pk']
    ImovelPhotosModelFormset = modelformset_factory(ImovelPhotos, form=ImovelPhotosForm)
    formset = ImovelPhotosModelFormset(
            request.POST or None, request.FILES or None,
            queryset = Imovel.objects.get(pk=pk).imovelphotos_set.all(),
        )
    if formset.is_valid():
        for form in formset:
            if not request.FILES:
                break
            if form.is_valid():
                obj = form.save(commit=False)
                obj.user = request.user
                obj.imovel = Imovel.objects.get(pk=pk)
                obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))

    context = {
        "formset": formset,
    }
    return render(request, "imovel_photos.html", context)

The thing that looked more like a potential answer was this, but it didn't work, if I do this nothing happens:

if form.is_valid() and not form.empty_permitted:

Body:
I had to identify which forms were coming with with an empty cleaned_data.
The following code did the trick.

if formset.is_valid():
        if request.FILES:
            for form in formset:
                if form.is_valid():
                    if form.cleaned_data != {}:
                        obj = form.save(commit=False)
                        obj.user = request.user
                        obj.imovel = Imovel.objects.get(pk=pk)
                        obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))


问:
AspCore T4 Generation Adding Reference To System.Runtime.DLL
I'm writing a project that generates code.  I need to load System.Runtime.Dll into the T4 Generator as it does not seem to be apart of System.Core.Dll anymore

In previous version of the code this template header would of sufficed

```<code><#@ assembly name="System.Core" #>
</code>```

However, everything seems to be apart of the Nuget Packages now.  I would like a way to reference the System.Runtime.Dll v 4.1.0.0 universally so that it.

答:
After referencing the package via nuget you can do one of the following, if you are using asp.net core you can reference the package in your user folder (where all packages for all solutions are kept):

example:

```<code><#@ assembly name="$(UserProfile)\.nuget\packages\Humanizer.Core\2.1.0\lib\netstandard1.0\Humanizer.dll" #>
</code>```

or for pre .net core, reference the package form your solution folder:

example:

```<code><#@ assembly name="$(SolutionDir)\packages\Humanizer.1.37.7\lib\portable-win+net40+sl50+wp8+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Humanizer.dll" #>
</code>```

Body:
I'm writing a project that generates code.  I need to load System.Runtime.Dll into the T4 Generator as it does not seem to be apart of System.Core.Dll anymore

In previous version of the code this template header would of sufficed

<#@ assembly name="System.Core" #>

However, everything seems to be apart of the Nuget Packages now.  I would like a way to reference the System.Runtime.Dll v 4.1.0.0 universally so that it.

Body:
After referencing the package via nuget you can do one of the following, if you are using asp.net core you can reference the package in your user folder (where all packages for all solutions are kept):

example:

<#@ assembly name="$(UserProfile)\.nuget\packages\Humanizer.Core\2.1.0\lib\netstandard1.0\Humanizer.dll" #>

or for pre .net core, reference the package form your solution folder:

example:

<#@ assembly name="$(SolutionDir)\packages\Humanizer.1.37.7\lib\portable-win+net40+sl50+wp8+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Humanizer.dll" #>


问:
How to set Animation Slide Down to card view when click on arrow down in ViewHolder?
I tried to set slide down animation to card when the user click on the arrow down icon but it not work when I setAnimationListener(this). it error at "this" keyword.
Note I use recycler view and card in the fragment.
here my code below

```<code>class ListViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle, tvDescription;
        ImageView ivDropDown;
        LinearLayout ll_footer;
        Button btnClose;
        Animation slideDown;

        public ListViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
            ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
            ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
            btnClose = (Button) itemView.findViewById(R.id.btn_close);

            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                    ll_footer.setVisibility(View.GONE);
                }
            });

            ivDropDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callBack.onImageClick(getAdapterPosition());
                    slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                    ll_footer.setAnimation(slideDown);
                    slideDown.setAnimationListener();
                    ll_footer.setVisibility(View.VISIBLE);
                }
            });
        }
    }
</code>```

答:
```<code> Pass context from activity to adapter class using adapter constructor.
</code>```

Then use the following lines and remove animation listener.

```<code> slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                        ll_footer.startAnimation(slideDown);
</code>```

Body:
I tried to set slide down animation to card when the user click on the arrow down icon but it not work when I setAnimationListener(this). it error at "this" keyword.
Note I use recycler view and card in the fragment.
here my code below

class ListViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle, tvDescription;
        ImageView ivDropDown;
        LinearLayout ll_footer;
        Button btnClose;
        Animation slideDown;

        public ListViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
            ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
            ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
            btnClose = (Button) itemView.findViewById(R.id.btn_close);

            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                    ll_footer.setVisibility(View.GONE);
                }
            });

            ivDropDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callBack.onImageClick(getAdapterPosition());
                    slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                    ll_footer.setAnimation(slideDown);
                    slideDown.setAnimationListener();
                    ll_footer.setVisibility(View.VISIBLE);
                }
            });
        }
    }

Body:
 Pass context from activity to adapter class using adapter constructor.

Then use the following lines and remove animation listener.

 slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                        ll_footer.startAnimation(slideDown);


问:
Get data from text in UTF8 format URL
There is a text hosted on a server, in plain text but I try to get that data in UTF-8 format that is able to recognize "ñ" and more. I tried this

```<code>String readLine;
    try {
        URL url = new URL("http://miurl/data.txt");
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

        while ((readLine = in.readLine()) != null) {
           byte ptext[] = readLine.getBytes(ISO_8859_1);
           String value = new String(ptext, UTF_8);
           System.out.println(value);
        }

    }
    catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

The problem is that it reads data from url but not encoded as utf8, the letters such as "ñ" are printed strangely.

答:
I also had the same issue while reading some special characters from CSV file.
So I used below code to read the files

BufferedReader bufRdr = new BufferedReader(new InputStreamReader(new FileInputStream(userCsv), "ISO-8859-1"));

In your case you may try

```<code>URL url = new URL("http://miurl/data.txt");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-1"));
</code>```

Title: Get data from text in UTF8 format URL

Body:
There is a text hosted on a server, in plain text but I try to get that data in UTF-8 format that is able to recognize "ñ" and more. I tried this

String readLine;
    try {
        URL url = new URL("http://miurl/data.txt");
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

        while ((readLine = in.readLine()) != null) {
           byte ptext[] = readLine.getBytes(ISO_8859_1);
           String value = new String(ptext, UTF_8);
           System.out.println(value);
        }

    }
    catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

The problem is that it reads data from url but not encoded as utf8, the letters such as "ñ" are printed strangely.

Body:
I also had the same issue while reading some special characters from CSV file.
So I used below code to read the files

BufferedReader bufRdr = new BufferedReader(new InputStreamReader(new FileInputStream(userCsv), "ISO-8859-1"));

In your case you may try

URL url = new URL("http://miurl/data.txt");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-1"));


问:
Bash - how to count number of instructions?
I have a number of *.s assembly files. I would like to count how many instructions they contain. For example, to count all mul instructions I do:

```<code>cat *.s | grep -P '\t'"mul" | wc -l
</code>```

which gives me a compound number of all mul instructions.

I would like to have an output like:

```<code>mul: 893
add: 12054
sub: 2356
...
</code>```

The problem is that there is no table of instructions supported by a target platform. Each target platform has different set of instructions. The supported instructions must be deduced from existed assembly files. Can I do it in Bash only without Perl/Python foundry?

答:
Bash 4 without any external utilities:

```<code>declare -A c;while IFS=$'\n' read -r t;do [[ ! $t =~ ^[[:space:]] ]] && continue;w=($t);((c[${w[0]}]++));done<asm.s;for op in ${!c[@]};do echo $op ${c[$op]};done
</code>```

To do multiple files, wrap the while loop in a for f in *.s loop with the while's done like this: done < "$f" or do the while's done like this: done < <(cat *.s) instead of the for f.

Slightly shorter to count the first word on each line without regard to indentation:

```<code>declare -A c;while read -ra t;do [[ $t ]]&&((c[${t[0]}]++));done<asm.s;for op in ${!c[@]};do echo $op ${c[$op]};done
</code>```

Still, it's longer than the other answers.

Body:
I have a number of *.s assembly files. I would like to count how many instructions they contain. For example, to count all mul instructions I do:

cat *.s | grep -P '\t'"mul" | wc -l

which gives me a compound number of all mul instructions.

I would like to have an output like:

mul: 893
add: 12054
sub: 2356
...

The problem is that there is no table of instructions supported by a target platform. Each target platform has different set of instructions. The supported instructions must be deduced from existed assembly files. Can I do it in Bash only without Perl/Python foundry?

Body:
Bash 4 without any external utilities:

declare -A c;while IFS=$'\n' read -r t;do [[ ! $t =~ ^[[:space:]] ]] && continue;w=($t);((c[${w[0]}]++));done<asm.s;for op in ${!c[@]};do echo $op ${c[$op]};done

To do multiple files, wrap the while loop in a for f in *.s loop with the while's done like this: done < "$f" or do the while's done like this: done < <(cat *.s) instead of the for f.

Slightly shorter to count the first word on each line without regard to indentation:

declare -A c;while read -ra t;do [[ $t ]]&&((c[${t[0]}]++));done<asm.s;for op in ${!c[@]};do echo $op ${c[$op]};done

Still, it's longer than the other answers.


问:
replace multiple values in json/jsObject/string
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

```<code>[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]
</code>```

now my custom map is like this

```<code>const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};
</code>```

All I want is

```<code>[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]
</code>```

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))

答:
Will it be faster as compared to tree traverser?

I don't know. I think it would depend on the size of the input, and the size of the replacement map. You could run some tests at JSPerf.com.

If yes, how should I do that?

It's fairly easy to do with a regex-based string replacement if the values you are replacing don't need any special escaping or whatever. Something like this:

const input = [
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
];

const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};

// create a regex that matches any of the map keys, adding ':' and quotes
// to be sure to match whole property values and not property names
const regex = new RegExp(':\\s*"(' + Object.keys(map).join('|') + ')"', 'g');

// NOTE: if you've received this data as JSON then do the replacement
// *before* parsing it, don't parse it then restringify it then reparse it.
const json = JSON.stringify(input);
const result = JSON.parse(
  json.replace(regex, function(m, key) { return ': "' + map[key] + '"'; })
);

console.log(result);```

Body:
I have a response from a web service and want to replace some values in the response with my custom values.

One way is to write a tree traverser and then check for the value and replace with my custom value

so the response is some what like this:

[
  {
    "name": "n1",
    "value": "v1",
    "children": [
      {
        "name": "n2",
        "value": "v2"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v3"
  }
]

now my custom map is like this

const map = {
  "v1": "v11",
  "v2": "v22",
  "v3": "v33"
};

All I want is

[
  {
    "name": "n1",
    "value": "v11",
    "children": [
      {
        "name": "n2",
        "value": "v22"
      }
    ]
  },
  {
    "name": "n3",
    "value": "v33"
  }
]

I was thinking if I could stringify my response and then replace values using a custom build regex from my map of values.

Will it be faster as compared to tree traverser?

If yes, how should I do that?

somewhat like this

originalString.replace(regexp, function (replacement))


问:
When and how to give up cpu in a busy kernel thread loop?
I'm writing a Linux module, in which I have a loop to process work like below:

```<code>while (1) {
    while (there's work) {
        process_work
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}
</code>```

When there's lots of work, it would result in softlockup. The message is like this:

```<code>[ 1426.067061] BUG: soft lockup - CPU#3 stuck for 23s! [comp_wqa:2969]
[ 1426.067903] Modules linked in: testmodule(OE+) xt_CHECKSUM ipt_MASQUERADE nf_nat_masquerade_ipv4 tun ip6t_rpfilter ip6t_REJECT ipt_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_nat nf_conntrack_ipv6 nf_defrag_ipv6 nf_nat_ipv6 ip6table_mangle ip6table_security ip6table_raw ip6table_filter ip6_tables iptable_nat nf_conntrack_ipv4 nf_defrag_ipv4 nf_nat_ipv4 nf_nat nf_conntrack iptable_mangle iptable_security iptable_raw iptable_filter hwmon_vid dm_mirror dm_region_hash dm_log dm_mod snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic intel_powerclamp coretemp intel_rapl kvm eeepc_wmi crc32_pclmul asus_wmi ghash_clmulni_intel sparse_keymap rfkill mxm_wmi aesni_intel wmi lrw snd_hda_intel gf128mul glue_helper snd_hda_codec pcspkr ablk_helper sg
[ 1426.067924]  cryptd shpchp snd_hda_core snd_hwdep snd_seq snd_seq_device snd_pcm tpm_infineon acpi_pad snd_timer mei_me mei snd soundcore nfsd auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 sd_mod crc_t10dif crct10dif_generic crct10dif_pclmul crct10dif_common crc32c_intel serio_raw i915 ahci libahci libata i2c_algo_bit drm_kms_helper drm e1000e ptp pps_core i2c_core video
[ 1426.067939] CPU: 3 PID: 2969 Comm: comp_wqa Tainted: G           OE  ------------   3.10.0-327.28.3.el7.x86_64 #1
[ 1426.067940] Hardware name: ASUS All Series/Z97-A, BIOS 2401 04/24/2015
[ 1426.067941] task: ffff88080f212280 ti: ffff880810a68000 task.ti: ffff880810a68000
[ 1426.067942] RIP: 0010:[<ffffffff8107e11f>]  [<ffffffff8107e11f>] vprintk_emit+0x1bf/0x530
[ 1426.067946] RSP: 0018:ffff880810a6bbc0  EFLAGS: 00000246
[ 1426.067947] RAX: 0000000000000001 RBX: 0000000000000003 RCX: 0000000000000000
[ 1426.067948] RDX: 0000000000000001 RSI: ffff88083fb8f6c8 RDI: 0000000000000246
[ 1426.067948] RBP: ffff880810a6bc20 R08: 0000000000000092 R09: 0000000000007d0d
[ 1426.067949] R10: 0000000000008000 R11: ffffc90023effff8 R12: 0000000000000081
[ 1426.067950] R13: ffffffff81a08020 R14: 000000009176cc6c R15: 0000000000000000
[ 1426.067951] FS:  0000000000000000(0000) GS:ffff88083fb80000(0000) knlGS:0000000000000000
[ 1426.067951] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1426.067952] CR2: 00007f42411ff00e CR3: 000000000194a000 CR4: 00000000001407e0
[ 1426.067953] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 1426.067954] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 1426.067954] Stack:
[ 1426.067955]  ffffffff81cae082 0000000000000071 0000000000000000 ffff880810a6bc40
[ 1426.067956]  ffffffffa07a45a0 000000008116c24e 0000000000000246 ffff8807dfbba800
[ 1426.067958]  ffff880810a70000 ffff8807dfbc5030 ffff8807dfbc4e00 ffff8807e65b3000
[ 1426.067959] Call Trace:
</code>```

So after some googling, I change the code to the following:

```<code>while (1) {
    while (there's work) {
        process_work
        cond_resched()
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}
</code>```

And with this code, the softlockups happens less likely. But still, it happens with heavier load. I thought if this thread had been occupying the cpu for long, then cond_resched would give up the cpu. I guess I was wrong.

I want to know how should the softlockups be avoided and at the same without being idle too much (I want the module process lots of work withou long latency).

After thinking more about this, I realize what I want is just make a cpu core run a dedicate thread, without being interrupted. It seems the kernel doesn't support this directly. There is a kernel parameter called watchdog_thresh which decides how many seconds can a thread continuously run. I have read other posts that suggest this kind of softlockups is harmless. And I now understand more deeply that the performance of my driver is heavily dependent on single cpu core performance, since I have to process the work with a single thread.

答:
There is a fundamental difference between writing user-space code and kernel code. Bad user code (with respect to scheduling) is often handled (read corrected) by the kernel, whereas bad kernel code is deadly -- there are many ways you can kill the entire machine when writing kernel code.
So the answer to your question is you must absolutely design this on paper first. Specifically, unlike writing user code, you must think about the scheduling and design something that will work for you. There are two basic questions to ask and of course to answer:

When does my task run?

When do all of the other tasks on the system run?

Note that you have not answered the second one.
Once you have the answers (they will define how the CPU will migrate from one task to another) you can start thinking about how to implement that.
Make sure you understand the current behavior; it will really help you with the relevant concepts. The soft lockup means your task is 1) holding the CPU and 2) not allowing the kernel to preempt it (for a long time). Find out why this task can't be preempted (let's hope it's not holding a spinlock). You mention wanting to avoid "being idle"; I am not sure if you mean "your task not running" or "the CPU being idle". Those are two very different cases -- your task must let all other tasks in the system run (as hinted above) so it will very definitely not run when the other tasks run, but you don't necessarily ever have to have an idle CPU, if you have "lots of work". If your goal is avoiding the latter, you are right -- it is often the result of a poor design (throwing in msleep(), instead of taking time to work out the appropriate scheduling algorithm/parameters).

As I said, the first step, before you write a single line of code, is to be able to describe how and when your task will run.

Body:
I'm writing a Linux module, in which I have a loop to process work like below:

while (1) {
    while (there's work) {
        process_work
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}

When there's lots of work, it would result in softlockup. The message is like this:

[ 1426.067061] BUG: soft lockup - CPU#3 stuck for 23s! [comp_wqa:2969]
[ 1426.067903] Modules linked in: testmodule(OE+) xt_CHECKSUM ipt_MASQUERADE nf_nat_masquerade_ipv4 tun ip6t_rpfilter ip6t_REJECT ipt_REJECT xt_conntrack ebtable_nat ebtable_broute bridge stp llc ebtable_filter ebtables ip6table_nat nf_conntrack_ipv6 nf_defrag_ipv6 nf_nat_ipv6 ip6table_mangle ip6table_security ip6table_raw ip6table_filter ip6_tables iptable_nat nf_conntrack_ipv4 nf_defrag_ipv4 nf_nat_ipv4 nf_nat nf_conntrack iptable_mangle iptable_security iptable_raw iptable_filter hwmon_vid dm_mirror dm_region_hash dm_log dm_mod snd_hda_codec_realtek snd_hda_codec_hdmi snd_hda_codec_generic intel_powerclamp coretemp intel_rapl kvm eeepc_wmi crc32_pclmul asus_wmi ghash_clmulni_intel sparse_keymap rfkill mxm_wmi aesni_intel wmi lrw snd_hda_intel gf128mul glue_helper snd_hda_codec pcspkr ablk_helper sg
[ 1426.067924]  cryptd shpchp snd_hda_core snd_hwdep snd_seq snd_seq_device snd_pcm tpm_infineon acpi_pad snd_timer mei_me mei snd soundcore nfsd auth_rpcgss nfs_acl lockd grace sunrpc ip_tables ext4 mbcache jbd2 sd_mod crc_t10dif crct10dif_generic crct10dif_pclmul crct10dif_common crc32c_intel serio_raw i915 ahci libahci libata i2c_algo_bit drm_kms_helper drm e1000e ptp pps_core i2c_core video
[ 1426.067939] CPU: 3 PID: 2969 Comm: comp_wqa Tainted: G           OE  ------------   3.10.0-327.28.3.el7.x86_64 #1
[ 1426.067940] Hardware name: ASUS All Series/Z97-A, BIOS 2401 04/24/2015
[ 1426.067941] task: ffff88080f212280 ti: ffff880810a68000 task.ti: ffff880810a68000
[ 1426.067942] RIP: 0010:[<ffffffff8107e11f>]  [<ffffffff8107e11f>] vprintk_emit+0x1bf/0x530
[ 1426.067946] RSP: 0018:ffff880810a6bbc0  EFLAGS: 00000246
[ 1426.067947] RAX: 0000000000000001 RBX: 0000000000000003 RCX: 0000000000000000
[ 1426.067948] RDX: 0000000000000001 RSI: ffff88083fb8f6c8 RDI: 0000000000000246
[ 1426.067948] RBP: ffff880810a6bc20 R08: 0000000000000092 R09: 0000000000007d0d
[ 1426.067949] R10: 0000000000008000 R11: ffffc90023effff8 R12: 0000000000000081
[ 1426.067950] R13: ffffffff81a08020 R14: 000000009176cc6c R15: 0000000000000000
[ 1426.067951] FS:  0000000000000000(0000) GS:ffff88083fb80000(0000) knlGS:0000000000000000
[ 1426.067951] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1426.067952] CR2: 00007f42411ff00e CR3: 000000000194a000 CR4: 00000000001407e0
[ 1426.067953] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 1426.067954] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 1426.067954] Stack:
[ 1426.067955]  ffffffff81cae082 0000000000000071 0000000000000000 ffff880810a6bc40
[ 1426.067956]  ffffffffa07a45a0 000000008116c24e 0000000000000246 ffff8807dfbba800
[ 1426.067958]  ffff880810a70000 ffff8807dfbc5030 ffff8807dfbc4e00 ffff8807e65b3000
[ 1426.067959] Call Trace:

So after some googling, I change the code to the following:

while (1) {
    while (there's work) {
        process_work
        cond_resched()
    }
    if (should_stop)
        break
    sleep  // wait to be woken up
}

And with this code, the softlockups happens less likely. But still, it happens with heavier load. I thought if this thread had been occupying the cpu for long, then cond_resched would give up the cpu. I guess I was wrong.

I want to know how should the softlockups be avoided and at the same without being idle too much (I want the module process lots of work withou long latency).

After thinking more about this, I realize what I want is just make a cpu core run a dedicate thread, without being interrupted. It seems the kernel doesn't support this directly. There is a kernel parameter called watchdog_thresh which decides how many seconds can a thread continuously run. I have read other posts that suggest this kind of softlockups is harmless. And I now understand more deeply that the performance of my driver is heavily dependent on single cpu core performance, since I have to process the work with a single thread.


问:
C++ Rest SDK Casablanca Sigtrap
I am using the C++ Rest SDK ("Casablanca") to receive feed from Websocket-Servers. Currently, I have three different connections to three different servers running at the same time using the websocket_callback_client class.

The program runs for an undefined time and then suddenly receives SIGTRAP, Trace/ Breakpoint trap. This is the output of GDB:

```<code>#0  0x00007ffff5abec37 in __GI_raise (sig=5) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1  0x000000000047bb8e in pplx::details::_ExceptionHolder::~_ExceptionHolder() ()
#2  0x000000000044be29 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() ()
#3  0x000000000047fa39 in pplx::details::_Task_impl<unsigned char>::~_Task_impl() ()
#4  0x000000000044be29 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() ()
#5  0x00007ffff6feb09f in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7fffc8021420, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr_base.h:546
#6  0x00007ffff6fffa38 in std::__shared_ptr<pplx::details::_Task_impl<unsigned char>, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7fffc8021418, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr_base.h:781
#7  0x00007ffff6fffa52 in std::shared_ptr<pplx::details::_Task_impl<unsigned char> >::~shared_ptr (this=0x7fffc8021418, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr.h:93
#8  0x00007ffff710f766 in pplx::details::_PPLTaskHandle<unsigned char, pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>, pplx::details::_TaskProcHandle>::~_PPLTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>)
    at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:1631
#9  0x00007ffff716e6f2 in pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>::~_InitialTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>) at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:3710
#10 0x00007ffff716e722 in pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>::~_InitialTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>) at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:3710
#11 0x00007ffff71f9cdd in boost::_bi::list1<boost::_bi::value<void*> >::operator()<void (*)(void*), boost::_bi::list0> (this=0x7fffdc7d7d28, f=@0x7fffdc7d7d20: 0x479180 <pplx::details::_TaskProcHandle::_RunChoreBridge(void*)>, a=...)
    at /usr/local/include/boost/bind/bind.hpp:259
#12 0x00007ffff71f9c8f in boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > >::operator() (this=0x7fffdc7d7d20) at /usr/local/include/boost/bind/bind.hpp:1222
#13 0x00007ffff71f9c54 in boost::asio::asio_handler_invoke<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > > (function=...) at /usr/local/include/boost/asio/handler_invoke_hook.hpp:69
#14 0x00007ffff71f9bea in boost_asio_handler_invoke_helpers::invoke<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > >, boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > > (function=..., context=...) at /usr/local/include/boost/asio/detail/handler_invoke_helpers.hpp:37
#15 0x00007ffff71f9b2e in boost::asio::detail::completion_handler<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > >::do_complete (owner=0x7488d0, base=0x7fffc801ecd0)
    at /usr/local/include/boost/asio/detail/completion_handler.hpp:68
#16 0x00000000004c34c1 in boost::asio::detail::task_io_service::run(boost::system::error_code&) ()
#17 0x00007ffff709fb27 in boost::asio::io_service::run (this=0x7ffff759ab78 <crossplat::threadpool::shared_instance()::s_shared+24>) at /usr/local/include/boost/asio/impl/io_service.ipp:59
#18 0x00007ffff7185a81 in crossplat::threadpool::thread_start (arg=0x7ffff759ab60 <crossplat::threadpool::shared_instance()::s_shared>) at /home/cpprestsdk/Release/include/pplx/threadpool.h:133
#19 0x00007ffff566e184 in start_thread (arg=0x7fffdc7d8700) at pthread_create.c:312
#20 0x00007ffff5b8237d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111
</code>```

At line #18 the soruce /pplx/threadpool.h:133 is given.
This is the source-code around these lines:

```<code>  123     static void* thread_start(void *arg)
  124     {
  125 #if (defined(ANDROID) || defined(__ANDROID__))
  126         // Calling get_jvm_env() here forces the thread to be attached.
  127         get_jvm_env();
  128         pthread_cleanup_push(detach_from_java, nullptr);
  129 #endif
  130         threadpool* _this = reinterpret_cast<threadpool*>(arg);
  131         try
  132         {
  133             _this->m_service.run();
  134         }
  135         catch (const _cancel_thread&)
  136         {
  137             // thread was cancelled
  138         }
  139         catch (...)
  140         {
  141             // Something bad happened
  142 #if (defined(ANDROID) || defined(__ANDROID__))
  143             // Reach into the depths of the 'droid!
  144             // NOTE: Uses internals of the bionic library
  145             // Written against android ndk r9d, 7/26/2014
  146             __pthread_cleanup_pop(&__cleanup, true);
  147             throw;
  148 #endif
  149         }
  150 #if (defined(ANDROID) || defined(__ANDROID__))
  151         pthread_cleanup_pop(true);
  152 #endif
  153         return arg;
  154     }
</code>```

For clarification, m_service is a boost::asio::io_service.
To me it looks like line #133 throws an exception, it gets caught at line #139 and then rethrown. At this point, I have to catch it personally, because if I don't and the pplx-object gets destroyed with an uncaught exception, it will raise SIGTRAP.

This is how far I got with my research. The problem is I do not have a clue where this is happening. I have surrounded every position where data is sent through or received from websocket_callback_client with try {} catch(...){} and it is still happening.

Maybe someone who has used this library before can help me out.

答:
In my experience this happens due to a separate issue.

When the websocket_callback_client's close handler gets called, most people try to delete the websocket_callback_client. This internally calls the close function.

When this happens the websocket_callback_client will wait for the close to finish. If another thread realizes the connection is dead and tries to clean up you will have the same object being deleted from 2 different locations, which will cause major issues.

Howto reconnect to a server which does not answer to close() has a fairly thorough review of what happens when cpprestsdk calls close.

Hope this helps :)

Edit:
As it turns out (the response I gave in the linked question has this), if you try to close or delete the websocket_callback_client from the close handler it will itself call the close handler, which will lock the thread.

The solution I have found that works best for me is to set a flag in the close handler and handle the cleanup in the main thread or at the very least an alternate thread.

Title: C++ Rest SDK Casablanca Sigtrap

Body:
I am using the C++ Rest SDK ("Casablanca") to receive feed from Websocket-Servers. Currently, I have three different connections to three different servers running at the same time using the websocket_callback_client class.

The program runs for an undefined time and then suddenly receives SIGTRAP, Trace/ Breakpoint trap. This is the output of GDB:

#0  0x00007ffff5abec37 in __GI_raise (sig=5) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1  0x000000000047bb8e in pplx::details::_ExceptionHolder::~_ExceptionHolder() ()
#2  0x000000000044be29 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() ()
#3  0x000000000047fa39 in pplx::details::_Task_impl<unsigned char>::~_Task_impl() ()
#4  0x000000000044be29 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() ()
#5  0x00007ffff6feb09f in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7fffc8021420, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr_base.h:546
#6  0x00007ffff6fffa38 in std::__shared_ptr<pplx::details::_Task_impl<unsigned char>, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7fffc8021418, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr_base.h:781
#7  0x00007ffff6fffa52 in std::shared_ptr<pplx::details::_Task_impl<unsigned char> >::~shared_ptr (this=0x7fffc8021418, __in_chrg=<optimized out>) at /usr/include/c++/4.8/bits/shared_ptr.h:93
#8  0x00007ffff710f766 in pplx::details::_PPLTaskHandle<unsigned char, pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>, pplx::details::_TaskProcHandle>::~_PPLTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>)
    at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:1631
#9  0x00007ffff716e6f2 in pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>::~_InitialTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>) at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:3710
#10 0x00007ffff716e722 in pplx::task<unsigned char>::_InitialTaskHandle<void, void web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<websocketpp::config::asio_tls_client>(std::weak_ptr<void> const&, bool)::{lambda()#1}, pplx::details::_TypeSelectorNoAsync>::~_InitialTaskHandle() (this=0x7fffc8021410, __in_chrg=<optimized out>) at /home/cpprestsdk/Release/include/pplx/pplxtasks.h:3710
#11 0x00007ffff71f9cdd in boost::_bi::list1<boost::_bi::value<void*> >::operator()<void (*)(void*), boost::_bi::list0> (this=0x7fffdc7d7d28, f=@0x7fffdc7d7d20: 0x479180 <pplx::details::_TaskProcHandle::_RunChoreBridge(void*)>, a=...)
    at /usr/local/include/boost/bind/bind.hpp:259
#12 0x00007ffff71f9c8f in boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > >::operator() (this=0x7fffdc7d7d20) at /usr/local/include/boost/bind/bind.hpp:1222
#13 0x00007ffff71f9c54 in boost::asio::asio_handler_invoke<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > > (function=...) at /usr/local/include/boost/asio/handler_invoke_hook.hpp:69
#14 0x00007ffff71f9bea in boost_asio_handler_invoke_helpers::invoke<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > >, boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > > (function=..., context=...) at /usr/local/include/boost/asio/detail/handler_invoke_helpers.hpp:37
#15 0x00007ffff71f9b2e in boost::asio::detail::completion_handler<boost::_bi::bind_t<void, void (*)(void*), boost::_bi::list1<boost::_bi::value<void*> > > >::do_complete (owner=0x7488d0, base=0x7fffc801ecd0)
    at /usr/local/include/boost/asio/detail/completion_handler.hpp:68
#16 0x00000000004c34c1 in boost::asio::detail::task_io_service::run(boost::system::error_code&) ()
#17 0x00007ffff709fb27 in boost::asio::io_service::run (this=0x7ffff759ab78 <crossplat::threadpool::shared_instance()::s_shared+24>) at /usr/local/include/boost/asio/impl/io_service.ipp:59
#18 0x00007ffff7185a81 in crossplat::threadpool::thread_start (arg=0x7ffff759ab60 <crossplat::threadpool::shared_instance()::s_shared>) at /home/cpprestsdk/Release/include/pplx/threadpool.h:133
#19 0x00007ffff566e184 in start_thread (arg=0x7fffdc7d8700) at pthread_create.c:312
#20 0x00007ffff5b8237d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111

At line #18 the soruce /pplx/threadpool.h:133 is given.
This is the source-code around these lines:

  123     static void* thread_start(void *arg)
  124     {
  125 #if (defined(ANDROID) || defined(__ANDROID__))
  126         // Calling get_jvm_env() here forces the thread to be attached.
  127         get_jvm_env();
  128         pthread_cleanup_push(detach_from_java, nullptr);
  129 #endif
  130         threadpool* _this = reinterpret_cast<threadpool*>(arg);
  131         try
  132         {
  133             _this->m_service.run();
  134         }
  135         catch (const _cancel_thread&)
  136         {
  137             // thread was cancelled
  138         }
  139         catch (...)
  140         {
  141             // Something bad happened
  142 #if (defined(ANDROID) || defined(__ANDROID__))
  143             // Reach into the depths of the 'droid!
  144             // NOTE: Uses internals of the bionic library
  145             // Written against android ndk r9d, 7/26/2014
  146             __pthread_cleanup_pop(&__cleanup, true);
  147             throw;
  148 #endif
  149         }
  150 #if (defined(ANDROID) || defined(__ANDROID__))
  151         pthread_cleanup_pop(true);
  152 #endif
  153         return arg;
  154     }

For clarification, m_service is a boost::asio::io_service.
To me it looks like line #133 throws an exception, it gets caught at line #139 and then rethrown. At this point, I have to catch it personally, because if I don't and the pplx-object gets destroyed with an uncaught exception, it will raise SIGTRAP.

This is how far I got with my research. The problem is I do not have a clue where this is happening. I have surrounded every position where data is sent through or received from websocket_callback_client with try {} catch(...){} and it is still happening.

Maybe someone who has used this library before can help me out.


答:
If you have a datetime you can use strftime()

```<code>your_time.strftime('%Y%m%d.%H%M%S')
</code>```

And if your variables are string, You can use replace()

```<code>dt = '2015-05-13 23:53:00'
date = dt.split()[0].replace('-','')
time = dt.split()[1].replace(':','')
fl = float(date+ '.' + time)
</code>```

Title: Converting date and time into float in python

Body:
Below is my data set

  Date         Time
  2015-05-13   23:53:00

I want to convert date and time into floats as separate columns in a python script.

The output should be like date as 20150513 and time as 235300

Body:
If you have a datetime you can use strftime()

your_time.strftime('%Y%m%d.%H%M%S')

And if your variables are string, You can use replace()

dt = '2015-05-13 23:53:00'
date = dt.split()[0].replace('-','')
time = dt.split()[1].replace(':','')
fl = float(date+ '.' + time)


问:
Express parameterized route conflict
I have two routes in Express 4.13 app:

```<code>router.get('/:id', function (req, res) {
});

router.get('/new', function(req,res){
});
</code>```

But when I'm trying to access /new - I get 404, because there is no 'new' object. So how can I change set up that I can access /new route without confusion with /:id route.

Thanks.

答:
Do it like this . Dynamic api should be on bottom

```<code>router.get('/new', function(req,res){
});

router.get('/:id', function (req, res) {
});
</code>```

Title: Express parameterized route conflict

Body:
I have two routes in Express 4.13 app:

router.get('/:id', function (req, res) {
});

router.get('/new', function(req,res){
});

But when I'm trying to access /new - I get 404, because there is no 'new' object. So how can I change set up that I can access /new route without confusion with /:id route.

Thanks.

Body:
Do it like this . Dynamic api should be on bottom

router.get('/new', function(req,res){
});

router.get('/:id', function (req, res) {
});