问:
Android App not loading in Emulator after Android Studio 2.3 Update
I have just uploaded my Android Studio version to 2.3, and I am now having problems testing my app in my emulator. It is a Nexus 5X emulator with Android 7.0 Nougat loaded on it (API 24), with an ABI: armeabi-v7a (I have an AMD processor, so to the best of my knowledge I can only use this). Before, it was a bit slow and would sometimes come up with a 'Not Responding' error, but clicking 'Wait' would always do the trick.

After the Android Studio update, when I press 'Run', it opens up & boots the emulator. However, once booted, it gets stuck on the "Launching App - Installing APKs" process. It probably shows that it is doing this for about 2 minutes, before stopping. It then shows "Launching Instant Run Service" for a few seconds. The green 'run' arrow then becomes active again, as if there is no emulator open. The emulator is open, but there is no app. If I click the green 'run' arrow with the emulator already open, it does a gradle build sync & then doesn't even attempt to launch the app/install APKs - it only says "Launching Instant Run Service" for a few seconds, even though nothing happens.

I have tried removing the emulator & recreating it, and I have also tried fiddling with some of the parameters as suggested in other posts which concern similar (but not identical) issues to this. The first time I tried to run the app on the emulator after the update, I had many messages pop up in the event log, saying Android Studio Can't Bind to Local 86xx for debugger, whilst the Android Device Monitor was opened. Ever since then, with the ADM closed, I have had the problem described above, with no error messages showing in the error log.

Any help with this issue would be very much appreciated - please note it concerns the very latest version of Android Studio which I have only just had a popup requesting that I install. Build Tools Version in build.gradle has also been updated from 24.0.2 to 25.0.0.

答:
I tried all of the aforementioned and it didn't help. What helped was disabling Instant Run in Settings -> Build, Execution, Deployment -> Instant Run.

Relevant issue in AOSP bugtracker: https://code.google.com/p/android/issues/detail?id=235879


来源: stackexchange

问:
How to get the current time in android
I want to get the current time in Android. It should be displayed like 2:30pm and I want to store it in a database. I searched a lot. But I don't know how to do it. How can I achieve this?</p>

答:
I get perfect time using below........</p>
```<code> String Time = java.text.DateFormat.**getTimeInstance()**.format(new Date());
 //and for to get date try it as below
 String date_L = java.text.DateFormat.**getDateInstance()**.format(new Date());
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get the current time in android

Body:
I get perfect time using below........

 String Time = java.text.DateFormat.**getTimeInstance()**.format(new Date());
 //and for to get date try it as below
 String date_L = java.text.DateFormat.**getDateInstance()**.format(new Date());

ContentLicense: CC BY-SA 4.0


问:
Prototypal inheritance with nested objects
I'm trying to get my head around prototype inheritance in Javascript. I think I got the basic concept, but when I was playing around with this I ran into the following which still has me puzzled.

There is a very similar question and answer here but it doesn't fully answer why this is happening, at least not for me.

I create a new object like this:

```<code>var User = {
  username: "",
  name: {
    first: "",
    last: ""
  }
}
</code>```

Next I create two "instances" of that object:

```<code>var user1 = Object.create(User);
var user2 = Object.create(User);
</code>```

Now I set the name property like so:

```<code>user1.name = { first: "John", last: "Jackson"}
user2.name = { first: "James", last: "Jameson"}
</code>```

Now I do

alert(user1.name.first) \\ -> John
alert(user2.name.first) \\ -> James

All as expected. So far so good.

However, if I set the name.first property like this:

```<code>user1.name.first = "John";
user2.name.first = "James";
</code>```

and I get

```<code>alert(user1.name.first) \\ -> James
alert(user2.name.first) \\ -> James
</code>```

Clearly now the property is being set on the prototype object User (or rather the contained name object) instead of overriding it in the current object user1. Why does that occur?

Further if I do

```<code>user1.name.middle = "Mortimer"
</code>```

I can now do

```<code>alert(User.name.middle) // -> Mortimer
</code>```

which is not what I would expect. Generally, whenever a property is set on a derived object, that object either already has that property as an ownProperty in which case the value is simply assigned, or the property is newly created as an ownProperty on the derived object, overriding the prototype property. Just like happens when I assign to user1.name.

So why does assigning to an object contained in the prototype object cause such (at least to me) unexpected and counter-intuitive behavior?

The way I understand it, when the assignment is made the first check is to see if user1 has an ownProperty called name, which it doesn't. If this were a read operation the prototype property would now be looked up and User checked to see if it has ownProperty name. But since this is a set operation why walk the prototype chain when usually a missing ownProperty is simply created?

答:
Since you've already read over similar questions and answers and still seem to be having trouble understanding the behavior, I'll try to make my explanation as clear as possible. Here is where I think you are going wrong (emphasis mine):

Generally, whenever a property is set on a derived object, that object either already has that property as an ownProperty in which case the value is simply assigned, or the property is newly created as an ownProperty on the derived object, overriding the prototype property. Just like happens when I assign to user1.name.

The problem here is that you assume that user.name.first counts as "a property  . . . set on a derived object" (an instance of User). However, this is simply not the case. In JavaScript, inheritance of properties is only shallow (a single layer deep). user.name is just an object value shared by reference through the prototype, so modifications to it from one place are reflected everywhere.

Think of user1.name and user2.name like firstReference and secondReference in the following example snippet, and hopefully the behavior will seem a bit clearer to you.

var User = {
  username: "",
  name: {
    first: "",
    last: ""
  }
}

var firstReference = User.name
var secondReference = User.name

firstReference.name.first = 'First!'

console.log(secondReference.name) //=> 'First!' (logical and expected result)```

Body:
I'm trying to get my head around prototype inheritance in Javascript. I think I got the basic concept, but when I was playing around with this I ran into the following which still has me puzzled.

There is a very similar question and answer here but it doesn't fully answer why this is happening, at least not for me.

I create a new object like this:

var User = {
  username: "",
  name: {
    first: "",
    last: ""
  }
}

Next I create two "instances" of that object:

var user1 = Object.create(User);
var user2 = Object.create(User);

Now I set the name property like so:

user1.name = { first: "John", last: "Jackson"}
user2.name = { first: "James", last: "Jameson"}

Now I do

alert(user1.name.first) \\ -> John
alert(user2.name.first) \\ -> James

All as expected. So far so good.

However, if I set the name.first property like this:

user1.name.first = "John";
user2.name.first = "James";

and I get

alert(user1.name.first) \\ -> James
alert(user2.name.first) \\ -> James

Clearly now the property is being set on the prototype object User (or rather the contained name object) instead of overriding it in the current object user1. Why does that occur?

Further if I do

user1.name.middle = "Mortimer"

I can now do

alert(User.name.middle) // -> Mortimer

which is not what I would expect. Generally, whenever a property is set on a derived object, that object either already has that property as an ownProperty in which case the value is simply assigned, or the property is newly created as an ownProperty on the derived object, overriding the prototype property. Just like happens when I assign to user1.name.

So why does assigning to an object contained in the prototype object cause such (at least to me) unexpected and counter-intuitive behavior?

The way I understand it, when the assignment is made the first check is to see if user1 has an ownProperty called name, which it doesn't. If this were a read operation the prototype property would now be looked up and User checked to see if it has ownProperty name. But since this is a set operation why walk the prototype chain when usually a missing ownProperty is simply created?


答:
The Object.create method creates an object using the first parameter as a prototype, and the second, optional, parameter is an additional object of own properties.

I think the problem here is that name is, by definition, in the prototype, and so not an own property.

If you want separate properties, then you should use the second parameter. The prototype is where you store methods and shared properties.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

has more details.

The key is that you want both prototype and own properties.

Title: Prototypal inheritance with nested objects


问:
Recv with TCP packet stream not sending ACK packet
Hi I am writing a application that uses TCP to communicate with a HTTP server. However I am seeing that I don't respond with an ACK packet after each data packet is received.

Is this handled by the RECV routine?

答: If you are referring to the TCP level ACK, then yes, this is handled by the protocol stack.</p>

ContentLicense: CC BY-SA 2.5


问:
C#: non-flag enum, is there any easier way for checking enum to match one of multiple values?
Here is the sample, CommandType is an enum. It's a none flag enum.

```<code>CommandType cmdType = CommandType.back;
if (cmdType == CommandType.back || cmdType == CommandType.forward || cmdType == CommandType.previous || cmdType == CommandType.home)
{
//do something
}
</code>```

