问:
Append DOM element not working with jQuery selectable
Try to move selected item from one List to Another but append dom element not working:

//Assign action modules
    $('#Modal_Task #assigned_module').click(function () {
        var list = $("#Modal_Task .unassigned li.ui-selected");
        $('#Modal_Task .assigned').append(list);
        list.remove();
    });

//UnAssign action modules
    $('#Modal_Task #unassigned_module').click(function () {
        var list = $("#Modal_Task .assigned li.ui-selected");
        $('#Modal_Task .unassigned').append(list);
        list.remove();
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal fade in" id="Modal_Task" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;"><div class="modal-backdrop fade in"></div>
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Link Tasks</h4>
                </div>
                <div class="modal-body">
                    <div class="row" id="actionee_modal">
                        <div id="info_message_task" class="alert hidden-element dv-message"></div>
                        <div class="col-md-4 side-box">
                            <label>Unassigned:</label>
                            <div class="selectable-wraper">
                                <ul class="unassigned selectable ui-selectable"><li data-id="3" class="ui-selectee"><strong class="ui-selectee">Title 3</strong></li><li data-id="2" class="ui-selectee"><strong class="ui-selectee">Title 2</strong></li></ul>
                            </div>
                        </div>
                        <div class="col-md-2 center-box">
                            <label>Action</label>
                            <button type="button" class="btn btn-success btn-xs" id="assigned_module"><i class="fa fa-arrow-circle-right"></i></button>
                            <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"><i class="fa fa-arrow-circle-left"></i></button>
                        </div>
                        <div class="col-md-4 side-box">
                            <label>Assigned:</label>
                            <div class="selectable-wraper">
                                <ul class="assigned selectable ui-selectable"></ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save_task">Save changes</button>
                </div>
            </div>
        </div>
    </div></code>```

答:
You have typos ui-selectee -> ui-selected

Ur adding the element then instanly removing it. Add a clone.

$('#Modal_Task #assigned_module').click(function () {
    var list = $("#Modal_Task .unassigned li.ui-selected");
      $('#Modal_Task .assigned').append(list.clone());
    list.remove();
});

$('#Modal_Task #unassigned_module').click(function () {
    var list = $("#Modal_Task .assigned li.ui-selected");
    $('#Modal_Task .unassigned').append(list.clone());
    list.remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal fade in" id="Modal_Task" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
  <div class="modal-backdrop fade in"></div>
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">Link Tasks</h4>
        </div>
        <div class="modal-body">
          <div class="row" id="actionee_modal">
            <div id="info_message_task" class="alert hidden-element dv-message"></div>
              <div class="col-md-4 side-box">
                <label>Unassigned:</label>
                <div class="selectable-wraper">
                  <ul class="unassigned selectable ui-selectable">
                    <li data-id="3" class="ui-selected">
                      <strong class="ui-selected">Title 3</strong>
                    </li>
                    <li data-id="2" class="ui-selected">
                      <strong class="ui-selected">Title 2</strong>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="col-md-2 center-box">
                <label>Action</label>
                <button type="button" class="btn btn-success btn-xs" id="assigned_module"><i class="fa fa-arrow-circle-right">1</i></button>
                <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"><i class="fa fa-arrow-circle-left">2</i></button>
              </div>
              <div class="col-md-4 side-box">
                <label>Assigned:</label>
                <div class="selectable-wraper">
                  <ul class="assigned selectable ui-selectable"></ul>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="save_task">Save changes</button>
          </div>
        </div>
      </div>
  </div></code>```

Body:
Try to move selected item from one List to Another but append dom element not working:

//Assign action modules
    $('#Modal_Task #assigned_module').click(function () {
        var list = $("#Modal_Task .unassigned li.ui-selected");
        $('#Modal_Task .assigned').append(list);
        list.remove();
    });

//UnAssign action modules
    $('#Modal_Task #unassigned_module').click(function () {
        var list = $("#Modal_Task .assigned li.ui-selected");
        $('#Modal_Task .unassigned').append(list);
        list.remove();
    });

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

Link Tasks

                            Unassigned:

Title 3

Title 2

                            Action
                            <button type="button" class="btn btn-success btn-xs" id="assigned_module"></button>
                            <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"></button>

                            Assigned:

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save_task">Save changes</button>

Body:
You have typos ui-selectee -> ui-selected

Ur adding the element then instanly removing it. Add a clone.

$('#Modal_Task #assigned_module').click(function () {
    var list = $("#Modal_Task .unassigned li.ui-selected");
      $('#Modal_Task .assigned').append(list.clone());
    list.remove();
});

$('#Modal_Task #unassigned_module').click(function () {
    var list = $("#Modal_Task .assigned li.ui-selected");
    $('#Modal_Task .unassigned').append(list.clone());
    list.remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal fade in" id="Modal_Task" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
  <div class="modal-backdrop fade in"></div>
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">Link Tasks</h4>
        </div>
        <div class="modal-body">
          <div class="row" id="actionee_modal">
            <div id="info_message_task" class="alert hidden-element dv-message"></div>
              <div class="col-md-4 side-box">
                <label>Unassigned:</label>
                <div class="selectable-wraper">
                  <ul class="unassigned selectable ui-selectable">
                    <li data-id="3" class="ui-selected">
                      <strong class="ui-selected">Title 3</strong>
                    </li>
                    <li data-id="2" class="ui-selected">
                      <strong class="ui-selected">Title 2</strong>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="col-md-2 center-box">
                <label>Action</label>
                <button type="button" class="btn btn-success btn-xs" id="assigned_module"><i class="fa fa-arrow-circle-right">1</i></button>
                <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"><i class="fa fa-arrow-circle-left">2</i></button>
              </div>
              <div class="col-md-4 side-box">
                <label>Assigned:</label>
                <div class="selectable-wraper">
                  <ul class="assigned selectable ui-selectable"></ul>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="save_task">Save changes</button>
          </div>
        </div>
      </div>
  </div>


来源: stackexchange

问:
Global type doesn't work in Webstorm
I started using Flow with webstorm and IDE can't intercept global type which I declared (while flow compiler doesn't complain).

flow-typed/libDefs.js

```<code>// @flow
import type { UI } from 'data/redux/redux.flow';
declare var module: {
  hot:? {
    accept(reducers:? string, func:? Function): any,
  }
};

declare type State = {| //btw. eslint gives me here error 'no-undef' State is not defined
  +ui: UI,
|}
</code>```

src/data/redux/reducers/ui.js

答: Known issue, please follow WEB-27102 for updates. </p>

ContentLicense: CC BY-SA 3.0

Title: Global type doesn't work in Webstorm

Body:
I started using Flow with webstorm and IDE can't intercept global type which I declared (while flow compiler doesn't complain).

flow-typed/libDefs.js

// @flow
import type { UI } from 'data/redux/redux.flow';
declare var module: {
  hot:? {
    accept(reducers:? string, func:? Function): any,
  }
};

declare type State = {| //btw. eslint gives me here error 'no-undef' State is not defined
  +ui: UI,
|}

src/data/redux/reducers/ui.js


问:
Is there a JQuery plugin for displaying default text in a text field?
When I hit the page, the text box says "Search...", in gray font.

Then, I click the textbox.  Then, the "search..." disappears. And I can type.

答: What you're looking for is called a watermark effect. You can find appropriate jQuery plugins here.

ContentLicense: CC BY-SA 2.5


问:
Printing top three repeated elements in LCD display
I have an array whose input is given by the user by using keypad. All the inputs are stored in an array named storeKeys. The index of the array is held by a variable storeKeysIndex is initialized to 0 and when a key is pressed, the value of pressed key is stored in storeKeys array and the value of storeKeysIndex is incremented. Let the storeKeys have values

```<code>storeKeys = {3,2,5,7,1,1,9,9,9,1,3,1};
</code>```

I want the lcd to display the top three repeated elements in the array. In above array, lcd should display 1,9,3 since value '1' is repeated four times in the above array, '9' is repeated three times, '3' is repeated two times. Other values should not be displayed by lcd.

I have tried to count the frequency of each element and store the frequencies in an array freq. I can display the frequency of each element in the serial monitor. But I'm not getting how to display the top three repeated numbers on the lcd (or in serial monitor). Here is the code:

```<code>for(int i=0; i<12; i++)
{
    freq[i] = -1;
}
for(int i=0; i<12; i++)
{
    count = 1;
    for(int j=i+1; j<12; j++)
    {
        if(storeKeys[i] == storeKeys[j])
        {
            count++;
            freq[j] = 0;
        }
    }

    if(freq[i]!=0)
    {
        freq[i] = count;
    }
}
for(int i=0; i<12; i++)
{
    if(freq[i]!=0 && storeKeys[i] != NULL)
    {
        Serial.println(storeKeys[i]);
        Serial.println(freq[i]);
        Serial.println("==========");
    }
}
</code>```

The above code works but displaying frequency of all elements. I want to display the top three repeated elements only.

Here is the link for simulator online:

https://circuits.io/circuits/5073094-the-unnamed-circuit/edit

Thanks.

答:
The answer is from here

Sort your frequency array with the below function and then only take the last three elements of sorted array.

```<code> void sort(int a[], int size)
 {
   for(int i=0; i<(size-1); i++)
   {
    for(int o=0; o<(size-(i+1)); o++)
       {
            if(a[o] > a[o+1])
            {
                int t = a[o];
                a[o] = a[o+1];
                a[o+1] = t;
            }
        }
    }

  }
</code>```

Body:
I have an array whose input is given by the user by using keypad. All the inputs are stored in an array named storeKeys. The index of the array is held by a variable storeKeysIndex is initialized to 0 and when a key is pressed, the value of pressed key is stored in storeKeys array and the value of storeKeysIndex is incremented. Let the storeKeys have values

storeKeys = {3,2,5,7,1,1,9,9,9,1,3,1};

I want the lcd to display the top three repeated elements in the array. In above array, lcd should display 1,9,3 since value '1' is repeated four times in the above array, '9' is repeated three times, '3' is repeated two times. Other values should not be displayed by lcd.

I have tried to count the frequency of each element and store the frequencies in an array freq. I can display the frequency of each element in the serial monitor. But I'm not getting how to display the top three repeated numbers on the lcd (or in serial monitor). Here is the code:

for(int i=0; i<12; i++)
{
    freq[i] = -1;
}
for(int i=0; i<12; i++)
{
    count = 1;
    for(int j=i+1; j<12; j++)
    {
        if(storeKeys[i] == storeKeys[j])
        {
            count++;
            freq[j] = 0;
        }
    }

    if(freq[i]!=0)
    {
        freq[i] = count;
    }
}
for(int i=0; i<12; i++)
{
    if(freq[i]!=0 && storeKeys[i] != NULL)
    {
        Serial.println(storeKeys[i]);
        Serial.println(freq[i]);
        Serial.println("==========");
    }
}

The above code works but displaying frequency of all elements. I want to display the top three repeated elements only.

Here is the link for simulator online:

https://circuits.io/circuits/5073094-the-unnamed-circuit/edit

Thanks.

Body:
The answer is from here

Sort your frequency array with the below function and then only take the last three elements of sorted array.

 void sort(int a[], int size)
 {
   for(int i=0; i<(size-1); i++)
   {
    for(int o=0; o<(size-(i+1)); o++)
       {
            if(a[o] > a[o+1])
            {
                int t = a[o];
                a[o] = a[o+1];
                a[o+1] = t;
            }
        }
    }

  }


问:
Execute stored procedure by using batch file
I wanna pass two parameters and execute stored procedure by using batch file.

If possible, I need something like below:

Please enter Param1:
Please enter Param2:

I have codes as below in my batch but is not working.

```<code>@ECHO OFF
SET /P Param1=Enter the Param1:
SET /P Param2=Enter the Param2:
ECHO sqlcmd -E -Q "USE localdb\SQLSERVER2014 -d DemoDatabase;EXEC sp_MasterConsolidateJob @param1=N'%Param1%', @Param2=N'%Param2%'"
SET Param1=
SET Param2=

pause
</code>```

Thank you very much.

答:
there is syntax issue in your provided code. We dont specify instance name. Run this, it should work :</p>

```<code>@ECHO OFF
SET /P Param1=Enter the Param1:
SET /P Param2=Enter the Param2:
sqlcmd -E -Q " -d DemoDatabase;EXEC sp_MasterConsolidateJob $(Param1), $(Param2)"
SET Param1=
SET Param2=

pause
</code>```

Body:
I wanna pass two parameters and execute stored procedure by using batch file.

If possible, I need something like below:

Please enter Param1:
Please enter Param2:

I have codes as below in my batch but is not working.

@ECHO OFF
SET /P Param1=Enter the Param1:
SET /P Param2=Enter the Param2:
ECHO sqlcmd -E -Q "USE localdb\SQLSERVER2014 -d DemoDatabase;EXEC sp_MasterConsolidateJob @param1=N'%Param1%', @Param2=N'%Param2%'"
SET Param1=
SET Param2=

pause

Thank you very much.

Body:
there is syntax issue in your provided code. We dont specify instance name. Run this, it should work :

@ECHO OFF
SET /P Param1=Enter the Param1:
SET /P Param2=Enter the Param2:
sqlcmd -E -Q " -d DemoDatabase;EXEC sp_MasterConsolidateJob $(Param1), $(Param2)"
SET Param1=
SET Param2=

pause


问:
jquery validation ignore and include
I have a form with large set of fields that includes both read only and hidden fields. I want to enable validation for hidden field but disable validation for ready only fields

In the new version of jQuery validation plugin by the default validation of hidden fields are ignored. So to enable it I have to use :

$("form[name='Formname']").validate({
 ignore: []
});
```

<p>and it is working fine. But I need to ignore the validation for readonly fields and for that I need to use </p>

<pre class="lang-js prettyprint-override"><code>$("form[name='Formname']").validate({
 ignore: [readonly=readonly]
});
</code>```

Even if i merge the two,it still doesn't work because than it only ignore readonly but doesn't apply vaildation on hidden field

答:
You have to pass selector to ignore like this

ignore: '[readonly]', // This will select all input with readonly and ignore

Elements to ignore when validating, simply filtering them out.
  jQuery's not-method is used, therefore everything that is accepted by
  not() can be passed as this option. Inputs of type submit and reset
  are always ignored, so are disabled elements.

SNIPPET

$("form[name='Formname']").validate({
 ignore: '[readonly]',
 rules: {
    field: {
      required: true
    },
    field1: {
      required: true
    }}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>

<form name="Formname">

<input readonly name="field1">
<input type="text" id="field" name="field">

<input type="submit" value="Validate!">

</form></code>```

Title: jquery validation ignore and include

Body:
I have a form with large set of fields that includes both read only and hidden fields. I want to enable validation for hidden field but disable validation for ready only fields

In the new version of jQuery validation plugin by the default validation of hidden fields are ignored. So to enable it I have to use :

$("form[name='Formname']").validate({
 ignore: []
});

and it is working fine. But I need to ignore the validation for readonly fields and for that I need to use

$("form[name='Formname']").validate({
 ignore: [readonly=readonly]
});

Even if i merge the two,it still doesn't work because than it only ignore readonly but doesn't apply vaildation on hidden field

Body:
You have to pass selector to ignore like this

ignore: '[readonly]', // This will select all input with readonly and ignore

Elements to ignore when validating, simply filtering them out.
  jQuery's not-method is used, therefore everything that is accepted by
  not() can be passed as this option. Inputs of type submit and reset
  are always ignored, so are disabled elements.

SNIPPET

$("form[name='Formname']").validate({
 ignore: '[readonly]',
 rules: {
    field: {
      required: true
    },
    field1: {
      required: true
    }}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>

<form name="Formname">

<input readonly name="field1">
<input type="text" id="field" name="field">

<input type="submit" value="Validate!">

</form>


问:
Digital assets and able to transfer those
I need some guidance on how to support having access to digital assets and being able to transfer those between other user on the hyperledger via composer?</p>

答:
To quote from the tag information (https://stackoverflow.com/tags/hyperledger-composer/info)

Hyperledger Composer provides a layer of abstraction on top of the Hyperledger Fabric blockchain. Developers can design in terms of business networks, participants, identity, assets, registries, transactions, events and links, in contrast to the low level abstractions of chaincode and key-value stores.

So if you wish to do something with a digital asset, say an MP3, you need to create a model - similar to an entity-relationship model or an ObjectOriented hierachy. With that you can then define the operations on it.

An actual asset maybe the MP3 wouldn't necessarily be stored - but would be linked to. Composer then handles how this is put onto the underlying fabric - to give your applications the quality of service of Fabric's blockchain but without the requirement to write chain-code etc.

Hope that puts Composer into context, if you need more please include a broader description of your use case/problem you're solving.


问:
PHP won't echo the correct date
```<code>/* yeardate = 2000 monthdate = 02 daydate = 02 */
$date = new DateTime($yeardate.'-'.$monthdate.'-'.$daydate);
echo date('Y/m/d', strtotime($date));
</code>```

Keeps echoing 1970/01/01 or something on the lines of that.

答:
here you are, try to use proper class like below:</p>

```<code><?php
$date = DateTime::createFromFormat('Y-m-d', '2000-02-02');
echo $date->format('Y/m/d');
?>
</code>```

Title: PHP won't echo the correct date

Body:
/* yeardate = 2000 monthdate = 02 daydate = 02 */
$date = new DateTime($yeardate.'-'.$monthdate.'-'.$daydate);
echo date('Y/m/d', strtotime($date));

Keeps echoing 1970/01/01 or something on the lines of that.

Body:
here you are, try to use proper class like below:

<?php
$date = DateTime::createFromFormat('Y-m-d', '2000-02-02');
echo $date->format('Y/m/d');
?>


问:
Symfony 2 - disable translations on certain paths/routes
I would like to disable translations or force using english ones for paths which starts with /admin.

Is there a way to approach it in config?

If not what would be the best practice? EventListener checking routes and forcing english translation no matter the locale set in request?

答:
taken from the docs:

```<code>app.admin:
  resource: '@AppBundle/Controller/Admin/'
  type: annotation
  prefix: /{_locale}/admin
  requirements:
      _locale: nl
</code>```

put the locale in the url, this is much more search engine friendly.  As the docs say:

A better policy is to include the locale in the URL. This is fully-supported by the routing system using the special _locale parameter:

Body:
taken from the docs:

app.admin:
  resource: '@AppBundle/Controller/Admin/'
  type: annotation
  prefix: /{_locale}/admin
  requirements:
      _locale: nl

put the locale in the url, this is much more search engine friendly.  As the docs say:

A better policy is to include the locale in the URL. This is fully-supported by the routing system using the special _locale parameter:


问:
Function is returning Undefined
I need small help in a small code. The function is returning undefined and i want to return the console.log of the sum. The code is here http://jsbin.com/jedigigigo/edit?js,console

var addDigits = function a(num) {
  var length = num.toString().length;
  var value = num.toString();
  var sum = 0;
  for (var i = 0; i < value.length; i++) {
    sum += Number(value[i]);
  }
  if (sum > 9) {
    a(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(addDigits(38));```

答:
```<code>var addDigits = function a(num) {
         var length=num.toString().length;
         var value=num.toString();
         var sum=0;
         for(var i=0;i<value.length;i++) {
             sum+=Number(value[i]);
         }
         if(sum > 9) {
             return a(sum);
         }
         else
         {
            return sum;
         }

    };

    console.log(addDigits(38));
</code>```

Title: Function is returning Undefined


问:
SQL Server Replication Add Check Constraint in Publisher Table
I'm new to replication and would like to know the impact of creating a check constraint on a publisher table both in case of merge replication and transaction repl.

Both the cases, repl is already setup, would the replication break if I set up the check the constraint or would I need to re-initialize the subs after creating the check constraint.

Please let know what are precautionary steps I need to take

```<code> ALTER TABLE [dbo].[table]  WITH CHECK ADD  CONSTRAINT xx CHECK ()
 GO

 ALTER TABLE [dbo].[table] CHECK CONSTRAINT [xx]
 GO
</code>```

Thanks

答:
For existing publications you can view the properties to see if CHECK CONSTRAINTS are published to the subscriber.

Right Click - Properties - Articles - Set Properties of Highlighted Article.

If it's false, you don't need to worry about it being pushed to the subscriber.

Properties viewed using SSMS on Publisher

Body:
I'm new to replication and would like to know the impact of creating a check constraint on a publisher table both in case of merge replication and transaction repl.

Both the cases, repl is already setup, would the replication break if I set up the check the constraint or would I need to re-initialize the subs after creating the check constraint.

Please let know what are precautionary steps I need to take

 ALTER TABLE [dbo].[table]  WITH CHECK ADD  CONSTRAINT xx CHECK ()
 GO

 ALTER TABLE [dbo].[table] CHECK CONSTRAINT [xx]
 GO

Thanks


问:
What is HibernateTemplate class?
I am new in Hibernate currently want to implement the Hibernate Template  classes , any one please tell me about the Hibernate Template classes.

xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root" />
        <property name="password" value="mnrpass" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>employee.hbm.xml</value>
            </list>
        </property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>
    <bean id="springHibernateExample" class="com.javarticles.spring.hibernate.SpringHibernateExample">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>
</code>```

答:
HibernateTemplate is the class of org.springframework.orm.hibernate3. HibernateTemplate provides the integration of hibernate and spring. Spring manages database connection DML, DDL etc commands by itself. HibernateTemplate has the methods like save,update, delete etc.
Try to understand how to configure HibernateTemplate in our spring application.

Add xml configuration in application.xml of spring application.

```<code><bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
  <ref bean="sessionFactory" />
</property>
</code>```

hibernateTemplate will be used in the dao classes. Initialize hibernateTemplate. Provide a setter method to set hibernateTemplate by spring.

```<code>private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    this.hibernateTemplate = hibernateTemplate;
}

public void persist(){
    User u1= new User(1,"Ankita");
    hibernateTemplate.save(u1);

    User u2= new User(2,"Renu");
    hibernateTemplate.save(u2);

}
</code>```

Title: What is HibernateTemplate class?

Body:
I am new in Hibernate currently want to implement the Hibernate Template  classes , any one please tell me about the Hibernate Template classes.

xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root" />
        <property name="password" value="mnrpass" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>employee.hbm.xml</value>
            </list>
        </property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>
    <bean id="springHibernateExample" class="com.javarticles.spring.hibernate.SpringHibernateExample">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

Body:
HibernateTemplate is the class of org.springframework.orm.hibernate3. HibernateTemplate provides the integration of hibernate and spring. Spring manages database connection DML, DDL etc commands by itself. HibernateTemplate has the methods like save,update, delete etc.
Try to understand how to configure HibernateTemplate in our spring application.

Add xml configuration in application.xml of spring application.

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
  <ref bean="sessionFactory" />
</property>

hibernateTemplate will be used in the dao classes. Initialize hibernateTemplate. Provide a setter method to set hibernateTemplate by spring.

private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    this.hibernateTemplate = hibernateTemplate;
}

public void persist(){
    User u1= new User(1,"Ankita");
    hibernateTemplate.save(u1);

    User u2= new User(2,"Renu");
    hibernateTemplate.save(u2);

}


问:
how to solve this gradle project refresh failed

Error:Could not find com.android.tools.build:gradle:2.4.2.

答:
Recommended

You should use latest gradle version.

please update your gradle with all uses library than problem would be solved.

For More Helps You Can view this problem. Otherwise upload your gradle file image


问:
Concatenation of different positions of the same variable in PHP
I have a trouble in a php code, the problem is that I want to display the variable Cell new from the variable Cell old

$Cell old = ARI_0089_sect2

$Cell new = ARI_0089_h2 (replace 'sect' with 'h' )

all example that I found concatenate two different variables like first name and last name

I didn't find how to concatenate different position of the same variable, it is possible in microsoft excel but I didn't find how to resolve it with a php code.

答:
```<code>$Cell new = str_replace('sect','h',$Cell old);

echo $Cell new;
</code>```

ContentLicense: CC BY-SA 4.0


问:
IdentityServer4 refresh_token revocation
I have SPA app that uses IdentityServer4 ROPC flow for auth with access and refresh tokens from this example https://github.com/robisim74/AngularSPAWebAPI. Every 15 minutes I update refresh_token for a new pair of refresh and access tokens.

However If I restart IdentityServer4 app old refresh_tokens issued before restart no longer valid. How to fix it? I suspect I should implement some interface to store issued refresh tokens?

答:
You need to implement persisted grants by using the IPersistedGrantStore contract. This stores things like refresh_tokens into a defined persistence. By default IdentityServer 4 will use an InMemory persistence store, which is why you keep on losing your refresh_token references when you restart the application.

It is pretty much mandatory to have a persistence layer for this in production if you are going to be using refresh_tokens.


问:
WKWebView WKScriptMessageHandler not called with iOS 10, Xcode 8 beta
I need to update my code to swift 3. The code below is the original solution what is works perfectly, but in Xcode 8 beta and iOS 10 with swift 3 the userContentController delegate does not called when I use the original html+js code to call the native side.

```<code>class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, WKNavigationDelegate,UIWebViewDelegate,CLLocationManagerDelegate,URLSessionDataDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

....

func initWebView(){
    // JAVASCRIPT PART
    let contentController = WKUserContentController();

    let jScript:String = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    let wkUScript:WKUserScript = WKUserScript(source: jScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true);

    contentController.addUserScript(wkUScript)
    contentController.add(
        self,
        name: "refreshWebPage"
    )
    contentController.add(
        self,
        name: "forceStepBack"
    )
    contentController.add(
        self,
        name: "setPageTitle"
    )
    contentController.add(
        self,
        name: "allowBackNavigate"
    )
    contentController.add(
        self,
        name: "changeBackNavigationURL"
    )

    contentController.add(
        self,
        name: "changeLeftButtonIconVisibility"
    )
    contentController.add(
        self,
        name: "changeRightButtonIconVisibility"
    )
    contentController.add(
        self,
        name: "clearWebCache"
    )
    contentController.add(
        self,
        name: "changeMobileAndPassword"
    )

    let config = WKWebViewConfiguration()
    config.userContentController = contentController

    self.webView = WKWebView(frame: CGRect.zero, configuration: config)

    self.view.translatesAutoresizingMaskIntoConstraints = false
    self.webView!.navigationDelegate = self
    self.webView!.uiDelegate = self;
    self.webView!.scrollView.bounces = false;
    view = webView

    webView?.loadHTMLString(self.baseURL!, baseURL: nil)

}
...
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("JavaScript is sending a message: \(message.body)")
        print("JavaScript is sending a message.name: \(message.name)")

    }
</code>```

答:
Afer I debug a lot of times and conditions , I found that :

The function postMessage() in your JS must have a parameter, the parameter never be null

The parameter must be JSON type

For example :
webkit.messageHandlers.refreshWebPage.postMessage("status":"ok");

If you have followed the three advices above and have the delegate set correct. The delegate function didReceiveScriptMessage will be called. Hope this help you.

Body:
I need to update my code to swift 3. The code below is the original solution what is works perfectly, but in Xcode 8 beta and iOS 10 with swift 3 the userContentController delegate does not called when I use the original html+js code to call the native side.

class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, WKNavigationDelegate,UIWebViewDelegate,CLLocationManagerDelegate,URLSessionDataDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

....

func initWebView(){
    // JAVASCRIPT PART
    let contentController = WKUserContentController();

    let jScript:String = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    let wkUScript:WKUserScript = WKUserScript(source: jScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true);

    contentController.addUserScript(wkUScript)
    contentController.add(
        self,
        name: "refreshWebPage"
    )
    contentController.add(
        self,
        name: "forceStepBack"
    )
    contentController.add(
        self,
        name: "setPageTitle"
    )
    contentController.add(
        self,
        name: "allowBackNavigate"
    )
    contentController.add(
        self,
        name: "changeBackNavigationURL"
    )

    contentController.add(
        self,
        name: "changeLeftButtonIconVisibility"
    )
    contentController.add(
        self,
        name: "changeRightButtonIconVisibility"
    )
    contentController.add(
        self,
        name: "clearWebCache"
    )
    contentController.add(
        self,
        name: "changeMobileAndPassword"
    )

    let config = WKWebViewConfiguration()
    config.userContentController = contentController

    self.webView = WKWebView(frame: CGRect.zero, configuration: config)

    self.view.translatesAutoresizingMaskIntoConstraints = false
    self.webView!.navigationDelegate = self
    self.webView!.uiDelegate = self;
    self.webView!.scrollView.bounces = false;
    view = webView

    webView?.loadHTMLString(self.baseURL!, baseURL: nil)

}
...
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("JavaScript is sending a message: \(message.body)")
        print("JavaScript is sending a message.name: \(message.name)")

    }


问:
Azure Rest API What resourceRestoreRequest syntax for VM Restore
I'm using Python with Rest API requests to manage backup&restore on Azure VM. I'm able to backup VM, but I can't restore them.

My code in Python to POST

```<code>headers = {"Authorization": 'Bearer ' + restapi_azure_authentication()}
myResponse = requests.post(url, headers=headers)
</code>```

and to POST with JSON push

```<code>headers = {"Authorization": 'Bearer ' + restapi_azure_authentication()}
myResponse = requests.post(url, headers=headers, json=json)
</code>```

I get two messages.
If I use this request:

```<code>POST /Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/restore?api-version=2016-06-01
</code>```

I get this message :

{"error":{"code":"CloudInternalError","message":"Microsoft Azure Backup encountered an internal error.\r\nWait for a few minutes and then try the operatio
  n again. If the issue persists, please contact Microsoft support.","target":null,"details":null,"innerError":null}}

If I use this request with JSON push :

```<code>json = {
    "properties": {}
}
</code>```

I get this message:

{"error":{"code":"UserErrorInvalidRestoreRequest","message":"Restore operation failed due to invalid parameters or format of the parameters is not correct
  .\r\nPlease ensure parameters provided to restore operation are valid. If the issue persists, please contact Microsoft support.","target":null,"details":n
  ull,"innerError":null}}

I don't know what to put into "properties" to successfully restore my VM.
I'm trying to follow this doc, unfortunately, without success : https://learn.microsoft.com/en-us/rest/api/recoveryservices/restores

答:
As the other community mentioned that we can refer the parameters by using PowerShell command-let to restore the backup data. Here is the request which capture using the Fiddler for your reference:

```<code>POST:https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultsName}/backupFabrics/Azure/protectionContainers/{backupContainerName}/protectedItems/{backUpItemName}/recoveryPoints/{recoveryPointId}/restore?api-version=2016-05-01
Authorization: Bearer {access_token}

{
  "properties": {
    "objectType": "IaasVMRestoreRequest",
    "recoveryPointId": "{recoveryPointId}",
    "recoveryType": "RestoreDisks",
    "storageAccountId": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageaccountName}",
    "createNewCloudService": false,
    "region": "{region}",
    "sourceResourceId": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{VMName}"
  }
}
</code>```

In addition, if you have any feedback about the document provide by Microsoft, you can submit it from the right bottom page(Is this page helpful).

Body:
I'm using Python with Rest API requests to manage backup&restore on Azure VM. I'm able to backup VM, but I can't restore them.

My code in Python to POST

headers = {"Authorization": 'Bearer ' + restapi_azure_authentication()}
myResponse = requests.post(url, headers=headers)

and to POST with JSON push

headers = {"Authorization": 'Bearer ' + restapi_azure_authentication()}
myResponse = requests.post(url, headers=headers, json=json)

I get two messages.
If I use this request:

POST /Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/restore?api-version=2016-06-01

I get this message :

{"error":{"code":"CloudInternalError","message":"Microsoft Azure Backup encountered an internal error.\r\nWait for a few minutes and then try the operatio
  n again. If the issue persists, please contact Microsoft support.","target":null,"details":null,"innerError":null}}

If I use this request with JSON push :

json = {
    "properties": {}
}

I get this message:

{"error":{"code":"UserErrorInvalidRestoreRequest","message":"Restore operation failed due to invalid parameters or format of the parameters is not correct
  .\r\nPlease ensure parameters provided to restore operation are valid. If the issue persists, please contact Microsoft support.","target":null,"details":n
  ull,"innerError":null}}

I don't know what to put into "properties" to successfully restore my VM.
I'm trying to follow this doc, unfortunately, without success : https://learn.microsoft.com/en-us/rest/api/recoveryservices/restores

Body:
As the other community mentioned that we can refer the parameters by using PowerShell command-let to restore the backup data. Here is the request which capture using the Fiddler for your reference:

POST:https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultsName}/backupFabrics/Azure/protectionContainers/{backupContainerName}/protectedItems/{backUpItemName}/recoveryPoints/{recoveryPointId}/restore?api-version=2016-05-01
Authorization: Bearer {access_token}

{
  "properties": {
    "objectType": "IaasVMRestoreRequest",
    "recoveryPointId": "{recoveryPointId}",
    "recoveryType": "RestoreDisks",
    "storageAccountId": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageaccountName}",
    "createNewCloudService": false,
    "region": "{region}",
    "sourceResourceId": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{VMName}"
  }
}

In addition, if you have any feedback about the document provide by Microsoft, you can submit it from the right bottom page(Is this page helpful).


问:
make a private route to async route in react router v4
I am using react router v4 for routing in my application. The component, sagas and reducers are loaded asynchronously. How can i now implement private routing and public routing in such case? </p>

<p>Here is the code for routing and loading </p>

```<code>/**
 * A wrapper component that will lazily render a component after it has been loaded.
 */
