答:
Try input - it handles paste too:

$(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    $(".removetext").toggle(val.length>0); // test anything not blank
  });
  // the event handler needs to be HERE and not inside the inout handler
  $(".removetext").on('click', function() {
      alert('hey');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels" value="">

×

```
</div>
</div>
</p>

<p>If you need a callback you do need show and hide</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>$(function() {
  $('.search-hotels').on('input', function() {
    var show = $.trim(this.value).length>0;
    if (show) {
      $(".removetext").show("slow",function() {
        console.log("showing");
      });
    }
    else {
      $(".removetext").hide("slow",function() {
        console.log("hiding");
      });
    }

  });
});</code>```

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels" value="">
  <div class="removetext">×</div>
</div></code>```

Title: How does the keydown event work?

Body:
I want that if my input text value is not empty then show my .removetext div but it doesn't work properly. If you type a something after second character my .removetext is being hidden but if my input is not empty don't hide my .removetext class.

Where is my mistake? I guess I don't understand the keydown event

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    if (!val == "") {
      $(".removetext").show(val.length > 0, function() {
        var clear = $(this);
        clear.on('click', function() {
          alert('hey');
        })
      });
    } else {
      $(".removetext").hide();
    }
  });

});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

  <input type="text" class="search-hotels">

×

Body:
Try input - it handles paste too:

$(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    $(".removetext").toggle(val.length>0); // test anything not blank
  });
  // the event handler needs to be HERE and not inside the inout handler
  $(".removetext").on('click', function() {
      alert('hey');
  });
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels" value="">
  <div class="removetext">&times;</div>
</div>

If you need a callback you do need show and hide

$(function() {
  $('.search-hotels').on('input', function() {
    var show = $.trim(this.value).length>0;
    if (show) {
      $(".removetext").show("slow",function() {
        console.log("showing");
      });
    }
    else {
      $(".removetext").hide("slow",function() {
        console.log("hiding");
      });
    }

  });
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels" value="">
  <div class="removetext">&times;</div>
</div>


来源: stackexchange

问:
Split lines on spaces in Sublime Text
How can i split lines in Sublime Text 3? I tried ctrl+t, ctrl+x

but it does not work.

I have line such as

```<code>this is a sentence
</code>```

i would like to make it

```<code>this
is
a
sentence
</code>```

答: for Mac, select the first space between "this" and "is" then press command+d to select the same pattern in the file, then press enter~</p>

ContentLicense: CC BY-SA 3.0

Title: Split lines on spaces in Sublime Text

Body:
How can i split lines in Sublime Text 3? I tried ctrl+t, ctrl+x

but it does not work.

I have line such as

this is a sentence

i would like to make it

this
is
a
sentence


问:
SQL Server: SUM multiple rows depending on a conditon
My table looks like this (I work at an energy company)

```<code>dte             hub            Peak            Offpeak
07-04-2017      SoCo           36.19           18.23
07-04-2017      SwapBID        0.5             0.25
07-05-2017      SoCo           32.12           21.72
07-05-2017      SwapBID        0.25            0.25
07-06-2017      SoCo           33.87           20.34
07-06-2017      SwapBID        0.5             0.5
</code>```

I want to be able to pull the data from this table using a select query and make it so that the two hubs' peak and offpeak prices are added together for the same days. For example, on the day 07/04/2017 i want it to show that the Peak was 36.69 and the Offpeak was 18.48. I would like to do this for every day in the table. How do I code this?

答:
Just aggregate your table by date and sum the peak and offpeak values:

```<code>SELECT
    dte,
    SUM(Peak) AS Peak,
    SUM(Offpeak) AS Offpeak
FROM yourTable
GROUP BY dte
</code>```

If a given date could have more than one hub type but we wanted to only consider SoCo and SwapBID hubs, then we could consider adding a WHERE clause to the query:

```<code>WHERE hub IN ('SoCo', 'SwapBID')
</code>```

Body:
My table looks like this (I work at an energy company)

dte             hub            Peak            Offpeak
07-04-2017      SoCo           36.19           18.23
07-04-2017      SwapBID        0.5             0.25
07-05-2017      SoCo           32.12           21.72
07-05-2017      SwapBID        0.25            0.25
07-06-2017      SoCo           33.87           20.34
07-06-2017      SwapBID        0.5             0.5

I want to be able to pull the data from this table using a select query and make it so that the two hubs' peak and offpeak prices are added together for the same days. For example, on the day 07/04/2017 i want it to show that the Peak was 36.69 and the Offpeak was 18.48. I would like to do this for every day in the table. How do I code this?

Body:
Just aggregate your table by date and sum the peak and offpeak values:

SELECT
    dte,
    SUM(Peak) AS Peak,
    SUM(Offpeak) AS Offpeak
FROM yourTable
GROUP BY dte

If a given date could have more than one hub type but we wanted to only consider SoCo and SwapBID hubs, then we could consider adding a WHERE clause to the query:

WHERE hub IN ('SoCo', 'SwapBID')


问:
how to give background color for button in android
i have three button which is arranged in table row .I gave background for the three button but it wraps the button .  </p>

答:
For starters read my blog :-)

Now my suggestion is to use background definitions with gradients. They look nice and are simpler to create then background images. As I said in the blog you need three of them for the button to work as expected. I have a demo for you here: button_type_0.xml

You will also need to define the colours: colors.xml

and dimensions: dimens.xml

you might also want to consider different dimensions for various dpi values. for example I use half size corners and border for ldpi: ldpi/dimens.xml

Looks all very complicated at the beginning but it is worth it. In the end it will look like this:

ContentLicense: CC BY-SA 2.5


问:
How to use the Entity Framework connection string in log4net?
Is there any way to configure the connection string of log4net and to use the same connection string of entity framework?

This is my entity framework connection string:

```<code><add name="EntityFrameworkConnection" connectionString="metadata=res://*/Data.BinAppModel.csdl|res://*/Data.BinAppModel.ssdl|res://*/Data.BinAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=database;user id=user;password=pwd;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

This is my log4net configuration

```<code><connectionType value="System.Data.SqlClient.SqlConnection, System.Data,  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

<connectionStringName value="EntityFrameworkConnection" />
</code>```

But I get this error:

```<code>log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Could not open database connection [metadata=res://*/Data.BinAppModel.csdl|res://*/Data.BinAppModel.ssdl|res://*/Data.BinAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=data source=.\sqlexpress;initial catalog=database;user id=user;password=pwd;multipleactiveresultsets=True;application name=EntityFramework""]. Connection string context [ConnectionStringName].
</code>```

答:
In continue to @Klinger's answer:

I've faced an issue that was caused by the EntityFramework connectionString (the one with metadata... as in the OP). An exception was thrown when trying to
create connection with the message about metadata not a keyword.

What I had to do is extract the provider's connection string and pass it to both the factory.CreateConnection function and the instance.ConnectionString property, as seen in the below code.

```<code>using System;
using System.Data;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Infrastructure;

namespace AdvancedPackagesTracker.DataAccess
{
    public class EFNetAppender : log4net.Appender.AdoNetAppender
    {
        protected override IDbConnection CreateConnection(Type connectionType, string connectionString)
        {
            var factory = (IDbConnectionFactory)Activator.CreateInstance(connectionType);

            var builder = new EntityConnectionStringBuilder();
            var providerConnectionString = new EntityConnectionStringBuilder(connectionString).ProviderConnectionString;
            IDbConnection instance = factory.CreateConnection(providerConnectionString);
            instance.ConnectionString = providerConnectionString;
            return instance;
        }
    }
}
</code>```

Body:
Is there any way to configure the connection string of log4net and to use the same connection string of entity framework?

This is my entity framework connection string:

<add name="EntityFrameworkConnection" connectionString="metadata=res://*/Data.BinAppModel.csdl|res://*/Data.BinAppModel.ssdl|res://*/Data.BinAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=database;user id=user;password=pwd;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

This is my log4net configuration

<connectionType value="System.Data.SqlClient.SqlConnection, System.Data,  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

<connectionStringName value="EntityFrameworkConnection" />

But I get this error:

log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Could not open database connection [metadata=res://*/Data.BinAppModel.csdl|res://*/Data.BinAppModel.ssdl|res://*/Data.BinAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=data source=.\sqlexpress;initial catalog=database;user id=user;password=pwd;multipleactiveresultsets=True;application name=EntityFramework""]. Connection string context [ConnectionStringName].

Body:
In continue to @Klinger's answer:

I've faced an issue that was caused by the EntityFramework connectionString (the one with metadata... as in the OP). An exception was thrown when trying to
create connection with the message about metadata not a keyword.

What I had to do is extract the provider's connection string and pass it to both the factory.CreateConnection function and the instance.ConnectionString property, as seen in the below code.

using System;
using System.Data;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Infrastructure;

namespace AdvancedPackagesTracker.DataAccess
{
    public class EFNetAppender : log4net.Appender.AdoNetAppender
    {
        protected override IDbConnection CreateConnection(Type connectionType, string connectionString)
        {
            var factory = (IDbConnectionFactory)Activator.CreateInstance(connectionType);

            var builder = new EntityConnectionStringBuilder();
            var providerConnectionString = new EntityConnectionStringBuilder(connectionString).ProviderConnectionString;
            IDbConnection instance = factory.CreateConnection(providerConnectionString);
            instance.ConnectionString = providerConnectionString;
            return instance;
        }
    }
}


问:
How does the keydown event work?
I want that if my input text value is not empty then show my .removetext div but it doesn't work properly. If you type a something after second character my .removetext is being hidden but if my input is not empty don't hide my .removetext class.

Where is my mistake? I guess I don't understand the keydown event

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    if (!val == "") {
      $(".removetext").show(val.length > 0, function() {
        var clear = $(this);
        clear.on('click', function() {
          alert('hey');
        })
      });
    } else {
      $(".removetext").hide();
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

答:
keydown event fires when the button is pressed, at that moment your value isn't updated, try using keyup event fires when the button is released and the input value is updated...

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    console.log(this,$(this).val());
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

Title: How does the keydown event work?

Body:
keydown event fires when the button is pressed, at that moment your value isn't updated, try using keyup event fires when the button is released and the input value is updated...

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    console.log(this,$(this).val());
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>


问:
Convert select query to update MYSQL
How to convert select to update for this query for field 'year_from':

```<code>SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles
</code>```

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

答:
You could try this:</p>

```<code>UPDATE lc_vehicles SET year_from = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5))
</code>```

Title: Convert select query to update MYSQL

Body:
How to convert select to update for this query for field 'year_from':

SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

Body:
You could try this:

UPDATE lc_vehicles SET year_from = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5))


问:
Save Wordpress post in edit mode through a custom save button
Wordpress provides default save post button. Now, I want to do some preprocessing on the content written in wordpress editor (which is not yet saved into database) and then save it in database (both the tasks in a single button click). I don't want to use wp_insert_post hook because I want to give the option of preprocessing on demand through a different button and then save the preprocessed post also.</p>

答: You can use wp_insert_post_data for changes data before save process</p>


问:
How to reference a value at time in day to create a binary vector (xts)
There is an xts object with data in 15 minute intervals. Everyday at 930 I average the values of the 900 & 915 periods, and, if average > 5, I record a 1 in vector of 1s and 0s BinVect. The script below achieves that:

```<code>library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
BinVect <- ifelse(AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30
XTS1 <- merge.xts(XTS1,AvgPrior2,BinVect)

#Output:
                    XTS1 AvgPrior2 BinVect
2014-10-22 08:45:00   12        NA       0
2014-10-22 09:00:00    7        NA       0
2014-10-22 09:15:00    7       9.5       0
2014-10-22 09:30:00   22       7.0       1
2014-10-22 09:45:00   24      14.5       0
2014-10-22 10:00:00   30      23.0       0
2014-10-22 10:15:00   26      27.0       0
2014-10-22 10:30:00   23      28.0       0
2014-10-22 10:45:00   27      24.5       0
2014-10-22 11:00:00   30      25.0       0
</code>```

Now the part that I can't figure out: would like to create a new vector that will have 1s every day between 09:30:00 and 10:15:00 whenever on that day BinVect==1 @ 09:30:00. Think need to use function apply.daily, question is how.

```<code>#Desired Output:
                        XTS1 AvgPrior2 BinVect NewBinVect
2014-10-22 08:45:00   12        NA       0              0
2014-10-22 09:00:00    7        NA       0              0
2014-10-22 09:15:00    7       9.5       0              0
2014-10-22 09:30:00   22       7.0       1              1
2014-10-22 09:45:00   24      14.5       0              1
2014-10-22 10:00:00   30      23.0       0              1
2014-10-22 10:15:00   26      27.0       0              1
2014-10-22 10:30:00   23      28.0       0              0
2014-10-22 10:45:00   27      24.5       0              0
2014-10-22 11:00:00   30      25.0       0              0

#This is the closest I got to getting anywhere (out of several trials):
XTS1$NewBinVect <- apply.daily(BinVect, function(x) ifelse(x == 1, 1, 0))
#Think it says if BinVect=1 on a given day => NewBinVect=1 on that day (but doesn't do that)
</code>```

答:
You can also do this using xts' time-of-day subsetting.  First, some data for a reproducible example:

```<code>x1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30),
  .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "America/New_York",
  tclass = c("POSIXct", "POSIXt"), tzone = "America/New_York",
  class = c("xts", "zoo"), index = structure(c(1413981900, 1413982800, 1413983700,
  1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100,
  1413990000), tzone = "America/New_York", tclass = c("POSIXct", "POSIXt")),
  .Dim = c(10L, 1L))
x2 <- x1 - 25
.index(x2) <- .index(x2) + 86400
XTS1 <- rbind(x1, x2)
colnames(XTS1) <- "XTS1"
</code>```

Now, you can use time-of-day subsetting to extract only the time periods you want to use in your mean calculation. (Note that the leading zero is required for times with less than 2 digits.) Then you can use apply.daily to calculate the mean for each day.

```<code>XTS1$BinVec <- apply.daily(XTS1["T0900/T0915"], mean) > 5
</code>```

When you add a column to an xts object using the $<- function, it implicitly merges the original object with the object created on the right-hand-side.  By default, merge.xts fills with NA, which is why most of the observations in BinVec are NA.

Now that you have BinVec, you can again use the time-of-day subsetting to extract the time periods you want to fill in with the value of BinVec. So you can extract all the observations between 09:15-10:15 and fill the NA with the value of the observation at 09:15.

```<code>XTS1$NewBinVec <- na.locf(XTS1["T0915/T1015", "BinVec"])
</code>```

Now XTS1 looks like this (again, all the NA are from the implicit merges):

```<code>                    XTS1 BinVec NewBinVec
2014-10-22 08:45:00   12     NA        NA
2014-10-22 09:00:00    7     NA        NA
2014-10-22 09:15:00    7      1         1
2014-10-22 09:30:00   22     NA         1
2014-10-22 09:45:00   24     NA         1
2014-10-22 10:00:00   30     NA         1
2014-10-22 10:15:00   26     NA         1
2014-10-22 10:30:00   23     NA        NA
2014-10-22 10:45:00   27     NA        NA
2014-10-22 11:00:00   30     NA        NA
2014-10-23 08:45:00  -13     NA        NA
2014-10-23 09:00:00  -18     NA        NA
2014-10-23 09:15:00  -18      0         0
2014-10-23 09:30:00   -3     NA         0
2014-10-23 09:45:00   -1     NA         0
2014-10-23 10:00:00    5     NA         0
2014-10-23 10:15:00    1     NA         0
2014-10-23 10:30:00   -2     NA        NA
2014-10-23 10:45:00    2     NA        NA
2014-10-23 11:00:00    5     NA        NA
</code>```

You can fill all the NA with 0, if you want.

```<code>XTS1[is.na(XTS1)] <- 0
XTS1
                    XTS1 BinVec NewBinVec
2014-10-22 08:45:00   12      0         0
2014-10-22 09:00:00    7      0         0
2014-10-22 09:15:00    7      1         1
2014-10-22 09:30:00   22      0         1
2014-10-22 09:45:00   24      0         1
2014-10-22 10:00:00   30      0         1
2014-10-22 10:15:00   26      0         1
2014-10-22 10:30:00   23      0         0
2014-10-22 10:45:00   27      0         0
2014-10-22 11:00:00   30      0         0
2014-10-23 08:45:00  -13      0         0
2014-10-23 09:00:00  -18      0         0
2014-10-23 09:15:00  -18      0         0
2014-10-23 09:30:00   -3      0         0
2014-10-23 09:45:00   -1      0         0
2014-10-23 10:00:00    5      0         0
2014-10-23 10:15:00    1      0         0
2014-10-23 10:30:00   -2      0         0
2014-10-23 10:45:00    2      0         0
2014-10-23 11:00:00    5      0         0
</code>```

Body:
There is an xts object with data in 15 minute intervals. Everyday at 930 I average the values of the 900 & 915 periods, and, if average > 5, I record a 1 in vector of 1s and 0s BinVect. The script below achieves that:

library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
BinVect <- ifelse(AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30
XTS1 <- merge.xts(XTS1,AvgPrior2,BinVect)

#Output:
                    XTS1 AvgPrior2 BinVect
2014-10-22 08:45:00   12        NA       0
2014-10-22 09:00:00    7        NA       0
2014-10-22 09:15:00    7       9.5       0
2014-10-22 09:30:00   22       7.0       1
2014-10-22 09:45:00   24      14.5       0
2014-10-22 10:00:00   30      23.0       0
2014-10-22 10:15:00   26      27.0       0
2014-10-22 10:30:00   23      28.0       0
2014-10-22 10:45:00   27      24.5       0
2014-10-22 11:00:00   30      25.0       0

Now the part that I can't figure out: would like to create a new vector that will have 1s every day between 09:30:00 and 10:15:00 whenever on that day BinVect==1 @ 09:30:00. Think need to use function apply.daily, question is how.

#Desired Output:
                        XTS1 AvgPrior2 BinVect NewBinVect
2014-10-22 08:45:00   12        NA       0              0
2014-10-22 09:00:00    7        NA       0              0
2014-10-22 09:15:00    7       9.5       0              0
2014-10-22 09:30:00   22       7.0       1              1
2014-10-22 09:45:00   24      14.5       0              1
2014-10-22 10:00:00   30      23.0       0              1
2014-10-22 10:15:00   26      27.0       0              1
2014-10-22 10:30:00   23      28.0       0              0
2014-10-22 10:45:00   27      24.5       0              0
2014-10-22 11:00:00   30      25.0       0              0

#This is the closest I got to getting anywhere (out of several trials):
XTS1$NewBinVect <- apply.daily(BinVect, function(x) ifelse(x == 1, 1, 0))
#Think it says if BinVect=1 on a given day => NewBinVect=1 on that day (but doesn't do that)

Body:
You can also do this using xts' time-of-day subsetting.  First, some data for a reproducible example:

x1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30),
  .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "America/New_York",
  tclass = c("POSIXct", "POSIXt"), tzone = "America/New_York",
  class = c("xts", "zoo"), index = structure(c(1413981900, 1413982800, 1413983700,
  1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100,
  1413990000), tzone = "America/New_York", tclass = c("POSIXct", "POSIXt")),
  .Dim = c(10L, 1L))
x2 <- x1 - 25
.index(x2) <- .index(x2) + 86400
XTS1 <- rbind(x1, x2)
colnames(XTS1) <- "XTS1"

Now, you can use time-of-day subsetting to extract only the time periods you want to use in your mean calculation. (Note that the leading zero is required for times with less than 2 digits.) Then you can use apply.daily to calculate the mean for each day.

XTS1$BinVec <- apply.daily(XTS1["T0900/T0915"], mean) > 5

When you add a column to an xts object using the $<- function, it implicitly merges the original object with the object created on the right-hand-side.  By default, merge.xts fills with NA, which is why most of the observations in BinVec are NA.

Now that you have BinVec, you can again use the time-of-day subsetting to extract the time periods you want to fill in with the value of BinVec. So you can extract all the observations between 09:15-10:15 and fill the NA with the value of the observation at 09:15.

XTS1$NewBinVec <- na.locf(XTS1["T0915/T1015", "BinVec"])

Now XTS1 looks like this (again, all the NA are from the implicit merges):

                    XTS1 BinVec NewBinVec
2014-10-22 08:45:00   12     NA        NA
2014-10-22 09:00:00    7     NA        NA
2014-10-22 09:15:00    7      1         1
2014-10-22 09:30:00   22     NA         1
2014-10-22 09:45:00   24     NA         1
2014-10-22 10:00:00   30     NA         1
2014-10-22 10:15:00   26     NA         1
2014-10-22 10:30:00   23     NA        NA
2014-10-22 10:45:00   27     NA        NA
2014-10-22 11:00:00   30     NA        NA
2014-10-23 08:45:00  -13     NA        NA
2014-10-23 09:00:00  -18     NA        NA
2014-10-23 09:15:00  -18      0         0
2014-10-23 09:30:00   -3     NA         0
2014-10-23 09:45:00   -1     NA         0
2014-10-23 10:00:00    5     NA         0
2014-10-23 10:15:00    1     NA         0
2014-10-23 10:30:00   -2     NA        NA
2014-10-23 10:45:00    2     NA        NA
2014-10-23 11:00:00    5     NA        NA

You can fill all the NA with 0, if you want.

XTS1[is.na(XTS1)] <- 0
XTS1
                    XTS1 BinVec NewBinVec
2014-10-22 08:45:00   12      0         0
2014-10-22 09:00:00    7      0         0
2014-10-22 09:15:00    7      1         1
2014-10-22 09:30:00   22      0         1
2014-10-22 09:45:00   24      0         1
2014-10-22 10:00:00   30      0         1
2014-10-22 10:15:00   26      0         1
2014-10-22 10:30:00   23      0         0
2014-10-22 10:45:00   27      0         0
2014-10-22 11:00:00   30      0         0
2014-10-23 08:45:00  -13      0         0
2014-10-23 09:00:00  -18      0         0
2014-10-23 09:15:00  -18      0         0
2014-10-23 09:30:00   -3      0         0
2014-10-23 09:45:00   -1      0         0
2014-10-23 10:00:00    5      0         0
2014-10-23 10:15:00    1      0         0
2014-10-23 10:30:00   -2      0         0
2014-10-23 10:45:00    2      0         0
2014-10-23 11:00:00    5      0         0


问:
How to make Table in PHP
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "<br>";
                $z++;
            }
        }
    }
