问:
How to convert *.RESX XML file to JSON file in C#
How can I convert *.RESX XML file to JSON file in C#?

I have regular RESX file. For example:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</root>
</code>```

I need to convert this file to JSON file:

```<code>{
  "Texts": [
    {
      "id": "KEY_1",
      "text": "Text A"
    },
    {
      "id": "KEY_2",
      "text": "Text B"
    }
  ]
}
</code>```

As you can see for conversion is relevant only part with data:

```<code>    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</code>```

Everything else is irrelevant for transformation.

Name in data attribute XML => is id in JSON file.

Value in XML=> is text in JSON file.

EDIT:
I have solution, but I think that it can be done better

```<code>using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace XMLtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // To convert an XML node contained in string xml into a JSON string
            var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList node = doc.GetElementsByTagName("data");
            foreach (XmlNode item in node)
            {
                var value = item.InnerText.Trim();
                var keyName = item.Attributes.Cast<XmlAttribute>().FirstOrDefault(f => f.Name == "name");
                if (keyName != null)
                {
                    var key = keyName.InnerText.Trim();
                    result.Add(key, value);
                }
            }

            string res = @"{ ""Text"" : [ ";
            foreach (var item in result)
            {
                res += "{";
                res += $" \"id\":\"{item.Key}\",\"text\":\"{item.Value}\"";
                res += "},";
            }
            res = res.Remove(res.Length - 1);
            res += @" ]} ";
        }

    }
}
</code>```

答:
I'd recommend you the JSON.NET Framework.
It has built-in functions for converting XML to JSON and vice versa.

Example:

```<code>string xml = @"<?xml version='1.0' standalone='no'?>
<root>
  <person id='1'>
    <name>Alan</name>
    <url>http://www.google.com</url>
  </person>
  <person id='2'>
    <name>Louis</name>
    <url>http://www.yahoo.com</url>
  </person>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string jsonText = JsonConvert.SerializeXmlNode(doc);
//{
//  "?xml": {
//    "@version": "1.0",
//    "@standalone": "no"
//  },
//  "root": {
//    "person": [
//      {
//        "@id": "1",
//        "name": "Alan",
//        "url": "http://www.google.com"
//      },
//      {
//        "@id": "2",
//        "name": "Louis",
//        "url": "http://www.yahoo.com"
//      }
//    ]
//  }
//}
</code>```

Body:
How can I convert *.RESX XML file to JSON file in C#?

I have regular RESX file. For example:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</root>

I need to convert this file to JSON file:

{
  "Texts": [
    {
      "id": "KEY_1",
      "text": "Text A"
    },
    {
      "id": "KEY_2",
      "text": "Text B"
    }
  ]
}

As you can see for conversion is relevant only part with data:

    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>

Everything else is irrelevant for transformation.

Name in data attribute XML => is id in JSON file.

Value in XML=> is text in JSON file.

EDIT:
I have solution, but I think that it can be done better

using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace XMLtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // To convert an XML node contained in string xml into a JSON string
            var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList node = doc.GetElementsByTagName("data");
            foreach (XmlNode item in node)
            {
                var value = item.InnerText.Trim();
                var keyName = item.Attributes.Cast<XmlAttribute>().FirstOrDefault(f => f.Name == "name");
                if (keyName != null)
                {
                    var key = keyName.InnerText.Trim();
                    result.Add(key, value);
                }
            }

            string res = @"{ ""Text"" : [ ";
            foreach (var item in result)
            {
                res += "{";
                res += $" \"id\":\"{item.Key}\",\"text\":\"{item.Value}\"";
                res += "},";
            }
            res = res.Remove(res.Length - 1);
            res += @" ]} ";
        }

    }
}

Body:
I'd recommend you the JSON.NET Framework.
It has built-in functions for converting XML to JSON and vice versa.

Example:

string xml = @"<?xml version='1.0' standalone='no'?>
<root>
  <person id='1'>
    <name>Alan</name>
    <url>http://www.google.com</url>
  </person>
  <person id='2'>
    <name>Louis</name>
    <url>http://www.yahoo.com</url>
  </person>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string jsonText = JsonConvert.SerializeXmlNode(doc);
//{
//  "?xml": {
//    "@version": "1.0",
//    "@standalone": "no"
//  },
//  "root": {
//    "person": [
//      {
//        "@id": "1",
//        "name": "Alan",
//        "url": "http://www.google.com"
//      },
//      {
//        "@id": "2",
//        "name": "Louis",
//        "url": "http://www.yahoo.com"
//      }
//    ]
//  }
//}


来源: stackexchange

问:
PHP Remove Domain Name Extension from String
I was wondering of the best way of removing certain things from a domain using PHP.

For example:

"http://mydomain.com/" into "mydomain"

or

"http://mydomain.co.uk/" into "mydomain"

I'm looking for a quick function that will allow me to remove such things as:

"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc

Thanks in advance :)

答: I would str_replace out the 'http://' and then explode the periods in the full domain name.</p>

ContentLicense: CC BY-SA 2.5


问:
Returned objects from ionic native - Sim
I am trying to fetch the device phone number of the mobile phone on which the ionic app is installed  I am using

 (ionic cordova plugin add cordova-plugin-sim)

I do get an object as response,

  What i need to find is what are the elements of the abject as i need to parse it.

Code below

The HTML file

```<code><ion-content padding>
<button ion-button full (click)="getDeviceInfo()">Password Reset</button>
  <ion-item>
    {{deviceInfo}}
  </ion-item>
</ion-content>
</code>```

The typescript file

```<code>getDeviceInfo(){
this.sim.getSimInfo().then((info)=>{
  this.deviceInfo = info;
  console.log(this.deviceInfo);
  alert(this.deviceInfo);
}, Error=>{
  alert('Could not capture device information!');
});
}
</code>```

The response i get is an object
[Object][Object]

I tried looking at the log cat in android studio but did not find anything

How do i parse this?
Any advise will be great help.

Thanks in advance

答:
Convert the object into a string using JSON.stringify

```<code>console.log(JSON.stringify(this.deviceInfo));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to fetch the device phone number of the mobile phone on which the ionic app is installed  I am using

 (ionic cordova plugin add cordova-plugin-sim)

I do get an object as response,

  What i need to find is what are the elements of the abject as i need to parse it.

Code below

The HTML file

<ion-content padding>
<button ion-button full (click)="getDeviceInfo()">Password Reset</button>
  <ion-item>
    {{deviceInfo}}
  </ion-item>
</ion-content>

The typescript file

getDeviceInfo(){
this.sim.getSimInfo().then((info)=>{
  this.deviceInfo = info;
  console.log(this.deviceInfo);
  alert(this.deviceInfo);
}, Error=>{
  alert('Could not capture device information!');
});
}

The response i get is an object
[Object][Object]

I tried looking at the log cat in android studio but did not find anything

How do i parse this?
Any advise will be great help.

Thanks in advance

Body:
Convert the object into a string using JSON.stringify

console.log(JSON.stringify(this.deviceInfo));


问:
pip library is not visible with sudo
I am trying to inatall one of libraries for python (plotly). I used command:

```<code>pip install -U plotly
</code>```

to get permission denied error... okay.
so i put:

```<code>sudo pip install -U plotly
</code>```

to get:

Could not find a version that satisfies the requirement plotly (from versions: )
No matching distribution found for plotly

something is wrong with this debian setup, but I cannot figure out what. To check, I've used same commands for paramiko... all went ok.

答: Someone created /root/.pip/pip.conf with extra settings :/</p>

Title: pip library is not visible with sudo

Body:
I am trying to inatall one of libraries for python (plotly). I used command:

pip install -U plotly

to get permission denied error... okay.
so i put:

sudo pip install -U plotly

to get:

Could not find a version that satisfies the requirement plotly (from versions: )
No matching distribution found for plotly

something is wrong with this debian setup, but I cannot figure out what. To check, I've used same commands for paramiko... all went ok.


问:
Sharing logins across different devices
I am working on a project where we have multiple computers (running chrome) that are used to present webpages automatically.
Some of the webpages displayed on these computers require a login.
Currently we need to remotely login into every computer and enter passwords in order for them to load the pages. However, I would like to be able to login to a site only once and then share the logins throught the different computers.

Is there some way to synchronize sessions across chrome clients, so that I only log on to the machine once?

Or is it required to use something like Selenium to type in passwords. I don't really like selenium for this because:
1. It usually stops working when someone upgrades the browser
2. It seems like alot of work: Need to "reverse engineer" the login page for each site...