class Bundle extends Component {
  static contextTypes = {
    store: React.PropTypes.object
  };

  state = {
    // short for "module" but that's a keyword in js, so "mod"
    mod: null
  };

  componentWillMount() {
    this.load(this.props);
  }

  /* istanbul ignore next */
  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps);
    }
  }

  load(props) {
    this.setState({
      mod: null
    });
    props.load(this.context.store, mod => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      });
    });
  }

  render() {
    // eslint-disable-next-line no-unused-vars
    const { load, ...otherProps } = this.props;
    return this.state.mod && <this.state.mod {...otherProps} />;
  }
}

const AsyncRoute = ({ load, ...others }) => (
  <Route {...others} render={props => <Bundle load={load} {...props} />} />
);

AsyncRoute.propTypes = {
  computedMatch: React.PropTypes.object,
  path: React.PropTypes.string,
  load: React.PropTypes.func
};

export default AsyncRoute;

// how can i make private route with different layout not a children of App
function Routes({ location }) {
  return (
    <Switch location={location}>
      <AsyncRoute exact path="/" load={loadHomePage} />
      <AsyncRoute exact path="/signup" load={loadSignupPage} />
      <AsyncRoute path="" load={loadNotFoundPage} />
    </Switch>
  );
}

export default (store, cb) => {
  const { injectReducer, injectSagas } = getAsyncInjectors(store);
  const importModules = Promise.all([
    import("./reducer"),
    import("./sagas"),
    import("./index")
  ]);

  importModules.then(([reducer, sagas, component]) => {
    injectReducer("signup", reducer.default);
    injectSagas(sagas.default);

    cb(component);
  });

  importModules.catch(errorLoading);
};

