问:
Including third-party libraries in C applications
I'm a bit naive when it comes to application development in C. I've been writing a lot of code for a programming language I'm working on and I want to include stuff from ICU (for internationalization and unicode support).

The problem is, I'm just not sure if there are any conventions for including a third party library. for something like readline where lots of systems are probably going to have it installed already, it's safe to just link to it (I think). But what about if I wanted to include a version of the library in my own code? Is this common or am I thinking about this all wrong?

答: If it is a .lib and it has no runtime linked libraries it gets complied into you code.  If you need to link to dynamic libraries you will have to assure they are there provide a installer or point the user to where they can obtain them. </p>


来源: stackexchange

问:
How do I make sure successed2000.json has more than 1000 files, not 25 files?
I have sucessed json file format of image 1. I have 2,000 csv data, and I want 2,000 json files that are kept in 25 rather than nextpage and skip.

答:
Um, do you mean "How do i change the pageSize value from 25 to 2000?

json works as dictionaries in python. So i think you should be able to do:

```<code>dataJson['nextPage']['pageSize'] = 2000
</code>```

ref: Manipulating python json dictionaries

Or did i misunderstand your question?

ContentLicense: CC BY-SA 4.0

Body:
Um, do you mean "How do i change the pageSize value from 25 to 2000?

json works as dictionaries in python. So i think you should be able to do:

dataJson['nextPage']['pageSize'] = 2000

ref: Manipulating python json dictionaries

Or did i misunderstand your question?

ContentLicense: CC BY-SA 3.0


问:
How to Use Required Field validator on a check box CHECKED true or false
I  have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check

```<code><asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />

<div class="col-xs-9 form-inline" id="PChange" style="display: none;">
   <asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password"  ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
   <asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
   <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>
</div>
</code>```

gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.

```<code><asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />
</code>```

If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?

Java script function to show/hide div.

```<code><script type="text/javascript">
        function showhidepasswordFields() {
            if (document.getElementById('<%=cbPassword.ClientID%>').checked) {
                document.getElementById('PChange').style.display = 'block';
            }
            else if (!document.getElementById('<%=cbPassword.ClientID%>').checked) {
                document.getElementById('PChange').style.display = 'none';
            }
        }
    </script>
</code>```

答:
.aspx:

```<code><asp:CheckBox ID="cbTest" runat="server" OnCheckedChanged="cbTest_CheckedChanged"></asp:CheckBox>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFV" Enabled="false" runat="server" ErrorMessage="*****" ControlToValidate="txtTest" ></asp:RequiredFieldValidator>
</code>```

.aspx.cs:

```<code>protected void cbTest_CheckedChanged(object sender, EventArgs e)
{
    reqFV.Enabled = cbTest.Checked;
}
</code>```

Body:
I  have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check

<asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />

   <asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password"  ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
   <asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
   <asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
   <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
   <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>

gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.

<asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />

If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?

Java script function to show/hide div.

Body:
.aspx:

<asp:CheckBox ID="cbTest" runat="server" OnCheckedChanged="cbTest_CheckedChanged"></asp:CheckBox>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFV" Enabled="false" runat="server" ErrorMessage="*****" ControlToValidate="txtTest" ></asp:RequiredFieldValidator>

.aspx.cs:

protected void cbTest_CheckedChanged(object sender, EventArgs e)
{
    reqFV.Enabled = cbTest.Checked;
}


问:
Set Spring profile in Tomcat web app with no web.xml file
I have a webapp that is a RestEASY JAX-RS application and that uses the latest servlet specifications, such as Java EE annotations so that I don't need to create a web.xml file.

The webapp is bundled as foobar.war and dumped into the webapps directory in Tomcat. In fact the same foobar.war is deployed twice in the same Tomcat instance, once as foobar.war and the other as foobar#demo.war (which maps it to foobar/demo as you know).

I configure each mounted webapp by placing conf/Catalina/localhost/foobar.xml and conf/Catalina/localhost/foobar#demo.xml files, that look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="foo" type="java.lang.String" value="bar"/>
</Context>
</code>```

In my JAX-RS application I pull in the value of foo from JNDI using java:comp/env/foo.

So now I added a Java-based Spring configuration named FooBarConfiguration. I load it in my JAX-RS application using new AnnotationConfigApplicationContext(FooBarConfiguration.class). That all works fine.

So now I've added two profiles to FooBarConfiguration, one named foo and one named bar. But now... how do I tell the webapp which Spring profile to use? (Remember that I have no web.xml file.) Obviously I have to set spring.profiles.active somewhere. But where?

Because the documentation spoke of "environment" and "JNDI", I crossed my fingers and added an environment variable to conf/Catalina/localhost/foobar.xml:

```<code>  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>
</code>```

No luck.

I can't set a system property, because that will apply to all the webapps, and the idea here is that each foobar.war instance (foobar.war and foobar#demo.war) could each have a different profile specified.

I suppose I could manually pull it out of the Tomcat environment myself, using java:comp/env/spring.profiles.active, but then where do I set the value? (I thought maybe AnnotationConfigApplicationContext would have a constructor where I could set the profile, or at least have a profile setting, but that also seems to be missing.)

(Plus if I'm manually pulling out the setting from JNDI and setting it myself, I might as well switch to the more lightweight Guice and manually load the modules I want. I'm only using the humongous, clunky Spring because it promised to allow easy selection of profiles.)

How can I indicate, external to my WAR file, on a per-webapp basis, which Spring profile I'm using?

答:
The solution is to use AnnotationConfigWebApplicationContext instead of StandardServletEnvironment.

The trick is to get Spring to use a StandardServletEnvironment, which looks in several places including JNDI java:comp/env/... for spring.profiles.active. See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-property-source-abstraction .

My problem is that AnnotationConfigApplicationContext uses a StandardEnvironment, which only looks in a few places for the profile designation. Switching to a AnnotationConfigWebApplicationContext made Spring use a StandardServletEnvironment:

```<code>final AnnotationConfigWebApplicationContext webContext =
    new AnnotationConfigWebApplicationContext();
webContext.register(FooBarConfiguration.class);
webContext.refresh();
</code>```

Now my webapp environment configuration in conf/Catalina/localhost/foobar.xml works:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>
</Context>
</code>```

Body:
I have a webapp that is a RestEASY JAX-RS application and that uses the latest servlet specifications, such as Java EE annotations so that I don't need to create a web.xml file.

The webapp is bundled as foobar.war and dumped into the webapps directory in Tomcat. In fact the same foobar.war is deployed twice in the same Tomcat instance, once as foobar.war and the other as foobar#demo.war (which maps it to foobar/demo as you know).

I configure each mounted webapp by placing conf/Catalina/localhost/foobar.xml and conf/Catalina/localhost/foobar#demo.xml files, that look like this:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="foo" type="java.lang.String" value="bar"/>
</Context>

In my JAX-RS application I pull in the value of foo from JNDI using java:comp/env/foo.

So now I added a Java-based Spring configuration named FooBarConfiguration. I load it in my JAX-RS application using new AnnotationConfigApplicationContext(FooBarConfiguration.class). That all works fine.

So now I've added two profiles to FooBarConfiguration, one named foo and one named bar. But now... how do I tell the webapp which Spring profile to use? (Remember that I have no web.xml file.) Obviously I have to set spring.profiles.active somewhere. But where?

Because the documentation spoke of "environment" and "JNDI", I crossed my fingers and added an environment variable to conf/Catalina/localhost/foobar.xml:

  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>

No luck.

I can't set a system property, because that will apply to all the webapps, and the idea here is that each foobar.war instance (foobar.war and foobar#demo.war) could each have a different profile specified.

I suppose I could manually pull it out of the Tomcat environment myself, using java:comp/env/spring.profiles.active, but then where do I set the value? (I thought maybe AnnotationConfigApplicationContext would have a constructor where I could set the profile, or at least have a profile setting, but that also seems to be missing.)

(Plus if I'm manually pulling out the setting from JNDI and setting it myself, I might as well switch to the more lightweight Guice and manually load the modules I want. I'm only using the humongous, clunky Spring because it promised to allow easy selection of profiles.)

How can I indicate, external to my WAR file, on a per-webapp basis, which Spring profile I'm using?

Body:
The solution is to use AnnotationConfigWebApplicationContext instead of StandardServletEnvironment.

The trick is to get Spring to use a StandardServletEnvironment, which looks in several places including JNDI java:comp/env/... for spring.profiles.active. See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-property-source-abstraction .

My problem is that AnnotationConfigApplicationContext uses a StandardEnvironment, which only looks in a few places for the profile designation. Switching to a AnnotationConfigWebApplicationContext made Spring use a StandardServletEnvironment:

final AnnotationConfigWebApplicationContext webContext =
    new AnnotationConfigWebApplicationContext();
webContext.register(FooBarConfiguration.class);
webContext.refresh();