</code>```

I tried with this code. But the result is not in one table.

```<code>foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "<div class='row'>";
                    echo "<div class='col-sm-12'>";
                        echo "<h4 class='m-t-0 header-title'></h4>";
                        echo "<div class='table-responsive m-b-20'>";
                            echo "<p class='text-muted font-13 m-b-30'>";
                            echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
                                 echo "<thead>";
                                    echo "<tr>";
                                        echo "<th>No.</th>";
                                        echo "<th>Nama Item</th>";
                                        echo "<th>Jumlah</th>";
                                    echo"</tr>";
                                    echo "</thead>";
                                    echo "<tbody>";
                                    $no = 0;
                                    $no++;
                                        echo "<tr>";
                                            echo "<td> $no </td>";
                                            echo "<td> $ia_key </td>";
                                            echo "<td> $ia_value </td>";
                                            $z++;
                                        echo "</tr>";
                                    echo "</tbody>";
                                echo "</tr>";
                            echo "</table>";
                        echo "</div>";
                    echo "</div>";
                echo"</div>";
            }
        }
    }
</code>```

Result of above code <== Click to view image.

答:
the problem in your code is that you echo the table in the loop and this result in define table another table each time within the loop re arrange your code to print the table before the loop and end it after the loop may be like this          </p>

```<code> echo "<div class='row'>";
                                echo "<div class='col-sm-12'>";
                                    echo "<h4 class='m-t-0 header-title'></h4>";
                                    echo "<div class='table-responsive m-b-20'>";
                                        echo "<p class='text-muted font-13 m-b-30'>";
                                        echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
  echo "<thead>";
                                                echo "<tr>";
                                                    echo "<th>No.</th>";
                                                    echo "<th>Nama Item</th>";
                                                    echo "<th>Jumlah</th>";
                                                echo"</tr>";
                                                echo "</thead>";

            for($x = 0; $x < count($ia_key); $x++)
                    {
                        if (($ia_value>=$support))
                        {

                                                echo "<tbody>";
                                                $no = 0;
                                                $no++;
                                                    echo "<tr>";
                                                        echo "<td> $no </td>";
                                                        echo "<td> $ia_key </td>";
                                                        echo "<td> $ia_value </td>";
                                                        $z++;
                                                    echo "</tr>";
                                                echo "</tbody>";
                                            echo "</tr>";
                                                                                }
                }
    echo "</table>";
                                    echo "</div>";
                                echo "</div>";
                            echo"</div>";