Is there any way to simplify the "if" statement?

答:
You can use a switch statement</p>

```<code>CommandType cmdType = CommandType.home;

switch(cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
        // do somethinig
        break;
}
</code>```

Body:
Here is the sample, CommandType is an enum. It's a none flag enum.

CommandType cmdType = CommandType.back;
if (cmdType == CommandType.back || cmdType == CommandType.forward || cmdType == CommandType.previous || cmdType == CommandType.home)
{
//do something
}

Is there any way to simplify the "if" statement?

Body:
You can use a switch statement

CommandType cmdType = CommandType.home;

switch(cmdType)
{
    case CommandType.back:
    case CommandType.forward:
    case CommandType.previous:
    case CommandType.home:
        // do somethinig
        break;
}


问:
Loop through an excel file, find certain cell values and write into text files
I am making text files out of information from an existing excel file. Not all of the information in the excel file is supposed to be written in the text files, but I want my code to loop through the file and choose information from rows according to certain cell values.

Here is my code so far, however, when I run the code nothing happens and the text files are not generated. I do not get an error message either. Does anyone know what I am missing?

```<code>import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = 275
number_lines = 1

for row in range(number_rows):
    for col in 1, :     #Column where the cell value decides wether or not information in the row should be added to the text file.
        value = book.sheets()[0].cell(row, col).value
        if value == 19:   #Rows where 19 is the cell value in column 1 is to be focused on.
            txtfilename = 'Mytextfile' + str(row) + '.txt'
            with open(txtfilename, "w") as f:
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass
</code>```

Any help is greatly appreciated!
I am working in Python3.4.1

答:
To write all the rows that include the string "19" in column 1 into the same text file, you can do:

```<code>import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = book.sheets()[0].nrows
number_lines = 1
column_target = 1
txtfilename = 'Mytextfile.txt'

with open(txtfilename, "w") as f:
    for row in range(number_rows):
        value = book.sheets()[0].cell(row, column_target).value
        if value == "19":   #Rows where 19 is the cell value in column 1 is to be focused on.
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass
</code>```

Basically, just move the file scope outside of the loop so that the same file can be reused for multiple rows.

Body:
I am making text files out of information from an existing excel file. Not all of the information in the excel file is supposed to be written in the text files, but I want my code to loop through the file and choose information from rows according to certain cell values.

Here is my code so far, however, when I run the code nothing happens and the text files are not generated. I do not get an error message either. Does anyone know what I am missing?

import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = 275
number_lines = 1

for row in range(number_rows):
    for col in 1, :     #Column where the cell value decides wether or not information in the row should be added to the text file.
        value = book.sheets()[0].cell(row, col).value
        if value == 19:   #Rows where 19 is the cell value in column 1 is to be focused on.
            txtfilename = 'Mytextfile' + str(row) + '.txt'
            with open(txtfilename, "w") as f:
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass

Any help is greatly appreciated!
I am working in Python3.4.1

Body:
To write all the rows that include the string "19" in column 1 into the same text file, you can do:

import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = book.sheets()[0].nrows
number_lines = 1
column_target = 1
txtfilename = 'Mytextfile.txt'

with open(txtfilename, "w") as f:
    for row in range(number_rows):
        value = book.sheets()[0].cell(row, column_target).value
        if value == "19":   #Rows where 19 is the cell value in column 1 is to be focused on.
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass

Basically, just move the file scope outside of the loop so that the same file can be reused for multiple rows.


问:
Is there any limit of bundle in Android?
I want to know whether android bundle's data size has upper limit. I try to post data by bundle which size >80k,and throw android fatal exception.The data is Serializable.</p>

答:
Yes it has, and now in android Nougat it will crash if you exceeded the limit roughly(500Kb).

android nougat issue


问:
EntityFramework Interceptor not working in Config File
I am trying to integrate IDbCommandInterceptor to my project. I am using EntityFramework version 6.0. I created interceptor class like this:

```<code>namespace MyApp.Data
{
    public class EFCommandInterceptor : IDbCommandInterceptor
    {
        public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        private void LogInfo(string command, string commandText)
        {
            Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
        }
    }
}
</code>```

When I try to add this interceptor class using code configuration then its working fine. But I want to add this interceptor using config setting as mention in article Interception. My config file looks like this:

```<code><entityFramework>
<interceptors>
  <interceptor type="MyApp.Data.EFCommandInterceptor, MyApp.Data"></interceptor>
</interceptors>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</code>```

But it is giving error that:

Unrecognized element 'interceptors'

I have entity config setting in app config file:

```<code><configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</code>```

Note: My data access layer is in separate class library. EDMX file is present in Data project. Presentation layer has reference to Data layer. Entity framework is present in both the project and has same version.

答:
Short Answer: EF Interceptors can only be configured with Config file starting from 6.1, Refer

EF Config settings from Microsoft

Long Answer:
Moreover, If you go and check C:\Program Files (x86)\Microsoft Visual Studio 12.0\Xml\Schemas directory and try to open EntityFrameworkConfig_6_0_0.xsd you will notice that interceptors is not declared as child element:

Content of EntityFrameworkConfig_6_0_0.xsd (Does not contain
  Interceptors tag)

 <xs:element name="entityFramework">
    <xs:complexType>
    <xs:all>
    <xs:element name="defaultConnectionFactory" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
    <xs:element name="providers" type="ProviderList_Type" minOccurs="0" maxOccurs="1" />
    <xs:element name="contexts" type="ContextList_Type" minOccurs="0" maxOccurs="1" />
    </xs:all>
    <xs:attribute name="codeConfigurationType" type="NonEmptyString_Type" use="optional" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
    </xs:element>```
</div>
</div>
</p>

<blockquote>
  <p>Content of EntityFrameworkConfig_6_1_0.xsd (Does contain
  Interceptors tag)</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <xs:element name="entityFramework">
    <xs:complexType>
      <xs:all>
        <xs:element name="defaultConnectionFactory" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="providers" type="ProviderList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="contexts" type="ContextList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="interceptors" type="InterceptorList_Type" minOccurs="0" maxOccurs="1" />
      </xs:all>
      <xs:attribute name="codeConfigurationType" type="NonEmptyString_Type" use="optional" />
      <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
  </xs:element></code>```

Body:
I am trying to integrate IDbCommandInterceptor to my project. I am using EntityFramework version 6.0. I created interceptor class like this:

namespace MyApp.Data
{
    public class EFCommandInterceptor : IDbCommandInterceptor
    {
        public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
        {
            LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}", interceptionContext.IsAsync, command.CommandText));
        }

        private void LogInfo(string command, string commandText)
        {
            Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
        }
    }
}

When I try to add this interceptor class using code configuration then its working fine. But I want to add this interceptor using config setting as mention in article Interception. My config file looks like this:

<entityFramework>
<interceptors>
  <interceptor type="MyApp.Data.EFCommandInterceptor, MyApp.Data"></interceptor>
</interceptors>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

But it is giving error that:

Unrecognized element 'interceptors'

I have entity config setting in app config file:

<configSections>

Note: My data access layer is in separate class library. EDMX file is present in Data project. Presentation layer has reference to Data layer. Entity framework is present in both the project and has same version.

Body:
Short Answer: EF Interceptors can only be configured with Config file starting from 6.1, Refer

EF Config settings from Microsoft

Long Answer:
Moreover, If you go and check C:\Program Files (x86)\Microsoft Visual Studio 12.0\Xml\Schemas directory and try to open EntityFrameworkConfig_6_0_0.xsd you will notice that interceptors is not declared as child element:

Content of EntityFrameworkConfig_6_0_0.xsd (Does not contain
  Interceptors tag)

 <xs:element name="entityFramework">
    <xs:complexType>
    <xs:all>
    <xs:element name="defaultConnectionFactory" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
    <xs:element name="providers" type="ProviderList_Type" minOccurs="0" maxOccurs="1" />
    <xs:element name="contexts" type="ContextList_Type" minOccurs="0" maxOccurs="1" />
    </xs:all>
    <xs:attribute name="codeConfigurationType" type="NonEmptyString_Type" use="optional" />
    <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
    </xs:element>