Are there any other approaches I can take?

答:
Answering your Questions straight :

Is there some way to synchronize sessions across chrome clients : No, each chrome client will open a seperate session hence you have to login seperately. Inorder to synchronize these sessions you have to use Chrome Profiles and save them on each system.

Or is it required to use something like Selenium to type in passwords : This would be the most optimum way.

It usually stops working when someone upgrades the browser : You can uncheck/disable Automatic Updates to remain at a particular Chrome Browser Version

It seems like alot of work: Need to "reverse engineer" the login page for each site : Login Page for each site will render differently as a DOM Tree. Hence there is no short cuts.

Title: Sharing logins across different devices


答:
Since you feel that the issue is in pip setup/config, try easy_install.

easy_install plotly

Title: pip library is not visible with sudo


问:
Apache Camel RabbitMQ from queue to queue
I have to implement a micro-service which takes a message from a rabbitmq queue, transform it and push it to a rabbitmq exchange.

I am implementing this functionality using Apache Camel RabbitMq and Spring Boot, using Java SDL for Camel.
I am using (for now) a single rabbitmq server, on my machine.
The configuration looks like this:

```<code>from("rabbitmq://localhost:5672/exchange1?username=guest&password=guest&queue=q1&autoDelete=false");
.to("rabbitmq://localhost:5672/exchange2?username=guest&password=guest&exchangeType=fanout&skipQueueDeclare=false")
</code>```

The code anove is getting the  message from q1 and it is publishing it again in q1 over and over again. It works just to get a message from a queue and send it (for example) to file, or create a message separately and publish it to the exchange.

Is there any way to make it work as I expect it to do?

Thanks

答: The from() generates rabbitMQ headers. Unless you manually remove them, they are passed to your to(). This will create a mismatch in your connection. Best is to delete the rabbit headers after your from() so they don't interfer in your to().

Body:
I have to implement a micro-service which takes a message from a rabbitmq queue, transform it and push it to a rabbitmq exchange.

I am implementing this functionality using Apache Camel RabbitMq and Spring Boot, using Java SDL for Camel.
I am using (for now) a single rabbitmq server, on my machine.
The configuration looks like this:

from("rabbitmq://localhost:5672/exchange1?username=guest&password=guest&queue=q1&autoDelete=false");
.to("rabbitmq://localhost:5672/exchange2?username=guest&password=guest&exchangeType=fanout&skipQueueDeclare=false")

The code anove is getting the  message from q1 and it is publishing it again in q1 over and over again. It works just to get a message from a queue and send it (for example) to file, or create a message separately and publish it to the exchange.

Is there any way to make it work as I expect it to do?

Thanks


问:
ASP.NET Core 2 + Angular -> how set up VSTS?
I have my ASP.NET Core + Angular WebApp uploaded to GitHub(through VSTS) and now I would like to set up the CI pipeline. After that I would like to deploy my app to Azure.

In the template section - there is an ASP.NET Core template, but also an Azure Web App template.

Considering my case which is better suited for this case?

答:
I found the almost perfect working answer in Levi Fuller's blog.
You can get it working with a minor change: unlike what Levi states, you really need only a single npm task

set up the npm task

by clicking the three dots button -> set the Working folder with package.json to your folder that contains the package.json file.

set up the Azure App Service Deploy

by clicking the three dots button -> set the Package or folder to your folder that contains the .csproj file.


问:
DMV/DMX: How to get Measure's Folder and subfolders name?
As the question says, how can I list all the measures, folder and subsolder?
By looking on msdn I can't find any way to do thet, this is what I'm able to achieve so far, any help?</p>

```<code> SELECT
[CATALOG_NAME] AS SSAS_Database_Name,
[CUBE_NAME] AS Cube_or_Perspective_Name,
[MEASUREGROUP_NAME] AS MeasureGroup_Name,
[MEASURE_NAME] AS Measure_Name,
[MEASURE_Caption] AS Measure_Caption,
[MEASURE_IS_VISIBLE] AS Dimension_Visible,
[MEASURE_AGGREGATOR] AS Measure_Aggregator,
[DEFAULT_FORMAT_STRING] AS [Format_String],
[EXPRESSION] AS Calculated_Measure_Expression
FROM
$SYSTEM.MDSCHEMA_MEASURES
ORDER BY
[MEASURE_NAME]
</code>```

答:
I solved by using:

```<code>MEASURE_DISPLAY_FOLDER
</code>```

For further reference I managed to find the proper MSDN articole:

MDSCHEMA_MEASURES Rowset

Body:
As the question says, how can I list all the measures, folder and subsolder?
By looking on msdn I can't find any way to do thet, this is what I'm able to achieve so far, any help?

 SELECT
[CATALOG_NAME] AS SSAS_Database_Name,
[CUBE_NAME] AS Cube_or_Perspective_Name,
[MEASUREGROUP_NAME] AS MeasureGroup_Name,
[MEASURE_NAME] AS Measure_Name,
[MEASURE_Caption] AS Measure_Caption,
[MEASURE_IS_VISIBLE] AS Dimension_Visible,
[MEASURE_AGGREGATOR] AS Measure_Aggregator,
[DEFAULT_FORMAT_STRING] AS [Format_String],
[EXPRESSION] AS Calculated_Measure_Expression
FROM
$SYSTEM.MDSCHEMA_MEASURES
ORDER BY
[MEASURE_NAME]

Body:
I solved by using:

MEASURE_DISPLAY_FOLDER

For further reference I managed to find the proper MSDN articole:

MDSCHEMA_MEASURES Rowset


问:
HTTP Post requests using HttpClient take 2 seconds, why?

Update:
Found the answer myself, see below :-)

Hi,

I'am currently coding an android app that submits stuff in the background using HTTP Post and AsyncTask. I use the org.apache.http.client Package for this. I based my code on this example.

Basically, my code looks like this:

```<code>public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.137:8880/form");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
     Log.e(TAG,e.toString());
    } catch (IOException e) {
     Log.e(TAG,e.toString());
    }
}
</code>```

The problem is that the httpclient.execute(..) line takes around 1.5 to 3 seconds, and I do not understand why. Just requesting a page with HTTP Get takes around 80 ms or so, so the problem doesn't seem to be the network latency itself.

The problem doesn't seem to be on the server side either, I have also tried POSTing data to http://www.disney.com/ with similarly slow results. And Firebug shows 1 ms response time when POSTing data to my server locally.

This happens on the Emulator and with my Nexus One (both with Android 2.2).

If you want to look at the complete code, I've put it on GitHub.

It's just a dummy program to do HTTP Post in the background using AsyncTask on the push of a button. It's my first Android app, and my first java code for a long time. And incidentially, also my first question on Stackoverflow ;-)

Any ideas why httpclient.execute(httppost) takes so long?

答:
i am not on android, but i faced exactly the same kind of problem on windows platform with httpclient 4.0.1, after quite a bit of head scratching, i found the solution.

```<code>HttpParams params = new BasicHttpParams();
//this how tiny it might seems, is actually absoluty needed. otherwise http client lags for 2sec.
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpResponse httpResponse;

HttpPost httpPost = new HttpPost("http://"+server+":"+port+"/");
StringEntity entity = new StringEntity(content, "utf-8");
entity.setContentType("text/plain; charset=utf-8");
httpPost.setEntity(entity);

httpResponse=httpClient.execute(httpPost);

String response = IOUtils.toString(httpResponse.getEntity().getContent(),encoding);
httpResponse.getEntity().consumeContent();

httpClient.getConnectionManager().shutdown();
return(response);
</code>```

i have no idea why setting the parameters with HTTP1.1 version solves the problem. but it does.
also even weirder, the symptom did not show if executing an HTTP Get request.

anyhow, i hope this helps some out there !

h

Body:
Update:
Found the answer myself, see below :-)

Hi,

I'am currently coding an android app that submits stuff in the background using HTTP Post and AsyncTask. I use the org.apache.http.client Package for this. I based my code on this example.

Basically, my code looks like this:

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.137:8880/form");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
     Log.e(TAG,e.toString());
    } catch (IOException e) {
     Log.e(TAG,e.toString());
    }
}

The problem is that the httpclient.execute(..) line takes around 1.5 to 3 seconds, and I do not understand why. Just requesting a page with HTTP Get takes around 80 ms or so, so the problem doesn't seem to be the network latency itself.

The problem doesn't seem to be on the server side either, I have also tried POSTing data to http://www.disney.com/ with similarly slow results. And Firebug shows 1 ms response time when POSTing data to my server locally.