</code>```

Title: How to make Table in PHP

Body:
I want to make table with this result (look Echo),  When I put it in the table it happens is all the results are not in one table but one result of one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "$ia_key($ia_value)";
                echo "
";
                $z++;
            }
        }
    }

I tried with this code. But the result is not in one table.

foreach ($item_array as $ia_key => $ia_value)
    {
        //$theitems = explode('|',$ia_key);
        for($x = 0; $x < count($ia_key); $x++)
        {
            if (($ia_value>=$support))
            {
                echo "
";
                    echo "
";
                        echo "

";
                        echo "
";
                            echo "
";
                            echo "
";
                                 echo "
";
                                    echo "
";
                                        echo "No.	";
                                        echo "Nama Item	";
                                        echo "Jumlah	";
                                    echo"
";
                                    echo "
";
                                    echo "
";
                                    $no = 0;
                                    $no++;
                                        echo "
";
                                            echo " $no 	";
                                            echo " $ia_key 	";
                                            echo " $ia_value 	";
                                            $z++;
                                        echo "
";
                                    echo "
";
                                echo "
";
                            echo "
";
                        echo "
";
                    echo "
";
                echo"
";
            }
        }
    }

Result of above code <== Click to view image.

Body:
the problem in your code is that you echo the table in the loop and this result in define table another table each time within the loop re arrange your code to print the table before the loop and end it after the loop may be like this

 echo "<div class='row'>";
                                echo "<div class='col-sm-12'>";
                                    echo "<h4 class='m-t-0 header-title'></h4>";
                                    echo "<div class='table-responsive m-b-20'>";
                                        echo "<p class='text-muted font-13 m-b-30'>";
                                        echo "<table id='datatable-buttons' class='table table-striped table-bordered'>";
  echo "<thead>";
                                                echo "<tr>";
                                                    echo "<th>No.</th>";
                                                    echo "<th>Nama Item</th>";
                                                    echo "<th>Jumlah</th>";
                                                echo"</tr>";
                                                echo "</thead>";

            for($x = 0; $x < count($ia_key); $x++)
                    {
                        if (($ia_value>=$support))
                        {

                                                echo "<tbody>";
                                                $no = 0;
                                                $no++;
                                                    echo "<tr>";
                                                        echo "<td> $no </td>";
                                                        echo "<td> $ia_key </td>";
                                                        echo "<td> $ia_value </td>";
                                                        $z++;
                                                    echo "</tr>";
                                                echo "</tbody>";
                                            echo "</tr>";
                                                                                }
                }
    echo "</table>";
                                    echo "</div>";
                                echo "</div>";
                            echo"</div>";


问:
psycopg2 on cygwin: no such process
I am trying to install postgrepsql to cygwin on a windows 7 machine and want it to work with django.

After built and installed postgrepsql in cygwin, I built and installed psycopg2 in cygwin as well and got no error, but when use it in python with cygwin, I got the "no such process" error:

import psycopg2
      Traceback (most recent call last):
      File "", line 1, in
      File "/usr/lib/python2.5/site-packages/psycopg2/init.py", line 60, in
      from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
      ImportError: No such process

any clues?

Thanks!

Jerry

答:
you could try these:
http://www.stickpeople.com/projects/python/win-psycopg/</p>

OwnerDisplayName: Jerry

Title: psycopg2 on cygwin: no such process


问:
Twitter API get Account tweet likes per day
I need to get the following stats for a twitter account on daily basis:
Likes per day
Replies per day
Retweets per day
Followers per day

Just like facebook graph API request "/me/insights/page_impressions?period=day"

I am trying twitter ads api but its not working. Can someone please tell me exact api and query.

Thanks in advance!!

答: This is possible using the commercial Twitter Engagements API from Gnip. The Ads API is for promoted content.</p>


问:
Concatenating embedded inputs to feed recurrent LSTM in keras
I'm trying to figure out how to feed a functional model to LSTM gates in keras. I've got a time series of tuples (int, float, float). The ints are not ordered and should go through and embedding layer. I then want the tuples (after embedding the int) to go through an LSTM layer.

I've started with

from keras.layers import Input
from keras.layers import Embedding
from keras.layers import LSTM

import keras

inputs = [(42, 0.5, 0.6), (36, 0.4, 0.7), (50, 0.2, 0.9)] # example. The real data is a sequence of millions of tuples

input_id = Input(shape=(1,), dtype='int32', name='input_type') # id is within [0, 99]
embed_id = Embedding(output_dim=3, input_dim=20, input_length=1)(input_id)

input_v1 = Input(shape=(1,), dtype='float', name='input_v1')
input_v2 = Input(shape=(1,), dtype='float', name='input_v2')

input_merged = keras.layers.concatenate([embed_id, input_v1, input_v2], axis=-1)

lstm = LSTM(40) # how do I tell it to use input_merged as input ?```