Content of EntityFrameworkConfig_6_1_0.xsd (Does contain
  Interceptors tag)

 <xs:element name="entityFramework">
    <xs:complexType>
      <xs:all>
        <xs:element name="defaultConnectionFactory" type="ElementWithTypeAndParameters_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="providers" type="ProviderList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="contexts" type="ContextList_Type" minOccurs="0" maxOccurs="1" />
        <xs:element name="interceptors" type="InterceptorList_Type" minOccurs="0" maxOccurs="1" />
      </xs:all>
      <xs:attribute name="codeConfigurationType" type="NonEmptyString_Type" use="optional" />
      <xs:anyAttribute namespace="http://schemas.microsoft.com/XML-Document-Transform" processContents="strict"/>
    </xs:complexType>
  </xs:element>


问:
Calculating SHA 3 Hash in Java
I have been using CryptoJS (i.e. CryptoJS.algo.SHA3.creat()) library to SHA-3 hash on the front end. (see http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha3.js)

I was wondering if there are any Java library equivalence? But so far I haven't found any. There are not so many Java SHA-3 examples either.

sun.security.Provider has SHA-3, but it's not visible under Eclipse. Also, I am not sure whether this sun's SHA-3 is same as the CryptoJS's SHA-3.

Could anyone please provide some examples?

答:
Thanks to @jdv for his answer.
I'm adding more information to have a quick start and an example.

First, add the BouncyCastle maven dependency, or get it on Maven Central :

```<code>    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk15on</artifactId>
        <version>1.56</version>
    </dependency>
</code>```

Then we can test it :

```<code>import org.bouncycastle.jcajce.provider.digest.SHA3;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;

@Test
public void testSha3() throws Exception {
    String input = "Hello world !";
    SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest512();
    byte[] digest = digestSHA3.digest(input.getBytes());

    System.out.println("SHA3-512 = " + Hex.toHexString(digest));
}
</code>```

You'll get this result (512 bits or 64 bytes in hexadecimal) :

SHA3-512 = e9a4fd120d684537d57f314d51213ce5acef8ff6974e2b7599674ef0f0a3cf111f0d26ed602db946739da448210fb76a7621d7a8f07728372b10a975f36d8e37

You can compare it with this result : https://duckduckgo.com/?q=sha3+%22Hello+world+!%22&ia=answer

Title: Calculating SHA 3 Hash in Java

Body:
Thanks to @jdv for his answer.
I'm adding more information to have a quick start and an example.

First, add the BouncyCastle maven dependency, or get it on Maven Central :

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk15on</artifactId>
        <version>1.56</version>
    </dependency>

Then we can test it :

import org.bouncycastle.jcajce.provider.digest.SHA3;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;

@Test
public void testSha3() throws Exception {
    String input = "Hello world !";
    SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest512();
    byte[] digest = digestSHA3.digest(input.getBytes());

    System.out.println("SHA3-512 = " + Hex.toHexString(digest));
}

You'll get this result (512 bits or 64 bytes in hexadecimal) :

SHA3-512 = e9a4fd120d684537d57f314d51213ce5acef8ff6974e2b7599674ef0f0a3cf111f0d26ed602db946739da448210fb76a7621d7a8f07728372b10a975f36d8e37

You can compare it with this result : https://duckduckgo.com/?q=sha3+%22Hello+world+!%22&ia=answer


问:
yii2 BizleyDetailView css class
I have a very very nice basic horizontal DetailView from Bizley

I would like to add:

```<code>'contentOptions' => ['class' => 'danger'],
</code>```

based on this tip. But unfortunately it's not working. Am I missing something, or it shouldn't work? Can you please point me to the right direction? Many thanks!

答:
This option is available from 2.0.10. You need to modify my class like this:</p>

```<code>namespace app\widgets;

use yii\widgets\DetailView;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MyDetailView extends DetailView
{
    public $template = '<td{contentOptions}>{value}</td>';
    public $headerTemplate = '<th{captionOptions}>{label}</th>';

    public function run()
    {
        $rows = [];
        $headers = [];
        $i = 0;
        foreach ($this->attributes as $attribute) {
            list($row, $header) = $this->renderAttribute($attribute, $i++);
            $rows[] = $row;
            $headers[] = $header;
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        $topRow = Html::tag('tr', implode("\n", $headers));
        $dataRow = Html::tag('tr', implode("\n", $rows));
        echo Html::tag($tag, $topRow . $dataRow, $options);
    }

    protected function renderAttribute($attribute, $index)
    {
        if (is_string($this->template)) {
            $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', []));
            $row = strtr($this->template, [
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
                '{contentOptions}' =>  $contentOptions,
            ]);
        } else {
            $row = call_user_func($this->template, $attribute, $index, $this);
        }
        if (is_string($this->headerTemplate)) {
            $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', []));
            $header = strtr($this->headerTemplate, [
                '{label}' => $attribute['label'],
                '{captionOptions}' => $captionOptions,
            ]);
        } else {
            $header = call_user_func($this->headerTemplate, $attribute, $index, $this);
        }
        return [$row, $header];
    }
}
</code>```

Title: yii2 BizleyDetailView css class

Body:
I have a very very nice basic horizontal DetailView from Bizley

I would like to add:

'contentOptions' => ['class' => 'danger'],

based on this tip. But unfortunately it's not working. Am I missing something, or it shouldn't work? Can you please point me to the right direction? Many thanks!

Body:
This option is available from 2.0.10. You need to modify my class like this:

namespace app\widgets;