This happens on the Emulator and with my Nexus One (both with Android 2.2).

If you want to look at the complete code, I've put it on GitHub.

It's just a dummy program to do HTTP Post in the background using AsyncTask on the push of a button. It's my first Android app, and my first java code for a long time. And incidentially, also my first question on Stackoverflow ;-)

Any ideas why httpclient.execute(httppost) takes so long?

Body:
i am not on android, but i faced exactly the same kind of problem on windows platform with httpclient 4.0.1, after quite a bit of head scratching, i found the solution.

HttpParams params = new BasicHttpParams();
//this how tiny it might seems, is actually absoluty needed. otherwise http client lags for 2sec.
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpResponse httpResponse;

HttpPost httpPost = new HttpPost("http://"+server+":"+port+"/");
StringEntity entity = new StringEntity(content, "utf-8");
entity.setContentType("text/plain; charset=utf-8");
httpPost.setEntity(entity);

httpResponse=httpClient.execute(httpPost);

String response = IOUtils.toString(httpResponse.getEntity().getContent(),encoding);
httpResponse.getEntity().consumeContent();

httpClient.getConnectionManager().shutdown();
return(response);

i have no idea why setting the parameters with HTTP1.1 version solves the problem. but it does.
also even weirder, the symptom did not show if executing an HTTP Get request.

anyhow, i hope this helps some out there !

h


问:
Get Column name along with JSON response
I have three entity classes, I have written the query which includes join of two tables.

Table: ExpensesCategories

```<code>@Entity
@Table(name = "ExpensesCategories")
public class ExpensesCategories {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id", unique = true)
    private int categoryId;

    @NotNull
    private String categoryName;

    @NotNull
    private String categoryCodeInBankStats;

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryCodeInBankStats() {
        return categoryCodeInBankStats;
    }

    public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
        this.categoryCodeInBankStats = categoryCodeInBankStats;
    }
}
</code>```

Table: Transactions

```<code>@Entity
@Table(name = "TransactionHistory")
public class TransactionHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Temporal(TemporalType.DATE)
    private Date dateOfTransaction;

    private String transactionType;

    private String refNo;

    private Date valueDate;

    private double withdrawalAmount;

    private double depositAmount;

    private double closingBalance;

    @ManyToOne
    @JoinColumn(name="userDetailsId", referencedColumnName="user_id")
    private UserDetails userDetails;

    @ManyToOne
    @JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
    private ExpensesCategories expenseCategories;

    public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
            double withdrawalAmount, double depositAmount, double closingBalance) {
        this.dateOfTransaction = dateOfTransaction;
        this.transactionType = transactionType;
        this.refNo = refNo;
        this.valueDate = valueDate;
        this.withdrawalAmount = withdrawalAmount;
        this.depositAmount = depositAmount;
        this.closingBalance = closingBalance;
    }

    public TransactionHistory() {
    }

    public Date getDateOfTransaction() {
        return dateOfTransaction;
    }

    public void setDateOfTransaction(Date date) {
        this.dateOfTransaction = date;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public Date getValueDate() {
        return valueDate;
    }

    public void setValueDate(Date valueDate) {
        this.valueDate = valueDate;
    }

    public double getWithdrawalAmount() {
        return withdrawalAmount;
    }

    public void setWithdrawalAmount(double withdrawalAmount) {
        this.withdrawalAmount = withdrawalAmount;
    }

    public double getDepositAmount() {
        return depositAmount;
    }

    public void setDepositAmount(double depositAmount) {
        this.depositAmount = depositAmount;
    }

    public double getClosingBalance() {
        return closingBalance;
    }

    public void setClosingBalance(double closingBalance) {
        this.closingBalance = closingBalance;
    }

    public UserDetails getUserDetails() {
        return userDetails;
    }

    public void setUserDetails(UserDetails userDetails) {
        this.userDetails = userDetails;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public ExpensesCategories getExpenseCategories() {
        return expenseCategories;
    }

    public void setExpenseCategories(ExpensesCategories expenseCategories) {
        this.expenseCategories = expenseCategories;
    }
}
</code>```

Table: User Details

```<code>@Entity
@Table(name = "Employee")
public class UserDetails {

    @Id
    @Column(name = "user_id", unique = true)
    private int id;
    @NotNull
    private String firstname;
    @NotNull
    private String lastname;
    @Column(unique = true)
    @NotNull
    private String emailaddress;
    @NotNull
    private String role;

    public UserDetails(String firstname, String lastname, String emailaddress, String role) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.emailaddress = emailaddress;
        this.role = role;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public UserDetails() {
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmailaddress() {
        return emailaddress;
    }

    public void setEmailaddress(String emailaddress) {
        this.emailaddress = emailaddress;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
                + emailaddress + ", role=" + role + "]";
    }
</code>```

I have written query like this in transaction entity.

```<code>    @Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id

")
        List<Object[]> getCategorizedExpenses();
</code>```

My Json Response is like:

```<code>[
    [
        1,
        21,
        "UPI",
        "UPI Payments"
    ],
    [
        2,
        3733.59,
        "POS",
        "Shopping"
    ]
]
</code>```

But i want json response with column names as well:

```<code>[
    [
       expense_categories_id: 1,
       Total_withdrawal_Amount: 21,
       category_code_in_bank_stats: "UPI",
       category_name: "UPI Payments"
    ],
    [
        expense_categories_id: 2,
        Total_withdrawal_Amount: 3733.59,
        category_code_in_bank_stats: "POS",
        category_name: "Shopping"
    ]
]
</code>```

Please help me out..

答:
You would need to map the results directly to a POJO class and ad some json config:

1) Define the pojo

```<code>public ResultClass implements Serializable{

   @JsonProperty("expense_categories_id")
   private Integer expenseCategoriesId;

   ...

   public ResultClass(Integer expenseCategoriesId ... // rest params){
      this.expenseCategoriesId = expenseCategoriesId;
      ...
   }
}
</code>```

2) Define the mapping:

```<code>@SqlResultSetMapping(
    name="myMapping",
    classes={
        @ConstructorResult(
            targetClass=ResultClass.class,
            columns={
                @ColumnResult(name="expenseCategoriesId"),
                @ColumnResult(name="totalWithdrawalAmount")
                // further mappings ...
            }
        )
    }
)
</code>```

3) Define a native query

```<code>@NamedNativeQuery(name="TransactionHistory.myQuery"
    , query="SELECT new mypackage.ResultClass(a.expense_categories_id as expeneCategoriesId ... ) from ...")
</code>```

4) Define this method in the CrudRepository without the @Query annotation:

```<code>public List<ResultClass> myQuery();
</code>```

Teh @SqlResultSetMapping and @NamedNativeQuery would need to be defined on one of your mapped entities.

Body:
I have three entity classes, I have written the query which includes join of two tables.

Table: ExpensesCategories

@Entity
@Table(name = "ExpensesCategories")
public class ExpensesCategories {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id", unique = true)
    private int categoryId;

    @NotNull
    private String categoryName;

    @NotNull
    private String categoryCodeInBankStats;

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryCodeInBankStats() {
        return categoryCodeInBankStats;
    }

    public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
        this.categoryCodeInBankStats = categoryCodeInBankStats;
    }
}

Table: Transactions