const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById("app")
  );
};
</code>```

答:
Assuming you have used react-router-redux to sync your history with your redux store, you can create a saga in the main chunk that takes the latest LOCATION_CHANGE action type from react-router-redux and refresh your authentication (store it in auth reducer) by calling some API.

To distinguish between private and public components, you can modify Bundle such that it defers from asynchronously loading private chunks until the auth state is valid.

Here are some code sketch

sagas/auth.js

```<code>import { LOCATION_CHANGE } from 'react-router-redux'

function *checkAuth() {
   yield put(authenticateStart())
   // Assuming using some token authentication
   const token = yield select(state => state.auth.token)
   const result = yield call(Api.refreshAuth, token)
   if (result.isAuthenticated) {
      yield put(authenticateSuccess(result.user)
   } else {
      // Need auth
      yield put(authenticateError())
   }
}
// Put this saga on main bundle
function *authSaga() {
    yield* takeLatest(LOCATION_CHANGE, checkAuth)
}
</code>```

bundle.js

```<code>class Bundle extends Component {
  static contextTypes = {
    store: React.PropTypes.object
  };

  state = {
    // short for "module" but that's a keyword in js, so "mod"
    mod: null
  };

  componentWillMount() {
    if (this.props.isProtected && !this.props.isAuthenticated)
       return
    this.load(this.props);
  }

  /* istanbul ignore next */
  componentWillReceiveProps(nextProps) {
    // Modify similar to above
  }

  load(props) {
    this.setState({
      mod: null
    });
    props.load(this.context.store, mod => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      });
    });
  }

  render() {
    // eslint-disable-next-line no-unused-vars
    const { load, ...otherProps } = this.props;
    return this.state.mod && <this.state.mod {...otherProps} />;
  }
}