use yii\widgets\DetailView;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class MyDetailView extends DetailView
{
    public $template = '<td{contentOptions}>{value}</td>';
    public $headerTemplate = '<th{captionOptions}>{label}</th>';

    public function run()
    {
        $rows = [];
        $headers = [];
        $i = 0;
        foreach ($this->attributes as $attribute) {
            list($row, $header) = $this->renderAttribute($attribute, $i++);
            $rows[] = $row;
            $headers[] = $header;
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');
        $topRow = Html::tag('tr', implode("\n", $headers));
        $dataRow = Html::tag('tr', implode("\n", $rows));
        echo Html::tag($tag, $topRow . $dataRow, $options);
    }

    protected function renderAttribute($attribute, $index)
    {
        if (is_string($this->template)) {
            $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', []));
            $row = strtr($this->template, [
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
                '{contentOptions}' =>  $contentOptions,
            ]);
        } else {
            $row = call_user_func($this->template, $attribute, $index, $this);
        }
        if (is_string($this->headerTemplate)) {
            $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', []));
            $header = strtr($this->headerTemplate, [
                '{label}' => $attribute['label'],
                '{captionOptions}' => $captionOptions,
            ]);
        } else {
            $header = call_user_func($this->headerTemplate, $attribute, $index, $this);
        }
        return [$row, $header];
    }
}


问:
Find name using like operator in SQL Server
I have table with columns

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard
</code>```

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
</code>```

答:
```<code>select
c.* from table c
join
(select substring(surname,1,charindex(' ',surname,1)) as namee,forename from table
group by
substring(surname,1,charindex(' ',surname,1)),forename
having count(*)>1
) b
on c.surname like '%'+b.namee+'%'
and c.forename=b.forename
</code>```

one more approach :

```<code>;with cte
as
(
select *,count(*) over (partition by substring(surname,1,charindex(' ',surname,1)),forename ) as cnt
from table
)
select * from cte  where cnt>1
</code>```

Body:
I have table with columns

surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

surname    forename
Dane jr    Carlo
Dane Br    Carlo

Body:
select
c.* from table c
join
(select substring(surname,1,charindex(' ',surname,1)) as namee,forename from table
group by
substring(surname,1,charindex(' ',surname,1)),forename
having count(*)>1
) b
on c.surname like '%'+b.namee+'%'
and c.forename=b.forename

one more approach :

;with cte
as
(
select *,count(*) over (partition by substring(surname,1,charindex(' ',surname,1)),forename ) as cnt
from table
)
select * from cte  where cnt>1


问:
enable and disable jquery draggable containment on click
i have created an jquery draggable example,

```<code> <!DOCTYPE html>
<html>
<head>
  <style type="text/css">
.container{
    width:400px;
    height:200px;
    border:1px solid red;
}
#draggable{
    width: 100px;
    height: 50px;
}
  </style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script type="text/javascript">
    $( "#draggable" ).draggable({
    containment: ".container"
        });
  </script>
</head>
<body>
<div class="container">
    <div id="draggable" class="ui-widget-content">
        <p>Drag me around</p>
    </div>
</div>
<input type= "button" value="toggle containment" id="buttonContain">
</body>
</html>
</code>```

in which, can i remove jquery draggable containment option after adding jquery drggable widget?  plz help

答:
You can use

```<code> $("#draggable").draggable('disable');
</code>```

for disable and

```<code>$("#draggable").draggable('enable');
</code>```

for enable on button click

Body:
i have created an jquery draggable example,

 <!DOCTYPE html>

Drag me around

<input type= "button" value="toggle containment" id="buttonContain">

in which, can i remove jquery draggable containment option after adding jquery drggable widget?  plz help

Body:
You can use

 $("#draggable").draggable('disable');

for disable and

$("#draggable").draggable('enable');

for enable on button click


问:
Standard or Legacy SQL for Google Analytics Data in BigQuery?
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?<br>
In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ? </p>

答:
Go with Standard SQL, as that's on the longterm roadmap.

From experience some queries are faster under Legacy SQL, but this is changing as Standard SQL is the one that is actively developed.

Body:
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?

In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ?


问:
How to drop columns by name pattern in R?
I have this dataframe:

```<code>state county city  region  mmatrix  X1 X2 X3    A1     A2     A3      B1     B2     B3      C1      C2      C3

  1      1     1      1     111010   1  0  0     2     20    200       Push      8     12      NA      NA      NA
  1      2     1      1     111010   1  0  0     4     NA    400       Shove      9     NA
</code>```

Now I want to exclude columns whose names end with a certain string, say "1" (i.e. A1 and B1). I wrote this code:

```<code>df_redacted <- df[, -grep("\\1$", colnames(df))]
</code>```

However, this seems to delete every column. How can I modify the code so that it only deletes the columns that matches the pattern (i.e. ends with "3" or any other string)?

The solution has to be able to handle a dataframe with has both numerical and categorical values.

答:
Just as an additional answer, since I stumbled across this, when looking for the data.table solution to this problem.

```<code>library(data.table)
dt <- data.table(df)
drop.cols <- grep("1$", colnames(dt))
dt[, (drop.cols) := NULL]
</code>```

Body:
I have this dataframe:

state county city  region  mmatrix  X1 X2 X3    A1     A2     A3      B1     B2     B3      C1      C2      C3

  1      1     1      1     111010   1  0  0     2     20    200       Push      8     12      NA      NA      NA
  1      2     1      1     111010   1  0  0     4     NA    400       Shove      9     NA

Now I want to exclude columns whose names end with a certain string, say "1" (i.e. A1 and B1). I wrote this code:

df_redacted <- df[, -grep("\\1$", colnames(df))]

However, this seems to delete every column. How can I modify the code so that it only deletes the columns that matches the pattern (i.e. ends with "3" or any other string)?

The solution has to be able to handle a dataframe with has both numerical and categorical values.

Body:
Just as an additional answer, since I stumbled across this, when looking for the data.table solution to this problem.

library(data.table)
dt <- data.table(df)
drop.cols <- grep("1$", colnames(dt))
dt[, (drop.cols) := NULL]


问:
how can i access value outside the if condition in c#
How can I use this 'download' outside the if condition?

```<code>if (rblFinancialYear.Checked)
{
  var download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}
</code>```

If I return using return type means which datatypes I use here.

答:
Then create the variable outside if condition with exact type like

```<code>type download = null;
if (rblFinancialYear.Checked)
{
  //rest code
}
</code>```

Well looks like you are projecting a Anomymous type as seen below and thus you have no other way than using var and using var to create variable is illegal.

```<code>                select new
                {
                  appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                  empId = appraisals.EmpID,
                })
</code>```

This the solution would to create a DTO or ViewModel and use that instead like

```<code>public class TestViewModel
{
  public int appraisalActivityMasteId {get; set; }
  public int empId {get; set; }
}
</code>```

//Create variable

```<code>List<TestViewModel> model = null;
</code>```

Now you can use it like

```<code>model = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new TestViewModel
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}
</code>```

Body:
How can I use this 'download' outside the if condition?

if (rblFinancialYear.Checked)
{
  var download = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}

If I return using return type means which datatypes I use here.

Body:
Then create the variable outside if condition with exact type like

type download = null;
if (rblFinancialYear.Checked)
{
  //rest code
}

Well looks like you are projecting a Anomymous type as seen below and thus you have no other way than using var and using var to create variable is illegal.

                select new
                {
                  appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                  empId = appraisals.EmpID,
                })

This the solution would to create a DTO or ViewModel and use that instead like

public class TestViewModel
{
  public int appraisalActivityMasteId {get; set; }
  public int empId {get; set; }
}

//Create variable

List<TestViewModel> model = null;

Now you can use it like

model = (from appraisals in dbClientContext.PmsAppraisalActivityMasters
                    select new TestViewModel
                    {
                      appraisalActivityMasteId = appraisals.AppraisalActivityMasterID,
                      empId = appraisals.EmpID,
                    })
                    Where(r => r.kpiStartDate >= dtFYStart && r.kpiStartDate <= dtFYEnd).ToList();
}


问:
Angular 2/PrimeNg - Update Chart via @ViewChild
I am using Angular2 with PrimeNG for my app.
I have a dashboard with charts.
I tried to update to PrimeNG rc7 (from rc5, where they fixed an issue with updating charts), but because of their changes I don't know how to update my chart anymore, as it has to be done by calling a method.

I've read about the @ViewChild decorator, but I don't really know how to use it.

my chart.html:

```<code><p-chart #linechart  type="line" #linechart
 id="linechart" [data]="ntwdata" [options]="options">
</p-chart>
</code>```

my dashboard.ts:

```<code>import { NTWDATA } from '../resources/mock/chartdata';

import { UIChart } from 'primeng/primeng';

@Component({
   selector: 'my-dashboard',
   templateUrl: 'dist/html/dashboard.component.html',
})

export class DashboardComponent {
   ntwdata = NTWDATA;
   options: any;

   constructor() {

   }

   ngOnInit() {

         this.options = {
            animation: false,
            legend: {
               display: true,
               labels: {
                  boxWidth: 0,
               }

            },
            scales: {
               yAxes: [{
                  scaleLabel: {
                     display: true,
                     labelString: "ms"
                  },
                  ticks: {
                     beginAtZero: true,
                     suggestedMax: 100,
                  }

               }],
               xAxes: [{
                  ticks: {
                     beginAtZero: true,
                     maxTicksLimit: 6,
                  }
               }]

            }
      }
   }
}
</code>```

The NTWDATA gets updates every 2.5s and with my data everything is fine.

My DashboardComponent is a child of the component where the data gets updated it.

parent component:

```<code>...
setInterval(()=>{
   NTWDATA.push(//mydata)
},2500);
...
</code>```

I have tried to add @ViewChild to my parent like so:

```<code>@ViewChild("linechart") chart: UIChart
</code>```

Then I called the refresh() methode within my setInterval:

```<code>setInterval(()=>{
   NTWDATA.push(//mydata)
   this.chart.refresh();
},2500);
</code>```

But this.chart is undefined.

Then I tried to use @ViewChild like so:

```<code>@ViewChild(Dashboard) dashcomp: Dashboard;
setInterval(()=>{
       NTWDATA.push(//mydata)
       this.dashcomp.chart.refresh();
    },2500);
</code>```

and in my child:

```<code>@ViewChild('linechart') chart: UIChart;
</code>```

As I said, I never rly worked with @ViewChild before and I dont think I understand it that well by now, so if any of you guys has an idea, I'd appreciate it, if you'd talk to me as if I'm stupid! :D

Thanks in advance!

答:
update labels and datasets also.

```<code>this.chart.data.labels = labels;
this.chart.data.datasets = datasets;
</code>```

try setting a timeout on chart.refresh() with a delay of few seconds 100ms or 1 200ms.

It works for me.

Body:
I am using Angular2 with PrimeNG for my app.
I have a dashboard with charts.
I tried to update to PrimeNG rc7 (from rc5, where they fixed an issue with updating charts), but because of their changes I don't know how to update my chart anymore, as it has to be done by calling a method.

I've read about the @ViewChild decorator, but I don't really know how to use it.

my chart.html:

my dashboard.ts:

import { NTWDATA } from '../resources/mock/chartdata';

import { UIChart } from 'primeng/primeng';

@Component({
   selector: 'my-dashboard',
   templateUrl: 'dist/html/dashboard.component.html',
})