@Entity
@Table(name = "TransactionHistory")
public class TransactionHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Temporal(TemporalType.DATE)
    private Date dateOfTransaction;

    private String transactionType;

    private String refNo;

    private Date valueDate;

    private double withdrawalAmount;

    private double depositAmount;

    private double closingBalance;

    @ManyToOne
    @JoinColumn(name="userDetailsId", referencedColumnName="user_id")
    private UserDetails userDetails;

    @ManyToOne
    @JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
    private ExpensesCategories expenseCategories;

    public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
            double withdrawalAmount, double depositAmount, double closingBalance) {
        this.dateOfTransaction = dateOfTransaction;
        this.transactionType = transactionType;
        this.refNo = refNo;
        this.valueDate = valueDate;
        this.withdrawalAmount = withdrawalAmount;
        this.depositAmount = depositAmount;
        this.closingBalance = closingBalance;
    }

    public TransactionHistory() {
    }

    public Date getDateOfTransaction() {
        return dateOfTransaction;
    }

    public void setDateOfTransaction(Date date) {
        this.dateOfTransaction = date;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public Date getValueDate() {
        return valueDate;
    }

    public void setValueDate(Date valueDate) {
        this.valueDate = valueDate;
    }

    public double getWithdrawalAmount() {
        return withdrawalAmount;
    }

    public void setWithdrawalAmount(double withdrawalAmount) {
        this.withdrawalAmount = withdrawalAmount;
    }

    public double getDepositAmount() {
        return depositAmount;
    }

    public void setDepositAmount(double depositAmount) {
        this.depositAmount = depositAmount;
    }

    public double getClosingBalance() {
        return closingBalance;
    }

    public void setClosingBalance(double closingBalance) {
        this.closingBalance = closingBalance;
    }

    public UserDetails getUserDetails() {
        return userDetails;
    }

    public void setUserDetails(UserDetails userDetails) {
        this.userDetails = userDetails;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public ExpensesCategories getExpenseCategories() {
        return expenseCategories;
    }

    public void setExpenseCategories(ExpensesCategories expenseCategories) {
        this.expenseCategories = expenseCategories;
    }
}

Table: User Details

@Entity
@Table(name = "Employee")
public class UserDetails {

    @Id
    @Column(name = "user_id", unique = true)
    private int id;
    @NotNull
    private String firstname;
    @NotNull
    private String lastname;
    @Column(unique = true)
    @NotNull
    private String emailaddress;
    @NotNull
    private String role;

    public UserDetails(String firstname, String lastname, String emailaddress, String role) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.emailaddress = emailaddress;
        this.role = role;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public UserDetails() {
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmailaddress() {
        return emailaddress;
    }

    public void setEmailaddress(String emailaddress) {
        this.emailaddress = emailaddress;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
                + emailaddress + ", role=" + role + "]";
    }

I have written query like this in transaction entity.

    @Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id

")
        List<Object[]> getCategorizedExpenses();

My Json Response is like:

[
    [
        1,
        21,
        "UPI",
        "UPI Payments"
    ],
    [
        2,
        3733.59,
        "POS",
        "Shopping"
    ]
]

But i want json response with column names as well:

[
    [
       expense_categories_id: 1,
       Total_withdrawal_Amount: 21,
       category_code_in_bank_stats: "UPI",
       category_name: "UPI Payments"
    ],
    [
        expense_categories_id: 2,
        Total_withdrawal_Amount: 3733.59,
        category_code_in_bank_stats: "POS",
        category_name: "Shopping"
    ]
]

Please help me out..

Body:
You would need to map the results directly to a POJO class and ad some json config:

1) Define the pojo

public ResultClass implements Serializable{

   @JsonProperty("expense_categories_id")
   private Integer expenseCategoriesId;

   ...

   public ResultClass(Integer expenseCategoriesId ... // rest params){
      this.expenseCategoriesId = expenseCategoriesId;
      ...
   }
}

2) Define the mapping:

@SqlResultSetMapping(
    name="myMapping",
    classes={
        @ConstructorResult(
            targetClass=ResultClass.class,
            columns={
                @ColumnResult(name="expenseCategoriesId"),
                @ColumnResult(name="totalWithdrawalAmount")
                // further mappings ...
            }
        )
    }
)

3) Define a native query

@NamedNativeQuery(name="TransactionHistory.myQuery"
    , query="SELECT new mypackage.ResultClass(a.expense_categories_id as expeneCategoriesId ... ) from ...")

4) Define this method in the CrudRepository without the @Query annotation:

public List<ResultClass> myQuery();

Teh @SqlResultSetMapping and @NamedNativeQuery would need to be defined on one of your mapped entities.


问:
Haskell convert type error
I'm writing a simple program in Haskell that lets user input exponent of the power of 2

```<code>power a = 2^a
main = do
   number <- readLn
   let x = (read number :: Int)
   power x
</code>```

 I figured out that I need to convert String to Int but i still get following error: No instance for (Num (IO t0)) arising from a use of 'power'
 How do I make it work?

答:
Got it running that way - number is not an Int:

```<code>power :: (Num a, Integral b) => b -> a
power a = 2^a

main :: IO ()
main = do
  number <- getLine
  let x = read number
  print $ power x
</code>```

Title: Haskell convert type error

Body:
I'm writing a simple program in Haskell that lets user input exponent of the power of 2

power a = 2^a
main = do
   number <- readLn
   let x = (read number :: Int)
   power x

 I figured out that I need to convert String to Int but i still get following error: No instance for (Num (IO t0)) arising from a use of 'power'
 How do I make it work?

Body:
Got it running that way - number is not an Int:

power :: (Num a, Integral b) => b -> a
power a = 2^a

main :: IO ()
main = do
  number <- getLine
  let x = read number
  print $ power x


问:
Refresh ng-repeat data
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

```<code><div ng-controller="BrainRegionsCtrl">

    <div ng-repeat="region in brain_regions">

        <label>

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           <b>{/region.name/}</b>

         </label>

    </div>
</div>
</code>```

Selected regions list:

```<code><div ng-controller="BrainRegionsCtrl">

    <label ng-repeat="region in selected_brain_regions">
        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        <b>{/region.name/}</b>
    </label>

 </div>
</code>```

Controller:

```<code>ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});
</code>```

Here is a jsfiddle
Thank you.

答: AngularJS promises already call .apply() on their callbacks. You cannot call .apply again inside the callbacks since they're already being .applied, and the error "In Progress" tells exactly that. Just remove the .apply call and it will work, unless you have further errors.</p>

Title: Refresh ng-repeat data

Body:
I have a big list containing all of my data, and I have another shorter list containing only the selected data.
Originally, all the data is selected so both lists are identical, and the user must uncheck the checkbox of the unwanted data, and then the unchecked data must disappear from the selected_data_list.

When the page is loaded, the two lists are being filled correctly. But when I uncheck the unwanted data, the selected_data_list is not updating.

I tried to use $scope.$apply(), but it gave me this error:

Error: $rootScope:inprog
  Action Already In Progress

Here is my code:

Complete list:

           <input type="checkbox"
              name="checkbox_brain_region__included"
              id="checkbox_brain_region_{/region.id/}"
              value="{/region.id/}"
              ng-model="region.show"
              ng-change="update_selected_Brain_regions(region)">

           {/region.name/}

Selected regions list:

        <input type="radio" name="radio_brain_regions_graphical_search_soma" value="{/region.id/}">
        {/region.name/}

Controller:

ngApp.controller('BrainRegionsCtrl', function ($scope, $http) {

    $scope.brain_regions = [];
    $scope.selected_brain_regions = [];

    $scope.update_selected_Brain_regions = function (region) {

        for (var i = 0; i < $scope.brain_regions.length; i++) {
            var current_region = $scope.brain_regions[i];
            if (current_region.id === region.id) {
                if (region.show) {
                    $scope.selected_brain_regions.push(current_region);
                }
                else {
                    $scope.selected_brain_regions.splice(i,1);
                }
            }
        }
        console.log($scope.selected_brain_regions);

    };

});

Here is a jsfiddle
Thank you.


问:
How to make a 2 way relation in Laravel
Is there a way to set up the relation between 2 Models so when loading the hasMany relation, the belongsTo relation is automaticly set to the caller/parent?

We run in to a memmory issue when using a save-trigger on the product, that loaded in a new copy of the order, with a new copy of each products.
So if an order had 100 products, and trying to loop over the order->products->order->products it loaded 101 orders with total 10100 products.

one way to solve it was to use the setRelation() to set the belongsTo relation, in the loop in the controller.

I'd prefer if there was a way to set that relation from the Model instead.

```<code><?php
class Order extends Model {
    public function products() {
        return $this->hasMany(Product::class);
    }

    public function updateTotals() {
        foreach ($this->products as $product) {
            // code
        }
        $this->save();
    }
}

class Product extends Model {
    public function order() {
        return $this->belongsTo(Order::class);
    }

    public static function boot() {
        parent::boot();
        static::updated(function (Product $product) {
            $product->order->updateTotals();
        });
    }
}

class OrderController extends Controller {
    public function postView(UserOrderSaveRequest $request) {
        $order = $request->getOrder();
        foreach ($order->products as $product) {
            $product->setRelation('order', $order);
            // code
            $product->save();
        }
    }
}
</code>```

Update 1:
Test i used to test the answer

```<code>// tinker function to fetch the first order
$o = Order();

// load 2 products
$o->products[0];
$o->products[1];

// Set relation
$o->products[0]->setRelation('order', $o);
$o->products[1]->setRelation('order', $o);

// load 2 products orders
$o->products[0]->order;
$o->products[1]->order;

// Test 1 (true if setRelation was used)
// (false in @Bilal Maqsood answer)
$o === $o->products[0]->order;

// Test 2 (true if setRelation was used)
// (true in @Bilal Maqsood answer)
$o->products[1]->order === $o->products[0]->order;

// Test 3 (false?)
$o->products[1]->order->products[0] === $o->products[0]->order->prodcuts[0]
</code>```