export default connect(state => ({ isAuthenticated: state.auth.isAuthenticated }))(Bundle)
</code>```

Body:
I am using react router v4 for routing in my application. The component, sagas and reducers are loaded asynchronously. How can i now implement private routing and public routing in such case?

Here is the code for routing and loading

/**
 * A wrapper component that will lazily render a component after it has been loaded.
 */
class Bundle extends Component {
  static contextTypes = {
    store: React.PropTypes.object
  };

  state = {
    // short for "module" but that's a keyword in js, so "mod"
    mod: null
  };

  componentWillMount() {
    this.load(this.props);
  }

  /* istanbul ignore next */
  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps);
    }
  }

  load(props) {
    this.setState({
      mod: null
    });
    props.load(this.context.store, mod => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      });
    });
  }

  render() {
    // eslint-disable-next-line no-unused-vars
    const { load, ...otherProps } = this.props;
    return this.state.mod && <this.state.mod {...otherProps} />;
  }
}

const AsyncRoute = ({ load, ...others }) => (
  <Route {...others} render={props => <Bundle load={load} {...props} />} />
);

AsyncRoute.propTypes = {
  computedMatch: React.PropTypes.object,
  path: React.PropTypes.string,
  load: React.PropTypes.func
};

export default AsyncRoute;

// how can i make private route with different layout not a children of App
function Routes({ location }) {
  return (
    <Switch location={location}>
      <AsyncRoute exact path="/" load={loadHomePage} />
      <AsyncRoute exact path="/signup" load={loadSignupPage} />
      <AsyncRoute path="" load={loadNotFoundPage} />
    </Switch>
  );
}

export default (store, cb) => {
  const { injectReducer, injectSagas } = getAsyncInjectors(store);
  const importModules = Promise.all([
    import("./reducer"),
    import("./sagas"),
    import("./index")
  ]);

  importModules.then(([reducer, sagas, component]) => {
    injectReducer("signup", reducer.default);
    injectSagas(sagas.default);

    cb(component);
  });

  importModules.catch(errorLoading);
};

const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById("app")
  );
};

Body:
Assuming you have used react-router-redux to sync your history with your redux store, you can create a saga in the main chunk that takes the latest LOCATION_CHANGE action type from react-router-redux and refresh your authentication (store it in auth reducer) by calling some API.

To distinguish between private and public components, you can modify Bundle such that it defers from asynchronously loading private chunks until the auth state is valid.

Here are some code sketch

sagas/auth.js

import { LOCATION_CHANGE } from 'react-router-redux'

function *checkAuth() {
   yield put(authenticateStart())
   // Assuming using some token authentication
   const token = yield select(state => state.auth.token)
   const result = yield call(Api.refreshAuth, token)
   if (result.isAuthenticated) {
      yield put(authenticateSuccess(result.user)
   } else {
      // Need auth
      yield put(authenticateError())
   }
}
// Put this saga on main bundle
function *authSaga() {
    yield* takeLatest(LOCATION_CHANGE, checkAuth)
}

bundle.js

class Bundle extends Component {
  static contextTypes = {
    store: React.PropTypes.object
  };

  state = {
    // short for "module" but that's a keyword in js, so "mod"
    mod: null
  };

  componentWillMount() {
    if (this.props.isProtected && !this.props.isAuthenticated)
       return
    this.load(this.props);
  }

  /* istanbul ignore next */
  componentWillReceiveProps(nextProps) {
    // Modify similar to above
  }

  load(props) {
    this.setState({
      mod: null
    });
    props.load(this.context.store, mod => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      });
    });
  }

  render() {
    // eslint-disable-next-line no-unused-vars
    const { load, ...otherProps } = this.props;
    return this.state.mod && <this.state.mod {...otherProps} />;
  }
}

export default connect(state => ({ isAuthenticated: state.auth.isAuthenticated }))(Bundle)


问:
remove extra + from text SQL
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

```<code>Name     Value
A+B+C+   1+2+3+
A++B     1++2
</code>```

this should be updated to

```<code>   Name     Value
    A+B+C   1+2+3
    A+B     1+2