export class DashboardComponent {
   ntwdata = NTWDATA;
   options: any;

   constructor() {

   }

   ngOnInit() {

         this.options = {
            animation: false,
            legend: {
               display: true,
               labels: {
                  boxWidth: 0,
               }

            },
            scales: {
               yAxes: [{
                  scaleLabel: {
                     display: true,
                     labelString: "ms"
                  },
                  ticks: {
                     beginAtZero: true,
                     suggestedMax: 100,
                  }

               }],
               xAxes: [{
                  ticks: {
                     beginAtZero: true,
                     maxTicksLimit: 6,
                  }
               }]

            }
      }
   }
}

The NTWDATA gets updates every 2.5s and with my data everything is fine.

My DashboardComponent is a child of the component where the data gets updated it.

parent component:

...
setInterval(()=>{
   NTWDATA.push(//mydata)
},2500);
...

I have tried to add @ViewChild to my parent like so:

@ViewChild("linechart") chart: UIChart

Then I called the refresh() methode within my setInterval:

setInterval(()=>{
   NTWDATA.push(//mydata)
   this.chart.refresh();
},2500);

But this.chart is undefined.

Then I tried to use @ViewChild like so:

@ViewChild(Dashboard) dashcomp: Dashboard;
setInterval(()=>{
       NTWDATA.push(//mydata)
       this.dashcomp.chart.refresh();
    },2500);

and in my child:

@ViewChild('linechart') chart: UIChart;

As I said, I never rly worked with @ViewChild before and I dont think I understand it that well by now, so if any of you guys has an idea, I'd appreciate it, if you'd talk to me as if I'm stupid! :D

Thanks in advance!

Body:
update labels and datasets also.

this.chart.data.labels = labels;
this.chart.data.datasets = datasets;

try setting a timeout on chart.refresh() with a delay of few seconds 100ms or 1 200ms.

It works for me.


问:
JasperReports: java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser
I would like to share my experience with a more or less common error with JasperReports.

When executing JasperReports to make a PDF report, I have an exception :

```<code>java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser
net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:108)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:69)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:57)
net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:200)
net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:215)
net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:115)
net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:667)
net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:983)
</code>```

My environment :

CentOs 6.6 - Kernel 2.6.32-504.el6.x86_64

Java 1.7_79 (Sun)

JasperReport 6.2.2

Apache Tomcat 7.0.68

Same question that:

java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser

http://community.jaspersoft.com/questions/536539/noclassdeffounderror-jrstyledtextparser-initialization-failure

I tried these solutions without success.

答:
So here some checks to do :

Red Hat KB : https://access.redhat.com/solutions/1311113.

 VMWare KB : https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2010240.

 Your environment should have X11 and/or graphic packages (fonts etc.)  installed OR you have to run Java with -Djava.awt.headless=true option. With headless, your libraries needs to have fonts included (Default JasperReport font is Pictonic.ttf)

Clean your Tomcat Cache and don't do hot deployment. Some JasperReport versions have memory leaks with ThreadLocal uses in some classes. See for example http://community.jaspersoft.com/jasperreports-library/issues/4403-0

JRStyledTextParser have a static initializer which can mask some exceptions. It especially initializes the loading of fonts (on the OS or included in jar) in a cache by using Font implement in java.awt. But, see the source code of Font :

```<code>private static boolean hasTempPermission() {

if (System.getSecurityManager() == null) {
    return true;
}
File f = null;
boolean hasPerm = false;
try {
    f = Files.createTempFile("+~JT", ".tmp").toFile();
    f.delete();
    f = null;
    hasPerm = true;
} catch (Throwable t) {
    /* inc. any kind of SecurityException */
}
return hasPerm;
}
</code>```

Java create temp file (using java.io.tmp option if you have specified it). So check that your temporary folder is not full and writable by the user/group of Java PID. If it is not the case, an exception will be thrown, but catched and invisible...

Body:
I would like to share my experience with a more or less common error with JasperReports.

When executing JasperReports to make a PDF report, I have an exception :

java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser
net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:108)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:69)
net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:57)
net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:200)
net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:215)
net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:115)
net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:667)
net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:983)

My environment :

CentOs 6.6 - Kernel 2.6.32-504.el6.x86_64

Java 1.7_79 (Sun)

JasperReport 6.2.2

Apache Tomcat 7.0.68

Same question that:

java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser

http://community.jaspersoft.com/questions/536539/noclassdeffounderror-jrstyledtextparser-initialization-failure

I tried these solutions without success.

Body:
So here some checks to do :

Red Hat KB : https://access.redhat.com/solutions/1311113.

 VMWare KB : https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2010240.

 Your environment should have X11 and/or graphic packages (fonts etc.)  installed OR you have to run Java with -Djava.awt.headless=true option. With headless, your libraries needs to have fonts included (Default JasperReport font is Pictonic.ttf)

Clean your Tomcat Cache and don't do hot deployment. Some JasperReport versions have memory leaks with ThreadLocal uses in some classes. See for example http://community.jaspersoft.com/jasperreports-library/issues/4403-0

JRStyledTextParser have a static initializer which can mask some exceptions. It especially initializes the loading of fonts (on the OS or included in jar) in a cache by using Font implement in java.awt. But, see the source code of Font :

private static boolean hasTempPermission() {

if (System.getSecurityManager() == null) {
    return true;
}
File f = null;
boolean hasPerm = false;
try {
    f = Files.createTempFile("+~JT", ".tmp").toFile();
    f.delete();
    f = null;
    hasPerm = true;
} catch (Throwable t) {
    /* inc. any kind of SecurityException */
}
return hasPerm;
}

Java create temp file (using java.io.tmp option if you have specified it). So check that your temporary folder is not full and writable by the user/group of Java PID. If it is not the case, an exception will be thrown, but catched and invisible...


问:
How to make checkbox selected during rendering
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

```<code><input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

and

```<code>//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});
</code>```

答:
i don't know exactly what you need , please check the below snippet

jQuery(function($) {
   $('#chkbox').prop('checked', true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="chkbox" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script></code>```