答:
Update you Product model code like

class Product extends Model {

    protected $with = ['order'];

  public function order() {
        return $this->belongsTo(Order::class);
  }

}
```

the $with property load the defined relations for each record of product.

Title: How to make a 2 way relation in Laravel

Body:
Is there a way to set up the relation between 2 Models so when loading the hasMany relation, the belongsTo relation is automaticly set to the caller/parent?

We run in to a memmory issue when using a save-trigger on the product, that loaded in a new copy of the order, with a new copy of each products.
So if an order had 100 products, and trying to loop over the order->products->order->products it loaded 101 orders with total 10100 products.

one way to solve it was to use the setRelation() to set the belongsTo relation, in the loop in the controller.

I'd prefer if there was a way to set that relation from the Model instead.

<?php
class Order extends Model {
    public function products() {
        return $this->hasMany(Product::class);
    }

    public function updateTotals() {
        foreach ($this->products as $product) {
            // code
        }
        $this->save();
    }
}

class Product extends Model {
    public function order() {
        return $this->belongsTo(Order::class);
    }

    public static function boot() {
        parent::boot();
        static::updated(function (Product $product) {
            $product->order->updateTotals();
        });
    }
}

class OrderController extends Controller {
    public function postView(UserOrderSaveRequest $request) {
        $order = $request->getOrder();
        foreach ($order->products as $product) {
            $product->setRelation('order', $order);
            // code
            $product->save();
        }
    }
}

Update 1:
Test i used to test the answer

// tinker function to fetch the first order
$o = Order();

// load 2 products
$o->products[0];
$o->products[1];

// Set relation
$o->products[0]->setRelation('order', $o);
$o->products[1]->setRelation('order', $o);

// load 2 products orders
$o->products[0]->order;
$o->products[1]->order;

// Test 1 (true if setRelation was used)
// (false in @Bilal Maqsood answer)
$o === $o->products[0]->order;

// Test 2 (true if setRelation was used)
// (true in @Bilal Maqsood answer)
$o->products[1]->order === $o->products[0]->order;

// Test 3 (false?)
$o->products[1]->order->products[0] === $o->products[0]->order->prodcuts[0]

Body:
Update you Product model code like

class Product extends Model {

    protected $with = ['order'];

  public function order() {
        return $this->belongsTo(Order::class);
  }

}

the $with property load the defined relations for each record of product.


问:
Cost of developing a Google Assistant App?
What costs are involved with developing and/or releasing a Google Assistant App? </p>

<p>eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn? </p>

答:
Dialogflow is for  free if you don't use it as an enterprise:
https://dialogflow.com/pricing/

And Firebase free tier should be enough if you not using firebase
already for other projects.  enter link description here

But of course you have to calculate your own time so in case of the
spent time probably not.

For everything else yes it is, as long as you not using it already somewhere. You can for development also host your server local and use an ngrok tunnel as sever address for Dialogflow.

Body:
What costs are involved with developing and/or releasing a Google Assistant App?

eg: Can you develop an app using DialogFlow and a backend (say Firebase) without having to pay while you learn?

ContentLicense: CC BY-SA 4.0


问:
Expanding on the API roles
Expanding on the API roles using Keycloak

when I try to make an API call to

```<code>http://localhost:8080/keycloak/url/auth/realms/master/protocol/openid-connect/token
</code>```

with some data:

```<code>{
    client_id : 'clientId',
    username : 'name',
    password : '@#$%^&',
    grant_type : "password"

}
</code>```

Its showing an error

Client secret not provided in request.

答:
Keycloak is expecting secret key.
 The client that you are trying to access might have the access type ( on the first tab) as Confidential or Bearer-only.
In that case you need to send the secret key which you can take from the Credentials tab.

Update:

```<code>http://server_url/auth/realms/master/protocol/openid-connect/token

{
  "username": "",
  "password": "",
  "realm": "",
  "redirect_url": "",
  "client_secret": "",
  "grant_type": ""
}
</code>```

Mare sure choose the x-www-form-urlencoded, while sending the request.

Title: Expanding on the API roles

Body:
Expanding on the API roles using Keycloak

when I try to make an API call to

http://localhost:8080/keycloak/url/auth/realms/master/protocol/openid-connect/token

with some data:

{
    client_id : 'clientId',
    username : 'name',
    password : '@#$%^&',
    grant_type : "password"

}

Its showing an error

Client secret not provided in request.

Body:
Keycloak is expecting secret key.
 The client that you are trying to access might have the access type ( on the first tab) as Confidential or Bearer-only.
In that case you need to send the secret key which you can take from the Credentials tab.

Update:

http://server_url/auth/realms/master/protocol/openid-connect/token

{
  "username": "",
  "password": "",
  "realm": "",
  "redirect_url": "",
  "client_secret": "",
  "grant_type": ""
}

Mare sure choose the x-www-form-urlencoded, while sending the request.


问:
Insert an entry in DynamoDB table with two conditions
Conditions:

(hashKey, rangekey) combination should not already exist in the table

Newly inserted range Key value must be one more than the maximum rangeKey till now.

I'm trying to use expectedValueAttribute specified here:
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExpectedAttributeValue.html

But I can only put one condition at a time. How to enforce both the conditions?

```<code>Map<String, ExpectedAttributeValue> expectedAttributes = ...
    .put(hashKey, new ExpectedAttributeValue(false))
    .put(rangeKey, new ExpectedAttributeValue(false))
    .build();
</code>```

This satisfies only condition 1 above.

答:
As you cannot compare the maximum value of the existing range key without first querying for it, you will need to do this in two steps.

1) Get the item with the highest range key for your given partition key

2) Compare that returned range key with the one you have, if the returned key is exactly one less, put the new item. (Note you don't actually need to check whether the item already exists - as the query already confirmed it does not exist).

DynamoDB stores your items in range key order for a given partition, and it will also return your items for a given partition in this order. If your range key is a number, the sort order is numeric and you want the last result for your partition not the first. You can revere the order of your query using ScanIndexForward, then take the first item.

The query would be:

```<code>Table table = dynamoDB.getTable("YOUR_TABLE");