Now my webapp environment configuration in conf/Catalina/localhost/foobar.xml works:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>
</Context>


问:
Addition of extract value from the string
I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot

DEMO: https://jsfiddle.net/1xn1eLfs/6/

JS:

```<code>$('.ct-chart').each(function() {
 var graphTitle;

 $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');
    var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
    //graphTimeVal = graphTime.parseInt();

    $('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
 });
});
</code>```

答:
First, be carefull because you use "," and not "." in your string. To add those number, you must parseFloat on them.

Demo : https://jsfiddle.net/1xn1eLfs/6/

```<code> var val = 0;
$('.ct-chart').each(function() {
    var graphTitle;

    $(this).find('.work-day-graph').each(function() {
        graphTitle = $(this).attr('title');
        var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
        graphTime = graphTime.replace(',', '.');
        val += parseFloat(graphTime);

        $('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
    });
});
console.log(val); // 23.5
</code>```

Do the same but changing the second ct-chart class by ct-chart2 or whatever, so you can add element independently.

Body:
I extracted value from the title as you can see. But I have problem with the addition. Basically I dont know how to add every .work-day-graph element in .ct-chart. So it will be like 1,25+8,25+0,75+0,5 = XY and 2,25+7,25+2,75+0,5 =XY. Any ideas ? Thanks a lot

DEMO: https://jsfiddle.net/1xn1eLfs/6/

JS:

$('.ct-chart').each(function() {
 var graphTitle;

 $(this).find('.work-day-graph').each(function() {
    graphTitle = $(this).attr('title');
    var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
    //graphTimeVal = graphTime.parseInt();

    $('' + graphTime + '
' + '').appendTo('.output');
 });
});

Body:
First, be carefull because you use "," and not "." in your string. To add those number, you must parseFloat on them.

Demo : https://jsfiddle.net/1xn1eLfs/6/

 var val = 0;
$('.ct-chart').each(function() {
    var graphTitle;

    $(this).find('.work-day-graph').each(function() {
        graphTitle = $(this).attr('title');
        var graphTime = graphTitle.substring(graphTitle.lastIndexOf('(') + 1, graphTitle.lastIndexOf('h'));
        graphTime = graphTime.replace(',', '.');
        val += parseFloat(graphTime);

        $('<span class=output-val>' + graphTime + '</br>' + '</span>').appendTo('.output');
    });
});
console.log(val); // 23.5

Do the same but changing the second ct-chart class by ct-chart2 or whatever, so you can add element independently.


问:
Aggregating values in groups of irregular length using a stop values
I'm trying to create groups of values using keywords that have been manually entered. for example if I have a rollcall sheet with values that can be produced with the following code

```<code>df <- data.frame(name = c("Fred", "Victoria", "Jim", "Sally", "Ted", "Pamela", "end", "Victoria", "Fred", "Sally", "end", "Sally", "Pamela"),
                 sex = c("man", "woman", "man", "woman", "man", "woman", "neither", "woman", "man", "woman", "neither", "woman", "woman"))
</code>```

Is it possible to group these values into days such that I have three days, arranged so that one could ask the question, "On what day(s), was Sally present with a man" ?

答:
This may require two parts and use the dplyr package:

```<code>df.1 <- df %>%
        mutate(day = cumsum(name == "end")) %>%
        group_by(day) %>%
        summarise(man = any(sex == "man"), woman = any(sex == "female"))

df   <- df %>%
        mutate(day = cumsum(name == "end")) %>%
        left_join(df.1, by = "day")
</code>```

From here you can now search seeing as you have a day column, and if man was present on that day column, and if woman was present on that day. To determine the answer to your question you can simply search using

```<code>df$day[which(df$name == "Sally" & df$man == TRUE)]
</code>```

which results in

```<code>[1] 0 1
</code>```

This method creates a table for you to search along these components.

Body:
I'm trying to create groups of values using keywords that have been manually entered. for example if I have a rollcall sheet with values that can be produced with the following code

df <- data.frame(name = c("Fred", "Victoria", "Jim", "Sally", "Ted", "Pamela", "end", "Victoria", "Fred", "Sally", "end", "Sally", "Pamela"),
                 sex = c("man", "woman", "man", "woman", "man", "woman", "neither", "woman", "man", "woman", "neither", "woman", "woman"))

Is it possible to group these values into days such that I have three days, arranged so that one could ask the question, "On what day(s), was Sally present with a man" ?

Body:
This may require two parts and use the dplyr package:

df.1 <- df %>%
        mutate(day = cumsum(name == "end")) %>%
        group_by(day) %>%
        summarise(man = any(sex == "man"), woman = any(sex == "female"))

df   <- df %>%
        mutate(day = cumsum(name == "end")) %>%
        left_join(df.1, by = "day")

From here you can now search seeing as you have a day column, and if man was present on that day column, and if woman was present on that day. To determine the answer to your question you can simply search using

df$day[which(df$name == "Sally" & df$man == TRUE)]

which results in

[1] 0 1

This method creates a table for you to search along these components.


问:
Roadmap for functionality with office.js in PowerPoint
Is there a roadmap on extending office.js for PowerPoint? Would be nice to be able to interact with the elements on a slide. As a possibly quicker route if you enabled Office.CoercionType.Ooxml for more apps other than Word we could parse and manipulate the data ourselves.

The current PowerPoint capabilities for inserting text/images is very limited. My specific scenario is to move an old VSTO plugin over to the add-in model, where I iterate all text elements and look at the metadata.

答:
I'm afraid not, PowerPoint has not provided a open specification along the lines of Excel or Word at this time. </p>

<p>I would strongly suggest posting your suggestions and blockers into the User Voice. For blocking issues, please be sure and note that this is blocking migration from VSTO. This information invaluable when it comes time to prioritize items on the roadmap. </p>

Body:
I'm afraid not, PowerPoint has not provided a open specification along the lines of Excel or Word at this time.

I would strongly suggest posting your suggestions and blockers into the User Voice. For blocking issues, please be sure and note that this is blocking migration from VSTO. This information invaluable when it comes time to prioritize items on the roadmap.


问:
Toggle div, if already open then hide
I'm trying to build a toggling panel that once opened, if the active element is clicked again it closes yet if the sibling element is click the content is updated only I'm having mixed results. Can anybody see where im going wrong?

https://jsfiddle.net/9b3mecc2/

```<code>$('.sectors-list li').on('click', function(e){
  e.preventDefault();
  var order = $(this).index();
  $('.sub-sectors div').hide();
  $('.sub-sectors div').eq(order).show();
  if($('.digital-sectors').is(':visible')
  && order === 0){
    $('.sub-sectors').removeClass('active');
  } else {
      $('.sub-sectors').addClass('active');
  }
});
</code>```

答:
I think this will works.</p>

```<code>   $('.sectors-list li').on('click', function(e){
        e.preventDefault();
        var order = $(this).index();
        $('.sub-sectors div').hide();
        // $('.sub-sectors div').eq(order).show(); //moving this line to eles part
        if($('.digital-sectors').is(':visible')
        && order === 0){
            $('.sub-sectors').removeClass('active');
        } else {
        $('.sub-sectors').addClass('active');
        $('.sub-sectors div').eq(order).show();
        }
    });
</code>```

Title: Toggle div, if already open then hide

Body:
I'm trying to build a toggling panel that once opened, if the active element is clicked again it closes yet if the sibling element is click the content is updated only I'm having mixed results. Can anybody see where im going wrong?

https://jsfiddle.net/9b3mecc2/

$('.sectors-list li').on('click', function(e){
  e.preventDefault();
  var order = $(this).index();
  $('.sub-sectors div').hide();
  $('.sub-sectors div').eq(order).show();
  if($('.digital-sectors').is(':visible')
  && order === 0){
    $('.sub-sectors').removeClass('active');
  } else {
      $('.sub-sectors').addClass('active');
  }
});

Body:
I think this will works.

   $('.sectors-list li').on('click', function(e){
        e.preventDefault();
        var order = $(this).index();
        $('.sub-sectors div').hide();
        // $('.sub-sectors div').eq(order).show(); //moving this line to eles part
        if($('.digital-sectors').is(':visible')
        && order === 0){
            $('.sub-sectors').removeClass('active');
        } else {
        $('.sub-sectors').addClass('active');
        $('.sub-sectors div').eq(order).show();
        }
    });


问:
Qt SQLite search query speed
I'm creating a database in SQLite as follows:

```<code>QSqlQuery create_address;
create_address.prepare("CREATE TABLE addresses (addressid INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE)");
QSqlQuery create_devices;
create_devices.prepare("CREATE TABLE devices (ch TEXT PRIMARY KEY, addressid INTEGER REFERENCES addresses(addressid))");

create_devices.exec();
create_address.exec();
</code>```

I need to access this database a lot of times (~660'000) passing ch and retrieving the corresponding address, the ch passed could not be in the database (empty string is returned).

To do so i made the following query

```<code>//outside loop
QSqlQuery find_address;
find_address.prepare("SELECT address FROM addresses,devices WHERE devices.addressid = addresses.addressid AND devices.ch = :chcode");

//in loop
find_address.bindValue(":chcode",QString::fromStdString(ch_code));

find_address.exec();
</code>```

The problem is that this process is very slow (it takes almost 12 minutes to finish all the 660'000 searches).

Before this i tried with an INNER JOIN but the performance was pretty much the same.

Is there a better way to write the query and/or structure the DB to get a faster execution time?

答:
Since you have a loop with SQL query, you can wrap it into transaction which may improve the performance:

```<code>QSqlDatabase::database().transaction();
.........
// your loop
.........
QSqlDatabase::database().commit();
</code>```

Also the performance may be improved by adding indexes. In your case index can be created on the fields devices.addressid and devices.ch. In sqlite console do the following:

```<code>CREATE INDEX devices_index ON devices(ch, addressid);
</code>```

Title: Qt SQLite search query speed

Body:
I'm creating a database in SQLite as follows:

QSqlQuery create_address;
create_address.prepare("CREATE TABLE addresses (addressid INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE)");
QSqlQuery create_devices;
create_devices.prepare("CREATE TABLE devices (ch TEXT PRIMARY KEY, addressid INTEGER REFERENCES addresses(addressid))");

create_devices.exec();
create_address.exec();

I need to access this database a lot of times (~660'000) passing ch and retrieving the corresponding address, the ch passed could not be in the database (empty string is returned).

To do so i made the following query

//outside loop
QSqlQuery find_address;
find_address.prepare("SELECT address FROM addresses,devices WHERE devices.addressid = addresses.addressid AND devices.ch = :chcode");

//in loop
find_address.bindValue(":chcode",QString::fromStdString(ch_code));

find_address.exec();

The problem is that this process is very slow (it takes almost 12 minutes to finish all the 660'000 searches).

Before this i tried with an INNER JOIN but the performance was pretty much the same.

Is there a better way to write the query and/or structure the DB to get a faster execution time?

Body:
Since you have a loop with SQL query, you can wrap it into transaction which may improve the performance:

QSqlDatabase::database().transaction();
.........
// your loop
.........
QSqlDatabase::database().commit();

Also the performance may be improved by adding indexes. In your case index can be created on the fields devices.addressid and devices.ch. In sqlite console do the following:

CREATE INDEX devices_index ON devices(ch, addressid);


问:
Should workbox-backround-sync auto detect device is back online
I have been experimenting with workbox service worker toolkit.

The copy here suggests that the workbox-backround-sync QueuePlugin will catch failed requests and later replay them back. So with a bit of a digging I discovered how to get this working on POST method calls.

But the replaying of requests seems a bit hit and miss. Using Chrome dev tools to take the app offline, does indeed place the requests in a queue within IndexedDB. Nothing seemed to be happening and I wanted to debug. I noted that in the demo on github it uses a BroadcastChannel to trigger the replay. So I implemented that. Then from the console in the active tab, I unchecked offline in dev tools and I sent a postMessage. Now the requests fired off happily and the responses were stored for each item in the queue.

I then left the machine running, go into standby etc for a couple of hours. I then noted in the logs that it had happily been sending duplicate requests even though every item had a response.

At this point I try and replicate but can't. I send a BroadcastChannel message and it only fires of requests without responses. So I now go back to the start, and make more offline requests, confirm they are in the DB, restore online and wait. Nothing.

I see that in the constructor of Queue it creates a new RequestManager and in the constructor of that it sets up the sync event listener. So I am guessing that it should be doing something at some point.

I just want to be sure I understand the expected behaviour if someone can help.

Here is the code I have in place.

```<code>let bgQueue = new workbox.backgroundSync.QueuePlugin({
  callbacks: {
    onResponse: async(hash, res) => {
      console.log(hash, res);
    }
  }
});

const requestWrapper = new workbox.runtimeCaching.RequestWrapper({
  plugins: [bgQueue]
});

const route = new workbox.routing.RegExpRoute({
  regExp: new RegExp('^http://localhost:4200/api/create/note'),
  handler: new workbox.runtimeCaching.NetworkOnly({requestWrapper}),
  method: 'POST' // Not obvious you need to do this in the docs without digging.
});

const router = new workbox.routing.Router();
router.registerRoute({route});

// Code to manaully trigger a replay.
const replayBroadcastChannel = new BroadcastChannel('replay_channel');
replayBroadcastChannel.onmessage = function() {
  bgQueue.replayRequests();
};
</code>```

Testing in Chrome 58 on macOS Sierra.

答:
I guess flipping offline -> online -> offline via dev tools wont trigger sync for you(neither will "sync" option in this case), so I am afraid you will have to toggle network on->off from your system.

Upon doing so, you should be able to see the requests getting replayed just as you thought.

Also if you are still able to reproduce the duplicate requests(requests which have been responded with 2XX response) please feel free to open a bug.

Body:
I have been experimenting with workbox service worker toolkit.

The copy here suggests that the workbox-backround-sync QueuePlugin will catch failed requests and later replay them back. So with a bit of a digging I discovered how to get this working on POST method calls.

But the replaying of requests seems a bit hit and miss. Using Chrome dev tools to take the app offline, does indeed place the requests in a queue within IndexedDB. Nothing seemed to be happening and I wanted to debug. I noted that in the demo on github it uses a BroadcastChannel to trigger the replay. So I implemented that. Then from the console in the active tab, I unchecked offline in dev tools and I sent a postMessage. Now the requests fired off happily and the responses were stored for each item in the queue.

I then left the machine running, go into standby etc for a couple of hours. I then noted in the logs that it had happily been sending duplicate requests even though every item had a response.

At this point I try and replicate but can't. I send a BroadcastChannel message and it only fires of requests without responses. So I now go back to the start, and make more offline requests, confirm they are in the DB, restore online and wait. Nothing.

I see that in the constructor of Queue it creates a new RequestManager and in the constructor of that it sets up the sync event listener. So I am guessing that it should be doing something at some point.

I just want to be sure I understand the expected behaviour if someone can help.

Here is the code I have in place.

let bgQueue = new workbox.backgroundSync.QueuePlugin({
  callbacks: {
    onResponse: async(hash, res) => {
      console.log(hash, res);
    }
  }
});

const requestWrapper = new workbox.runtimeCaching.RequestWrapper({
  plugins: [bgQueue]
});

const route = new workbox.routing.RegExpRoute({
  regExp: new RegExp('^http://localhost:4200/api/create/note'),
  handler: new workbox.runtimeCaching.NetworkOnly({requestWrapper}),
  method: 'POST' // Not obvious you need to do this in the docs without digging.
});

const router = new workbox.routing.Router();
router.registerRoute({route});

// Code to manaully trigger a replay.
const replayBroadcastChannel = new BroadcastChannel('replay_channel');
replayBroadcastChannel.onmessage = function() {
  bgQueue.replayRequests();
};

Testing in Chrome 58 on macOS Sierra.


问:
React: Element is changing a controlled input of type text to be uncontrolled
I'm getting the following error but haven't been able to identify why it is happening

warning.js:36 Warning: Searchbox is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component

I've got the following files:

Searchbox.js

import React, { Component } from 'react';

    class Searchbox extends Component {

      // render method
      render() {
        const { value, onChange, onSubmit, children } = this.props
        console.log(value)
        console.log(onChange)
        console.log(onSubmit)
        console.log(children)
        return (

            <form onSubmit={onSubmit}>
              <input
                type="text"
                className="search-box"
                value={value}
                onChange={onChange}
              />
              <button type="submit">{children}</button>
            </form>

        )
      }
    }

    export default Searchbox```
</div>
</div>
</p>

<p>And the App.js file</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import Searchbox from './components/Searchbox'
//import logo from './logo.svg';
import './App.css';

const DEFAULT_TERM = 'High Fidelity'

class App extends Component {

  // Constructor
  constructor(props) {
    super(props)

    this.state = {
      movie: null,
      searchTerm: DEFAULT_TERM
    }

    this.onSearchSubmit = this.onSearchSubmit.bind(this)
    this.onSearchChange = this.onSearchChange.bind(this)
  }

  // onSearchSubmit method
  onSearchSubmit(e) {
    e.preventDefault()
    console.log("Searching movie with name" + this.status.searchTerm)
  }

  onSearchChange(e){
    console.log(event.target.value)
    this.setState({ searchTerm: event.target.value })
  }

  // render method
  render() {

    const { movie, searchTerm } = this.state

    return (
      <div className="App">
        <Searchbox
          value={searchTerm}
          onChange={this.onSearchChange}
          onSubmit={this.onSearchSubmit}
        >Search
        </Searchbox>
      </div>
    );
  }
}

export default App;</code>```

On load everything's fine, but when I type something in the text field then the error is triggered.

Any suggestions?

答:
I was receiving the same exact warning. My TextFieldItem is a child component that is being updated through its props. The following line was the culprit.

```<code>const fieldValue = (field.Value == null) ? undefined : field.Value;
</code>```

upon changing the line to set the value from undefined to '' resolved warning.

```<code>const fieldValue = (field.Value == null) ? '' : field.Value;
</code>```

React component

```<code>class TextFieldItem extends React.Component{
        constructor(props){
            super(props);
            this.onChange=this.onChange.bind(this);
        }
        onChange(e){
            event.preventDefault();
            const {onFieldChange,field} = this.props;
            onFieldChange(e.target.id, e.target.value, e.target.name,field.Type);
        }
        render(){
            const {field, onFieldChange, onRecordUpdate, IsLookupField,record,currentDocumentType} = this.props;
            const fieldValue = (field.Value == null) ? '' : field.Value;
            return (
                <div>
                    <label>{field.Name}</label>
                    <input type="text" key={field.Id} className="form-control" id={field.Id} name={field.Name} onChange={this.onChange} value={fieldValue} />
                    {IsLookupField && <LookupFieldItem record={record} field={field} onRecordUpdate={onRecordUpdate} documentType={currentDocumentType} /> }
                </div>
                );
        }
    }
         export default TextFieldItem;
</code>```

Body:
I'm getting the following error but haven't been able to identify why it is happening

warning.js:36 Warning: Searchbox is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component

I've got the following files:

Searchbox.js

import React, { Component } from 'react';

    class Searchbox extends Component {

      // render method
      render() {
        const { value, onChange, onSubmit, children } = this.props
        console.log(value)
        console.log(onChange)
        console.log(onSubmit)
        console.log(children)
        return (

            <form onSubmit={onSubmit}>
              <input
                type="text"
                className="search-box"
                value={value}
                onChange={onChange}
              />
              <button type="submit">{children}</button>
            </form>

        )
      }
    }

    export default Searchbox

And the App.js file

import React, { Component } from 'react';
import Searchbox from './components/Searchbox'
//import logo from './logo.svg';
import './App.css';

const DEFAULT_TERM = 'High Fidelity'

class App extends Component {

  // Constructor
  constructor(props) {
    super(props)

    this.state = {
      movie: null,
      searchTerm: DEFAULT_TERM
    }

    this.onSearchSubmit = this.onSearchSubmit.bind(this)
    this.onSearchChange = this.onSearchChange.bind(this)
  }

  // onSearchSubmit method
  onSearchSubmit(e) {
    e.preventDefault()
    console.log("Searching movie with name" + this.status.searchTerm)
  }

  onSearchChange(e){
    console.log(event.target.value)
    this.setState({ searchTerm: event.target.value })
  }

  // render method
  render() {

    const { movie, searchTerm } = this.state

    return (

        <Searchbox
          value={searchTerm}
          onChange={this.onSearchChange}
          onSubmit={this.onSearchSubmit}
        >Search
        </Searchbox>

    );
  }
}

export default App;

On load everything's fine, but when I type something in the text field then the error is triggered.

Any suggestions?

Body:
I was receiving the same exact warning. My TextFieldItem is a child component that is being updated through its props. The following line was the culprit.

const fieldValue = (field.Value == null) ? undefined : field.Value;

upon changing the line to set the value from undefined to '' resolved warning.

const fieldValue = (field.Value == null) ? '' : field.Value;

React component

class TextFieldItem extends React.Component{
        constructor(props){
            super(props);
            this.onChange=this.onChange.bind(this);
        }
        onChange(e){
            event.preventDefault();
            const {onFieldChange,field} = this.props;
            onFieldChange(e.target.id, e.target.value, e.target.name,field.Type);
        }
        render(){
            const {field, onFieldChange, onRecordUpdate, IsLookupField,record,currentDocumentType} = this.props;
            const fieldValue = (field.Value == null) ? '' : field.Value;
            return (
                <div>
                    <label>{field.Name}</label>
                    <input type="text" key={field.Id} className="form-control" id={field.Id} name={field.Name} onChange={this.onChange} value={fieldValue} />
                    {IsLookupField && <LookupFieldItem record={record} field={field} onRecordUpdate={onRecordUpdate} documentType={currentDocumentType} /> }
                </div>
                );
        }
    }
         export default TextFieldItem;


问:
Postgres: Query that returns percentage
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

```<code>articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046
</code>```

I was able to get the raw counts like this, but not sure how to get the percentage

```<code>SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;
</code>```

答:
You can try this:
The below sample query will give the total record count and also the count of records that are satisfying your condition. (This is MYSQL example)</p>

```<code>SELECT
((COUNT * 100)/TOTAL_REC_COUNT) AS PERCENT
FROM
(
SELECT COUNT(*) as TOTAL_REC_COUNT,SUM(CASE WHEN STATUS='404 NOT FOUND' then 1 ELSE 0 END) AS COUNT
FROM test.sample_table
) TMP
</code>```

Title: Postgres: Query that returns percentage

Body:
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046

I was able to get the raw counts like this, but not sure how to get the percentage

SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;

Body:
You can try this:
The below sample query will give the total record count and also the count of records that are satisfying your condition. (This is MYSQL example)

SELECT
((COUNT * 100)/TOTAL_REC_COUNT) AS PERCENT
FROM
(
SELECT COUNT(*) as TOTAL_REC_COUNT,SUM(CASE WHEN STATUS='404 NOT FOUND' then 1 ELSE 0 END) AS COUNT
FROM test.sample_table
) TMP


问:
ASP.Net MVC 3 Grids
I see that there is the Telerik Grid, jqGrid and WebHelper WebGrid as part of the framework.  Am I missing any others?

Which one works best on a commercial application with thousands of rows and master/detail relationships for ASP.Net MVC 3?

答: there is also grid supplied by mvccontrib. I personally use telerik grid having some cool features and scale for large data Q3 2010 has some good improvements such as inline editing etc. For MVC 3 grid i am waiting for rtm of mvc 3 coming in January </p>

ContentLicense: CC BY-SA 2.5

Title: ASP.Net MVC 3 Grids


问:
Prevent copy-construction with make_shared
I have a manager class that allow clients to add components through two methods: one with no argument that default-construct the component and another one that takes an rvalue (which should allow client to use a custom constructor of the component).

Here's the code I came up with:

template <class TComponent>
std::shared_ptr<TComponent> AddComponent()
{
    return AddComponent(TComponent{ this });
}

template <class TComponent>
std::shared_ptr<TComponent> AddComponent(const TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(obj);
    vec.push_back(ptr);
    return ptr;
}
```

The problem I have is that std::make_shared always copy-constructs the object. Is there a way to prevent this behavior?
I read about perfect forwarding but it doesn't seem to help here.

答:
I read about perfect forwarding but it doesn't seem to help here.

I don't see why it wouldn't.

Simply remove the const to make move construction possible, and add std::forward:

```<code>template <class TComponent>
std::shared_ptr<TComponent> AddComponent(TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(std::forward<TComponent>(obj));
    vec.push_back(ptr);
    return ptr;
}
</code>```

Now, rvalues will be moved. Lvalues will be copied which you cannot avoid.

Body:
I have a manager class that allow clients to add components through two methods: one with no argument that default-construct the component and another one that takes an rvalue (which should allow client to use a custom constructor of the component).

Here's the code I came up with:

template <class TComponent>
std::shared_ptr<TComponent> AddComponent()
{
    return AddComponent(TComponent{ this });
}

template <class TComponent>
std::shared_ptr<TComponent> AddComponent(const TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(obj);
    vec.push_back(ptr);
    return ptr;
}

The problem I have is that std::make_shared always copy-constructs the object. Is there a way to prevent this behavior?
I read about perfect forwarding but it doesn't seem to help here.

Body:
I read about perfect forwarding but it doesn't seem to help here.

I don't see why it wouldn't.

Simply remove the const to make move construction possible, and add std::forward:

template <class TComponent>
std::shared_ptr<TComponent> AddComponent(TComponent &&obj)
{
    auto ptr = std::make_shared<TComponent>(std::forward<TComponent>(obj));
    vec.push_back(ptr);
    return ptr;
}

Now, rvalues will be moved. Lvalues will be copied which you cannot avoid.


问:
Node.js Execution order queries
At the end of my code, I have two actions that run at the same time, a query that makes an Atler table. The second insertion.

The problem is that sometimes the insertion happens before the alter table.

How can I execute the first part of the code in the for loop for all keys, then proceed with the insertion ?

```<code>if (count >1) {
       for( var i = 0; i < keys.length -1; i++ ) {
         client.execute (queryadd, { prepare: true }, function (err) {
         console.log("do");
         });
       }
    }

 client.execute(queryinsert, { prepare: true }, function (err) {
   console.log(err);
   client.shutdown();
  });
</code>```

答:
Nodejs cassandra driver supports promises, so it can be done as simple as:

```<code>if (count > 1) {
   for (const key of keys) {
     await client.execute(queryadd);
   }
}

await client.execute(queryinsert, params, { prepare: true });
await client.shutdown();
</code>```

If you want to execute all queryadd in parallel and then queryinsert, then you can do:

```<code>if (count > 1) {
   let queryadds = [];
   for (const key of keys) {
     queryadds.push(client.execute(queryadd));
   }
   await Promise.all(queryadds);
}

await client.execute(queryinsert, params, { prepare: true });
await client.shutdown();
</code>```

Title: Node.js Execution order queries

Body:
At the end of my code, I have two actions that run at the same time, a query that makes an Atler table. The second insertion.

The problem is that sometimes the insertion happens before the alter table.

How can I execute the first part of the code in the for loop for all keys, then proceed with the insertion ?

if (count >1) {
       for( var i = 0; i < keys.length -1; i++ ) {
         client.execute (queryadd, { prepare: true }, function (err) {
         console.log("do");
         });
       }
    }

 client.execute(queryinsert, { prepare: true }, function (err) {
   console.log(err);
   client.shutdown();
  });

Body:
Nodejs cassandra driver supports promises, so it can be done as simple as:

if (count > 1) {
   for (const key of keys) {
     await client.execute(queryadd);
   }
}

await client.execute(queryinsert, params, { prepare: true });
await client.shutdown();

If you want to execute all queryadd in parallel and then queryinsert, then you can do:

if (count > 1) {
   let queryadds = [];
   for (const key of keys) {
     queryadds.push(client.execute(queryadd));
   }
   await Promise.all(queryadds);
}

await client.execute(queryinsert, params, { prepare: true });
await client.shutdown();


问:
How to get ajax accordion selected index from javascript
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

```<code><script type="text/javascript">
    function pageLoad(sender, args) {

        $(".billinginformation").click(function (event, ui) {
            alert("hi");

            alert($(".billinginformation").accordion("option", "active"))
        });
    }
</script>
</code>```

HTML code

```<code> <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">
            <Header><h2>Billing Information</h2></Header>
            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            <Header>Shipping Information</Header>
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>
</code>```

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

答:
Not sure how that html actually looks like in the browser, so I've chosen to use click on element with widget class: EDIT: now using CssClass</p>

```<code>$('#OPCPanels [CssClass="widget"]').click(function (event, ui) {
     alert("Index: " + $(this).index() );
});
</code>```

Body:
Hi I have used Ajax accordion. what I need is to get current selected index when I click on accordion tab that is on billing information I should get selectedindex=0 in Javascript or in jquery

I have set javascript as

Note : billing information is a class which is set in OPCPanels

HTML code

 <ajax:Accordion ID="OPCPanels" runat="server" SelectedIndex="0" HeaderCssClass="widget billinginformation" ContentCssClass="content" AutoSize="None">
        <Panes>
        <ajax:AccordionPane ID="BillingInformation" runat="server" CssClass="widget">

Billing Information

            <Content>HI</Content>
        </ajax:AccordionPane>
        <ajax:AccordionPane ID="ShippingInformation" runat="server" CssClass="widget">
            Shipping Information
            <Content>hello</content>
        </ajax:AccordionPane>
    </Panes>
</ajax:Accordion>

I have set billinginformation class to my main accordion and on click of any accordion I get the alert of "hi".

but how should I get that which selected Index I have selected in JavaScript?

Body:
Not sure how that html actually looks like in the browser, so I've chosen to use click on element with widget class: EDIT: now using CssClass

$('#OPCPanels [CssClass="widget"]').click(function (event, ui) {
     alert("Index: " + $(this).index() );
});


问:
How to get values from clicking listview item on Android? (NullException error)
I'm trying to retrieve the item name and quantity from my listview,
and display it onto the new class: Details.java.

Here are my codes for listview.java:

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item);

        //create items to display in customized listview (Arraylist)
        displayiteminfo.add(new SalesItemInformationLV("Bread", 2));
        displayiteminfo.add(new SalesItemInformationLV("Butter", 9));
        displayiteminfo.add(new SalesItemInformationLV("Margarine", 8));

        //New array adapter for customised ArrayAdapter
        final ArrayAdapter<SalesItemInformationLV> adapter = new itemArrayAdapter(this, 0, displayiteminfo);
        //displayiteminfo - the ArrayList of item objects to display.

        //Find the list view, bind it with custom adapter
        final ListView listView = (ListView)findViewById(R.id.customListview);
        listView.setAdapter(adapter);

        //Selecting the listview item!
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();
 String namevalue = saleitem.getItemname(); ---> WHERE ERROR OCCURS
 int qtyvalue = saleitem.getItemquantity();

                Intent myintent = new Intent(ListView.this, Details.class);
                myintent.putExtra("itemname", namevalue);
                myintent.putExtra("itemqty", qtyvalue);

                startActivity(myintent);

            }
        });

    }

    //custom Arrayadapter
    class itemArrayAdapter extends ArrayAdapter<SalesItemInformationLV>
    {
        private  Context context;
        private List<SalesItemInformationLV> item;

        //constructor, call on creation
        public itemArrayAdapter(Context context, int resource, ArrayList<SalesItemInformationLV> objects) {

            //chaining to "default constructor" of ArrayAdapter manually
            super(context, resource, objects);
            this.context = context;
            this.item = objects;

        }

        //called to render the list

        public View getView(int position, View convertView, ViewGroup parent)
        {
            //get the item we are displaying
            SalesItemInformationLV iteminfo = item.get(position);

            //get the inflater and inflate the xml layout for each item
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.item_layout, null);

            //Each component of the custom item_layout
            TextView name = (TextView) view.findViewById(R.id.ItemNameSales);
            TextView qty = (TextView)view.findViewById(R.id.ItemNameQty);

            //set the name of item - access using an object!
            name.setText(String.valueOf(iteminfo.getItemname()));

            //set the quantity of item - access using an object!
            qty.setText(String.valueOf(iteminfo.getItemquantity()));

            return view;
            //Now return to onCreate to use this cuztomized ArrayAdapter
        }
    }
</code>```

Upon implementing the above codes, I got an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ... on a null object reference
</code>```

答:
Clicked and Selected are different things.

Replace

```<code>SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();
</code>```

with

```<code>SalesItemInformationLV saleitem = displayiteminfo.get(position)
</code>```

Body:
I'm trying to retrieve the item name and quantity from my listview,
and display it onto the new class: Details.java.

Here are my codes for listview.java:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item);

        //create items to display in customized listview (Arraylist)
        displayiteminfo.add(new SalesItemInformationLV("Bread", 2));
        displayiteminfo.add(new SalesItemInformationLV("Butter", 9));
        displayiteminfo.add(new SalesItemInformationLV("Margarine", 8));

        //New array adapter for customised ArrayAdapter
        final ArrayAdapter<SalesItemInformationLV> adapter = new itemArrayAdapter(this, 0, displayiteminfo);
        //displayiteminfo - the ArrayList of item objects to display.

        //Find the list view, bind it with custom adapter
        final ListView listView = (ListView)findViewById(R.id.customListview);
        listView.setAdapter(adapter);

        //Selecting the listview item!
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();
 String namevalue = saleitem.getItemname(); ---> WHERE ERROR OCCURS
 int qtyvalue = saleitem.getItemquantity();

                Intent myintent = new Intent(ListView.this, Details.class);
                myintent.putExtra("itemname", namevalue);
                myintent.putExtra("itemqty", qtyvalue);

                startActivity(myintent);

            }
        });

    }

    //custom Arrayadapter
    class itemArrayAdapter extends ArrayAdapter<SalesItemInformationLV>
    {
        private  Context context;
        private List<SalesItemInformationLV> item;

        //constructor, call on creation
        public itemArrayAdapter(Context context, int resource, ArrayList<SalesItemInformationLV> objects) {

            //chaining to "default constructor" of ArrayAdapter manually
            super(context, resource, objects);
            this.context = context;
            this.item = objects;

        }

        //called to render the list

        public View getView(int position, View convertView, ViewGroup parent)
        {
            //get the item we are displaying
            SalesItemInformationLV iteminfo = item.get(position);

            //get the inflater and inflate the xml layout for each item
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.item_layout, null);

            //Each component of the custom item_layout
            TextView name = (TextView) view.findViewById(R.id.ItemNameSales);
            TextView qty = (TextView)view.findViewById(R.id.ItemNameQty);

            //set the name of item - access using an object!
            name.setText(String.valueOf(iteminfo.getItemname()));

            //set the quantity of item - access using an object!
            qty.setText(String.valueOf(iteminfo.getItemquantity()));

            return view;
            //Now return to onCreate to use this cuztomized ArrayAdapter
        }
    }

Upon implementing the above codes, I got an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ... on a null object reference

Body:
Clicked and Selected are different things.

Replace

SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();

with

SalesItemInformationLV saleitem = displayiteminfo.get(position)


问:
Using OSB fuction bea in java xquery processor
For my transformation i'm using org.apache.xmlbeans

(xmlObject.execQuery(xqueryFileContent, options);)

Now I come up with an issue that somehow fn-bea functions are not working:
in this example: fn-bea:uuid()

The stacktrace:

```<code>Caused by: weblogic.xml.query.exceptions.XQueryStaticException: line 15, column 18: {err}XQ0017: "{http://www.bea.com/xquery/xquery-functions}uuid": unknown function (or number of arguments (0) is wrong)
</code>```

I've read a thread where they say it's not supported, but this isn't satisfying.

How can I grant my java processor access to the bea functions?

EDIT:
The XQuery at line 15:

```<code>    <bp-id>{replace(fn-bea:uuid(), '-', '')}</bp-id>
</code>```

the declaration:

```<code>declare namespace fn-bea ="http://www.bea.com/xquery/xquery-functions";
</code>```

答:
You can enable most of the fn-bea functions using the Oracle XQuery Processor for Java:
OSB fn-bea functions using Xquery processor in Java

But as you noticed, this is not supported and it will not enable several of the fn-bea functions including fn-bea:uuid().

You could implement your own external function:
https://docs.oracle.com/database/121/ADXDK/adx_j_xqj.htm#GUID-4B1AD5F7-FAF2-44C3-B577-5A5CF44B5AFF

Body:
For my transformation i'm using org.apache.xmlbeans

(xmlObject.execQuery(xqueryFileContent, options);)

Now I come up with an issue that somehow fn-bea functions are not working:
in this example: fn-bea:uuid()

The stacktrace:

Caused by: weblogic.xml.query.exceptions.XQueryStaticException: line 15, column 18: {err}XQ0017: "{http://www.bea.com/xquery/xquery-functions}uuid": unknown function (or number of arguments (0) is wrong)

I've read a thread where they say it's not supported, but this isn't satisfying.

How can I grant my java processor access to the bea functions?

EDIT:
The XQuery at line 15:

    <bp-id>{replace(fn-bea:uuid(), '-', '')}</bp-id>

the declaration:

declare namespace fn-bea ="http://www.bea.com/xquery/xquery-functions";


问:
Spring MVC @PathVariable treated as @RequestParam
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

```<code>import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}
</code>```

Implementation :

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}
</code>```

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?

答:
Pathvariable is missing from your method implementation.
So to fix, you need to write something like this:</p>

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

    private final CurrenciesService service;

    @Autowired
    public ParametersApiController(CurrenciesService service) {
        this.service = service;
    }

    @Override
    public ResponseEntity<List<Currency>> GetCurrencies(@PathVariable String theCurrencyCode) {
        final List<Currency> currencies = service.getCurrencies(theCurrencyCode);
        return new ResponseEntity<>(currencies, HttpStatus.OK);
    }
}
</code>```

Body:
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}

Implementation :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?

Body:
Pathvariable is missing from your method implementation.
So to fix, you need to write something like this:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

    private final CurrenciesService service;

    @Autowired
    public ParametersApiController(CurrenciesService service) {
        this.service = service;
    }

    @Override
    public ResponseEntity<List<Currency>> GetCurrencies(@PathVariable String theCurrencyCode) {
        final List<Currency> currencies = service.getCurrencies(theCurrencyCode);
        return new ResponseEntity<>(currencies, HttpStatus.OK);
    }
}


问:
LINQ to SQL: Reusing DataContext
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

```<code>public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}
</code>```

I also have a few methods that need to perform multiple operations that use a DataContext:

```<code>public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}
</code>```

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

答:
If you examine those "two" operations, you might see that they could be performed in 1 database roundtrip.  Minimizing database roundtrips is a major performance objective (second to minimizing database io).

If you have multiple datacontexts, they view the same record differently.  Normally, ObjectTracking requires that the same instance is always used to represent a single record.  If you have 2 DataContexts, they each do their own object tracking on their own instances.

Suppose the record changes between DC1 observing it and and DC2 observing it.  In this case, the record will not only have 2 different instances, but those different instances will have different values.  It can be very challenging to express business logic against such a moving target.

You should definately retire the DataContext after the UnitOfWork, to protect yourself from stale instances of records.

Title: LINQ to SQL: Reusing DataContext

Body:
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}

I also have a few methods that need to perform multiple operations that use a DataContext:

public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?


问:
Temporarily disable (ignore / not display) the animation on a complex QML component
Is it possible to temporarily disable (ignore / not display) the animation on a complex QML component until a certain point in time? And later activate the animation and work as usual.

For example. A complex page on QML displays the data of the object, there are many small animations. When changing a data object, these animations should be ignored.

```<code>Rectangle {
    anchors.fill: parent
        property variant cppViewModel: MyCppViewModel {
            onBeforDataObjectChanged: {

            }
            onAfterDataObjectChanged: {

            }
        }

    Rectangle {
        id: idRect1
        Behavior on x { NumberAnimation { ... }}
        Behavior on y { NumberAnimation { ... }}
        x: cppViewModel.dataObject.offsetX
        y: cppViewModel.dataObject.offsetY
        scale: cppViewModel.dataObject.scale

        Rectangle {
            id: idRect2

            width: cppViewModel.dataObject.width
            heigth: cppViewModel.dataObject.heigth
            Behavior on width { NumberAnimation { ... }}
            Behavior on heigth { NumberAnimation { ... }}

            ColumnLayout {
                Rectangle {
                    Layout.preferredHeight: 100 * cppViewModel.dataObject.width1
                    Behavior on Layout.preferredHeight { NumberAnimation { duration: 500; easing.type: Easing.OutQuad; }}
                    //... Any number of children with animation
                }
            }
        }
    }

    PropertyAnimation { target: idRect1; property: "scale"; from: 0.9; to: 1.0; ... }
}
</code>```

If the values of the properties of the current data object change, then animation is needed. If the entire object changes to another, then the animation needs to be blocked.

答:
To disable Animations, there are various ways, and the right one depends on how the Animation is started.

If the Animation is started by setting the running-property, you can simply add a && animationsEnabled
to the condition where animationsEnabled is a property, you have to define somewhere else and toggle it accordingly.

If you use the function: run() to start your Animation, the solution is to not do it.

If you use the Animation within a Behavior, you can use the Behaviors enabled-property to deactivate the Behavior and its Animation.

Finally, I can think of Transitions. Just as Behavior, Transition has an enabled-property, to deactivate it.

I hope I have not forgotten a way to animate and you will find the appropriate solution for your problem!

Body:
Is it possible to temporarily disable (ignore / not display) the animation on a complex QML component until a certain point in time? And later activate the animation and work as usual.

For example. A complex page on QML displays the data of the object, there are many small animations. When changing a data object, these animations should be ignored.

Rectangle {
    anchors.fill: parent
        property variant cppViewModel: MyCppViewModel {
            onBeforDataObjectChanged: {

            }
            onAfterDataObjectChanged: {

            }
        }

    Rectangle {
        id: idRect1
        Behavior on x { NumberAnimation { ... }}
        Behavior on y { NumberAnimation { ... }}
        x: cppViewModel.dataObject.offsetX
        y: cppViewModel.dataObject.offsetY
        scale: cppViewModel.dataObject.scale

        Rectangle {
            id: idRect2

            width: cppViewModel.dataObject.width
            heigth: cppViewModel.dataObject.heigth
            Behavior on width { NumberAnimation { ... }}
            Behavior on heigth { NumberAnimation { ... }}

            ColumnLayout {
                Rectangle {
                    Layout.preferredHeight: 100 * cppViewModel.dataObject.width1
                    Behavior on Layout.preferredHeight { NumberAnimation { duration: 500; easing.type: Easing.OutQuad; }}
                    //... Any number of children with animation
                }
            }
        }
    }

    PropertyAnimation { target: idRect1; property: "scale"; from: 0.9; to: 1.0; ... }
}

If the values of the properties of the current data object change, then animation is needed. If the entire object changes to another, then the animation needs to be blocked.


问:
Java drawImage() not drawing
Within my program, I have the following code:

```<code>package io.github.AdmiralSbs.DiceWars;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Scanner;

public class HexDisplay extends JPanel {
    private static final long serialVersionUID = 1L;
    public static final int SIZE = 200;
    private int height;
    private int width;
    private Hex[][] hex;
    private BufferedImage myImage;
    private Graphics drawer;

    public HexDisplay(File f) throws IOException {
        Scanner key = new Scanner(f);
        int[] temp = commaSplit(key.nextLine());
        height = temp[0];
        width = temp[1];
        hex = new Hex[width][height];
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {
                //temp = commaSplit(key.nextLine());
                if (h % 2 == 0)
                    hex[w][h] = new Hex((int) (SIZE * (w + 0.5)),
                            (int) (SIZE * (h + 0.5)), SIZE);
                else
                    hex[w][h] = new Hex((int) (SIZE * (w + 1.5)),
                            (int) (SIZE * (h + 0.5)), SIZE);
                System.out.println(hex[w][h].getX() + " " + hex[w][h].getY());
            }
        }
        key.close();
        starting();
        ImageIO.write(myImage, "jpg", new File("outPic.jpg"));
    }

    public void starting() {
        setPreferredSize(new Dimension(400,400));
        setLayout(new FlowLayout());
        myImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        drawer = myImage.getGraphics();
        drawer.setColor(Color.BLUE);
        drawer.fillRect(0, 0, 400, 400);
        drawStuff(drawer);
        repaint();
    }

    public int[] commaSplit(String s) {
        String[] str = s.split(",");
        int[] ret = new int[str.length];
        for (int i = 0; i < str.length; i++) {
            ret[i] = Integer.parseInt(str[i]);
        }
        return ret;
    }

    public void paintComponents(Graphics g) {
        g.drawImage(myImage, 0, 0, this);
        System.out.println("Painted");
    }

    public void drawStuff(Graphics g) {
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {
                hex[w][h].draw(g);
            }
        }
        System.out.println("Drew");
        revalidate();
        repaint();
        paintComponents(g);
    }
}
</code>```

What I would expect to happen is for the frame that contains this JPanel to display the image, but it does not.  All System.out.println() methods are called as expected, and I am able to save the image as a .jpg file.  However, the image is not displayed in the GUI.  What can be done?

答:
You have a typo:

```<code>//                        v
public void paintComponents(Graphics g) {
</code>```

It should be paintComponent.

And should contain a call to super method:

```<code>super.paintComponent(g);
</code>```

as the first line in the method

Title: Java drawImage() not drawing

Body:
Within my program, I have the following code:

package io.github.AdmiralSbs.DiceWars;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Scanner;

public class HexDisplay extends JPanel {
    private static final long serialVersionUID = 1L;
    public static final int SIZE = 200;
    private int height;
    private int width;
    private Hex[][] hex;
    private BufferedImage myImage;
    private Graphics drawer;

    public HexDisplay(File f) throws IOException {
        Scanner key = new Scanner(f);
        int[] temp = commaSplit(key.nextLine());
        height = temp[0];
        width = temp[1];
        hex = new Hex[width][height];
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {
                //temp = commaSplit(key.nextLine());
                if (h % 2 == 0)
                    hex[w][h] = new Hex((int) (SIZE * (w + 0.5)),
                            (int) (SIZE * (h + 0.5)), SIZE);
                else
                    hex[w][h] = new Hex((int) (SIZE * (w + 1.5)),
                            (int) (SIZE * (h + 0.5)), SIZE);
                System.out.println(hex[w][h].getX() + " " + hex[w][h].getY());
            }
        }
        key.close();
        starting();
        ImageIO.write(myImage, "jpg", new File("outPic.jpg"));
    }

    public void starting() {
        setPreferredSize(new Dimension(400,400));
        setLayout(new FlowLayout());
        myImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
        drawer = myImage.getGraphics();
        drawer.setColor(Color.BLUE);
        drawer.fillRect(0, 0, 400, 400);
        drawStuff(drawer);
        repaint();
    }

    public int[] commaSplit(String s) {
        String[] str = s.split(",");
        int[] ret = new int[str.length];
        for (int i = 0; i < str.length; i++) {
            ret[i] = Integer.parseInt(str[i]);
        }
        return ret;
    }

    public void paintComponents(Graphics g) {
        g.drawImage(myImage, 0, 0, this);
        System.out.println("Painted");
    }

    public void drawStuff(Graphics g) {
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {
                hex[w][h].draw(g);
            }
        }
        System.out.println("Drew");
        revalidate();
        repaint();
        paintComponents(g);
    }
}

What I would expect to happen is for the frame that contains this JPanel to display the image, but it does not.  All System.out.println() methods are called as expected, and I am able to save the image as a .jpg file.  However, the image is not displayed in the GUI.  What can be done?

Body:
You have a typo:

//                        v
public void paintComponents(Graphics g) {

It should be paintComponent.

And should contain a call to super method:

super.paintComponent(g);

as the first line in the method


问:
Including third-party libraries in C applications
I'm a bit naive when it comes to application development in C. I've been writing a lot of code for a programming language I'm working on and I want to include stuff from ICU (for internationalization and unicode support).

The problem is, I'm just not sure if there are any conventions for including a third party library. for something like readline where lots of systems are probably going to have it installed already, it's safe to just link to it (I think). But what about if I wanted to include a version of the library in my own code? Is this common or am I thinking about this all wrong?

答:
If you are talking about shipping your software off to end users and are worried about dependencies - you have to provide them correct packages/installers that include the dependencies needed to run your software, or otherwise make sure the user can get them (subject to local laws, export laws, etc, etc, etc, but that's all about licensing).

You could build your software and statically link in ICU and whatever else you use, or you can ship your software and the ICU shared libraries.


问:
MAU calculation how it works
We have integrated crashlytics in one of our mobile application and it has been working good till now.

I have couple of question related to its display of MAU (monthly active users).

How do you guys calculate this. Is it based on number of unique devices on which app was active in last month or is it unique number of users?

Also how do you define a user/device to be active for a month?

Any insights into this would be helpful as we are getting the same values from a different source as well and 2 are very different.

答:
Mike from Fabric here.

For reference, Answers metrics are defined here: https://docs.fabric.io/android/answers/answers-metrics.html#monthly-active-users

1) MAU is defined as the number of unique app installations across all devices that were active over the trailing 30-day period. Note: Foreground activity must happen for a device to be active.

2) A user is active if the app was launched on their device and brought to the foreground for a day in the past 30 rolling days.

Title: MAU calculation how it works


问:
issue using custom input in Control component react-redux-form
I am trying to pass the a custom input to react-redux-form Control component, and have the value of that new input passed on submit with the values from the standard inputs.

I have a codepen example here of the issue.

DatePicker:

```<code>import React, { Component } from 'react';
import 'react-datepicker/dist/react-datepicker.css';
import DatePicker from 'react-datepicker';
import moment from 'moment';

class DatePickerInput extends Component {
  constructor (props) {
      super(props)
      this.state = {
        startDate: moment()
      };
      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(date) {
      this.setState({
        startDate: date
      });
    }

  render() {
    return (
      <div>
        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChange}
        />
      </div>
      );
  }
}

export default DatePickerInput;
</code>```

Form:

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Control, Form } from 'react-redux-form';
import ProgressIndicator from './ProgressIndicator';
import DatePickerInput from './DatePickerInput';

export default class SubmissionForm extends Component {
  handleSubmit(values) {
    console.log('value', values);
  }

  customInput(props) {
    return (
       <DatePickerInput {...props}/>
    );
  }

  renderDatePicker(displayName, attributeName) {
    const modelName = `newSubmission.${attributeName}`;
    return (
      <div>
          <Control
            model={modelName}
            component={this.customInput}
          />
      </div>
    );
  }

  renderStep() {
    return (
      <Form
        model="newSubmission"
        onSubmit={(data) => this.handleSubmit(data)}
      >
       <div>
          <Control.text
            className="submission-form__field-input input"
            model="newSubmission.name"
          />
      </div>
      {this.renderDatePicker('Start Date', 'startDate')}
         <button
          type="next"
         >
           submit
         </button>
      </Form>
    );
  }

  render() {
    return (
      <div className="submission-form">
        {this.renderStep()}
      </div>
    );
  }
}

SubmissionForm.propTypes = {
  handleSubmit: PropTypes.func
};
</code>```

If anyone can see what is missing it would be a big help.
The "Name" is passed and I can see it in the console when I submit, but for the "Start Date" is not :(

答:
There is nowhere in your custom component that is actually sending the value over - it's all being kept in internal component state. You need to make sure you are sending over the changed value:

```<code>handleChange(date) {
  this.setState({
    startDate: date
  });
  this.props.onChange(date)
}
</code>```

Body:
I am trying to pass the a custom input to react-redux-form Control component, and have the value of that new input passed on submit with the values from the standard inputs.

I have a codepen example here of the issue.

DatePicker:

import React, { Component } from 'react';
import 'react-datepicker/dist/react-datepicker.css';
import DatePicker from 'react-datepicker';
import moment from 'moment';

class DatePickerInput extends Component {
  constructor (props) {
      super(props)
      this.state = {
        startDate: moment()
      };
      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(date) {
      this.setState({
        startDate: date
      });
    }

  render() {
    return (

        <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChange}
        />

      );
  }
}

export default DatePickerInput;

Form:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Control, Form } from 'react-redux-form';
import ProgressIndicator from './ProgressIndicator';
import DatePickerInput from './DatePickerInput';

export default class SubmissionForm extends Component {
  handleSubmit(values) {
    console.log('value', values);
  }

  customInput(props) {
    return (
       <DatePickerInput {...props}/>
    );
  }

  renderDatePicker(displayName, attributeName) {
    const modelName = `newSubmission.${attributeName}`;
    return (

          <Control
            model={modelName}
            component={this.customInput}
          />

    );
  }

  renderStep() {
    return (
      <Form
        model="newSubmission"
        onSubmit={(data) => this.handleSubmit(data)}
      >

          <Control.text
            className="submission-form__field-input input"
            model="newSubmission.name"
          />

      {this.renderDatePicker('Start Date', 'startDate')}
         <button
          type="next"
         >
           submit
         </button>
      </Form>
    );
  }

  render() {
    return (

        {this.renderStep()}

    );
  }
}

SubmissionForm.propTypes = {
  handleSubmit: PropTypes.func
};

If anyone can see what is missing it would be a big help.
The "Name" is passed and I can see it in the console when I submit, but for the "Start Date" is not :(

Body:
There is nowhere in your custom component that is actually sending the value over - it's all being kept in internal component state. You need to make sure you are sending over the changed value:

handleChange(date) {
  this.setState({
    startDate: date
  });
  this.props.onChange(date)
}


问:
Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip
Platform and Plugin Updates in Android Studio and
I get the error:

```<code>Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip
</code>```

In File > Project structure > Project Gradle version: 2.3.2/ Android plugin version 2.3.2

My Gradle:

```<code>buildscript {
  repositories {
      jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
}
}

 allprojects {
   repositories {
      jcenter()
   }
 }

task clean(type: Delete) {
  delete rootProject.buildDir
 }
</code>```

答:
Hope this helps :download gradle by->
click on Tools --> Android --> Sync Project with Gradle Files from the Android Studio menu bar.</p>

Body:
Platform and Plugin Updates in Android Studio and
I get the error:

Gradle sync failed: Cause: https://downloads.gradle.org/distributions/gradle-2.3.2-all.zip

In File > Project structure > Project Gradle version: 2.3.2/ Android plugin version 2.3.2

My Gradle:

buildscript {
  repositories {
      jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'
}
}

 allprojects {
   repositories {
      jcenter()
   }
 }

task clean(type: Delete) {
  delete rootProject.buildDir
 }


问:
Woocommerce add action before div in woocommerce_before_main_content
I want to add the woocommerce_catalog_ordering action right before my shop-header div. This will add it after my container div. Since my custom html isn't an action like woocommerce has built in, i'm not sure how to order them both.

```<code>function shop_page_header() {
    get_template_part('elements/header-nav');

        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
        // Remove the result count from WooCommerce
        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

    if (is_shop()) { ?>

    <div class="container">
        <?php add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 ); ?>
        <div class="shop-header">
            <div class="callout">
                <div class="inner">
                    <h4>test</h4>
                    <h1>test</h1>
                    <div class="price">$59.00 - $149.00</div>
                    <h4>test</h4>
                    <a href="" class="btn brown arrow white-arrow">Shop Now</a>
                    <a href="" class="btn white-outline">View More</a>
                </div>
            </div>
        </div>
    </div>
    <?php }
}

add_action('woocommerce_before_main_content', 'shop_page_header');
</code>```

答:
I restructured things to be like this. I had to break everything up. If there's a better way, please share</p>

```<code>// shop page header
function shop_page_header() {
    get_template_part('elements/header-nav');
}

function shop_page_banner() {

    if (is_shop()) { ?>

    <div class="container">
        <div class="shop-header">
            <div class="callout">
                <div class="inner">
                    <h4>test</h4>
                    <h1>test</h1>
                    <div class="price">$59.00 - $149.00</div>
                    <h4>test</h4>
                    <a href="" class="btn brown arrow white-arrow">Shop Now</a>
                    <a href="" class="btn white-outline">View More</a>
                </div>
            </div>
        </div>
    </div>
    <?php }
}

remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
// Remove the result count from WooCommerce
remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

add_action('woocommerce_before_main_content', 'shop_page_header', 10);
add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 );
add_action('woocommerce_before_main_content', 'shop_page_banner', 30);
</code>```

Body:
I want to add the woocommerce_catalog_ordering action right before my shop-header div. This will add it after my container div. Since my custom html isn't an action like woocommerce has built in, i'm not sure how to order them both.

function shop_page_header() {
    get_template_part('elements/header-nav');

        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
        // Remove the result count from WooCommerce
        remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

    if (is_shop()) { ?>

        <?php add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 ); ?>

test

test

$59.00 - $149.00

test

                    Shop Now
                    View More

    <?php }
}

add_action('woocommerce_before_main_content', 'shop_page_header');

Body:
I restructured things to be like this. I had to break everything up. If there's a better way, please share

// shop page header
function shop_page_header() {
    get_template_part('elements/header-nav');
}

function shop_page_banner() {

    if (is_shop()) { ?>

    <div class="container">
        <div class="shop-header">
            <div class="callout">
                <div class="inner">
                    <h4>test</h4>
                    <h1>test</h1>
                    <div class="price">$59.00 - $149.00</div>
                    <h4>test</h4>
                    <a href="" class="btn brown arrow white-arrow">Shop Now</a>
                    <a href="" class="btn white-outline">View More</a>
                </div>
            </div>
        </div>
    </div>
    <?php }
}

remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_catalog_ordering', 30 );
// Remove the result count from WooCommerce
remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 );