Body:
I have already look and applied lots of the solution methods on web i.e. Check/Uncheck checkbox with javascript? but my problem is make the checkbox to be checked after page load. I use $(window).load(function () and $(document).ready(function () but none of them working. However, if I can set checked property in html of checkbox the problem will be solved. But I cannot set this property via a Javascript variable. I also tried by jQuery but the problem is related to setting this property after rendering of checkbox. Any idea to fix the problem?

<input type="checkbox" class="form-check-input" id="chkAll" >

//Although the checkboz is already rendered at this stage I cannot set it
$(window).load(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

and

//As the checkbox is not rendering during page load this method is useless
$(document).ready(function () {
    if (@Html.Raw(Json.Encode(ViewBag.IsAll))) {
        document.getElementById("chkAll").checked = true;
    }
});

Body:
i don't know exactly what you need , please check the below snippet

jQuery(function($) {
   $('#chkbox').prop('checked', true);
});

<input type="checkbox" id="chkbox" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


问:
How to make this code less repetitive? (openpyxl)
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

```<code># Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():
</code>```

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.

答:
openpyxl provides all the necessary functions to do this quickly and easily. The best way to do this is to use named styles. You can create a single style for the header cells and apply it using a loop.

Create the first row:

ws.append(['Index', 'Name', 'Grade'])

Create the relevant style:

header = NamedStyle(…)

Apply the style to the first row:

```<code>for cell in ws[1]:
    cell.style = header
</code>```

Body:
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

# Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.

Body:
openpyxl provides all the necessary functions to do this quickly and easily. The best way to do this is to use named styles. You can create a single style for the header cells and apply it using a loop.

Create the first row:

ws.append(['Index', 'Name', 'Grade'])

Create the relevant style:

header = NamedStyle(…)

Apply the style to the first row:

for cell in ws[1]:
    cell.style = header


问:
Setting private field in abstract super class using mockito
I am having a abstract super class TP and which have a concrete sub class ETP. This is my code:

```<code>    abstract class TP {

    private Configuration app;
         protected MC bMC() {
         }
    }
</code>```

and sub class ETP code is:

```<code> public class ETP extends TP {
    private Configuration app;
       public MC pT() {
          bMC();
       }
   }
</code>```

I am writing test case for ETP which is ETPTest which looks like this

```<code>public class ETPTest {
 @Before
    public void setUp() throws Exception {
       // as TP is abstract i am initializing with ETP
          TP = new ETP();
       // some initialization
   }
    Whitebox.setInternalState(TP, app);
}
</code>```

but app is getting passed as null in TP and getting NPE in TP.

any ideas or suggestions?

app is a private variable defined in both TP and ETP; and I am trying to set internal state for app which is in TP.

答:
Your difficulties to such things can be seen as a symptom.

You can decide that the cure is to spent hours until you get the mocking parts to circumvent around that problem.

Whereas the other option is: understand that the given design is deficient:

sub classes should absolutely not care about private fields in super classes. The whole point of private is to make things an "implementation detail" that no other class should know or care about

Worse: by putting up a second private field with the same name, you just added to that confusion. Those will be to different private fields; there is no "overriding" or "polymorphism" here.

In the end, you probably do not understand how to properly design a solution that uses inheritance and abstract base classes. You should thus step back, and think for example, if a solution like this helps:

```<code>public abstract class Base {
  protected abstract Configuration getConfiguration();

  public final void doSomething() {
    ... calls getConfiguration() to do its jobs
  }
}
</code>```

and then:

```<code>public abstract class Subclass extends Base {
  protected Configuration getConfiguration() {
    return whatever
</code>```

As a rule of thumb: clean, straight-forward, non-surprising designs can most often be unit tested simply by using dependency injection and one mock here and another one there. As soon as you have to look into all these complex "solutions"; such as mocking super-class methods/fields; or mocking static methods, ... you are already suffering from a bad design; and instead of fixing that problem; you try to work around it.

That will not help you in the long run. Because the real problem is the "smelly" design in your production code.

Body:
I am having a abstract super class TP and which have a concrete sub class ETP. This is my code:

    abstract class TP {

    private Configuration app;
         protected MC bMC() {
         }
    }

and sub class ETP code is:

 public class ETP extends TP {
    private Configuration app;
       public MC pT() {
          bMC();
       }
   }

I am writing test case for ETP which is ETPTest which looks like this

public class ETPTest {
 @Before
    public void setUp() throws Exception {
       // as TP is abstract i am initializing with ETP
          TP = new ETP();
       // some initialization
   }
    Whitebox.setInternalState(TP, app);
}

but app is getting passed as null in TP and getting NPE in TP.

any ideas or suggestions?

app is a private variable defined in both TP and ETP; and I am trying to set internal state for app which is in TP.

Body:
Your difficulties to such things can be seen as a symptom.

You can decide that the cure is to spent hours until you get the mocking parts to circumvent around that problem.

Whereas the other option is: understand that the given design is deficient:

sub classes should absolutely not care about private fields in super classes. The whole point of private is to make things an "implementation detail" that no other class should know or care about

Worse: by putting up a second private field with the same name, you just added to that confusion. Those will be to different private fields; there is no "overriding" or "polymorphism" here.

In the end, you probably do not understand how to properly design a solution that uses inheritance and abstract base classes. You should thus step back, and think for example, if a solution like this helps:

public abstract class Base {
  protected abstract Configuration getConfiguration();

  public final void doSomething() {
    ... calls getConfiguration() to do its jobs
  }
}

and then:

public abstract class Subclass extends Base {
  protected Configuration getConfiguration() {
    return whatever

As a rule of thumb: clean, straight-forward, non-surprising designs can most often be unit tested simply by using dependency injection and one mock here and another one there. As soon as you have to look into all these complex "solutions"; such as mocking super-class methods/fields; or mocking static methods, ... you are already suffering from a bad design; and instead of fixing that problem; you try to work around it.

That will not help you in the long run. Because the real problem is the "smelly" design in your production code.


问:
Conflict errors (409) when creating documents with Automatic ID generation on Lazy-indexed collection
I use DocumentDB with the .NET SDK on a collection for which I set a custom indexing policy using IndexingMode.Lazy. This provides me eventual consistency for all operations on the collection.

I want to do upsert-like operation on non-critical data : I can afford duplicates and missed updates.

I use code like this :

public async Task UpsertChunk(MyChunk chunk)
{
    var id = _documentClient
                    .CreateDocumentQuery<PersistentChunk>()
                    .Where(c => c.ChunkKey == chunk.ChunkKey)
                    .Select(c => c.id)
                    .FirstOrDefault();

    var persistentChunk = chunk.ToPersistentChunk();
    if (string.IsNullOrEmpty(id))
    {
        await _documentClient.CreateDocumentAsync(_collectionUri, persistentChunk);
    }
    else
    {
        persistentChunk.id = id;
        var uri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, id);
        await _documentClient.ReplaceDocumentAsync(uri, persistentChunk);
    }
}
```

I get, non-consistently, Conflict errors : Microsoft.Azure.Documents.DocumentClientException: Message: {"Errors":["Resource with specified id or name already exists"]}

However, since I use Automatic ID Generation, it should not be possible to have duplicate ids, even in the case of concurrent writes.

Has anyone encountered this kind of behavior before ?
I suspect this could be triggered by retries executed by the .NET SDK if successful writes are not acknowledged as such by DocumentDB.

答:
Conflict errors : Microsoft.Azure.Documents.DocumentClientException: Message: {"Errors":["Resource with specified id or name already exists"]}

409 Conflict indicates the id provided for a resource on a PUT or POST operation has been taken by an existing resource. Please try to query documents by id property instead of ChunkKey property, and then you could determine to add/replace document based on the query result num.

```<code>var num = client.CreateDocumentQuery<MyChunk>("dbs/{your db}/colls/{your collection}").Where(c => c.id == chunk.id).AsEnumerable().Count();
</code>```

Body:
I use DocumentDB with the .NET SDK on a collection for which I set a custom indexing policy using IndexingMode.Lazy. This provides me eventual consistency for all operations on the collection.

I want to do upsert-like operation on non-critical data : I can afford duplicates and missed updates.

I use code like this :

public async Task UpsertChunk(MyChunk chunk)
{
    var id = _documentClient
                    .CreateDocumentQuery<PersistentChunk>()
                    .Where(c => c.ChunkKey == chunk.ChunkKey)
                    .Select(c => c.id)
                    .FirstOrDefault();

    var persistentChunk = chunk.ToPersistentChunk();
    if (string.IsNullOrEmpty(id))
    {
        await _documentClient.CreateDocumentAsync(_collectionUri, persistentChunk);
    }
    else
    {
        persistentChunk.id = id;
        var uri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, id);
        await _documentClient.ReplaceDocumentAsync(uri, persistentChunk);
    }
}

I get, non-consistently, Conflict errors : Microsoft.Azure.Documents.DocumentClientException: Message: {"Errors":["Resource with specified id or name already exists"]}

However, since I use Automatic ID Generation, it should not be possible to have duplicate ids, even in the case of concurrent writes.

Has anyone encountered this kind of behavior before ?
I suspect this could be triggered by retries executed by the .NET SDK if successful writes are not acknowledged as such by DocumentDB.

Body:
Conflict errors : Microsoft.Azure.Documents.DocumentClientException: Message: {"Errors":["Resource with specified id or name already exists"]}

409 Conflict indicates the id provided for a resource on a PUT or POST operation has been taken by an existing resource. Please try to query documents by id property instead of ChunkKey property, and then you could determine to add/replace document based on the query result num.

var num = client.CreateDocumentQuery<MyChunk>("dbs/{your db}/colls/{your collection}").Where(c => c.id == chunk.id).AsEnumerable().Count();


问:
Recv with TCP packet stream not sending ACK packet
Hi I am writing a application that uses TCP to communicate with a HTTP server. However I am seeing that I don't respond with an ACK packet after each data packet is received.

Is this handled by the RECV routine?

答: Yes, ACK packets are handled by the kernel.  In fact, the ACK will often be sent before your process returns from recv().


问:
dgrid dnd implement onDrop event
I would like to implement a custom behavior of the drop event of DnD in dgrid. I have the following gdrig declaration:

```<code>this.grid = new (declare([OnDemandGrid, Editor, DnD, DijitRegistry]))({
                        region: "center",
                        collection: this.store,
                        selectionMode: 'single',
                        columns: ...
                    }, this.gridNode);

                    this.grid.startup();
</code>```

What I exactly want is simple: after I drag and drop a row in the grid (reorder the items in dgrid) I want to trigger an event (function - say to get the current row and manipulate it, etc.).
The problem is that I do not know how to override the onDrop event or drag event. Can someone give me a hint.

答:
There is an easy mechanism to replace onDrop, however it is not at all obvious how to keep but extend the existing onDrop functionality.  This is because onDrop lives in a class called DnDSource which the grid creates.  Fortunately this is a dependency that can be injected (via a property called dndConstructor).  Here's my solution:</p>

```<code>var MyDnDSource = declare([DnDSource], {
    onDrop: function() {
        this.inherited(arguments); // This is the original onDrop functionality
        console.log('This is my additional onDrop functionality');
  }
});

this.grid = new (declare([OnDemandGrid, Editor, DnD, DijitRegistry]))({
                    dndConstructor: MyDnDSource,
                    region: "center",
                    collection: this.store,
                    selectionMode: 'single',
                    columns: ...
                }, this.gridNode);

this.grid.startup();
</code>```

Title: dgrid dnd implement onDrop event

Body:
I would like to implement a custom behavior of the drop event of DnD in dgrid. I have the following gdrig declaration:

this.grid = new (declare([OnDemandGrid, Editor, DnD, DijitRegistry]))({
                        region: "center",
                        collection: this.store,
                        selectionMode: 'single',
                        columns: ...
                    }, this.gridNode);

                    this.grid.startup();

What I exactly want is simple: after I drag and drop a row in the grid (reorder the items in dgrid) I want to trigger an event (function - say to get the current row and manipulate it, etc.).
The problem is that I do not know how to override the onDrop event or drag event. Can someone give me a hint.

Body:
There is an easy mechanism to replace onDrop, however it is not at all obvious how to keep but extend the existing onDrop functionality.  This is because onDrop lives in a class called DnDSource which the grid creates.  Fortunately this is a dependency that can be injected (via a property called dndConstructor).  Here's my solution:

var MyDnDSource = declare([DnDSource], {
    onDrop: function() {
        this.inherited(arguments); // This is the original onDrop functionality
        console.log('This is my additional onDrop functionality');
  }
});

this.grid = new (declare([OnDemandGrid, Editor, DnD, DijitRegistry]))({
                    dndConstructor: MyDnDSource,
                    region: "center",
                    collection: this.store,
                    selectionMode: 'single',
                    columns: ...
                }, this.gridNode);

this.grid.startup();


问:
what is the standard procedure for Generating keys for each document in java..?
I want to insert documents into Couchbase as a bulk in Java. So what is the standard procedure for Generating keys for each document in java..?</p>

答:
You could use a Couchbase "counter" document as a form of sequence. Using the reactive approach with the Java SDK, this would go something like this, assuming your batch is a List<JsonObject> with each content to save to Couchbase:

//start with a sequence of contents to save
Observable.from(listOfDocumentContent)
          //for each content, asynchronously generate something...
          .flatMap(content -> bucket.async() //assuming bucket is a `Bucket`
              //atomically generate an increasing value, starting from 0
              .counter("DOCUMENT_KEY_GENERATOR", 1, 0) //use a more relevant document key
              //this gives a `JsonLongDocument`, so extract the number and turn that + the original content into a `JsonDocument` to be saved
              .map(cDoc -> JsonDocument.create(KEY_PREFIX + cDoc.content(), content))
          )
          //next up, asynchronously saving each document we generated in the previous step... You could also use insert since you don't expect the keys to already exist in Couchbase
          .flatMap(docToSave -> bucket.async().upsert(docToSave))
          //this will perform the above asynchronously but wait for the last doc in the batch to finish saving:
          .toBlocking().last();
```

Notice we use a KEY_PREFIX when generating the document to be saved, so that there is less risk of collision (otherwise, other documents in the bucket could be named "1" if you do that for multiple types of documents inside the same bucket).

Also tune the saving method used to your needs (here upsert vs create vs update, TTL, durability requirements, etc...)

Body:
You could use a Couchbase "counter" document as a form of sequence. Using the reactive approach with the Java SDK, this would go something like this, assuming your batch is a List<JsonObject> with each content to save to Couchbase:

//start with a sequence of contents to save
Observable.from(listOfDocumentContent)
          //for each content, asynchronously generate something...
          .flatMap(content -> bucket.async() //assuming bucket is a `Bucket`
              //atomically generate an increasing value, starting from 0
              .counter("DOCUMENT_KEY_GENERATOR", 1, 0) //use a more relevant document key
              //this gives a `JsonLongDocument`, so extract the number and turn that + the original content into a `JsonDocument` to be saved
              .map(cDoc -> JsonDocument.create(KEY_PREFIX + cDoc.content(), content))
          )
          //next up, asynchronously saving each document we generated in the previous step... You could also use insert since you don't expect the keys to already exist in Couchbase
          .flatMap(docToSave -> bucket.async().upsert(docToSave))
          //this will perform the above asynchronously but wait for the last doc in the batch to finish saving:
          .toBlocking().last();

Notice we use a KEY_PREFIX when generating the document to be saved, so that there is less risk of collision (otherwise, other documents in the bucket could be named "1" if you do that for multiple types of documents inside the same bucket).

Also tune the saving method used to your needs (here upsert vs create vs update, TTL, durability requirements, etc...)


问:
Is there a way to rename network interfaces in Docker swarm?
When using Docker swarm mode and exposing ports outside, you have at least three networks, the ingress network, the bridge network and the overlay network (used for internal cluster communications). The container joins these networks using one of eth0-2 (randomically each time) interfaces and from an application point of view is not easy to understand which of these is the cluster network (the correct one to use for service discovery client publish - e.g Spring Eureka).
Is there a way to customize network interface names in some way?

答:
Not a direct answer to your question, but one of the key selling points of swarm mode is the built-in service discovery mechanism, which in my opinion works really nicely.

More related, I don't think it's possible to specify the desired interface for an overlay network. However, when creating a network, it is possible to define the subnet or the IP range of the network (https://docs.docker.com/engine/reference/commandline/network_create/). You could use that to identify the interface belonging to your overlay network, by checking if the bound IP address is part of the network you want to publish on.


问:
how to make phone number clickable in classifield wordpress
I tried everything to make the phone number clickable but for some reason it didn't work

```<code>    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>
    <li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><?php echo $post_phone; ?></li>
</code>```

I added this and it still didn't work :

```<code><a href="tel:$post_phone"> $post_phone</a>
</code>```

and this

```<code><li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a></li>
                        <?php }?>
</code>```

Thank you so much for your help

答:
If your php version is greater then 5.4, then you can write it as

```<code>   <a href="tel:<?== $post_phone; ?>"><?= $post_phone; ?></a>
</code>```

To check PHP version

```<code>    <?php phpinfo(); ?>
</code>```

Body:
I tried everything to make the phone number clickable but for some reason it didn't work

    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>

<?php esc_html_e( 'Phone', 'classiera' ); ?><?php echo $post_phone; ?>

I added this and it still didn't work :

 $post_phone

and this

<?php esc_html_e( 'Phone', 'classiera' ); ?><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?>

                        <?php }?>

Thank you so much for your help

Body:
If your php version is greater then 5.4, then you can write it as

   <a href="tel:<?== $post_phone; ?>"><?= $post_phone; ?></a>

To check PHP version

    <?php phpinfo(); ?>


问:
Dealing with randomly generated JSON
Pleaseeeeeeee help me, it's been three weeks since I turned around to found how make POJO jackson with this json, random is randonm keyname.

{
   "a": {
     "b1": "1",
     "b2": "{
        "random" : {
            "c1": "10"
            "c2": "20"
        }
    }
 }

Somebody can help me ?

答:
You can use Jackson's @JsonAnySetter annotation to direct all random/variable keys to one method and there you can assign/handle them as you wish:

```<code>public class Pojo
{
    // known/fixed properties
    public String b1;
    public String b2;
    ...

    // unknown/variable properties will go here
    @JsonAnySetter
    public void setRandom(String key, Object value)
    {
        System.out.println("variable key = '" + key + "'");
        System.out.println("value is of type = " + value.getClass());
        System.out.println("value toString = '" + value.toString() + "'");
    }
}
</code>```

in the case of the sample input, the output is:

```<code>variable key = 'random'
value is of type = class java.util.LinkedHashMap
value toString = '{c1=10, c2=20}'
</code>```

Title: Dealing with randomly generated JSON

Body:
You can use Jackson's @JsonAnySetter annotation to direct all random/variable keys to one method and there you can assign/handle them as you wish:

public class Pojo
{
    // known/fixed properties
    public String b1;
    public String b2;
    ...

    // unknown/variable properties will go here
    @JsonAnySetter
    public void setRandom(String key, Object value)
    {
        System.out.println("variable key = '" + key + "'");
        System.out.println("value is of type = " + value.getClass());
        System.out.println("value toString = '" + value.toString() + "'");
    }
}

in the case of the sample input, the output is:

variable key = 'random'
value is of type = class java.util.LinkedHashMap
value toString = '{c1=10, c2=20}'


问:
Unexpected T_CLONE using Math_Matrix PEAR library
I've not used PEAR before, and so I'm probably doing something dumb. I've installed the Math_Matrix library, but when I include it I just get an error. My entire code is this:

```<code><?php
  $path = '/home/PEAR/Math_Matrix-0.8.0';
  set_include_path(get_include_path() . PATH_SEPARATOR . $path);
  include_once 'Matrix.php';
?>
</code>```

The error I get is this:

```<code>Parse error: syntax error, unexpected T_CLONE, expecting T_STRING in /home/PEAR/Math_Matrix-0.8.0/Matrix.php on line 272
</code>```

I'm not really sure what to make of that. I guess the explanations I can think of are:

I've not installed the Math_Matrix library properly (I'm on a shared server which already had PEAR installed on it) or have downloaded the wrong version of it.

I'm supposed to include something else before I include Matrix.php

I've included the wrong file (or the right filename but with the wrong path, somehow).

To install it, I did the following:

```<code>pear install --alldeps channel://pear.phpunit.de/PHPUnit
pear install --alldeps channel://pear.php.net/Math_Vector-0.6.2
pear install Math_Matrix
</code>```

答:
From the [Math_Matrix](http://pear.php.net/package/Math_Matrix homepage) I can see that it was last updated in 2003.  Since then, PHP has added the clone keyword, which is conflicting with the clone() function defined in Matrix.php.

You need to update Matrix.php - a search & replace on "clone" with "clone2" should do it.

OwnerDisplayName: Ben

Body:
I've not used PEAR before, and so I'm probably doing something dumb. I've installed the Math_Matrix library, but when I include it I just get an error. My entire code is this:

<?php
  $path = '/home/PEAR/Math_Matrix-0.8.0';
  set_include_path(get_include_path() . PATH_SEPARATOR . $path);
  include_once 'Matrix.php';
?>

The error I get is this:

Parse error: syntax error, unexpected T_CLONE, expecting T_STRING in /home/PEAR/Math_Matrix-0.8.0/Matrix.php on line 272

I'm not really sure what to make of that. I guess the explanations I can think of are:

I've not installed the Math_Matrix library properly (I'm on a shared server which already had PEAR installed on it) or have downloaded the wrong version of it.

I'm supposed to include something else before I include Matrix.php

I've included the wrong file (or the right filename but with the wrong path, somehow).

To install it, I did the following:

pear install --alldeps channel://pear.phpunit.de/PHPUnit
pear install --alldeps channel://pear.php.net/Math_Vector-0.6.2
pear install Math_Matrix

OwnerDisplayName: RoBorg


问:
How to release event id from Google calendar?
I have an event with a particular id (e.g. "17448") and I deleted it and then removed from a trash. The problem is I can't use the same event id again. I can't create event, update or delete.

I always getting "Error":

```<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Forbidden"
   }
  ],
  "code": 403,
  "message": "Forbidden"
 }
}
</code>```

But still can use "get" method and I getting this:

```<code>{'end': {'date': '2000-01-02'},
 'etag': '"2980807593935000"',
 'iCalUID': '17448@google.com',
 'id': '17448',
 'kind': 'calendar#event',
 'start': {'date': '2000-01-01'},
 'status': 'cancelled',
 'transparency': 'transparent',
 'updated': '2017-03-27T07:32:07.111Z'}
</code>```

So, is a way to release the event id for reuse?

答:
There is no way to release a Calendar eventId.

The eventId is a unique identifier for each Calendar event and is expected to be kept that way in order to prevent collision (i.e. mix-ups) in records and/or logs.

Body:
I have an event with a particular id (e.g. "17448") and I deleted it and then removed from a trash. The problem is I can't use the same event id again. I can't create event, update or delete.

I always getting "Error":

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Forbidden"
   }
  ],
  "code": 403,
  "message": "Forbidden"
 }
}