QuerySpec spec = new QuerySpec()
    .withKeyConditionExpression("hash = :v_hash")
    .withValueMap(new ValueMap()
        .withString(":v_hash", "your_hash")
    .withScanIndexForward(false)
    .setMaxResultSize(1);

ItemCollection<QueryOutcome> items = table.query(spec);
</code>```

If the item range key is one less than the new item range key, put the item. Note you should consider the behaviour if the items list is empty (i.e. the partition key does not exist yet).

Body:
Conditions:

(hashKey, rangekey) combination should not already exist in the table

Newly inserted range Key value must be one more than the maximum rangeKey till now.

I'm trying to use expectedValueAttribute specified here:
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExpectedAttributeValue.html

But I can only put one condition at a time. How to enforce both the conditions?

Map<String, ExpectedAttributeValue> expectedAttributes = ...
    .put(hashKey, new ExpectedAttributeValue(false))
    .put(rangeKey, new ExpectedAttributeValue(false))
    .build();

This satisfies only condition 1 above.

Body:
As you cannot compare the maximum value of the existing range key without first querying for it, you will need to do this in two steps.

1) Get the item with the highest range key for your given partition key

2) Compare that returned range key with the one you have, if the returned key is exactly one less, put the new item. (Note you don't actually need to check whether the item already exists - as the query already confirmed it does not exist).

DynamoDB stores your items in range key order for a given partition, and it will also return your items for a given partition in this order. If your range key is a number, the sort order is numeric and you want the last result for your partition not the first. You can revere the order of your query using ScanIndexForward, then take the first item.

The query would be:

Table table = dynamoDB.getTable("YOUR_TABLE");

QuerySpec spec = new QuerySpec()
    .withKeyConditionExpression("hash = :v_hash")
    .withValueMap(new ValueMap()
        .withString(":v_hash", "your_hash")
    .withScanIndexForward(false)
    .setMaxResultSize(1);

ItemCollection<QueryOutcome> items = table.query(spec);

If the item range key is one less than the new item range key, put the item. Note you should consider the behaviour if the items list is empty (i.e. the partition key does not exist yet).


问:
there is a gap between the content layout and navigationbar
I have installed a application from Google play, but something wrong when I try to hide the navigationbar.

more details like blow:

Issue list:

a gap between Application content and navigationbar

Application content can't adjust when I hide navigationbar

Issue already exist When I landscape ,like below:

issue list:

a gap between Application content and navigationbar

Application content cann't adjust when I hide navigationbar

system bar time out of boundary

Question:

How can I remove the gap?

How can I dynamic adjust the application content when I hide navigationbar bar?

Why time out of boundary?

答:
```<code>  <android.support.v7.widget.Toolbar
        android:id="@+id/tool"
        android:layout_width="match_parent"
        android:layout_height="57dp"
        android:background="@color/colorPrimary"
        android:contentInsetEnd="0dp"
        android:contentInsetLeft="0dp"
        android:contentInsetRight="0dp"
        android:contentInsetStart="0dp"
        app:contentInsetEnd="0dp"
        app:contentInsetLeft="0dp"
        app:contentInsetRight="0dp"
        app:contentInsetStart="0dp"
        app:contentInsetStartWithNavigation="0dp">

</Toolbar>
</code>```


问:
Remove references from the .net tab of visual studio 2010
How can I remove references from the .net tab of the add reference dialog of visual studio 2010?

Visual studio 2010 autopoints my references to the .net tab location when I browse to them and I want to be sure to remove them so my references don't get changed.

答:
I think you're a bit confuzzled about what's happening here.  Yes, you use the Browse tab to add references to your assemblies.  Or the Projects tab if those projects are part of the solution.  But that does not add these assemblies to the .NET tab.  That one is filled from directories whose names are listed in a registry key.  Put there by an installer. You should never alter those keys yourself, that just causes misery whenever you switch machines.

You don't have to do anything.


问:
Get value insert in QR code without enter
Hello all please help me, i want to insert input value in qrcode without input anything.

```<code>         <input id="text" type="text" value="Please Enter Your NRIC or Work
         Permit" style="Width:20%"/ onblur='generateBarCode();'>

        <img id='barcode' src="https://api.qrserver.com/v1/create-qr-code/?
        data=HelloWorld&size=100x100" alt="" title="HELLO" width="50"
        height="50" />

           <script type="text/javascript">
              function generateBarCode()
              {
                 var nric = $('#text').val();
                 var url = 'https://api.qrserver.com/v1/create-qr-code/?data=' +
                 nric + '&size=50x50';
                 $('#barcode').attr('src', url);
              }
         </script>
</code>```

Please check this fiddle link:-

https://jsfiddle.net/v274z2oc/

答:
You have to add event listener on window.onload for this to work. See below

window.onload = generateBarCode;
function generateBarCode() {
  var nric = $('#text').val();
  var url = 'https://api.qrserver.com/v1/create-qr-code/?data=' + nric + '&size=50x50';
  $('#barcode').attr('src', url);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="text" type="text" value="Please Enter Your NRIC or Work Permit" style="Width:20%" / onblur='generateBarCode();'>

<img id='barcode' src="https://api.qrserver.com/v1/create-qr-code/?data=HelloWorld&size=100x100" alt="" title="HELLO" width="50" height="50" /></code>```

Body:
Hello all please help me, i want to insert input value in qrcode without input anything.

         <input id="text" type="text" value="Please Enter Your NRIC or Work
         Permit" style="Width:20%"/ onblur='generateBarCode();'>

Please check this fiddle link:-

https://jsfiddle.net/v274z2oc/

Body:
You have to add event listener on window.onload for this to work. See below

window.onload = generateBarCode;
function generateBarCode() {
  var nric = $('#text').val();
  var url = 'https://api.qrserver.com/v1/create-qr-code/?data=' + nric + '&amp;size=50x50';
  $('#barcode').attr('src', url);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="text" type="text" value="Please Enter Your NRIC or Work Permit" style="Width:20%" / onblur='generateBarCode();'>

<img id='barcode' src="https://api.qrserver.com/v1/create-qr-code/?data=HelloWorld&amp;size=100x100" alt="" title="HELLO" width="50" height="50" />


问:
Cannot Launch and Debug TypeScript Using Node
We're setting up a new OSx machine and getting this message when trying to launch and debug a TypeScript based node app:

Cannot launch program '/Projects/is/0.0.34/server/server/server.ts';
  setting the 'outDir or outFiles' attribute might help.

We've been using the same launch config for over a year and we're not writing the output to a separate directory, so there should no need to set 'outFiles'. The program runs fine from the command prompt. However, trying to launch the app in VsCode is now returning the error above. We did recently upgraded to Node v8.5.0 from v7.3.0. Based on the docs this should still work. The other posts regarding this issue relate to issues resulting from writing the source (and sourcemaps) to a different directory.

launch.json

```<code>{
    "configurations": [
        {
            "name": "Launch Program",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/server/server.ts",
            "cwd": "${workspaceRoot}"
        }
    ]
}
</code>```

Here's the tsconfig:

```<code>{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "watch": true,
        "allowUnreachableCode": true,
        "noImplicitUseStrict": true
    }
}
</code>```

答:
Use like this your launch.json file.</p>

```<code>{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
    "type": "node",
    "request": "launch",
    "name": "Launch Program",
    "program": "${workspaceFolder}/yourjsfile.js"
},
    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "program": "${file}",
        "outFiles": [
            "${workspaceFolder}/**/*.js"
        ]
    }
]
}
</code>```

Body:
We're setting up a new OSx machine and getting this message when trying to launch and debug a TypeScript based node app:

Cannot launch program '/Projects/is/0.0.34/server/server/server.ts';
  setting the 'outDir or outFiles' attribute might help.

We've been using the same launch config for over a year and we're not writing the output to a separate directory, so there should no need to set 'outFiles'. The program runs fine from the command prompt. However, trying to launch the app in VsCode is now returning the error above. We did recently upgraded to Node v8.5.0 from v7.3.0. Based on the docs this should still work. The other posts regarding this issue relate to issues resulting from writing the source (and sourcemaps) to a different directory.

launch.json

{
    "configurations": [
        {
            "name": "Launch Program",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/server/server.ts",
            "cwd": "${workspaceRoot}"
        }
    ]
}

Here's the tsconfig:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "watch": true,
        "allowUnreachableCode": true,
        "noImplicitUseStrict": true
    }
}

Body:
Use like this your launch.json file.

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
    "type": "node",
    "request": "launch",
    "name": "Launch Program",
    "program": "${workspaceFolder}/yourjsfile.js"
},
    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "program": "${file}",
        "outFiles": [
            "${workspaceFolder}/**/*.js"
        ]
    }
]
}


问:
Get the click event from the listview and open the video
I am making a small application, namely a custom listview, when I click on a line on the listview will open a new layout and play video online. I'm wrong every time click on the picture

Here is a video class

Here is the click event in the main activity

The one thing I want to ask is that can make the user click on a line on the listview, then the video will open in full screen (automatic screen rotation) is not? And how do you know how many users click on the number line on the listview?
Thank you everyone, look forward to helping everyone :D

p/s: Does the video view support real-time video playback? Because I making watch TV online app

答:
In your manifest file you're missing the declaration for ModuleDetailActivity. Just add this line inside your application tag to declare the activity:

```<code><activity android:name=".ModuleDetailActivity" />
</code>```

Body:
In your manifest file you're missing the declaration for ModuleDetailActivity. Just add this line inside your application tag to declare the activity:

<activity android:name=".ModuleDetailActivity" />


问:
Get the color range of a rating bar
I want to create a simple HTML rating bar. My rating bar got has a dynamic number of containers. For example 5:

And I need to calculate the color values [first+2,last-1]. The first and last colors are given.

$(document).ready(function() {
  ratingElements = $(".ratingEle"); // Find all rating containers

  ratingColors.push(initialColorDefault); // if not selected, set the container to gray // index 0
  ratingColors.push(initialColorMin); // red color // index 1

  // !! Calculate the missing colors here !!
  // from index 2 to ratingColors.length - 1
  // ratingColors.push("#" + hexValue);

  updateRatingBar(0); // set all containers to gray

  $(ratingElements).each(function(index, element) { // add some event handlers to the containers
    var ele = $(element);
    var i = index + 1;

    ele.click(function() {
      setRating(i);
    });

    ele.hover(function() {
      updateRatingBar(i);
    });

  });

});

var ratingElements;
var ratingColors = [];

var initialColorDefault = "#cccccc"; // pre set colors
var initialColorMin = "#ff0000";
var initialColorMax = "#80ff00";