</code>```

once this update has taken place, I can run the solution provided in the previous question.

Thanks

答:
if youre working with ssms, GIVE IT A GO:::</p>

```<code>UPDATE tablename
SET colname=
CASE colname WHEN LIKE '%++%' THEN
    WHILE colname LIKE '%++%'
        (REPLACE(colname,++,+))
    END LOOP

WHEN LIKE '%+' THEN
    SUBSTR(colname, 1, LENGTH(colname)-1)

WHEN LIKE '+%' THEN
    SUBSTR(colname, 2, LENGTH(colname))

ELSE
   colname
END
</code>```

Title: remove extra + from text SQL

Body:
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

Name     Value
A+B+C+   1+2+3+
A++B     1++2

this should be updated to

   Name     Value
    A+B+C   1+2+3
    A+B     1+2

once this update has taken place, I can run the solution provided in the previous question.

Thanks

Body:
if youre working with ssms, GIVE IT A GO:::

UPDATE tablename
SET colname=
CASE colname WHEN LIKE '%++%' THEN
    WHILE colname LIKE '%++%'
        (REPLACE(colname,++,+))
    END LOOP

WHEN LIKE '%+' THEN
    SUBSTR(colname, 1, LENGTH(colname)-1)

WHEN LIKE '+%' THEN
    SUBSTR(colname, 2, LENGTH(colname))

ELSE
   colname
END


问:
Seg fault doing new vector<string>
The following code gets a seg fault on the last line:

```<code>   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;
</code>```

Valgrind tells me:

```<code>==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)
</code>```

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

```<code>struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};
</code>```

答:
As Brian said, the error message points at str::string being initialized with NULL, which is forbidden. However, your code looks like written by someone who comes from Java or C# and is used to mindlessly new everything. In C++, however, automatic storage is preferred.

If you change your code to this

```<code>struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> params;
    HookAct() : hAct(HookAct::PRINT), params() {}
};
</code>```

no manual dynamic memory managing is necessary anymore:

```<code>HookAct hookAct;
</code>```

Title: Seg fault doing new vector<string>

Body:
The following code gets a seg fault on the last line:

   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;

Valgrind tells me:

==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};

Body:
As Brian said, the error message points at str::string being initialized with NULL, which is forbidden. However, your code looks like written by someone who comes from Java or C# and is used to mindlessly new everything. In C++, however, automatic storage is preferred.

If you change your code to this

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> params;
    HookAct() : hAct(HookAct::PRINT), params() {}
};

no manual dynamic memory managing is necessary anymore:

HookAct hookAct;


问:
PHP namespace syntax
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}
</code>```

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}
</code>```

But when I run the code I get

```<code>Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php
</code>```

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

```<code>namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}
</code>```

when I run phpcs with this sniff then I get the error

```<code>PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409
</code>```

I hope this makes things clearer

答:
you can follow this role :

```<code>file1:
        <?php
          namespace foo;
          class Cat {
            public function says(){
              echo 'meoow';
            }
          }
        ?>

        file2:
        <?php
          include 'file1.php';
          use foo;
          class bar extends foo{
              //......
         }