add_action('woocommerce_before_main_content', 'shop_page_header', 10);
add_action( 'woocommerce_before_main_content', 'woocommerce_catalog_ordering', 20 );
add_action('woocommerce_before_main_content', 'shop_page_banner', 30);


问:
VS 2010 Major Publish Version Change - New Application or Overwrite Previous Version
Using Visual Studio 2010 Professional Windows Form App. Currently a ClickOnce application has only been incrementing the Revision value (1.0.0.15). Settings are to Automatically increment revision with each publish. Client app updates automatically before application opens.

If I manually increment the Major value (2.0.0.0), is this going to install another version of the application or just overwrite/update the existing version on a client's machine? I recall using the express version and this happened.

答: Incrementing any part of the version number will not install another version of the application.  It will simply update the existing installation.


问:
A plugin stylesheet is overriding my own with !important – can I change the order in which they're loaded?
I have installed a Wordpress plugin that is using !important on a max-width value that is breaking my layouts. I have tried various ways of overriding it, with my own CSS, however I am unable to use a high specificity of selector, as the plugin is already using it. I spoke to the development team about this, and they said it's because the plugin's stylesheet is loading before mine. Is there a way in which I can get mine to load first?

This is how I am enqueuing my stylesheets in the functions folder –

As you can see I have divided it up into the custom page template in the first section (if), and the main stylesheet in the second section (else).