function setRating(currentValue) { // click handler
  $("#ratingOutput").html(currentValue + " / " + ratingElements.length);
  updateRatingBar(currentValue);
}

function updateRatingBar(currentValue) { // set colors
  $(ratingElements).each(function(index, element) {
    var i = index;

    if (i > currentValue) {
      i = 0;
    }

    $(element).css('background-color', ratingColors[i]);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}</code>```

```

So as you can see, I need to calculate the colors to make it work. I set a missing part in my JS file and need help, calculating it.

I don't know if I should go for hex or rgb values.

When hovering over the containers the colors should get updated automatically. When clicking a container, it should set a value.

But I already archieved this I just need to calculate the missing color range.

答:
With this answer as base

$(function() {
  var color1 = 'ff0000';
  var color2 = '80ff00';
  var ratio = 1 / $('.ratingEle').length;

  var hex = function(x) {
      x = x.toString(16);
      return (x.length == 1) ? '0' + x : x;
  };
  $i=1;
  $('.ratingEle').each(function() {
    var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
    var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
    var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));

    var color = hex(r) + hex(g) + hex(b);
    $(this).css('background-color', '#'+color);
    $i++;
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}</code>```

```
</div>
</div>
</p>
<h1>with more elements</h1>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  var color1 = 'ff0000';
  var color2 = '80ff00';
  var ratio = 1 / $('.ratingEle').length;

  var hex = function(x) {
      x = x.toString(16);
      return (x.length == 1) ? '0' + x : x;
  };
  $i=1;
  $('.ratingEle').each(function() {
    var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
    var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
    var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));

    var color = hex(r) + hex(g) + hex(b);
    $(this).css('background-color', '#'+color);
    $i++;
  });

});</code>```

.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="rating">

  <div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
  </div>

  <div>
    <p id="ratingOutput"></p>
  </div>

</div></code>```

Title: Get the color range of a rating bar

Body:
I want to create a simple HTML rating bar. My rating bar got has a dynamic number of containers. For example 5:

And I need to calculate the color values [first+2,last-1]. The first and last colors are given.

$(document).ready(function() {
  ratingElements = $(".ratingEle"); // Find all rating containers

  ratingColors.push(initialColorDefault); // if not selected, set the container to gray // index 0
  ratingColors.push(initialColorMin); // red color // index 1

  // !! Calculate the missing colors here !!
  // from index 2 to ratingColors.length - 1
  // ratingColors.push("#" + hexValue);

  updateRatingBar(0); // set all containers to gray

  $(ratingElements).each(function(index, element) { // add some event handlers to the containers
    var ele = $(element);
    var i = index + 1;

    ele.click(function() {
      setRating(i);
    });

    ele.hover(function() {
      updateRatingBar(i);
    });

  });

});

var ratingElements;
var ratingColors = [];

var initialColorDefault = "#cccccc"; // pre set colors
var initialColorMin = "#ff0000";
var initialColorMax = "#80ff00";

function setRating(currentValue) { // click handler
  $("#ratingOutput").html(currentValue + " / " + ratingElements.length);
  updateRatingBar(currentValue);
}

function updateRatingBar(currentValue) { // set colors
  $(ratingElements).each(function(index, element) {
    var i = index;

    if (i > currentValue) {
      i = 0;
    }

    $(element).css('background-color', ratingColors[i]);
  });
}

.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}

So as you can see, I need to calculate the colors to make it work. I set a missing part in my JS file and need help, calculating it.

I don't know if I should go for hex or rgb values.

When hovering over the containers the colors should get updated automatically. When clicking a container, it should set a value.

But I already archieved this I just need to calculate the missing color range.

Body:
With this answer as base

$(function() {
  var color1 = 'ff0000';
  var color2 = '80ff00';
  var ratio = 1 / $('.ratingEle').length;

  var hex = function(x) {
      x = x.toString(16);
      return (x.length == 1) ? '0' + x : x;
  };
  $i=1;
  $('.ratingEle').each(function() {
    var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
    var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
    var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));

    var color = hex(r) + hex(g) + hex(b);
    $(this).css('background-color', '#'+color);
    $i++;
  });

});

.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="rating">

  <div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
  </div>

  <div>
    <p id="ratingOutput"></p>
  </div>

</div>

with more elements

$(function() {
  var color1 = 'ff0000';
  var color2 = '80ff00';
  var ratio = 1 / $('.ratingEle').length;

  var hex = function(x) {
      x = x.toString(16);
      return (x.length == 1) ? '0' + x : x;
  };
  $i=1;
  $('.ratingEle').each(function() {
    var r = Math.ceil(parseInt(color1.substring(0,2), 16) * (ratio*$i) + parseInt(color2.substring(0,2), 16) * (1-(ratio*$i)));
    var g = Math.ceil(parseInt(color1.substring(2,4), 16) * (ratio*$i) + parseInt(color2.substring(2,4), 16) * (1-(ratio*$i)));
    var b = Math.ceil(parseInt(color1.substring(4,6), 16) * (ratio*$i) + parseInt(color2.substring(4,6), 16) * (1-(ratio*$i)));

    var color = hex(r) + hex(g) + hex(b);
    $(this).css('background-color', '#'+color);
    $i++;
  });

});