</code>```

more details: http://php.net/manual/en/language.namespaces.php

Title: PHP namespace syntax

Body:
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}

But when I run the code I get

Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}

when I run phpcs with this sniff then I get the error

PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409

I hope this makes things clearer

Body:
you can follow this role :

file1:
        <?php
          namespace foo;
          class Cat {
            public function says(){
              echo 'meoow';
            }
          }
        ?>

        file2:
        <?php
          include 'file1.php';
          use foo;
          class bar extends foo{
              //......
         }

more details: http://php.net/manual/en/language.namespaces.php


问:
function definition does't receive the array values using php
I have one function call remove_certificate_packages($certificate_id, array_keys($package_id)) this will invoke the below function

```<code>function remove_certificate_packages($certificate_id, $package_id)
{
    if (is_numeric($package_id)) // so this is list of package id:s
        $package_id = array($package_id);

    if (!$package_id) return true;

    **notify_package_unlinked($certificate_id,array_keys($package_id));**//one more func call

    return true;
}
</code>```

in this function, I have one more function call "notify_package_unlinked" I need to pass the "$package_id". It will call the appropriate function but the problem is, in the "notify_package_unlinked" function the value is showing "Array". What is the problem? Could you please help

```<code>function notify_package_unlinked($certificate_id,$package_id)
{
      $query="select id,filename,version from packages where id =$package_id";
      $res = db_query($query);
      $package= db_fetch_object($res);

      $packid=$package->id;
      $packname=$package->filename;
      $packversion=$package->version;
      print "$packid"; // here it is printing the value"Array"
 }
</code>```

答:
I got my output using foreach loop .</p>

```<code>foreach($package_id as $id){$pack=$id;}
</code>```

Body:
I have one function call remove_certificate_packages($certificate_id, array_keys($package_id)) this will invoke the below function

function remove_certificate_packages($certificate_id, $package_id)
{
    if (is_numeric($package_id)) // so this is list of package id:s
        $package_id = array($package_id);

    if (!$package_id) return true;

    **notify_package_unlinked($certificate_id,array_keys($package_id));**//one more func call

    return true;
}

in this function, I have one more function call "notify_package_unlinked" I need to pass the "$package_id". It will call the appropriate function but the problem is, in the "notify_package_unlinked" function the value is showing "Array". What is the problem? Could you please help

function notify_package_unlinked($certificate_id,$package_id)
{
      $query="select id,filename,version from packages where id =$package_id";
      $res = db_query($query);
      $package= db_fetch_object($res);

      $packid=$package->id;
      $packname=$package->filename;
      $packversion=$package->version;
      print "$packid"; // here it is printing the value"Array"
 }

Body:
I got my output using foreach loop .

foreach($package_id as $id){$pack=$id;}


问:
Why is this infinite for loop terminating after some time?
I am running this infinite for loop. Why is this for loop terminating after some time?

```<code>for(int i = 10; i > 0; i++) { }
</code>```

But if I print something in this for loop then it is not terminating. Why so?

答:
Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative.
In your case when it becomes negative and condition become false.</p>

Body:
I am running this infinite for loop. Why is this for loop terminating after some time?

for(int i = 10; i > 0; i++) { }

But if I print something in this for loop then it is not terminating. Why so?


答:
Try PHP function str_replace

```<code>$Cell_old = "ARI_0089_sect2";
$new = str_replace('sect', 'h', $Cell_old);
echo $new;
</code>```

Title: Concatenation of different positions of the same variable in PHP

Body:
I have a trouble in a php code, the problem is that I want to display the variable Cell new from the variable Cell old

$Cell old = ARI_0089_sect2

$Cell new = ARI_0089_h2 (replace 'sect' with 'h' )

all example that I found concatenate two different variables like first name and last name

I didn't find how to concatenate different position of the same variable, it is possible in microsoft excel but I didn't find how to resolve it with a php code.

Body:
Try PHP function str_replace

$Cell_old = "ARI_0089_sect2";
$new = str_replace('sect', 'h', $Cell_old);
echo $new;


问:
Select maximum/minimum with another column
Is there is a way to select the maximum of value + another column without the use of TOP and order by?

Assuming that we have a list of people and their ages, we want take the oldest/youngest. I want to select the name + the age. Even If it happens that we want to group them by name, that won't work.

```<code>SELECT   nom,
         max(age)
from     Agents
group by nom

╔════════╦═════╗
║  Name  ║ Age ║
╠════════╬═════╣
║ John   ║ 200 ║
║ Bob    ║ 150 ║
║ GSkill ║ 300 ║
║ Smith  ║ 250 ║
║ John   ║ 400 ║
║ Zid    ║ 300 ║
║ Wick   ║ 250 ║
║ Smith  ║ 140 ║
╚════════╩═════╝
</code>```

答:
Try this query --</p>

```<code>;WITH CTE
AS (
    SELECT [NAME]
        ,AGE
        ,DENSE_RANK() OVER (
            ORDER BY AGE DESC
            ) AS Older
        ,DENSE_RANK() OVER (
            ORDER BY AGE ASC
            ) AS Younger
    FROM tblSample
    )
SELECT [NAME] + ': ' + CAST(AGE AS VARCHAR(50))
FROM CTE
WHERE Older = 1 OR Younger = 1
</code>```

Body:
Is there is a way to select the maximum of value + another column without the use of TOP and order by?

Assuming that we have a list of people and their ages, we want take the oldest/youngest. I want to select the name + the age. Even If it happens that we want to group them by name, that won't work.

SELECT   nom,
         max(age)
from     Agents
group by nom

╔════════╦═════╗
║  Name  ║ Age ║
╠════════╬═════╣
║ John   ║ 200 ║
║ Bob    ║ 150 ║
║ GSkill ║ 300 ║
║ Smith  ║ 250 ║
║ John   ║ 400 ║
║ Zid    ║ 300 ║
║ Wick   ║ 250 ║
║ Smith  ║ 140 ║
╚════════╩═════╝

Body:
Try this query --

;WITH CTE
AS (
    SELECT [NAME]
        ,AGE
        ,DENSE_RANK() OVER (
            ORDER BY AGE DESC
            ) AS Older
        ,DENSE_RANK() OVER (
            ORDER BY AGE ASC
            ) AS Younger
    FROM tblSample
    )
SELECT [NAME] + ': ' + CAST(AGE AS VARCHAR(50))
FROM CTE
WHERE Older = 1 OR Younger = 1


问:
Write list of objects to text file
I've got a class Dish like this:

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
</code>```