Is there a way of making the main stylesheet take priority over those of the plugins I have installed?

```<code>if (is_page_template('page-templates/full-page.php')) {

    wp_enqueue_style( 'mytheme', get_stylesheet_uri() );
    wp_enqueue_style( 'mytheme-full-page', get_stylesheet_directory_uri() . '/css/full-page.css', array( 'mytheme_style' ) );

}

else { wp_enqueue_style( 'mytheme_style', get_stylesheet_uri() );

}

}

add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts' );
</code>```

答:
You can give priority to the add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts' ); function adding the value at the end try:

```<code>add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts', 99 );
</code>```

Body:
I have installed a Wordpress plugin that is using !important on a max-width value that is breaking my layouts. I have tried various ways of overriding it, with my own CSS, however I am unable to use a high specificity of selector, as the plugin is already using it. I spoke to the development team about this, and they said it's because the plugin's stylesheet is loading before mine. Is there a way in which I can get mine to load first?

This is how I am enqueuing my stylesheets in the functions folder –

As you can see I have divided it up into the custom page template in the first section (if), and the main stylesheet in the second section (else).

Is there a way of making the main stylesheet take priority over those of the plugins I have installed?

if (is_page_template('page-templates/full-page.php')) {

    wp_enqueue_style( 'mytheme', get_stylesheet_uri() );
    wp_enqueue_style( 'mytheme-full-page', get_stylesheet_directory_uri() . '/css/full-page.css', array( 'mytheme_style' ) );

}

else { wp_enqueue_style( 'mytheme_style', get_stylesheet_uri() );

}

}

add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts' );

Body:
You can give priority to the add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts' ); function adding the value at the end try:

add_action( 'wp_enqueue_scripts', 'enqueue_my_styles_and_scripts', 99 );