.ratingEle {
  float: left;
  cursor: pointer;
  height: 10px;
  width: 30px;
  margin-left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="rating">

  <div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
    <div class="ratingEle"></div>
  </div>

  <div>
    <p id="ratingOutput"></p>
  </div>

</div>


问:
Why does UPDATE statement give divide by zero even if that particular row doesn't exist?
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.</p>

```<code>  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp
</code>```

答:
why does the update statement gives divided by 0 operation even
  thought there is no row in the table. Does it execute the set function
  first and then try to apply to the where clause.

Question is not about dived by 0,rather it is about when does any error occur.

BTW query easily pass through "Parse stage" and hand it is handed over to "Optimization" stage.

Example,

declare @table table(id int identity(1,1),PhoneNumber int)

```<code>select *,0/0 from @table
</code>```

If you see "Estimated Execution plan (EEP)" then there is no error.that means it passes through Parse Stage and also EEP is created.

when we try to view Actual Execution Plan (AEP) then we get relevant error or divided by 0 error in this example.

```<code>select *,case when id=2 then 0/0 else 0 END
 from @table
</code>```

Here again there is no problem in getting EEP.
If we click on AEP then 1 rows is return and get error in 2nd row.

This prove that divided by 0/0 condition are executed when it meet certain condition.

```<code>select *
 from @table
 where id= case when id=2 then 0/0 else id END
</code>```

Here again there is no problem in getting EEP.
If we click on AEP then 1 rows is return and get error in 2nd row.

This prove that divided by 0/0 condition are executed when it meet certain condition.

Body:
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.

  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp

Body:
why does the update statement gives divided by 0 operation even
  thought there is no row in the table. Does it execute the set function
  first and then try to apply to the where clause.

Question is not about dived by 0,rather it is about when does any error occur.

BTW query easily pass through "Parse stage" and hand it is handed over to "Optimization" stage.

Example,

declare @table table(id int identity(1,1),PhoneNumber int)

select *,0/0 from @table

If you see "Estimated Execution plan (EEP)" then there is no error.that means it passes through Parse Stage and also EEP is created.

when we try to view Actual Execution Plan (AEP) then we get relevant error or divided by 0 error in this example.

select *,case when id=2 then 0/0 else 0 END
 from @table

Here again there is no problem in getting EEP.
If we click on AEP then 1 rows is return and get error in 2nd row.

This prove that divided by 0/0 condition are executed when it meet certain condition.

select *
 from @table
 where id= case when id=2 then 0/0 else id END

Here again there is no problem in getting EEP.
If we click on AEP then 1 rows is return and get error in 2nd row.

This prove that divided by 0/0 condition are executed when it meet certain condition.


问:
Signature for C function that returns a multidimensional array
If I have:

```<code>char* buffer[8][8];
</code>```

And inside the same file I want to write a function that returns this buffer, what would the signature of that function look like?

In the case of

```<code>char* buffer[8];
</code>```

I could write

```<code>char** get_buff() {
    return buffer;
}
</code>```

But in this case I cannot deference into a multidimensional array. The C compiler will tell me that

```<code>char* buffer[8][8]
</code>```

has type

```<code>char * (*)[8]
</code>```

The problem is that the type it gives isn't valid syntax in a signature, so I have no idea what it expects to go there. What should the signature look like?

答:
Because of a limitation in the C language, you cannot return arrays from functions. You can only return pointers to arrays.

It will be easiest to work with a pointer to the first element. The first element in your case is of type char*, so a pointer to that would be char**. Please note that the pointer-to-pointer syntax has nothing to do with arrays as such.

```<code>// my recommended solution
char** get_buff (void)
{
  return &buffer[0][0];
}
</code>```

Should you wish to return a pointer to the whole array, it turns much more complicated. Advanced topic follows.

The array pointer to an array of type char* buffer[8][8]; is declared as char* (*ptr)[8][8]. This is a pointer to the whole array. It would also be possible to use a pointer only to the first element, a char* (*)[8].

If you wish to return an array pointer, the C syntax for it is truly horrible:

```<code>char* (*get_buff(void))[8][8]
{
  return &buffer;  // return address of array
}
</code>```

This is completely unreadable. What we should do to avoid such C madness syntax, is to use a typedef to the array type, then return a pointer to such a type:

```<code>typedef char* c_arr_8x8 [8][8];

c_arr_8x8* get_buff (void)
{
  return &buffer;
}
</code>```

Alternatively, it is perfectly fine to return the pointer through a parameter, although then we'd have to pass the array pointer by pointer:

```<code>void get_buff (char* (**buf)[8][8])
{
  *buf = &buffer;
}
</code>```

Body:
If I have:

char* buffer[8][8];

And inside the same file I want to write a function that returns this buffer, what would the signature of that function look like?

In the case of

char* buffer[8];

I could write

char** get_buff() {
    return buffer;
}

But in this case I cannot deference into a multidimensional array. The C compiler will tell me that

char* buffer[8][8]

has type

char * (*)[8]

The problem is that the type it gives isn't valid syntax in a signature, so I have no idea what it expects to go there. What should the signature look like?

Body:
Because of a limitation in the C language, you cannot return arrays from functions. You can only return pointers to arrays.

It will be easiest to work with a pointer to the first element. The first element in your case is of type char*, so a pointer to that would be char**. Please note that the pointer-to-pointer syntax has nothing to do with arrays as such.

// my recommended solution
char** get_buff (void)
{
  return &buffer[0][0];
}

Should you wish to return a pointer to the whole array, it turns much more complicated. Advanced topic follows.

The array pointer to an array of type char* buffer[8][8]; is declared as char* (*ptr)[8][8]. This is a pointer to the whole array. It would also be possible to use a pointer only to the first element, a char* (*)[8].

If you wish to return an array pointer, the C syntax for it is truly horrible:

char* (*get_buff(void))[8][8]
{
  return &buffer;  // return address of array
}

This is completely unreadable. What we should do to avoid such C madness syntax, is to use a typedef to the array type, then return a pointer to such a type:

typedef char* c_arr_8x8 [8][8];

c_arr_8x8* get_buff (void)
{
  return &buffer;
}

Alternatively, it is perfectly fine to return the pointer through a parameter, although then we'd have to pass the array pointer by pointer:

void get_buff (char* (**buf)[8][8])
{
  *buf = &buffer;
}


问:
AttributedString with line break (\n) is not working properly
I am adding Continue reading in the last. If there is any line break in the text, the continue reading is not visible. Is this iOS specific bug or I am missing something?

```<code>let activityData.feed = "Hi this is \n \n stack overflow"

let formattedString = NSMutableAttributedString()
                formattedString.normal(activityData.feed!).bold(LanguageManager.shared.getLocale(key: "Continue Reading"))
                labelFeed.attributedText = formattedString
</code>```

Extension of attributed string

```<code>extension NSMutableAttributedString {
    @discardableResult func bold(_ text:String) -> NSMutableAttributedString {
        let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont.systemFont(ofSize: 16.0), NSForegroundColorAttributeName : UIColor.CNS_BlueColor]
        let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
        self.append(boldString)
        return self
    }

    @discardableResult func normal(_ text:String)->NSMutableAttributedString {
        let normal =  NSAttributedString(string: text)
        self.append(normal)
        return self
    }
}
</code>```

答:
Did you try the html tag
 instead of \n ?
If you already have an attributedstring, take antvantage of the html tags.

Body:
I am adding Continue reading in the last. If there is any line break in the text, the continue reading is not visible. Is this iOS specific bug or I am missing something?

let activityData.feed = "Hi this is \n \n stack overflow"

let formattedString = NSMutableAttributedString()
                formattedString.normal(activityData.feed!).bold(LanguageManager.shared.getLocale(key: "Continue Reading"))
                labelFeed.attributedText = formattedString

Extension of attributed string

extension NSMutableAttributedString {
    @discardableResult func bold(_ text:String) -> NSMutableAttributedString {
        let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont.systemFont(ofSize: 16.0), NSForegroundColorAttributeName : UIColor.CNS_BlueColor]
        let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
        self.append(boldString)
        return self
    }

    @discardableResult func normal(_ text:String)->NSMutableAttributedString {
        let normal =  NSAttributedString(string: text)
        self.append(normal)
        return self
    }
}

Body:
Did you try the html tag <br> instead of \n ?
If you already have an attributedstring, take antvantage of the html tags.


问:
Is there a good reason to use upper case for SQL keywords?
The default seems to be upper case, but is there really any reason to use upper case for keywords?

I started using upper case, because I was just trying to match what SQL Server gives me whenever I tried to create something, like a new stored procedure. But then, I felt terrible for my baby (5th) finger, that always needs to hold down the Shift button, so I stopped using upper case. Is there a reason why I should go back to upper case?

答:
Less than 10% of the letters in the text we read are upper case.  Hence our brains are more keen at recognizing lower case letters than upper case ones.  Studies have shown it takes longer to read upper case text.  Here is just one example:

http://www.guardian.co.uk/media/mind-your-language/2010/oct/04/new-york-street-signs-capitals

The above example I think emphasizes that even when you're talking about just one or two words, it makes a difference.

OwnerDisplayName: klughing


问:
where to find specific version of aws-java-sdk?
I want to download aws-java-sdk-1.9.5, could not find any archive for this jar.
Whatever I am finding is the latest jar from AWS site https://aws.amazon.com/sdk-for-java/

I also checked maven repository but there the available jar is of 2 KBs only that didn't contain any source in the jar.
http://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk/1.9.5

Any suggestion would be appreciated.

答:
You can download from official AWS Repo.

Here is the link for version 1.9.5


问:
Create Custom HTML Helper in ASP.Net Core
I want to create my own custom HTML Helper like the ones used in ASP.NET MVC, but I haven't been able to find how to implement them in the correct way.

I have found how to create custom Tag Helpers but not HTML Helpers. How do I create my own custom HTML Helpers?

答:
For me I thought my HTML helpers weren't working until I spotted that the extension method is now on IHtmlHelper not HtmlHelper.

So for .net core:

```<code>public static IHtmlContent CheckboxListFor<TModel>(this IHtmlHelper<TModel> html,
            Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
</code>```

Instead of for .net:

```<code>public static HtmlString CheckboxListFor<TModel>(this HtmlHelper<TModel> html,
            Expression<Func<TModel, List<CheckboxListItem>>> expression) ...
</code>```

EDIT: I've also updated the return type for .net core to be IHtmlContent as using something like HtmlContentBuilder is a nicer way to compose HTML content and returning that returns IHtmlContent

Body:
For me I thought my HTML helpers weren't working until I spotted that the extension method is now on IHtmlHelper not HtmlHelper.

So for .net core:

public static IHtmlContent CheckboxListFor<TModel>(this IHtmlHelper<TModel> html,
            Expression<Func<TModel, List<CheckboxListItem>>> expression) ...

Instead of for .net:

public static HtmlString CheckboxListFor<TModel>(this HtmlHelper<TModel> html,
            Expression<Func<TModel, List<CheckboxListItem>>> expression) ...

EDIT: I've also updated the return type for .net core to be IHtmlContent as using something like HtmlContentBuilder is a nicer way to compose HTML content and returning that returns IHtmlContent


问:
Streaming data from Twitter to HDFS command not working
I will like to stream data from tweeter to hdfs, i used this command: ./bin/flume-ng agent -n TwitterAgent -c conf -f /usr/lib/apache-flume-1.4.0-bin/conf/flume.conf

I can't get the result i am expecting. No data streamed.

Anyone who has a linus command for streaming data from tweeter to hdfs?

答:
First of all go to apache-flume-1.4.0-bin directory from your terminal

1] cd apache-flume-1.4.0-bin

Then write the below command on terminal

2] bin/flume-ng agent --conf ./conf/ -f conf/flume.conf -Dflume.root.logger=DEBUG,console -n TwitterAgent