The concatenate complains:
ValueError: Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 1, 3), (None, 1), (None, 1)]

This I'm pretty sure could be arrange with reshapes. But What I'm really wondering: Is this the right approach to feeding Keras time sequences of data needing some processing ?

I'm also unsure how to feed the LSTM gates the concatenated results. All the recurrent examples I could find use sequential models.

答:
The embedding layer will need that you have the entire sequence of integers, so it can compute correctly.

So, as a first step, I'd split the input data:

```<code>intInputs = np.array([el[0] for el in inputs])
floatInputs = np.array([el[1],el[2]] for el in inputs)
    #this could be optimized creating empty numpy arrays first and doing only one loop to fill them
</code>```

After that, we must understand that if we're giving the entire sequence to the embedding, we must also pass the entire sequence to the model. For that, I think it's best to reshape the inputs to have "one sample" of many time steps (unless you really have more than one sequence):

```<code>intInputs = intInputs.reshape((1,seqLength))
floatInputs = floatInputs.reshape((1,seqLength,2))
</code>```

Then we go to the model:

```<code>input_id=Input((seqLength,))
input_v =Input((seqLength,2))

embed_id = Embedding(output_dim=3,input_dim=20,input_length=seqLength)(input_id)
    #are you sure "input_dim" is 20? Normally you should have the total amount of existing Ids, and I suppose this should at least be the last id+1.
</code>```

With this, the concatenation will have shapes (None,seqLength,3), (None,seqLength,2), and you will be able to concat in the last axis (the others are equal in length).

```<code>input_merged = Concatenate(axis=-1)([embed_id,input_v])
</code>```

And the LSTM receives the input as any other layer:

```<code>lstm = LSTM(40)(input_merged)
</code>```

Body:
I'm trying to figure out how to feed a functional model to LSTM gates in keras. I've got a time series of tuples (int, float, float). The ints are not ordered and should go through and embedding layer. I then want the tuples (after embedding the int) to go through an LSTM layer.

I've started with

from keras.layers import Input
from keras.layers import Embedding
from keras.layers import LSTM

import keras

inputs = [(42, 0.5, 0.6), (36, 0.4, 0.7), (50, 0.2, 0.9)] # example. The real data is a sequence of millions of tuples

input_id = Input(shape=(1,), dtype='int32', name='input_type') # id is within [0, 99]
embed_id = Embedding(output_dim=3, input_dim=20, input_length=1)(input_id)