In the main form the user can enter the previous data.
Then I create a list of "Dish":

```<code>public static List<Piatto> List = new List<Piatto>();
</code>```

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

```<code>public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
</code>```

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

答:
When converting Dish instance into String, .Net uses ToString() method which default (i.e. Object.ToString()) implementation returns item's type name:

```<code>   WindowsFormsApplication1.Dish
</code>```

you can either provide your version of ToString:

```<code>   public class Dish
   {
     ...

       public override string ToString()
       {
           return $"{Cost} {Name}";
       }
   }
</code>```

Or put the right format in the very place you write it into the file (with a little help of Linq - Select):

```<code>   public static void SaveToTxt() {
     // File class allows to get rid of pesky readers and writers
     File.WriteAllLines(Path, Data.List.Select(dish => $"{dish.Cost} {dish.Name}"));
   }
</code>```

Title: Write list of objects to text file

Body:
I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data.
Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

Body:
When converting Dish instance into String, .Net uses ToString() method which default (i.e. Object.ToString()) implementation returns item's type name:

   WindowsFormsApplication1.Dish

you can either provide your version of ToString:

   public class Dish
   {
     ...

       public override string ToString()
       {
           return $"{Cost} {Name}";
       }
   }

Or put the right format in the very place you write it into the file (with a little help of Linq - Select):

   public static void SaveToTxt() {
     // File class allows to get rid of pesky readers and writers
     File.WriteAllLines(Path, Data.List.Select(dish => $"{dish.Cost} {dish.Name}"));
   }


问:
Please find below code to count chars in given string. I want to know my approach is right or what is the best way?
```<code>public String getCharCntStr(String inputStr){
        List<Character> alreadyCntChrs=new ArrayList<>();//store already counted chars
        StringBuilder outputStr=new StringBuilder();
        for(int i=0;i<inputStr.length();i++){
            char a=inputStr.charAt(i);
            if(alreadyCntChrs.contains(a)){
                continue;
            }
            int count=0;
            for(int j=i;i<inputStr.length();j++){// to find count of a char in string
                if(a==inputStr.charAt(j))
                    count++;
            }
            outputStr.append(a).append(count);
            alreadyCntChrs.add(a);
        }
        return outputStr.toString();
    }
</code>```

example input: sanaullahshaikh
 ouput: s2a3n1u1l2h3i1k1
Please suggest me the best way to do.

答:
Using forEach loops makes the code somewhat cleaner:

```<code>for (char c : input.toCharArray())
</code>```

Using a HashMap makes counting repetitions O(n), with n = length of string; your code is currently cuadratic O(n^2). However, HashMaps do not guarantee any ordering. Using a LinkedHashMap does guarantee ordering, at a slight performance penalty, which does not affect asymptotic (big-o) performance.

Therefore, fast, O(n) code could be the following:

```<code>public static String charCountsInString(String input) {
    // count character repetitions in a hashmap that preserves ordering
    Map<Character, Integer> counts = new LinkedHashMap<>();
    for (char c : input.toCharArray()) {
        counts.put(c, counts.getOrDefault(c, 0)+1);
    }

    // output characters in order, with their repetition counts
    StringBuilder output = new StringBuilder();
    for (Map.Entry<Character, Integer> e : counts.entrySet()) {
        output.append(e.getKey()).append(e.getValue());
    }
    return output.toString();
}
</code>```

Body:
public String getCharCntStr(String inputStr){
        List<Character> alreadyCntChrs=new ArrayList<>();//store already counted chars
        StringBuilder outputStr=new StringBuilder();
        for(int i=0;i<inputStr.length();i++){
            char a=inputStr.charAt(i);
            if(alreadyCntChrs.contains(a)){
                continue;
            }
            int count=0;
            for(int j=i;i<inputStr.length();j++){// to find count of a char in string
                if(a==inputStr.charAt(j))
                    count++;
            }
            outputStr.append(a).append(count);
            alreadyCntChrs.add(a);
        }
        return outputStr.toString();
    }

example input: sanaullahshaikh
 ouput: s2a3n1u1l2h3i1k1
Please suggest me the best way to do.

Body:
Using forEach loops makes the code somewhat cleaner:

for (char c : input.toCharArray())

Using a HashMap makes counting repetitions O(n), with n = length of string; your code is currently cuadratic O(n^2). However, HashMaps do not guarantee any ordering. Using a LinkedHashMap does guarantee ordering, at a slight performance penalty, which does not affect asymptotic (big-o) performance.

Therefore, fast, O(n) code could be the following:

public static String charCountsInString(String input) {
    // count character repetitions in a hashmap that preserves ordering
    Map<Character, Integer> counts = new LinkedHashMap<>();
    for (char c : input.toCharArray()) {
        counts.put(c, counts.getOrDefault(c, 0)+1);
    }

    // output characters in order, with their repetition counts
    StringBuilder output = new StringBuilder();
    for (Map.Entry<Character, Integer> e : counts.entrySet()) {
        output.append(e.getKey()).append(e.getValue());
    }
    return output.toString();
}


问:
How would I use enum on my project?
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

```<code>public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3
</code>```

}

答:
```<code>you can use something like this.

public enum lockUnlock {
    LOCK(1), UNLOCK(3);
    int value;

    lockUnlock(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

class Test {

    public static void main(String[] args) {
        lockUnlock[] b = lockUnlock.values();
        for (lockUnlock b1 : b) {
            System.out.println(b1 + "........" + b1.getValue());
        }
    }
}
</code>```

Title: How would I use enum on my project?

Body:
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3

}


问:
unable to open trace file
I want to test the performance of my app . I have started it with simple application and try to put traceview but its suddenly fail on my android phone with force to close. Please guide me how can i set my code propley for simple android app to get hands dirt with Trace view

Here is the code
package test.check;

```<code>import android.app.Activity;
import android.os.Bundle;
import android.os.Debug;

public class tracev extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Debug.startMethodTracing("traceview");
        setContentView(R.layout.main);
    }
    @Override
    protected void onStop() {
        Debug.stopMethodTracing();
        super.onStop();
    }
}
</code>```

Here is the manifest file

```<code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="test.check"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".tracev"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
</code>```

I have also added

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

but its not working . I think its becasue of this line in the logcat but i am not sure how  to deal with it

```<code>05-20 23:39:43.913: ERROR/dalvikvm(11673): Unable to open trace file '/sdcard/traceview.trace': Permission denied
</code>```

Logcat

```<code>05-20 23:39:43.903: DEBUG/dalvikvm(11673): +++ active profiler count now 1
05-20 23:39:43.913: INFO/dalvikvm(11673): TRACE STARTED: '/sdcard/traceview.trace' 8192KB
05-20 23:39:43.913: ERROR/dalvikvm(11673): Unable to open trace file '/sdcard/traceview.trace': Permission denied
05-20 23:39:43.913: DEBUG/dalvikvm(11673): +++ active profiler count now 0
05-20 23:39:43.913: DEBUG/AndroidRuntime(11673): Shutting down VM
05-20 23:39:43.913: WARN/dalvikvm(11673): threadid=3: thread exiting with uncaught exception (group=0x4001e390)
05-20 23:39:43.913: ERROR/AndroidRuntime(11673): Uncaught handler: thread main exiting due to uncaught exception
05-20 23:39:43.983: ERROR/AndroidRuntime(11673): java.lang.RuntimeException: Unable to start activity ComponentInfo{test.check/test.check.tracev}: java.lang.RuntimeException: file open failed
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Looper.loop(Looper.java:123)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at java.lang.reflect.Method.invokeNative(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at java.lang.reflect.Method.invoke(Method.java:521)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.NativeStart.main(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673): Caused by: java.lang.RuntimeException: file open failed
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.VMDebug.startMethodTracing(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.VMDebug.startMethodTracing(VMDebug.java:156)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Debug.startMethodTracing(Debug.java:443)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Debug.startMethodTracing(Debug.java:391)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at test.check.tracev.onCreate(tracev.java:12)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     ... 11 more
05-20 23:39:44.013: INFO/Process(94): Sending signal. PID: 11673 SIG: 3
05-20 23:39:44.013: INFO/dalvikvm(11673): threadid=7: reacting to signal 3
05-20 23:39:44.023: INFO/dalvikvm(11673): Wrote stack trace to '/data/anr/traces.txt'
05-20 23:39:51.213: DEBUG/KeyguardViewMediator(94): pokeWakelock(15000)
05-20 23:39:51.213: INFO/HtcLockScreen(94): Press Menu key to unlock screen
</code>```