But still can use "get" method and I getting this:

{'end': {'date': '2000-01-02'},
 'etag': '"2980807593935000"',
 'iCalUID': '17448@google.com',
 'id': '17448',
 'kind': 'calendar#event',
 'start': {'date': '2000-01-01'},
 'status': 'cancelled',
 'transparency': 'transparent',
 'updated': '2017-03-27T07:32:07.111Z'}

So, is a way to release the event id for reuse?


问:
Javascript - Change event trigger multiple times
I have the following table.

```<code><table class="table invoice-items-table">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr class="invoice-item-row">
            <td>
                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-quantity" value="1" type="text">
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-price" value="0.00" type="text">
            </td>
            <td class="text-right" style="padding-top:18px!important;">
                <span class="invoice-item-amount">0 </span>
                <span class="invoice-currency">₹</span>
            </td>
        </tr>
        <tr class="invoice-item-add-row">
            <td colspan="7">
                <a href="#" class="link invoice-item-add text-center">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                    Add an Item
                </a>
            </td>
        </tr>
    </tbody>
</table>
</code>```

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

```<code>$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});
</code>```

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

```<code>$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});
</code>```

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

答:
You can try in alternative way like this,

```<code>$('.invoice-item-select.bootstrap-select').on('changed.bs.select', function(){
// your code
});
</code>```