input_v1 = Input(shape=(1,), dtype='float', name='input_v1')
input_v2 = Input(shape=(1,), dtype='float', name='input_v2')

input_merged = keras.layers.concatenate([embed_id, input_v1, input_v2], axis=-1)

lstm = LSTM(40) # how do I tell it to use input_merged as input ?

The concatenate complains:
ValueError: Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 1, 3), (None, 1), (None, 1)]

This I'm pretty sure could be arrange with reshapes. But What I'm really wondering: Is this the right approach to feeding Keras time sequences of data needing some processing ?

I'm also unsure how to feed the LSTM gates the concatenated results. All the recurrent examples I could find use sequential models.

Body:
The embedding layer will need that you have the entire sequence of integers, so it can compute correctly.

So, as a first step, I'd split the input data:

intInputs = np.array([el[0] for el in inputs])
floatInputs = np.array([el[1],el[2]] for el in inputs)
    #this could be optimized creating empty numpy arrays first and doing only one loop to fill them

After that, we must understand that if we're giving the entire sequence to the embedding, we must also pass the entire sequence to the model. For that, I think it's best to reshape the inputs to have "one sample" of many time steps (unless you really have more than one sequence):

intInputs = intInputs.reshape((1,seqLength))
floatInputs = floatInputs.reshape((1,seqLength,2))

Then we go to the model:

input_id=Input((seqLength,))
input_v =Input((seqLength,2))

embed_id = Embedding(output_dim=3,input_dim=20,input_length=seqLength)(input_id)
    #are you sure "input_dim" is 20? Normally you should have the total amount of existing Ids, and I suppose this should at least be the last id+1.

With this, the concatenation will have shapes (None,seqLength,3), (None,seqLength,2), and you will be able to concat in the last axis (the others are equal in length).

input_merged = Concatenate(axis=-1)([embed_id,input_v])

And the LSTM receives the input as any other layer:

lstm = LSTM(40)(input_merged)


问:
install sonata ecommerce with composer.phar update
when i try to install sonata ecommerce with composer.phar update

error [runtimeExeption] Could not load package
  orange-opensource/orange-boosted-bootstrap in http://packagist.org:
  [unexpectedValueException] Could not parse version constraint
  v4.0.0-alpha.3.1 Invalid version string "v4.0.0-alpha.3.1" .

composer.json

```<code>{
"name": "symfony/framework-standard-edition",
"license": "MIT",
"type": "project",
"description": "The \"Symfony Standard Edition\" distribution",
"autoload": {
    "psr-0": {
        "": "src/"
    }
},
"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.7.*",
    "doctrine/orm": "~2.4,>=2.4.5",
    "doctrine/doctrine-bundle": "1.5.*",
     "twig/extensions": "1.2.*",
    "symfony/assetic-bundle": "2.3.*",
    "symfony/swiftmailer-bundle": "2.3.*",
    "symfony/security":  "@stable",
    "symfony/monolog-bundle": "@stable",
   "sensio/distribution-bundle": "4.0.*",
    "sensio/framework-extra-bundle": "3.0.*",
    "sensio/generator-bundle": "2.3.*",
    "leafo/lessphp": "*",
    "twitter/bootstrap": "*",
    "friendsofsymfony/jsrouting-bundle": "@stable",
    "friendsofsymfony/user-bundle": "@stable",
    "incenteev/composer-parameter-handler": "~2.0",
    "friendsofsymfony/comment-bundle":"@stable",
    "sonata-project/core-bundle": "@stable",
    "sonata-project/media-bundle": "2.3.3",
    "sonata-project/admin-bundle": "@stable",
    "sonata-project/doctrine-orm-admin-bundle": "@stable",
    "knplabs/knp-paginator-bundle": "@stable",
    "sonata-project/translation-bundle": "~1",
    "a2lix/translation-form-bundle": "1.*@dev",
    "a2lix/i18n-doctrine-bundle": "^0.1.0",
    "jordillonch/crud-generator": "dev-master",
    "knplabs/doctrine-behaviors": "@stable",
    "doctrine/doctrine-fixtures-bundle": "@stable",
    "sonata-project/user-bundle": "@stable",
    "fp/jsformvalidator-bundle":"@stable",
    "ensepar/html2pdf-bundle" : "@stable",
    "sonata-project/ecommerce": "@stable",
    "ibrows/newsletter-bundle": "*"

},
"scripts": {
    "post-install-cmd": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ],
    "post-update-cmd": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ]
},
"config": {
    "bin-dir": "bin"
},
"minimum-stability": "stable",
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": {
        "dev-master": "2.3-dev"
    }
}
</code>```

}

答:
Your composer.json file seems fine - I was able to run it with "composer.phar update" without any issue.

Try updating composer with "composer.phar self-update" and clearing it's cache with "composer.phar clear-cache".

Body:
when i try to install sonata ecommerce with composer.phar update

error [runtimeExeption] Could not load package
  orange-opensource/orange-boosted-bootstrap in http://packagist.org:
  [unexpectedValueException] Could not parse version constraint
  v4.0.0-alpha.3.1 Invalid version string "v4.0.0-alpha.3.1" .

composer.json

{
"name": "symfony/framework-standard-edition",
"license": "MIT",
"type": "project",
"description": "The \"Symfony Standard Edition\" distribution",
"autoload": {
    "psr-0": {
        "": "src/"
    }
},
"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.7.*",
    "doctrine/orm": "~2.4,>=2.4.5",
    "doctrine/doctrine-bundle": "1.5.*",
     "twig/extensions": "1.2.*",
    "symfony/assetic-bundle": "2.3.*",
    "symfony/swiftmailer-bundle": "2.3.*",
    "symfony/security":  "@stable",
    "symfony/monolog-bundle": "@stable",
   "sensio/distribution-bundle": "4.0.*",
    "sensio/framework-extra-bundle": "3.0.*",
    "sensio/generator-bundle": "2.3.*",
    "leafo/lessphp": "*",
    "twitter/bootstrap": "*",
    "friendsofsymfony/jsrouting-bundle": "@stable",
    "friendsofsymfony/user-bundle": "@stable",
    "incenteev/composer-parameter-handler": "~2.0",
    "friendsofsymfony/comment-bundle":"@stable",
    "sonata-project/core-bundle": "@stable",
    "sonata-project/media-bundle": "2.3.3",
    "sonata-project/admin-bundle": "@stable",
    "sonata-project/doctrine-orm-admin-bundle": "@stable",
    "knplabs/knp-paginator-bundle": "@stable",
    "sonata-project/translation-bundle": "~1",
    "a2lix/translation-form-bundle": "1.*@dev",
    "a2lix/i18n-doctrine-bundle": "^0.1.0",
    "jordillonch/crud-generator": "dev-master",
    "knplabs/doctrine-behaviors": "@stable",
    "doctrine/doctrine-fixtures-bundle": "@stable",
    "sonata-project/user-bundle": "@stable",
    "fp/jsformvalidator-bundle":"@stable",
    "ensepar/html2pdf-bundle" : "@stable",
    "sonata-project/ecommerce": "@stable",
    "ibrows/newsletter-bundle": "*"

},
"scripts": {
    "post-install-cmd": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ],
    "post-update-cmd": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ]
},
"config": {
    "bin-dir": "bin"
},
"minimum-stability": "stable",
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": {
        "dev-master": "2.3-dev"
    }
}

}


问:
Convert Keras model to CoreML on Ubuntu
Is it possible to convert Keras model to Apple's CoreML on Ubuntu?  </p>

<p>Is OSX required to run the scripts in the page Converting Trained Models to Core ML  </p>

答:
Keras 2 and Sklearn converters in coremltools 0.4.0 definitely work fine on Ubuntu.
I've just trained several models and converted them on Ubuntu. After importing to Xcode everything works.</p>

Title: Convert Keras model to CoreML on Ubuntu

Body:
Is it possible to convert Keras model to Apple's CoreML on Ubuntu?

Is OSX required to run the scripts in the page Converting Trained Models to Core ML