I am wondering about one point there is nothing in the sdcard and in front of it there is no device selected . May be it can be the cause of error , here is the picture

答:
The easiest solution I found is to use Context.getFileDir() as storage location. This has the following advantages over Context.getExternalFilesDir():

it also works when there is no SD-card (in your device or emulator)

it does not need any additional permissions

Example-code to start method-tracing:

```<code>final File methodTracingFile = new File(getFilesDir(), "AppStart.trace");
Log.d(TAG, "methodTracingPath=" + methodTracingFile.getPath());
Debug.startMethodTracing(methodTracingFile.getPath());
</code>```

Note: it's a good idea to log the methodTracingPath to see where the file will be stored.

Example: /data/data/com.YOUR_PACKAGE.debug/files/AppStart.trace

To copy the file from your Emulator to your PC, you can use the File Explorer in the Android Device Monitor (see Working with an emulator or device's file system)

select the trace file

click the Pull a file from device button to copy it to your local PC

Finally you can just drag&drop the trace file to Android Studio to see the method trace-view.

Title: unable to open trace file

Body:
I want to test the performance of my app . I have started it with simple application and try to put traceview but its suddenly fail on my android phone with force to close. Please guide me how can i set my code propley for simple android app to get hands dirt with Trace view

Here is the code
package test.check;

import android.app.Activity;
import android.os.Bundle;
import android.os.Debug;

public class tracev extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Debug.startMethodTracing("traceview");
        setContentView(R.layout.main);
    }
    @Override
    protected void onStop() {
        Debug.stopMethodTracing();
        super.onStop();
    }
}

Here is the manifest file

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="test.check"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".tracev"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

I have also added

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

but its not working . I think its becasue of this line in the logcat but i am not sure how  to deal with it

05-20 23:39:43.913: ERROR/dalvikvm(11673): Unable to open trace file '/sdcard/traceview.trace': Permission denied

Logcat

05-20 23:39:43.903: DEBUG/dalvikvm(11673): +++ active profiler count now 1
05-20 23:39:43.913: INFO/dalvikvm(11673): TRACE STARTED: '/sdcard/traceview.trace' 8192KB
05-20 23:39:43.913: ERROR/dalvikvm(11673): Unable to open trace file '/sdcard/traceview.trace': Permission denied
05-20 23:39:43.913: DEBUG/dalvikvm(11673): +++ active profiler count now 0
05-20 23:39:43.913: DEBUG/AndroidRuntime(11673): Shutting down VM
05-20 23:39:43.913: WARN/dalvikvm(11673): threadid=3: thread exiting with uncaught exception (group=0x4001e390)
05-20 23:39:43.913: ERROR/AndroidRuntime(11673): Uncaught handler: thread main exiting due to uncaught exception
05-20 23:39:43.983: ERROR/AndroidRuntime(11673): java.lang.RuntimeException: Unable to start activity ComponentInfo{test.check/test.check.tracev}: java.lang.RuntimeException: file open failed
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Looper.loop(Looper.java:123)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.main(ActivityThread.java:4595)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at java.lang.reflect.Method.invokeNative(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at java.lang.reflect.Method.invoke(Method.java:521)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.NativeStart.main(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673): Caused by: java.lang.RuntimeException: file open failed
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.VMDebug.startMethodTracing(Native Method)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at dalvik.system.VMDebug.startMethodTracing(VMDebug.java:156)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Debug.startMethodTracing(Debug.java:443)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.os.Debug.startMethodTracing(Debug.java:391)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at test.check.tracev.onCreate(tracev.java:12)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-20 23:39:43.983: ERROR/AndroidRuntime(11673):     ... 11 more
05-20 23:39:44.013: INFO/Process(94): Sending signal. PID: 11673 SIG: 3
05-20 23:39:44.013: INFO/dalvikvm(11673): threadid=7: reacting to signal 3
05-20 23:39:44.023: INFO/dalvikvm(11673): Wrote stack trace to '/data/anr/traces.txt'
05-20 23:39:51.213: DEBUG/KeyguardViewMediator(94): pokeWakelock(15000)
05-20 23:39:51.213: INFO/HtcLockScreen(94): Press Menu key to unlock screen

I am wondering about one point there is nothing in the sdcard and in front of it there is no device selected . May be it can be the cause of error , here is the picture

Body:
The easiest solution I found is to use Context.getFileDir() as storage location. This has the following advantages over Context.getExternalFilesDir():

it also works when there is no SD-card (in your device or emulator)

it does not need any additional permissions

Example-code to start method-tracing:

final File methodTracingFile = new File(getFilesDir(), "AppStart.trace");
Log.d(TAG, "methodTracingPath=" + methodTracingFile.getPath());
Debug.startMethodTracing(methodTracingFile.getPath());

Note: it's a good idea to log the methodTracingPath to see where the file will be stored.

Example: /data/data/com.YOUR_PACKAGE.debug/files/AppStart.trace

To copy the file from your Emulator to your PC, you can use the File Explorer in the Android Device Monitor (see Working with an emulator or device's file system)

select the trace file

click the Pull a file from device button to copy it to your local PC

Finally you can just drag&drop the trace file to Android Studio to see the method trace-view.


问:
Python - Transfer string without escape or with encoding?
Python 2.7.10 Shell

```<code>>>> a = "\\xe4\\xbb\\xa5\\xe5\\x8f\\xa5\\xe3\\x81\\x82\\xe3\\x81\\xae"
>>> b = "\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae"

>>> print a
\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae

>>> print b
以句あの

>>>
</code>```

Var a is exactly same as var b in our eyes, but they are different in bytes/bits level. Now I want the print-result of a is same as the print-result of b, any solutions?

In other word, how to transfer a to b ?

Thanks in advance :)

Thanks to @Bishakh Ghosh 's answer, help me a lot.

In the specific version of my Python:

```<code>>>> print a.decode('string-escape')
以句あの
>>> print a.decode('unicode_escape')
ä»¥å¥ãã

>>> b = a.decode('string-escape')
</code>```

Thanks ~~~ ((●'◡'●)ﾉ♥

答:
This should do the trick:

```<code>b = a.decode('string-escape')
</code>```

Or if you want to print a directly:

```<code>print(a.decode('string-escape'))
</code>```

Body:
Python 2.7.10 Shell

>>> a = "\\xe4\\xbb\\xa5\\xe5\\x8f\\xa5\\xe3\\x81\\x82\\xe3\\x81\\xae"
>>> b = "\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae"

>>> print a
\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae

>>> print b
以句あの

>>>

Var a is exactly same as var b in our eyes, but they are different in bytes/bits level. Now I want the print-result of a is same as the print-result of b, any solutions?

In other word, how to transfer a to b ?

Thanks in advance :)

Thanks to @Bishakh Ghosh 's answer, help me a lot.

In the specific version of my Python:

>>> print a.decode('string-escape')
以句あの
>>> print a.decode('unicode_escape')
ä»¥å¥ãã

>>> b = a.decode('string-escape')

Thanks ~~~ ((●'◡'●)ﾉ♥

Body:
This should do the trick:

b = a.decode('string-escape')

Or if you want to print a directly:

print(a.decode('string-escape'))


问:
SSRS: Filter 1 datasets with the value from the second dataset
I have two datasets from 2 different data Sources.
1- M
2- C
this two datasets have a column name ID. I want to filter M dataset with the id's in C datasets
can you help?</p>

答:
You cannot use one dataset to filter another dataset.  The only way you could get approximate functionality would be to either populate a multi-value parameter with one dataset and then use that as an exclusion criteria in the second, or to have a lookup filter on all your report items.

Both of these options will run very badly.

I would recommend looking at why you need to filter the results from one data source with the results of another, as this reeks of either bad design or misunderstanding requirements.