bootstrap-select class should be applied after loading DOM into the browser.

I hope this will solve your problem.

Body:
I have the following table.

            Item
            Quantity
            Price
            Amount

                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>

                <input class="form-control invoice-item-quantity" value="1" type="text">

                <input class="form-control invoice-item-price" value="0.00" type="text">

                0
                ₹

                    Add an Item

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

Body:
You can try in alternative way like this,

$('.invoice-item-select.bootstrap-select').on('changed.bs.select', function(){
// your code
});

bootstrap-select class should be applied after loading DOM into the browser.

I hope this will solve your problem.


问:
How to pass MSBuild arguments for mutliple projects in TFS Build definition
I am trying to pass different MSBuild arguments for two projects in TFS build definition.

I am building a single solution with two projects in it. I am able to pass MSBuild arguments without specifying a projects and it's working. Both projects are building correctly. Now, I want to pass MSBuild arguments separately to both projects because i have different arguments value for both project. I am not able to do that.

If I pass MSBuild arguments as below, common for both project, it's working both project is building correctly.

/p:DeployOnBuild=true /P:PackageTempRootDir=\Release
  /p:DeployIisAppPath="Default Web
  Site";DefaultPackageFileName=API.zip
  /p:OutputPath="$(Build.BinariesDirectory)\$(BuildPlatform)\$(BuildConfiguration)"

If i pass MSBuild arguments separate for both projects,

/t:Project1 /p:DeployOnBuild=true
  /P:PackageTempRootDir=\Release /p:DeployIisAppPath="Default Web
  Site";DefaultPackageFileName=API.zip
  /p:OutputPath="$(Build.BinariesDirectory)\$(BuildPlatform)\$(BuildConfiguration)"
  /t:Project2 /p:DeployOnBuild=true /P:PackageTempRootDir=\Release
  /p:DeployIisAppPath="Default Web
  Site";DefaultPackageFileName=WEB.zip
  /p:OutputPath="$(Build.BinariesDirectory)\$(BuildPlatform)\$(BuildConfiguration)"

I am only looking for a change in package name based on project as you can see above. for project1 i want API.zip, for project2 i want WEB.zip. I tried to pass it few different ways, it didn't work.

With above agruments i am getting output for both project with same package name and it's WEB.zip. I don't know why. it's building both project but names are same.

I found similar questions specify project file of a solution using msbuild,  but it doesn't specify how to pass separate MSBuild agruments to mutliple projects.

答:
Since you are using vNext build, you could build the two projects separately by adding multiple VS build tasks.

For more details you could take a look at below two questions:

How to configure multiple project in Team Build 2015

Build one web project from a Solution with multiple web projects in Visual Studio Online Build Definition