问:
Recursive-ish query for tags?
I have a table of tags that can be linked to other tags and I want to "recursively" select the tags in order of arrangement. So that when a search is made, we get the immediate (1-level) results and then carry on down to say 5-levels so that we always have a list of tags no matter if there wasn't enough exact matches on level 1.

I can manage this fine with making multiple queries until I get enough results, but surely there is a better, optimized, way via a one-trip query?

Any tips will be appreciated.
Thanks!

Results:

```<code>tagId, tagWord, child, child tagId
'513', 'Slap', 'Hog Slapper', '1518'
'513', 'Slap', 'Corporal Punishment', '147'
'513', 'Slap', 'Impact Play', '1394'
</code>```

Query:

```<code>SELECT t.tagId, t.tagWord as tag, tt.tagWord as child, tt.tagId as childId

FROM platform.tagWords t

INNER JOIN platform.tagsLinks l ON l.parentId = t.tagId
INNER JOIN platform.tagWords tt ON tt.tagId = l.tagId

WHERE t.tagWord = 'slap'
</code>```

Table Layouts:

```<code>mysql> explain tagWords;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| tagId   | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| tagWord | varchar(45)         | YES  | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> explain tagsLinks;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| tagId    | bigint(20) unsigned | NO   |     | NULL    |       |
| parentId | bigint(20)          | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
</code>```

答:
Here are the options that I consider each time I find myself in a situation when I need to query hierarchical data.

Nested Sets

Path enumeration

Explicit joins (when the maximum level is known)

Vendor Extensions (SQL Server CTE, Oracle Connect by etc)

Stored Procedures

Suck it up

Title: Recursive-ish query for tags?

Body:
I have a table of tags that can be linked to other tags and I want to "recursively" select the tags in order of arrangement. So that when a search is made, we get the immediate (1-level) results and then carry on down to say 5-levels so that we always have a list of tags no matter if there wasn't enough exact matches on level 1.

I can manage this fine with making multiple queries until I get enough results, but surely there is a better, optimized, way via a one-trip query?

Any tips will be appreciated.
Thanks!

Results:

tagId, tagWord, child, child tagId
'513', 'Slap', 'Hog Slapper', '1518'
'513', 'Slap', 'Corporal Punishment', '147'
'513', 'Slap', 'Impact Play', '1394'

Query:

SELECT t.tagId, t.tagWord as tag, tt.tagWord as child, tt.tagId as childId

FROM platform.tagWords t

INNER JOIN platform.tagsLinks l ON l.parentId = t.tagId
INNER JOIN platform.tagWords tt ON tt.tagId = l.tagId

WHERE t.tagWord = 'slap'

Table Layouts:

mysql> explain tagWords;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| tagId   | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| tagWord | varchar(45)         | YES  | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> explain tagsLinks;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| tagId    | bigint(20) unsigned | NO   |     | NULL    |       |
| parentId | bigint(20)          | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)


问:
When to choose multiple loops over single loop with if-statements
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

Would a different approach like this improve anything?

```<code>std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}
</code>```

答:
The first one has fewer statements (which is always a good rough guide: fewer similar statements often means better performance), but above everything else, it is far more readable.

Don't micro-optimise: leave that to the compiler.

If you are in any doubt check the generated assembly / profile the performance.

Finally (apologise, for I couldn't resist), if nums was a std::vector<unsigned>, then you could have written

```<code>for (std::size_t i = 0; i < nums.size(); ++i){
    nums[i] *= (nums[i] <= 3 ? 0 : nums[i]);
}
</code>```

which could help the branch predictor.

Body:
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}

Would a different approach like this improve anything?

std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}

Body:
The first one has fewer statements (which is always a good rough guide: fewer similar statements often means better performance), but above everything else, it is far more readable.

Don't micro-optimise: leave that to the compiler.

If you are in any doubt check the generated assembly / profile the performance.

Finally (apologise, for I couldn't resist), if nums was a std::vector<unsigned>, then you could have written

for (std::size_t i = 0; i < nums.size(); ++i){
    nums[i] *= (nums[i] <= 3 ? 0 : nums[i]);
}

which could help the branch predictor.


问:
angular 4 http.post not sending or working
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

```<code>this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
</code>```

...or...

```<code>this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })
</code>```

...or...

```<code> var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})
</code>```

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

答:
My mistake. I have been following a tutorial that included a fake backend script for testing which has been affecting all requests.

Just in case someone is having the same problem or has been following this tutorial; http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial make sure to disable the fake backend.

I simply removed these providers;

```<code>import { fakeBackendProvider } from './_helpers/fake-backend';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions } from '@angular/http';
</code>```

Body:
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);

...or...

this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })

...or...

 var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

Body:
My mistake. I have been following a tutorial that included a fake backend script for testing which has been affecting all requests.

Just in case someone is having the same problem or has been following this tutorial; http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial make sure to disable the fake backend.

I simply removed these providers;

import { fakeBackendProvider } from './_helpers/fake-backend';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions } from '@angular/http';


问:
How to determine the current section in a UITableView from a button press in the header
I have a button that is in a table header view and need the action to be able to determine in which section button is pressed (which header)

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let view = UIView(frame: CGRect(x:0, y:0, width: tableView.frame.size.width, height: 28))
    let button = UIButton(type: UIButtonType.system)
    button.setTitle("+", for: UIControlState.normal)
    button.addTarget(self, action: #selector(GLAccountTableViewController.buttonTouched), for: UIControlEvents.touchUpInside)
    view.addSubview(button)
    return view
}
</code>```

Is there a way to identify which section button is pressed?

答:
If I understand you correctly you need somehow to trigger the button click in headerView.

You can add a tag refer to the section when creating the button

```<code>button.tag = section
</code>```

Then in your onclick function you know in which section the button was pressed.

Body:
I have a button that is in a table header view and need the action to be able to determine in which section button is pressed (which header)

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let view = UIView(frame: CGRect(x:0, y:0, width: tableView.frame.size.width, height: 28))
    let button = UIButton(type: UIButtonType.system)
    button.setTitle("+", for: UIControlState.normal)
    button.addTarget(self, action: #selector(GLAccountTableViewController.buttonTouched), for: UIControlEvents.touchUpInside)
    view.addSubview(button)
    return view
}

Is there a way to identify which section button is pressed?

Body:
If I understand you correctly you need somehow to trigger the button click in headerView.

You can add a tag refer to the section when creating the button

button.tag = section

Then in your onclick function you know in which section the button was pressed.


问:
How to store in file outputs of a c/c++ program in unix
I have a program made on c++, let's call it program, which has a lot of output while running. I want to log that output on a file so is easier then to look at it. I tried already ./program & > file ./program & |tee file but it doesnt work (I want to run it in background if posible).

any idea?

Thanks

EDIT: It doesnt work ./program > file. I tried putting it on background, on foreground, but the file is empty....

答:
Redirect (>, 2>, 2>&1, etc) is the standard way of achieving this. However, this doesn't work in all possible scenarios.

Use script to capture everything displayed on your terminal:

script -c "./program arg1 --arg2" output.log


问:
Error in my PDO execute function
I have the following query:

```<code>SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc
</code>```

and array passed in execute function is :

```<code>Array
(
    [0] => 1
    [1] => rahul
)
</code>```

it is giving me error ..

```<code>Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179
</code>```

why this error is coming please suggest.

答:
This is most likely your problem:

```<code>CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
</code>```

Binding parameters does not work that way, you need to change it to

```<code>CONCAT_WS(' ',firstname,lastname)  end)  like ?
</code>```

and extend the value you're passing in with the wildcards.

Title: Error in my PDO execute function

Body:
I have the following query:

SELECT case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end
                     as cname ,cardid,card_type,isDeck,userid_from,status,cards.gibid,message ,userid_to,description,tagline,gibs.preview_thumb
                    ,case when  userid_from=userid_to then 'my card ' else 'other 'end as owner
            FROM cards LEFT JOIN gibs ON gibs.gibid=cards.gibid
                left join users on users.userid=cards.userid_from
            WHERE userid_to=? and cards.deleted='N'  and (case when card_type='A'  then name else  CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'
            order by status,card_type desc,owner,cname,isDeck desc

and array passed in execute function is :

Array
(
    [0] => 1
    [1] => rahul
)

it is giving me error ..

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/ryapi/Db.php on line 176

Fatal error: Uncaught exception 'PDOException' with message 'Database error [HY093]: , driver error code is ' in /var/www/ryapi/Db.php:179
Stack trace:
#0 /var/www/ryapi/Db.php(93): Db::_query('SELECT case whe...', Array)
#1 /var/www/ryapi/card.php(152): Db::getResult('SELECT case whe...', Array)
#2 /var/www/ryapi/index.php(103): Card->getcardlist('1', '', 'rahul')
#3 {main}
  thrown in /var/www/ryapi/Db.php on line 179

why this error is coming please suggest.

Body:
This is most likely your problem:

CONCAT_WS(' ',firstname,lastname)  end)  like '%?%'

Binding parameters does not work that way, you need to change it to

CONCAT_WS(' ',firstname,lastname)  end)  like ?

and extend the value you're passing in with the wildcards.


答:
You should not use keydown event because it is one keypress "behind" of what's written into input value.

Ideally you should use oninput (not even keyup as suggested by everyone, but @mplungjan who was faster :). oninput will also allow you to properly track copy/past events unlike onkeyup.

In addition, read input value by simply this.value but remember to trim it also to get rid of whitespaces.

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if (this.value.trim()) {
      $(".removetext").show();
    } else {
      $(".removetext").hide();
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}</code>```

  <input type="text" class="search-hotels">

×

```

Title: How does the keydown event work?

Body:
I want that if my input text value is not empty then show my .removetext div but it doesn't work properly. If you type a something after second character my .removetext is being hidden but if my input is not empty don't hide my .removetext class.

Where is my mistake? I guess I don't understand the keydown event

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    if (!val == "") {
      $(".removetext").show(val.length > 0, function() {
        var clear = $(this);
        clear.on('click', function() {
          alert('hey');
        })
      });
    } else {
      $(".removetext").hide();
    }
  });

});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

  <input type="text" class="search-hotels">

×

Body:
You should not use keydown event because it is one keypress "behind" of what's written into input value.

Ideally you should use oninput (not even keyup as suggested by everyone, but @mplungjan who was faster :). oninput will also allow you to properly track copy/past events unlike onkeyup.

In addition, read input value by simply this.value but remember to trim it also to get rid of whitespaces.

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if (this.value.trim()) {
      $(".removetext").show();
    } else {
      $(".removetext").hide();
    }
  })
});

.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}

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

<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>


问:
My ASP.NET Application - Drives me crazy, can't remove it
So I edited:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #AboutMeSection {
            border-right: 1px dashed #333;
                min-height:100px;
                height:100px;
        }

    </style>
    <title>@ViewBag.Title - Adam Kościelniak</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("//tinymce.cachefly.net/4.0/tinymce.min.js")
    <script>
    tinymce.init({ selector: 'textarea' });
    </script>

</head>
</code>```

of _Layout.cshtml

in the view I simply do:

```<code>@model KoscielniakInfo.ViewModels.CV
@{
    ViewBag.Title = "My Virtual CV";
}
</code>```

Even changed the _ViewStart.cshtml so it explicitly changes it:

```<code>@{
    ViewBag.Title = "Adam Kościelniak Homepage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
</code>```

NOTHING still after a 10 deploys I go to my domain:
adamkoscielniak.pl
and see this:

Where else can I change this? What am I missing?
The full project is on github...
https://github.com/Tackgnol/KoscielniakInfo

Web Deploy Screenshot:

答:
This is in your layout template. From the top of the solution, look into the folder Views > Shared > _Layout.cshtml

In the header lines

```<code><title>@ViewBag.Title - My ASP.NET Application</title>
</code>```

If you every run into something like this that you cannot find then you can also do ctrl + F to open up the search panel and search for the characters through the entire solution to locate where they are.

Edit: Just read you were modifying the _layout file. Just do the ctrl + f and search for the string solution wide.

Edit: Just downloaded your solution and that line is literally nowhere. Make sure you are deleting all the current files in the directory when you deploy the new code. Just manually delete and redeploy the first time then change your settings to remove all files on deploy after that. Also do a ctrl f5 to make sure your browser isnt caching the header info once you redeploy.

Body:
So I edited:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>@ViewBag.Title - Adam Kościelniak</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("//tinymce.cachefly.net/4.0/tinymce.min.js")

of _Layout.cshtml

in the view I simply do:

@model KoscielniakInfo.ViewModels.CV
@{
    ViewBag.Title = "My Virtual CV";
}

Even changed the _ViewStart.cshtml so it explicitly changes it:

@{
    ViewBag.Title = "Adam Kościelniak Homepage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

NOTHING still after a 10 deploys I go to my domain:
adamkoscielniak.pl
and see this:

Where else can I change this? What am I missing?
The full project is on github...
https://github.com/Tackgnol/KoscielniakInfo

Web Deploy Screenshot:

Body:
This is in your layout template. From the top of the solution, look into the folder Views > Shared > _Layout.cshtml

In the header lines

<title>@ViewBag.Title - My ASP.NET Application</title>

If you every run into something like this that you cannot find then you can also do ctrl + F to open up the search panel and search for the characters through the entire solution to locate where they are.

Edit: Just read you were modifying the _layout file. Just do the ctrl + f and search for the string solution wide.

Edit: Just downloaded your solution and that line is literally nowhere. Make sure you are deleting all the current files in the directory when you deploy the new code. Just manually delete and redeploy the first time then change your settings to remove all files on deploy after that. Also do a ctrl f5 to make sure your browser isnt caching the header info once you redeploy.


问:
Return both string and integer from a template function in C++
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
</code>```

and I would like to be able to call it like:

```<code>bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
</code>```

as an alternative for the char*, a string would be also fine:

```<code>string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
</code>```

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

答:
I think I'd be inclined to leverage the already-excellent functionality of std::tuple.

Combine that with tagged values and it's possible to produce expressive, type-safe code for this kind of thing with minimal effort.

```<code>#include <iostream>
#include <tuple>

template<class Tag, class Type>
struct xmlvalue : Type
{
    using Type::Type;
};

template<class Tag> struct xmlvalue<Tag, bool>
{
    xmlvalue(bool v) : value_(v) {}

    operator bool&() { return value_; }
    operator bool const&() const { return value_; }

private:
    bool value_;
};

template<class Tag> struct xmlvalue<Tag, int>
{
    xmlvalue(int v) : value_(v) {}

    operator int&() { return value_; }
    operator int const&() const { return value_; }

private:
    int value_;
};

struct is_publisher_tag {};
struct qos_tag {};
struct broker_url_tag {};

using is_publisher = xmlvalue<is_publisher_tag, bool>;
using qos = xmlvalue<qos_tag, int>;
using broker_url = xmlvalue<broker_url_tag, std::string>;

struct quote : std::tuple<is_publisher , qos, broker_url >
{
    using std::tuple<is_publisher , qos, broker_url >::tuple;
};

int main() {

    auto q1 = quote(true, 100, "http:://foo.com");
    auto q2 = quote(false, 50, "http:://bar.com");

    std::cout << std::get<broker_url>(q1) << ", " << std::get<qos>(q1) << ", " << std::get<is_publisher>(q1) << std::endl;
    std::cout << std::get<broker_url>(q2) << ", " << std::get<qos>(q2) << ", " << std::get<is_publisher>(q2) << std::endl;

    return 0;
}
</code>```

expected output:

```<code>http:://foo.com, 100, 1
http:://bar.com, 50, 0
</code>```

Body:
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

Body:
I think I'd be inclined to leverage the already-excellent functionality of std::tuple.

Combine that with tagged values and it's possible to produce expressive, type-safe code for this kind of thing with minimal effort.

#include <iostream>
#include <tuple>

template<class Tag, class Type>
struct xmlvalue : Type
{
    using Type::Type;
};

template<class Tag> struct xmlvalue<Tag, bool>
{
    xmlvalue(bool v) : value_(v) {}

    operator bool&() { return value_; }
    operator bool const&() const { return value_; }

private:
    bool value_;
};

template<class Tag> struct xmlvalue<Tag, int>
{
    xmlvalue(int v) : value_(v) {}

    operator int&() { return value_; }
    operator int const&() const { return value_; }

private:
    int value_;
};

struct is_publisher_tag {};
struct qos_tag {};
struct broker_url_tag {};

using is_publisher = xmlvalue<is_publisher_tag, bool>;
using qos = xmlvalue<qos_tag, int>;
using broker_url = xmlvalue<broker_url_tag, std::string>;

struct quote : std::tuple<is_publisher , qos, broker_url >
{
    using std::tuple<is_publisher , qos, broker_url >::tuple;
};

int main() {

    auto q1 = quote(true, 100, "http:://foo.com");
    auto q2 = quote(false, 50, "http:://bar.com");

    std::cout << std::get<broker_url>(q1) << ", " << std::get<qos>(q1) << ", " << std::get<is_publisher>(q1) << std::endl;
    std::cout << std::get<broker_url>(q2) << ", " << std::get<qos>(q2) << ", " << std::get<is_publisher>(q2) << std::endl;

    return 0;
}

expected output:

http:://foo.com, 100, 1
http:://bar.com, 50, 0


问:
Is it possible to rename default "Declarative: Checkout SCM" step?
When you use Jenkins multibranch pipeline, the first stage is named by default Declarative: Checkout SCM.

Is it possible to rename it? I know that it is possible to skip default checkout, but I do not want this - I just want to rename this default step.

答:
Since noone posted a better solution, I just did it this way:</p>

```<code>...
options {
    skipDefaultCheckout(true)
}
stages {
    stage('However I want to name a stage') {
        steps {
            checkout scm
...
</code>```

Body:
Since noone posted a better solution, I just did it this way:

...
options {
    skipDefaultCheckout(true)
}
stages {
    stage('However I want to name a stage') {
        steps {
            checkout scm
...


问:
SQL Server: SUM multiple rows depending on a conditon
My table looks like this (I work at an energy company)

```<code>dte             hub            Peak            Offpeak
07-04-2017      SoCo           36.19           18.23
07-04-2017      SwapBID        0.5             0.25
07-05-2017      SoCo           32.12           21.72
07-05-2017      SwapBID        0.25            0.25
07-06-2017      SoCo           33.87           20.34
07-06-2017      SwapBID        0.5             0.5
</code>```

I want to be able to pull the data from this table using a select query and make it so that the two hubs' peak and offpeak prices are added together for the same days. For example, on the day 07/04/2017 i want it to show that the Peak was 36.69 and the Offpeak was 18.48. I would like to do this for every day in the table. How do I code this?

答:
You're looking for  aggregationsgroup by

Try :

```<code>create table #t(dte date,hub varchar(100),Peak float,Offpeak float)
insert into #t values
('07-04-2017','SoCo',36.19,18.23),
('07-04-2017', 'SwapBID',0.5,0.25),
('07-05-2017','SoCo',32.12,21.72),
('07-05-2017','SwapBID',0.25,0.25),
('07-06-2017', 'SoCo,33.87,20.34),
('07-06-2017', 'SwapBID',0.5,0.5 )

select dte,
sum(Peak) as total_peak,
sum(Offpeak) as total_offpeak
 from #t
group by dte
</code>```

Body:
My table looks like this (I work at an energy company)

dte             hub            Peak            Offpeak
07-04-2017      SoCo           36.19           18.23
07-04-2017      SwapBID        0.5             0.25
07-05-2017      SoCo           32.12           21.72
07-05-2017      SwapBID        0.25            0.25
07-06-2017      SoCo           33.87           20.34
07-06-2017      SwapBID        0.5             0.5

I want to be able to pull the data from this table using a select query and make it so that the two hubs' peak and offpeak prices are added together for the same days. For example, on the day 07/04/2017 i want it to show that the Peak was 36.69 and the Offpeak was 18.48. I would like to do this for every day in the table. How do I code this?

Body:
You're looking for  aggregationsgroup by

Try :

create table #t(dte date,hub varchar(100),Peak float,Offpeak float)
insert into #t values
('07-04-2017','SoCo',36.19,18.23),
('07-04-2017', 'SwapBID',0.5,0.25),
('07-05-2017','SoCo',32.12,21.72),
('07-05-2017','SwapBID',0.25,0.25),
('07-06-2017', 'SoCo,33.87,20.34),
('07-06-2017', 'SwapBID',0.5,0.5 )

select dte,
sum(Peak) as total_peak,
sum(Offpeak) as total_offpeak
 from #t
group by dte


问:
Is a browser required for Onedrive/Graph Authentication
It appears via the OneDrive API documentation that a user must always "authenticate" using a web-browser to access the OneDrive API.  This is not helpful for system accounts.  Am I interpreting this correctly?  Or is there a way to achieve step one without a browser:

Step 1. Get an authorization code

To start the sign-in process with the code flow, use a web browser or web-browser control to load this URL request.

```<code>GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}
  &response_type=code&redirect_uri={redirect_uri}
</code>```

https://dev.onedrive.com/auth/graph_oauth.htm#code-flow

答:
What you're looking for is an App-Only integration. See Get access without a user for details on how this process works.

Keep in mind that there are scope differences between app-only and delegated scenarios. Also, app-only scenarios will require Admin Consent before they can operate against a given tenant (see v2 Endpoint and Admin Consent).

Body:
It appears via the OneDrive API documentation that a user must always "authenticate" using a web-browser to access the OneDrive API.  This is not helpful for system accounts.  Am I interpreting this correctly?  Or is there a way to achieve step one without a browser:

Step 1. Get an authorization code

To start the sign-in process with the code flow, use a web browser or web-browser control to load this URL request.

GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}
  &response_type=code&redirect_uri={redirect_uri}

https://dev.onedrive.com/auth/graph_oauth.htm#code-flow


问:
Is there any reason C++ 11+ std::mutex should be declared as a global variable instead of passed into a std::thread as a function parameter?
I've seen most examples using std::mutex where the mutex is global.  I was wondering is there any specific reason why this is done?  I've had programs of my own where I don't do this, and simply pass the mutex in as a std::thread std::ref.  Isn't it bad practice to have globals, what is the rational behind global std::mutexes in C++ if there is no language restricting reason to do this?

答:
Most likely this was done to make the example easier to follow, allowing the use of the mutex itself to be the focus of the example rather than the exact specifics.

Typically a mutex protects a resource and in many cases it makes sense for the mutex to live alongside the resource. For example if you have a class with a member container that needs to be protected by a mutex, make the mutex also a member of the class. Then as the class instance is acted on by multiple threads the member-mutex can be used to protect the needed accesses to the internal container.


问:
Angular2 update field and sum + 1 (save to firebase)
I´m trying to update a field on my firebase. I´d like to sum 1 to the field and save on firebase

See the code:

```<code> this.chat1
      .update({
        lastMessage: newMessage,
        timestamp: currentTimestamp,
        unreadMessage: unreadMessage + 1 //HERE. Trying to sum the field + 1
      });
</code>```

What is the best way to do it?

答:
use the firebase transaction method.

as I know this method is not available with angularfire2, so you will have to extract the reference:

```<code>this.chat1.$ref
    .ref.transaction(unreadMessage => {
        if (unreadMessages === null) {
            return unreadMessage = 1;
        } else {
            return unreadMessage + 1;
        }
    })
</code>```

read more about saving date as trasncations here

Body:
I´m trying to update a field on my firebase. I´d like to sum 1 to the field and save on firebase

See the code:

 this.chat1
      .update({
        lastMessage: newMessage,
        timestamp: currentTimestamp,
        unreadMessage: unreadMessage + 1 //HERE. Trying to sum the field + 1
      });

What is the best way to do it?

Body:
use the firebase transaction method.

as I know this method is not available with angularfire2, so you will have to extract the reference:

this.chat1.$ref
    .ref.transaction(unreadMessage => {
        if (unreadMessages === null) {
            return unreadMessage = 1;
        } else {
            return unreadMessage + 1;
        }
    })

read more about saving date as trasncations here