问:
Eclipse Kepler not connecting to internet via proxy
I have managed to get Eclipse Juno connecting to the internet. For this to accomplish, there are many posts here on stackoverflow. here is one of this links:
Eclipse not connecting to internet via proxy

Today i installed Eclipse Kepler on my Windows7 box. But accessing the eclipse marketplace or installing new software does not work.
I am using exactly the same proxy configuration as i used for Eclipse Juno. Juno can access the marketplace but Kepler does not.
The proxy uses NTLM Authentification.
Any one here with similar problem?

No success til now. I am still wondering why Juno can connect whereas Kepler can not:-(

答:
I had this issue, and i changed the proxy settings with password in eclipse.
go to windows-> preferences-> search for "proxy"
open Network connections.

Select Active Provider to Manual.
Set HTTP and HTTPS proxy, system username and password.
(it was not working without username and password in my machine)

Clear SOCKS proxy if its set.

File-> Restart


来源: stackexchange

问:
Formatting the header of a GridView control using Bootstrap
I've tried the other solutions offered here for formatting the header of an ASP.NET GridView control using Bootstrap, and I still can't get it to work properly.  I'm trying to make sure the header text of each column is centered, and it isn't happening, despite my best efforts.  I also need the zebra-striping to work for alternating rows, but that doesn't work either, although the hover on rows works.  Finally, the code that should fire when a row is selected doesn't fire, although there are no compile errors, so I don't get it.

Here's the HTML for the GridView:

```<code>        <div class="row">
            <asp:GridView ID="gvPlans" runat="server" AllowPaging="true" AllowSorting="true"
                PageSize="10" DataKeyNames="PlanID" AutoGenerateColumns="false"
                CssClass="table table-striped " DataSourceID="objPlans"
                OnPreRender="gvPlans_PreRender" OnSelectedIndexChanged="gvPlans_SelectedIndexChanged">
                <Columns>
                    <asp:BoundField DataField="PlanTitle" HeaderText="Title" ItemStyle-Width="55%"
                        ItemStyle-HorizontalAlign="Left" />
                    <asp:BoundField DataField="BasePrice" HeaderText="Price"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField DataField="MonthlyFee" HeaderText="Fee"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField DataField="TotalPrice" HeaderText="Total"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                </Columns>
            </asp:GridView>
        </div>
</code>```

Following the advice of several other posts, I added a PreRender event that should fix the problem.  There's also an event to capture when a row is selected.  Here's the code for that:

```<code>    protected void gvPlans_PreRender(object sender, EventArgs e)
{
    try
    {
        gvPlans.UseAccessibleHeader = true;
        gvPlans.HeaderRow.TableSection = TableRowSection.TableHeader;
        gvPlans.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
    }
    catch
    { }
}

protected void gvPlans_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = gvPlans.SelectedRow;

    planID = Convert.ToInt32(gvPlans.SelectedDataKey.Value);
    Plan plan = PlanDB.Get(planID);
}
</code>```

I've added code to each of the data column declarations to set the header column to center, and it doesn't work either.  Using the code above, here's what I get:

I would note that the formatting for the columns themselves works fine, as evidenced by the right-alignment of the number columns.

To summarize, I can't get the zebra-striping or the header column alignment to work, and the "SelectedIndexChanged" event doesn't fire.  I'll be danged if  understand why this is such a pain!  Any help would be appreciated.

答:
Add this to your .css file:

```<code>#gvPlans th {
       align: center;
}
</code>```

You overwrite the default styling for the '.th' class provided by Bootstrap.

ContentLicense: CC BY-SA 3.0

Body:
I've tried the other solutions offered here for formatting the header of an ASP.NET GridView control using Bootstrap, and I still can't get it to work properly.  I'm trying to make sure the header text of each column is centered, and it isn't happening, despite my best efforts.  I also need the zebra-striping to work for alternating rows, but that doesn't work either, although the hover on rows works.  Finally, the code that should fire when a row is selected doesn't fire, although there are no compile errors, so I don't get it.

Here's the HTML for the GridView:

            <asp:GridView ID="gvPlans" runat="server" AllowPaging="true" AllowSorting="true"
                PageSize="10" DataKeyNames="PlanID" AutoGenerateColumns="false"
                CssClass="table table-striped " DataSourceID="objPlans"
                OnPreRender="gvPlans_PreRender" OnSelectedIndexChanged="gvPlans_SelectedIndexChanged">
                <Columns>
                    <asp:BoundField DataField="PlanTitle" HeaderText="Title" ItemStyle-Width="55%"
                        ItemStyle-HorizontalAlign="Left" />
                    <asp:BoundField DataField="BasePrice" HeaderText="Price"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField DataField="MonthlyFee" HeaderText="Fee"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                    <asp:BoundField DataField="TotalPrice" HeaderText="Total"
                        ItemStyle-Width="15%" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Right" />
                </Columns>
            </asp:GridView>

Following the advice of several other posts, I added a PreRender event that should fix the problem.  There's also an event to capture when a row is selected.  Here's the code for that:

    protected void gvPlans_PreRender(object sender, EventArgs e)
{
    try
    {
        gvPlans.UseAccessibleHeader = true;
        gvPlans.HeaderRow.TableSection = TableRowSection.TableHeader;
        gvPlans.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
    }
    catch
    { }
}

protected void gvPlans_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = gvPlans.SelectedRow;

    planID = Convert.ToInt32(gvPlans.SelectedDataKey.Value);
    Plan plan = PlanDB.Get(planID);
}

I've added code to each of the data column declarations to set the header column to center, and it doesn't work either.  Using the code above, here's what I get:

I would note that the formatting for the columns themselves works fine, as evidenced by the right-alignment of the number columns.

To summarize, I can't get the zebra-striping or the header column alignment to work, and the "SelectedIndexChanged" event doesn't fire.  I'll be danged if  understand why this is such a pain!  Any help would be appreciated.

Body:
Add this to your .css file:

#gvPlans th {
       align: center;
}

You overwrite the default styling for the '.th' class provided by Bootstrap.


问:
How to install fluorinefx with support for .net framework 4.0?
I'm trying to integrate Flex and .net framework 4.0 classes, weborb is way too expensive and the only other option I have stumbled upon is fluorinefx but the installer on it's website doesn't support .net 4.0 and after downloading it's source code there is no clue about how to integrate it, no documentation at all and no answer on it's forum.

Have anyone been able to do this? and if so, how?

note: XML, JSON and such are not useful for me as the apps are data intensive, I'm looking for something that does the same job as weborb, fluorinefx, blazeds, etc for .net framework 4.0, fluorinefx seemed promising until I realized the forums are dead and there is absolutely no updated documentation.

答: Just in case if you missed it, WebORB Community Edition is absolutely free and does support .NET Framework 4.0. See this for more details: http://www.themidnightcoders.com/products/weborb-for-net/producteditions.html </p>

ContentLicense: CC BY-SA 2.5


问:
Difference between Google App Engine Flexible and Google Container Engine?
Specific to Docker based deployment, what are the differences between those two? Since Google App Engine Flexible now also supports Dockerfile based deployment and it is also fully-managed service, seems it's more preferred option rather than configuring Kubernetes deployment on Container Engine, isn't it?

What are the use cases where it's more preferred to use Google Container Engine over App Engine Flexible?

答:
They are different things. App Engine Flexible is focused on application development - i.e. you have an application and you want to be deployed and managed by Google). On the other hand, Kubernetes is more about having your own infrastructure. Obviously, you can also deploy applications in Kubernetes but, as it's your "own" infrastructure, you are the one to directly manage how both the and the application will behave  (create services, create scalability policies, RBAC, security policies...).

In this sense, Kubernetes is more flexible in what you can achieve. However, as a developer, you may not be interested in the infrastructure at all, only that your application works and scales. For this kind of profile, App Engine Flexible is more suitable.

If, on the other side, want to manage a complete Container infrastructure (more SRE profile), then Kubernetes is for you.


问:
If/else variable assigned before if statement executed
The first instance of the number_of_discs receives data from another page and this value is visible in the form.

```<code>#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form = SendForm()

        number_of_discs = request.args.get('number_of_discs', '')
</code>```

In the below code, If the function form.validate_on_submit() returns False, I want the number_of_discs variable to be reassigned the value that has been typed into the form to amended the original data.

```<code>#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form = SendForm()

        number_of_discs = request.args.get('number_of_discs', '')

        if form.validate_on_submit():
                        try:
                                models.insert(form)
                        except:
                                print ("hasn't worked")
                        else:
                                return redirect(url_for('success'))
        else:
                        number_of_discs = form.number_of_discs.data

        return render_template(
        'results.html', title='Results', number_of_discs=number_of_discs, form=form

    )
</code>```

It works to an extent in that the variable is reassigned whatever is typed into the form. However, my problem now is that when I first load the page, the number_of_discs variable in the else statement seems to be initialized as the default value, rather than the first declaration of the number_of_discs variable (i.e. the data from the other page). So to summarize, the variable in the if/else statement seems to precede the variable assigned before/outside of it.

答:
You can avoid overwriting that default value by
executing the current if/else only when the request is 'POST':

```<code>@app.route('/results', methods=['GET', 'POST'])
def results():
   ...
   number_of_discs = request.args.get('number_of_discs', '')
   if request.method == 'POST':
      if form.validate_on_submit():
         ...
      else:
         ...
</code>```

Body:
The first instance of the number_of_discs receives data from another page and this value is visible in the form.

#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form = SendForm()

        number_of_discs = request.args.get('number_of_discs', '')

In the below code, If the function form.validate_on_submit() returns False, I want the number_of_discs variable to be reassigned the value that has been typed into the form to amended the original data.

#####Results Page

@app.route('/results', methods=['GET', 'POST'])
def results():
        form = SendForm()

        number_of_discs = request.args.get('number_of_discs', '')

        if form.validate_on_submit():
                        try:
                                models.insert(form)
                        except:
                                print ("hasn't worked")
                        else:
                                return redirect(url_for('success'))
        else:
                        number_of_discs = form.number_of_discs.data

        return render_template(
        'results.html', title='Results', number_of_discs=number_of_discs, form=form

    )

It works to an extent in that the variable is reassigned whatever is typed into the form. However, my problem now is that when I first load the page, the number_of_discs variable in the else statement seems to be initialized as the default value, rather than the first declaration of the number_of_discs variable (i.e. the data from the other page). So to summarize, the variable in the if/else statement seems to precede the variable assigned before/outside of it.

Body:
You can avoid overwriting that default value by
executing the current if/else only when the request is 'POST':

@app.route('/results', methods=['GET', 'POST'])
def results():
   ...
   number_of_discs = request.args.get('number_of_discs', '')
   if request.method == 'POST':
      if form.validate_on_submit():
         ...
      else:
         ...


问:
CSS to target text, headers, blockquotes, after/before images
In my WordPress single.php I have images, text, headers and blockquotes mixed together. I want to be able to apply specific css to each based on their location to the images.

Problem is I have no control over if a blockquote will follow an image, or an h1, or just a regular p tag. For example I don't want to increase the top margin of p tags if there is a h1 tag first after the image, but I do if there isn't an h1 tag, etc.

html

```<code><div id="single-pg" class="row">
    <?php the_content(); ?>
</div>
</code>```

css

I tried JavaScript to wrap text in a container class to no avail, so I'm trying something along the lines of

```<code>#single-pg p { padding:0 20px; }
#single-pg p + img{ margin-top:30px }
</code>```

答:
An option can be trying to target all p tags that are after an image... like the exmaple...

#single-pg p{padding:0 20px; margin-top:0;}

#single-pg img + p{ margin-top:30px; background:red;}

#single-pg img + h1{ background:blue;}

#single-pg img + blockquote{ background:orange;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="single-pg">
    <img src="http://via.placeholder.com/350x150">
    <h1>h1</h1>
    <p>paragraph</p>
</div>

<div id="single-pg">
    <img src="http://via.placeholder.com/350x150">
    <p>paragraph</p>
</div></code>```

Body:
In my WordPress single.php I have images, text, headers and blockquotes mixed together. I want to be able to apply specific css to each based on their location to the images.

Problem is I have no control over if a blockquote will follow an image, or an h1, or just a regular p tag. For example I don't want to increase the top margin of p tags if there is a h1 tag first after the image, but I do if there isn't an h1 tag, etc.

html

    <?php the_content(); ?>

css

I tried JavaScript to wrap text in a container class to no avail, so I'm trying something along the lines of

#single-pg p { padding:0 20px; }
#single-pg p + img{ margin-top:30px }

Body:
An option can be trying to target all p tags that are after an image... like the exmaple...

#single-pg p{padding:0 20px; margin-top:0;}

#single-pg img + p{ margin-top:30px; background:red;}

#single-pg img + h1{ background:blue;}

#single-pg img + blockquote{ background:orange;}

<div id="single-pg">
    <img src="http://via.placeholder.com/350x150">
    <h1>h1</h1>
    <p>paragraph</p>
</div>

<div id="single-pg">
    <img src="http://via.placeholder.com/350x150">
    <p>paragraph</p>
</div>


问:
Solr DIH error while importing data from hive
I am trying to load and index hdfs data in solr 5.1.I stored the data in a  hive table and used DIH to import and index. i followed the steps provided in the link Solr DIH. I couldn't see any material on DIH with hive so Wanted to check if anyone have worked on this . Also looking for some suggestions on the above scenario.</p>

答:
I am able to get it working.
It is very interesting how it worked.

We got the hive2 jars first and made it working on through java to check the connectivity.
Then we realized the jars to be used are :

hadoop-common-2.7.0-mapr-1703.jar

hive-common-2.1.1-mapr-1703-r1.jar

hive-jdbc-2.1.1-mapr-1703-r1-standalone.jar

If you are using SOLR Cloud then these jars are to be transferred to the VM where SOLR is installed and then referenced in solrconfig.xml like this:

Import Part in solrconfig.xml

< lib dir="/users/path_to_folder_with_jar" regex=".*.jar" />

Then this is the most important part: Your hive connection string:

Connection Part

< dataConfig >
< dataSource name="ABC" driver="org.apache.hive.jdbc.HiveDriver" url="jdbc:hive2://....connectionString" user="username" password="password" />

< document name="collection_name">

< entity name="collection_lookup" query="select unique_key as id from table_name">

< /entity>

< /document>

< /dataConfig>

Push config through zookeeper

server/scripts/cloud-scripts/zkcli.sh -zkhost host1:2181,host2:2181 -cmd upconfig -confname configName -confdir server/solr/configsets/folder/

Go to http://host:8983/solr/#/collection_name/dataimport//dataimport
then check debug and first check with 10 or 20 records.

You will see the data flowing. CHEERS !!
I can help if you want to discuss further but I am assuming this should do. It is working for me.

Special thanks to Srini Samudrala for working with me on this.


问:
Oracle Developer Tools (ODT) & Visual Studio 2017 Integration
I need to create ADO.NET model from Oracle 12 DB. We are using VS2017. I've installed ODAC and ODT for VS (2015, since there is no version for 2017) according to recommendations in internet. However, EDMX model creation dialog does not show up Oracle DB in data source list (it's present in Connect to Database dialog section though). My suspicion is ODT for VS2015 is not compatible with VS2017. Is it true?
What i also tried to do was to add ODT.Net.Managed key to Registry with proper path to corresponding DLL, but this did not help either.
Any ideas?

答: Unfortunately, ORACLE ODT for VS2017 is not available, ORACLE has promised the VS2017 for years, but the latest information is that they are in trouble, and the VS2017 will be resolved as soon as it is solved.</p>


问:
If TRUE in one column, change value in other column
I have a character vector: (shortened version shown)

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
</code>```

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

```<code>"10e10" "10e11" "10e10" "10e11"
</code>```

I used startsWith() to create a TRUE/FALSE vector:

```<code>startsWith.e <- startsWith(Unit, "e")
</code>```

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

```<code>while(startsWith.e){
grep("e", "10e", Unit) }
</code>```

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

答:
We can use sub for this.  Match the letter 'e' at the start (^) of the string and replace with '10e'

```<code>sub("^e", "10e", Unit)
#[1] "10e10" "10e11" "10e10" "10e11"
</code>```

Body:
I have a character vector: (shortened version shown)

Unit <- c("e10", "e11", "10e10", "10e11")

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

"10e10" "10e11" "10e10" "10e11"

I used startsWith() to create a TRUE/FALSE vector:

startsWith.e <- startsWith(Unit, "e")

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

while(startsWith.e){
grep("e", "10e", Unit) }

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

Body:
We can use sub for this.  Match the letter 'e' at the start (^) of the string and replace with '10e'

sub("^e", "10e", Unit)
#[1] "10e10" "10e11" "10e10" "10e11"


问:
Where is the PostAsJsonAsync method in ASP.NET Core?
I was looking for the PostAsJsonAsync() extension method in ASP.NET Core. Based on this article, it's available in the Microsoft.AspNet.WebApi.Client assembly.

I had thought Microsoft had changed all of the assembly names from Microsoft.AspNet to Microsoft.AspNetCore to be more specific to .NET Core, however, and yet I cannot find an Microsoft.AspNetCore.WebApi.Client assembly.

Where is the PostAsJsonAsync() extension method in ASP.NET Core?

答:
That is not part of the ASP.NET Core project. However you can proceed with:</p>

```<code>HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://myurl/api");

string json = JsonConvert.SerializeObject(myObj);

request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

HttpClient http = new HttpClient();
HttpResponseMessage response = await http.SendAsync(request);

if (response.IsSuccessStatusCode)
    {
    }
else
    {
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
That is not part of the ASP.NET Core project. However you can proceed with:

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://myurl/api");

string json = JsonConvert.SerializeObject(myObj);

request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

HttpClient http = new HttpClient();
HttpResponseMessage response = await http.SendAsync(request);

if (response.IsSuccessStatusCode)
    {
    }
else
    {
    }


问:
Wordpress single item dynamic content
Wordpress offers great customization for posts, pages and custom post types, but  the only thing I cant figure out is how to make a single item.

Let me give you an example: I have one image on my front page and I want it to be dynamic or maybe I have a telephone in the footer. How can I make them dynamically editable without hardcoding page/post IDs in the theme.

Is this possible without plugins?

答:
You can use the shortcodes (custom or plugin):
https://wordpress.org/plugins/shortbus/
or
php function to /wp-content/your-theme/function.php</p>

Title: Wordpress single item dynamic content


问:
How to enable CORS on server-side code in java
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

```<code>import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

答:
In Jersey, I use the ResourceConfig class to register the CORSFilter. Like ,

```<code>import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;

public class JerseyApplication extends ResourceConfig {
    public JerseyApplication() {
        register(CORSFilter.class);
    }
}
</code>```

`

and link this in web.xml like,

```<code><init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.service.JerseyApplication</param-value>
        </init-param>
</code>```

Body:
We are having a situation where UI is running on one host, and it is trying to communicate with the resources which are available on another host. The problem here is that, the UI is not be able to make call to the resources because that resource lives in a different domain and cross domain requests will not work unless the server is CORS enabled .

In-order to make server CORS enabled, We have done the below changes .

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException
    {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

However I am not able to figure out where I need to map/configure this class,since there is no config files (web.xml).
I don't have much knowledge on enabling CORS on server-side .
Please suggest how to proceed further .

Body:
In Jersey, I use the ResourceConfig class to register the CORSFilter. Like ,

import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;

public class JerseyApplication extends ResourceConfig {
    public JerseyApplication() {
        register(CORSFilter.class);
    }
}

`

and link this in web.xml like,

<init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.service.JerseyApplication</param-value>
        </init-param>


问:
Apache Reverse Proxy and localhost - "Mixed content, the content must be served over HTTPS"
I have created a reverse proxy for my node server that runs on localhost, so that it can be served over HTTPS.

The forwarding works grate, however when the app tries to make requests I get:

Mixed Content: The page at 'https://foo.com/' was loaded over HTTPS,
  but requested an insecure XMLHttpRequest endpoint
  'http://localhost:8888/graphql?query=%7Bnotifications(userid)%7Bid%2C…
  This request has been blocked; the content must be served over HTTPS.

Vhost config:

```<code><VirtualHost *:443>
   ServerName www.foo.com
   ServerAlias foo.com
   DocumentRoot /var/www/foo/
   ErrorLog /var/www/foo/error.log
   CustomLog /var/www/foo/requests.log combined

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
   SSLCertificateFile "/etc/letsencrypt/live/foo.com/cert.pem"
   SSLCertificateKeyFile "/etc/letsencrypt/live/foo.com/privkey.pem"

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyPass / http://localhost:8888/
   ProxyPassReverse / http://localhost:8888/

</VirtualHost>
</code>```

What is missing from my setup?

答:
You are openning the page on https://foo.com/, but URLs within your page contain hardcoded localhost domain and port. While rendering the page, client browser will try to fetch 'http://localhost:8888/graphql effectively skipping apache (which is running on port 80, on server foo.com) and hitting directly your node app, which will 1) work only if you run the browser from the very same machine where you have your node app running, and 2) even then, you will get the above error since some page assets are loaded using http.

When you use relative URLs (for example URL that begins with /), browser will prepend the base URL, resulting in https://foo.com/graphql.

Absolute vs relative URLs

Body:
I have created a reverse proxy for my node server that runs on localhost, so that it can be served over HTTPS.

The forwarding works grate, however when the app tries to make requests I get:

Mixed Content: The page at 'https://foo.com/' was loaded over HTTPS,
  but requested an insecure XMLHttpRequest endpoint
  'http://localhost:8888/graphql?query=%7Bnotifications(userid)%7Bid%2C…
  This request has been blocked; the content must be served over HTTPS.

Vhost config:

<VirtualHost *:443>
   ServerName www.foo.com
   ServerAlias foo.com
   DocumentRoot /var/www/foo/
   ErrorLog /var/www/foo/error.log
   CustomLog /var/www/foo/requests.log combined

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
   SSLCertificateFile "/etc/letsencrypt/live/foo.com/cert.pem"
   SSLCertificateKeyFile "/etc/letsencrypt/live/foo.com/privkey.pem"

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyPass / http://localhost:8888/
   ProxyPassReverse / http://localhost:8888/

</VirtualHost>

What is missing from my setup?


问:
How should I be organizing my SharePoint code?
Over time, the code base I maintain has grown exponentially. We have a variety of different utility classes, webparts, event receivers, console applications, and more.

Typically, each webpart lives in a separate DLL (one solution and one project per web part). Our utility classes have also been largely separated out into their own separate DLLs (this includes any specialized list access classes that get grouped with their beans together in a DLL). This has led to a large amount of solutions which has become more difficult to maintain (upgrading each solution to Visual Studio 2008, or simply just trying to find out the maze of DLL references).

With my discovery of the SharePoint Guidance, I'm re-evaluating our current code structure. For example, it looks like they recommend combining all of your specialized list access classes into a Repository (we've done completely the opposite so far by splitting them into DLLs based on what "solution" the code is for).

Questions: How should I be organizing my code? How do you decide what goes into a solution vs project vs folder or what goes in a namespace? One solution per web part?

答:
I usually organize my code by functionality. Let's say I've got an extranet project and some code for some intranet webparts, I seperate it out into a Extranet and an Intranet project, and seperate the different classes of code (eventreceivers, timerjobs, webparts, etc.) into different namespace.
That way, I can deploy (sub)sets of functionality to different farms if I want to, and when editing code I got everything that depends on one another in the same place :)</p>


问:
iOS only, share image from gallery to my Ionic/Cordova/Phonegap application
I am trying to share image from gallery and want to get it in my ionic application. I have tried a lot but still not understanding this.

I have tried following plugins:

https://github.com/protonet/cordova-plugin-share-extension-helper

https://github.com/markmarijnissen/cordova-plugin-share

How to share content/data through other apps in an iOS app like we do in an Android app with Intent.ACTION_SEND?

http://www.technetexperts.com/mobile/share-extension-in-ios-application-overview-with-example/

https://github.com/LokeshPatel/iOS-Phonegap-app-share-extension

答:
After some detailed analysis, this is what I could conclude:

In Android, you could just get your application added in the share list using cordova-plugin-intent as described in this SO Post. You can also achieve this by adding intent filter in the activity as described here

In iOS, this is bit tricky as there are no straight forward plugins or readymade solution available to achieve this. But the best possible link i could get related to adding app in iOS share menu is getting listed in share menu The link includes apple documentation to do this and also some tweaking in Info.plist to achieve this.


问:
ssh are not enabled in cpanel
I am running hosting company. At first when i create any user then all the user get ssh access and ssl certificate, because i had enable ssh during package creation.

I was developing web programming which will enable the account from my own website "http://freewingsofficial.com/hosting_for_nepali". There I mistakenly activate ssh in user too.
Now all the user are not getting any ssh access.
Any help is most appreciable. thank you in advance

答: You have to edit that specific package in WHM and see if ssh is enabled or not.  WHM -> Packages -> Edit a Package. Select the package that coresponds to the hosting package from your website. There should be a check mark with 'Shell Access' on the Option section of your WHM package. You should enabled that so the new created accounts with that package can have ssh access.

Title: ssh are not enabled in cpanel


问:
Multi-threading with kivy
I'm writing this code in python using kivy libraries for the UI in which I do some URL requests.
I don't have the code with me right now to share but I'll try to explain it.
Basically, the user types in a text box and clicks a button, which will return a list of names and those names appear in the screen (all of this happens inside a popup).
The thing is, I want to show a spinning ball with a loading message while it waits for the request. I have all the URL functions in a different script.
What I need to do, is to open this second popup, start a new thread for the URL request and let the main thread run normally so the animation shows properly. Then, when the request is finished, close this popup and show the desired results.
Does anyone knows how to call kivys functions from outside the App and/or how to know when the thread finishes?
I'm lost here. Any guidance or example of something similar will be appreciated.
Thanks in advance!</p>

答:
Multithreading in kivy is pretty simple as long as you don't need to update the GUI (you don't). You have to remember one thing - the GUI runs on the main thread and you shouldn't block it. As long as your operation runs on another thread it will be okay.

I used this example when implementing a loading screen in my app.

Now, the hard part is knowing when to close your popup. You can pass a callback function like close_popup_load_data when you call your URL function, you can create two threads - one will do the work and the other will check if the work is done (you can check if a thread is alive) and the second one will close your popup and load the data. There are many ways to do this.

Try making something simple first and see if it works.

Title: Multi-threading with kivy


问:
Chrome Push Notification Updating Service-Worker.js
I am using Google Chrome Push Notification in my site.
Currently I have more than 1,00,000 subscribed users.

I'm facing this following issue.

- My users started using the notifications.

- I need to change the logic of the service-worker but could not able update it.

- I have not given any cache based installation with my previous Service-Wroker.js

- I have not used any fetch event with the previous Service-Worker.js

Changes done in new Service-Worker.js

- Landing URL (clickUrl) variable is added into the self.addEventListener function

My Existing Service-Wroker.js

```<code>'use strict';

var port;
var pushMessage;

var clickUrl;
var imgUrl;

self.addEventListener('push', function(event) {

    var obj      = event.data;
    pushMessage  = event.data ? event.data.text() : '';
    var pushData = pushMessage.split('####');

    clickUrl = pushData[2];
    imgUrl   = pushData[1];
    if (port) {
        port.postMessage(pushMessage);
    }

    event.waitUntil(self.registration.showNotification(pushData[3], {
        requireInteraction: true,
        body: pushData[0],
        icon: pushData[1]
    }));
});

self.addEventListener('notificationclick', function(event) {
    if (Notification.prototype.hasOwnProperty('data')) {
        event.notification.close();
        event.waitUntil(clients.openWindow(clickUrl));
    }
});

self.onmessage = function(e) {
    port = e.ports[0];
    if (pushMessage) {
        port.postMessage(pushMessage);
    }
};
</code>```

The new / updated Service-Worker.js [Changes I need to update / implement]

```<code>'use strict';

var port;
var pushMessage;

var clickUrl;
var imgUrl;

self.addEventListener('push', function(event) {

    var obj      = event.data;
    pushMessage  = event.data ? event.data.text() : '';
    var pushData = pushMessage.split('####');

    clickUrl = pushData[2];
    imgUrl   = pushData[1];
    if (port) {
        port.postMessage(pushMessage);
    }

    event.waitUntil(self.registration.showNotification(pushData[3], {
        requireInteraction: true,
        body: pushData[0],
        icon: pushData[1],
        data:{
            url : clickUrl
        }
    }));
});

self.addEventListener('notificationclick', function(event) {
    var landingUrl = event.notification.data.url;
    if (Notification.prototype.hasOwnProperty('data')) {
        event.notification.close();
        event.waitUntil(clients.openWindow(landingUrl));
    }
});

self.onmessage = function(e) {
    port = e.ports[0];
    if (pushMessage) {
        port.postMessage(pushMessage);
    }
};

self.addEventListener('install', function(event) {
    console.log('[ServiceWorker] Installed version', version);
    event.waitUntil(
        caches.open('my-cache').then(function(cache) {
            // Important to `return` the promise here to have `skipWaiting()`
            // fire after the cache has been updated.
            return cache.addAll([/* file1.jpg, file2.png, ... */]);
        }).then(function() {
            // `skipWaiting()` forces the waiting ServiceWorker to become the
            // active ServiceWorker, triggering the `onactivate` event.
            // Together with `Clients.claim()` this allows a worker to take effect
            // immediately in the client(s).
            return self.skipWaiting();
        })
    );
});

// Activate event
// Be sure to call self.clients.claim()
self.addEventListener('activate', function(event) {
    // `claim()` sets this worker as the active worker for all clients that
    // match the workers scope and triggers an `oncontrollerchange` event for
    // the clients.
    return self.clients.claim();
});
</code>```

答:
An update is triggered:

On navigation to an in-scope page.

On functional events such as push and sync, unless there's been an update check within the previous 24 hours.

On calling .register() only if the service worker URL has changed.

more here https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle

Body:
I am using Google Chrome Push Notification in my site.
Currently I have more than 1,00,000 subscribed users.

I'm facing this following issue.

- My users started using the notifications.

- I need to change the logic of the service-worker but could not able update it.

- I have not given any cache based installation with my previous Service-Wroker.js

- I have not used any fetch event with the previous Service-Worker.js

Changes done in new Service-Worker.js

- Landing URL (clickUrl) variable is added into the self.addEventListener function

My Existing Service-Wroker.js

'use strict';

var port;
var pushMessage;

var clickUrl;
var imgUrl;

self.addEventListener('push', function(event) {

    var obj      = event.data;
    pushMessage  = event.data ? event.data.text() : '';
    var pushData = pushMessage.split('####');

    clickUrl = pushData[2];
    imgUrl   = pushData[1];
    if (port) {
        port.postMessage(pushMessage);
    }

    event.waitUntil(self.registration.showNotification(pushData[3], {
        requireInteraction: true,
        body: pushData[0],
        icon: pushData[1]
    }));
});

self.addEventListener('notificationclick', function(event) {
    if (Notification.prototype.hasOwnProperty('data')) {
        event.notification.close();
        event.waitUntil(clients.openWindow(clickUrl));
    }
});

self.onmessage = function(e) {
    port = e.ports[0];
    if (pushMessage) {
        port.postMessage(pushMessage);
    }
};

The new / updated Service-Worker.js [Changes I need to update / implement]

'use strict';

var port;
var pushMessage;

var clickUrl;
var imgUrl;

self.addEventListener('push', function(event) {

    var obj      = event.data;
    pushMessage  = event.data ? event.data.text() : '';
    var pushData = pushMessage.split('####');

    clickUrl = pushData[2];
    imgUrl   = pushData[1];
    if (port) {
        port.postMessage(pushMessage);
    }

    event.waitUntil(self.registration.showNotification(pushData[3], {
        requireInteraction: true,
        body: pushData[0],
        icon: pushData[1],
        data:{
            url : clickUrl
        }
    }));
});

self.addEventListener('notificationclick', function(event) {
    var landingUrl = event.notification.data.url;
    if (Notification.prototype.hasOwnProperty('data')) {
        event.notification.close();
        event.waitUntil(clients.openWindow(landingUrl));
    }
});

self.onmessage = function(e) {
    port = e.ports[0];
    if (pushMessage) {
        port.postMessage(pushMessage);
    }
};

self.addEventListener('install', function(event) {
    console.log('[ServiceWorker] Installed version', version);
    event.waitUntil(
        caches.open('my-cache').then(function(cache) {
            // Important to `return` the promise here to have `skipWaiting()`
            // fire after the cache has been updated.
            return cache.addAll([/* file1.jpg, file2.png, ... */]);
        }).then(function() {
            // `skipWaiting()` forces the waiting ServiceWorker to become the
            // active ServiceWorker, triggering the `onactivate` event.
            // Together with `Clients.claim()` this allows a worker to take effect
            // immediately in the client(s).
            return self.skipWaiting();
        })
    );
});

// Activate event
// Be sure to call self.clients.claim()
self.addEventListener('activate', function(event) {
    // `claim()` sets this worker as the active worker for all clients that
    // match the workers scope and triggers an `oncontrollerchange` event for
    // the clients.
    return self.clients.claim();
});


问:
How to use DOM event onloadeddata in HTML5 audio element through Angularjs?
I am trying to use DOM event onloadeddata using angularjs. So far I was able to do this for click event, but was not able to replicate the same thing for onloadeddata event. What I am doing wrong?

```<code>.directive('audioLoaded', function() {
return {
    restrict: 'AE',
    link: function(scope, elem, attrs) {
        elem.on('onloadeddata', function() {
            console.log('loaded');
            //scope.audioLoadedFromURL = true;
        });
    }
};
});
</code>```

What I want to do is to change the value of a angularjs variable, after the audio element has loaded the data from the url.

答:
use the addEventListener on elem[0] element

```<code>elem[0].addEventListener("loadeddata", function () {
        console.log('loaded');
});
</code>```

Body:
I am trying to use DOM event onloadeddata using angularjs. So far I was able to do this for click event, but was not able to replicate the same thing for onloadeddata event. What I am doing wrong?

.directive('audioLoaded', function() {
return {
    restrict: 'AE',
    link: function(scope, elem, attrs) {
        elem.on('onloadeddata', function() {
            console.log('loaded');
            //scope.audioLoadedFromURL = true;
        });
    }
};
});

What I want to do is to change the value of a angularjs variable, after the audio element has loaded the data from the url.

Body:
use the addEventListener on elem[0] element

elem[0].addEventListener("loadeddata", function () {
        console.log('loaded');
});


问:
How to force a Windows 10 uwp webview app to load a url after suspend / resuming & auto reload when timing out
This (simplified) c# / XAML UWP Webview app displays a blank page after the app is resumed after about 90+ sec. when displaying a local security cam video stream webpage.  It appears to timeout after about 90 sec while the app is being suspended and then upon resuming the webview page is blank.  To give the sample code below something to display, I randomly picked a site from a web search and landed on http://www.porttampawebcam.com/.  The few youtube and webcam pages I've tried didn't reproduce the issue of timing out like my local web cam server does after a min. or so of inactivity.

A button can be used to manually refresh / reload the page, but how can it be coded to ...

A) Force the url to load every time the app gets resumed?
B) Detect that the page has timed out and then reload as needed?

I've done a bit of research on this (using the webview control & UWP application lifecyles), browsed uwp apps on GitHub, and have made progress on several other parts of the app, but have yet to figure out a working solution on these two points.

App was built using the Blank App (Universal Windows) template in Visual Studio 2015.

XAML:

```<code>Mainpage.xaml

<Page
    x:Class="WVMinimal.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" ></RowDefinition>
        <RowDefinition Height="auto" ></RowDefinition>

    </Grid.RowDefinitions>
    <WebView Name="WV" Source="http://www.porttampawebcam.com"/>
    </Grid>
</Page>
</code>```

c#:

```<code>Mainpage.xaml.cs

using Windows.UI.Xaml.Controls;

    // The Blank Page item template is documented at     https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

    namespace UWPWebviewTest5
    {
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        public MainPage()
        {
            this.InitializeComponent();

        }

}
</code>```

答:
I know it's a bit late and maybe not 100% answering your question but maybe you could try to refresh the WebView content like this:</p>

```<code>await WebView.ClearTemporaryWebDataAsync();
yourWebView.Navigate(new Uri("https://www.yourUri.com"));
</code>```

Body:
This (simplified) c# / XAML UWP Webview app displays a blank page after the app is resumed after about 90+ sec. when displaying a local security cam video stream webpage.  It appears to timeout after about 90 sec while the app is being suspended and then upon resuming the webview page is blank.  To give the sample code below something to display, I randomly picked a site from a web search and landed on http://www.porttampawebcam.com/.  The few youtube and webcam pages I've tried didn't reproduce the issue of timing out like my local web cam server does after a min. or so of inactivity.

A button can be used to manually refresh / reload the page, but how can it be coded to ...

A) Force the url to load every time the app gets resumed?
B) Detect that the page has timed out and then reload as needed?

I've done a bit of research on this (using the webview control & UWP application lifecyles), browsed uwp apps on GitHub, and have made progress on several other parts of the app, but have yet to figure out a working solution on these two points.

App was built using the Blank App (Universal Windows) template in Visual Studio 2015.

XAML:

Mainpage.xaml

<Page
    x:Class="WVMinimal.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" ></RowDefinition>
        <RowDefinition Height="auto" ></RowDefinition>

    </Grid.RowDefinitions>
    <WebView Name="WV" Source="http://www.porttampawebcam.com"/>
    </Grid>
</Page>

c#:

Mainpage.xaml.cs

using Windows.UI.Xaml.Controls;

    // The Blank Page item template is documented at     https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

    namespace UWPWebviewTest5
    {
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    public sealed partial class MainPage : Page
    {

        public MainPage()
        {
            this.InitializeComponent();

        }

}

Body:
I know it's a bit late and maybe not 100% answering your question but maybe you could try to refresh the WebView content like this:

await WebView.ClearTemporaryWebDataAsync();
yourWebView.Navigate(new Uri("https://www.yourUri.com"));


问:
Can Messenger Service be used for inter app IPC?
I have three applications out of which two applications need to connect to a service published by the third application. This service is supposed to send/receive data over GPRS  and pass it to both the applications. I have implemented this service as a Messenger Service in the 3rd application. It is mentioned in the android documentation that a Messenger service can be used for communication between two processes but in the same application.My question however is that is it possible to to use a Messenger Service for communication between two processes belonging to two different applications? If yes, could someone show me some sample code demonstrating how a client can bind to such a service.</p>

答:
As per android documentation a Messenger service can be used for communication between two processes but it does not restrict it in same application.Processes can be in same application or different application.

Messenger should be used if we want the requests to be processed sequentially as it enters the messages in handler's queue and they are processed one by one.


问:
Regex URL extract without www
I have this /href *= *[\'"]\Khttps?:\/\/(?:www\.)?twitter\.com[^\'"]+/ expression to extract twitter-urls. It works great for all urls starting with www, but not if www is missing. What do I have to change this line to, in order to have both links (with and without www) fetched with RegEx?

```<code><a href="//www.twitter.com/anything">LINK1</a>
<a href="//twitter.com/anything">LINK2</a>
</code>```

Thanks for your help!

Yes, I know there are some posts containing that issue and showing solutions to that, but none of them really helped me solve this.

答:
www is not the problem. As you can see, your pattern contains https?, you have to make it optional:

```<code>href *= *[\'"]\K(?:https?:)?\/\/(?:www\.)?twitter\.com[^\'"]+
</code>```

See demo.

Title: Regex URL extract without www

Body:
I have this /href *= *[\'"]\Khttps?:\/\/(?:www\.)?twitter\.com[^\'"]+/ expression to extract twitter-urls. It works great for all urls starting with www, but not if www is missing. What do I have to change this line to, in order to have both links (with and without www) fetched with RegEx?

LINK1
LINK2

Thanks for your help!

Yes, I know there are some posts containing that issue and showing solutions to that, but none of them really helped me solve this.

Body:
www is not the problem. As you can see, your pattern contains https?, you have to make it optional:

href *= *[\'"]\K(?:https?:)?\/\/(?:www\.)?twitter\.com[^\'"]+

See demo.


问:
How to delete data based on time interval
I  have a table in my database.The table has a field VehId(Int) and trackdt(Datetime)

My table has 3000 billion rows(yes, that's right 3000 billion). so i want to delete old data. but i want to delete data based on time interval.

I want to delete records of every 20 seconds for each vehicle.

Below is the table I have

```<code>VehId  Trackdt
1      2017-05-20 00:00:30.000
2      2017-05-20 00:00:32.000
2      2017-05-20 00:00:42.000
1      2017-05-20 00:00:40.000
2      2017-05-20 00:00:52.000
1      2017-05-20 00:00:50.000
1      2017-05-20 00:01:00.000
2      2017-05-20 00:01:02.000
1      2017-05-20 00:01:10.000
1      2017-05-20 00:01:20.000
2      2017-05-20 00:01:12.000
1      2017-05-20 00:01:30.000
2      2017-05-20 00:01:22.000
2      2017-05-20 00:01:32.000
</code>```

After delete data should be like below

```<code>VehId  TRackdt
1      2017-05-20 00:00:30.000
2      2017-05-20 00:00:32.000
1      2017-05-20 00:01:00.000
2      2017-05-20 00:01:02.000
1      2017-05-20 00:01:30.000
2      2017-05-20 00:01:32.000
</code>```

I tried below query but it is taking too much time

```<code>ALTER PROCEDURE [dbo].[DELETEINTERVALDATA]

@FROMDATE DATETIME,
@TODATE DATETIME,
@INTERVAL INT,
@FLAG INT

AS
BEGIN
SET NOCOUNT ON;

DECLARE @TRACKDT DATETIME
DECLARE @I INT =1
DECLARE @V INT =1
DECLARE @COUNT INT
DECLARE @VCOUNT INT
DECLARE @STARTDATE DATETIME = ''
DECLARE @VEHID INT
DECLARE @TIMEDIFF INT

 CREATE TABLE #TEMPVEHICLE
 (
    SNO INT IDENTITY(1,1),
    VEHID INT
 )

 CREATE TABLE #TEMPLOG
 (
    SNO INT IDENTITY(1,1),
    TRACKDT DATETIME
 )

 IF (@FLAG = 1 )
    BEGIN

        INSERT INTO #TEMPVEHICLE (VEHID) SELECT VEHID FROM VEHICLEMASTER ORDER BY VEHID

        SELECT @VCOUNT = COUNT(SNO) FROM #TEMPVEHICLE

        WHILE (@V <= @VCOUNT)
            BEGIN

                SELECT @VEHID = VEHID FROM #TEMPVEHICLE WHERE SNO = @V

                INSERT INTO #TEMPLOG(TRACKDT) SELECT TRACKDT
                FROM TRACKINGLOG WITH(NOLOCK)
                WHERE TRACKDT BETWEEN @FROMDATE AND @TODATE AND VEHID = @VEHID
                ORDER BY TRACKDT ASC

                SELECT @COUNT = COUNT(SNO) FROM #TEMPLOG

                WHILE (@I <= @COUNT)
                    BEGIN
                        SELECT @TRACKDT=TRACKDT FROM #TEMPLOG WHERE SNO = @I
                        IF (@I = 1)
                            BEGIN
                                SELECT @STARTDATE = @TRACKDT
                            END
                        ELSE
                            BEGIN
                                SELECT @TIMEDIFF = DATEDIFF(SECOND,@STARTDATE,@TRACKDT)
                                IF @TIMEDIFF <= 20
                                    BEGIN
                                        DELETE FROM TRACKINGLOG WHERE TRACKDT = @TRACKDT AND VEHID = @VEHID
                                    END
                                ELSE
                                    BEGIN
                                        SELECT @STARTDATE = @TRACKDT
                                    END
                            END
                        SELECT  @I = @I + 1
                    END
                TRUNCATE TABLE #TEMPLOG
                SELECT  @V = @V + 1,@STARTDATE= '',@I=1
            END
        DROP TABLE #TEMPLOG
        DROP TABLE #TEMPVEHICLE
    END
   END
</code>```

How can I write query which delete data based on time interval and should be quick??

Thanks in advance

答:
Your desired output corresponds to a 30 second interval.

You can retrieve previous values in a result set using window functions. For example, LAG(trackdt,1) will return the previous value. LEAD the next. FIRST_VALUE will return the first value in a set.

The query :

```<code>select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
from @mytable
</code>```

Will return the first trackdt value per vehicle, when the rows are ordered by trackdt.

```<code>1   2017-05-20 00:00:30.000 2017-05-20 00:00:30.000
1   2017-05-20 00:00:40.000 2017-05-20 00:00:30.000
1   2017-05-20 00:00:50.000 2017-05-20 00:00:30.000
</code>```

This way we can calculate the interval between the current and first value in the partition with datediff. The resulting query is a bit ugly:

```<code>select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0,
    datediff(s,FIRST_VALUE(trackdt) over (partition by vehid order by trackdt),
               trackdt) as interval
from @mytable
</code>```

Dividing by 30 would give us the interval bucket to which each row belongs.

```<code>1   2017-05-20 00:01:10.000 2017-05-20 00:00:30.000 1
1   2017-05-20 00:01:20.000 2017-05-20 00:00:30.000 1
1   2017-05-20 00:01:30.000 2017-05-20 00:00:30.000 2
2   2017-05-20 00:00:32.000 2017-05-20 00:00:32.000 0
2   2017-05-20 00:00:42.000 2017-05-20 00:00:32.000 0
</code>```

Calculating the remainder though, would return 0 for the first row in every 30-second bucket:

```<code>select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0,
    datediff(s,FIRST_VALUE(trackdt) over (partition by vehid order by trackdt),
               trackdt) %30 as remainder
from @mytable

1   2017-05-20 00:01:00.000 2017-05-20 00:00:30.000 0
1   2017-05-20 00:01:10.000 2017-05-20 00:00:30.000 10
1   2017-05-20 00:01:20.000 2017-05-20 00:00:30.000 20
1   2017-05-20 00:01:30.000 2017-05-20 00:00:30.000 0
2   2017-05-20 00:00:32.000 2017-05-20 00:00:32.000 0
</code>```

We can use one or more CTEs to tidy-up this query and perform the deletion:

```<code>with start_times as
(
    select * ,
        FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
    from @mytable
),
intervals as
(
    select * ,
        datediff(s,t0,trackdt) %30 as rem
    from start_times
)
delete
from intervals
where rem<>0
</code>```

This query depends on having values every 30 seconds.

In general, you can use the ROW_NUMBER() function to identify records within an interval bucket and simply pick the first row in a bucket. Since we want to retain the first row, we pick anything that has a ROW_NUMBER>1:

```<code>with start_times as
(
    select * ,
        FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
    from #mytable
),
intervals as
(
    select * ,
        datediff(s,t0,trackdt) /30 as interval
    from start_times
),
ordered as
(
    select *,
           ROW_NUMBER() over(partition by vehid,interval order by trackdt) row_num
    from intervals
)
select vehid,trackdt
from ordered
where row_num>1
</code>```

Even though this query is fast, I wouldn't use it on a 3 trillion row table. Windowing often results in spooling - temporary results are stored in tempdb to allow window calculations. It would be better to select the IDs of the rows that have to be deleted, insert them into a temporary table and then use a DELETE with a join clause:

```<code>DELETE HugeTable
From HugeTable
    INNER JOIN TempTable on TempTable.ID=HugeTable.ID
</code>```

Even so, you probably want to batch deletions. In this case you could use the NTILE function to calculate a batch number for each row between 1 and N:

```<code>select ID,NTILE(100) over(order by vehid,trackdt) as batch_number
from ordered
where row_num=1
</code>```

This will calculate a batch number between 1 and 100. You can store this in the temporary table and delete one batch of rows at a time.

Body:
I  have a table in my database.The table has a field VehId(Int) and trackdt(Datetime)

My table has 3000 billion rows(yes, that's right 3000 billion). so i want to delete old data. but i want to delete data based on time interval.

I want to delete records of every 20 seconds for each vehicle.

Below is the table I have

VehId  Trackdt
1      2017-05-20 00:00:30.000
2      2017-05-20 00:00:32.000
2      2017-05-20 00:00:42.000
1      2017-05-20 00:00:40.000
2      2017-05-20 00:00:52.000
1      2017-05-20 00:00:50.000
1      2017-05-20 00:01:00.000
2      2017-05-20 00:01:02.000
1      2017-05-20 00:01:10.000
1      2017-05-20 00:01:20.000
2      2017-05-20 00:01:12.000
1      2017-05-20 00:01:30.000
2      2017-05-20 00:01:22.000
2      2017-05-20 00:01:32.000

After delete data should be like below

VehId  TRackdt
1      2017-05-20 00:00:30.000
2      2017-05-20 00:00:32.000
1      2017-05-20 00:01:00.000
2      2017-05-20 00:01:02.000
1      2017-05-20 00:01:30.000
2      2017-05-20 00:01:32.000

I tried below query but it is taking too much time

ALTER PROCEDURE [dbo].[DELETEINTERVALDATA]

@FROMDATE DATETIME,
@TODATE DATETIME,
@INTERVAL INT,
@FLAG INT

AS
BEGIN
SET NOCOUNT ON;

DECLARE @TRACKDT DATETIME
DECLARE @I INT =1
DECLARE @V INT =1
DECLARE @COUNT INT
DECLARE @VCOUNT INT
DECLARE @STARTDATE DATETIME = ''
DECLARE @VEHID INT
DECLARE @TIMEDIFF INT

 CREATE TABLE #TEMPVEHICLE
 (
    SNO INT IDENTITY(1,1),
    VEHID INT
 )

 CREATE TABLE #TEMPLOG
 (
    SNO INT IDENTITY(1,1),
    TRACKDT DATETIME
 )

 IF (@FLAG = 1 )
    BEGIN

        INSERT INTO #TEMPVEHICLE (VEHID) SELECT VEHID FROM VEHICLEMASTER ORDER BY VEHID

        SELECT @VCOUNT = COUNT(SNO) FROM #TEMPVEHICLE

        WHILE (@V <= @VCOUNT)
            BEGIN

                SELECT @VEHID = VEHID FROM #TEMPVEHICLE WHERE SNO = @V

                INSERT INTO #TEMPLOG(TRACKDT) SELECT TRACKDT
                FROM TRACKINGLOG WITH(NOLOCK)
                WHERE TRACKDT BETWEEN @FROMDATE AND @TODATE AND VEHID = @VEHID
                ORDER BY TRACKDT ASC

                SELECT @COUNT = COUNT(SNO) FROM #TEMPLOG

                WHILE (@I <= @COUNT)
                    BEGIN
                        SELECT @TRACKDT=TRACKDT FROM #TEMPLOG WHERE SNO = @I
                        IF (@I = 1)
                            BEGIN
                                SELECT @STARTDATE = @TRACKDT
                            END
                        ELSE
                            BEGIN
                                SELECT @TIMEDIFF = DATEDIFF(SECOND,@STARTDATE,@TRACKDT)
                                IF @TIMEDIFF <= 20
                                    BEGIN
                                        DELETE FROM TRACKINGLOG WHERE TRACKDT = @TRACKDT AND VEHID = @VEHID
                                    END
                                ELSE
                                    BEGIN
                                        SELECT @STARTDATE = @TRACKDT
                                    END
                            END
                        SELECT  @I = @I + 1
                    END
                TRUNCATE TABLE #TEMPLOG
                SELECT  @V = @V + 1,@STARTDATE= '',@I=1
            END
        DROP TABLE #TEMPLOG
        DROP TABLE #TEMPVEHICLE
    END
   END

How can I write query which delete data based on time interval and should be quick??

Thanks in advance

Body:
Your desired output corresponds to a 30 second interval.

You can retrieve previous values in a result set using window functions. For example, LAG(trackdt,1) will return the previous value. LEAD the next. FIRST_VALUE will return the first value in a set.

The query :

select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
from @mytable

Will return the first trackdt value per vehicle, when the rows are ordered by trackdt.

1   2017-05-20 00:00:30.000 2017-05-20 00:00:30.000
1   2017-05-20 00:00:40.000 2017-05-20 00:00:30.000
1   2017-05-20 00:00:50.000 2017-05-20 00:00:30.000

This way we can calculate the interval between the current and first value in the partition with datediff. The resulting query is a bit ugly:

select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0,
    datediff(s,FIRST_VALUE(trackdt) over (partition by vehid order by trackdt),
               trackdt) as interval
from @mytable

Dividing by 30 would give us the interval bucket to which each row belongs.

1   2017-05-20 00:01:10.000 2017-05-20 00:00:30.000 1
1   2017-05-20 00:01:20.000 2017-05-20 00:00:30.000 1
1   2017-05-20 00:01:30.000 2017-05-20 00:00:30.000 2
2   2017-05-20 00:00:32.000 2017-05-20 00:00:32.000 0
2   2017-05-20 00:00:42.000 2017-05-20 00:00:32.000 0

Calculating the remainder though, would return 0 for the first row in every 30-second bucket:

select * ,
    FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0,
    datediff(s,FIRST_VALUE(trackdt) over (partition by vehid order by trackdt),
               trackdt) %30 as remainder
from @mytable

1   2017-05-20 00:01:00.000 2017-05-20 00:00:30.000 0
1   2017-05-20 00:01:10.000 2017-05-20 00:00:30.000 10
1   2017-05-20 00:01:20.000 2017-05-20 00:00:30.000 20
1   2017-05-20 00:01:30.000 2017-05-20 00:00:30.000 0
2   2017-05-20 00:00:32.000 2017-05-20 00:00:32.000 0

We can use one or more CTEs to tidy-up this query and perform the deletion:

with start_times as
(
    select * ,
        FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
    from @mytable
),
intervals as
(
    select * ,
        datediff(s,t0,trackdt) %30 as rem
    from start_times
)
delete
from intervals
where rem<>0

This query depends on having values every 30 seconds.

In general, you can use the ROW_NUMBER() function to identify records within an interval bucket and simply pick the first row in a bucket. Since we want to retain the first row, we pick anything that has a ROW_NUMBER>1:

with start_times as
(
    select * ,
        FIRST_VALUE(trackdt) over (partition by vehid order by trackdt) as t0
    from #mytable
),
intervals as
(
    select * ,
        datediff(s,t0,trackdt) /30 as interval
    from start_times
),
ordered as
(
    select *,
           ROW_NUMBER() over(partition by vehid,interval order by trackdt) row_num
    from intervals
)
select vehid,trackdt
from ordered
where row_num>1

Even though this query is fast, I wouldn't use it on a 3 trillion row table. Windowing often results in spooling - temporary results are stored in tempdb to allow window calculations. It would be better to select the IDs of the rows that have to be deleted, insert them into a temporary table and then use a DELETE with a join clause:

DELETE HugeTable
From HugeTable
    INNER JOIN TempTable on TempTable.ID=HugeTable.ID

Even so, you probably want to batch deletions. In this case you could use the NTILE function to calculate a batch number for each row between 1 and N:

select ID,NTILE(100) over(order by vehid,trackdt) as batch_number
from ordered
where row_num=1

This will calculate a batch number between 1 and 100. You can store this in the temporary table and delete one batch of rows at a time.


问:
Fatest way to check and create folder in document library within SharePoint Online (CSOM)?
I have a SharePoint Online where I can connect through my console application successfully:

```<code>private static ClientContext GetUserContext()
{
   var o365SecurePassword = new SecureString();

   foreach (char c in o365Password)
   {
       o365SecurePassword.AppendChar(c);
   }

   var o365Credentials = new SharePointOnlineCredentials(o365Username, o365SecurePassword);

   var o365Context = new ClientContext(o365SiteUrl);
   o365Context.Credentials = o365Credentials;

   return o365Context;
}
</code>```

But what I need now to do is to go into my SharePoint Document Library named "doc_archive" and check if there exists a folder with name "K20170409-01".
If not create a new one.

Failed Attempt

```<code>ClientContext context = GetUserContext();

Web web = context.Web;
Web webroot = context.Site.RootWeb;
context.Load(web);
context.Load(webroot);

List list = webroot.GetList("doc_archive");
context.Load(list);

FolderCollection folders = list.RootFolder.Folders;
context.Load(folders);

IEnumerable<Folder> existingFolders = context.LoadQuery(
    folders.Include(
    folder => folder.Name)
);
context.ExecuteQuery();
</code>```

What is the fastest ways to check and create a folder within a document library in SharePoint Online via CSOM (commandline application)?

答:
If you are happy with using external libraries then the OfficeDevPnP.Core has some great CSOM extensions for SharePoint and SharePoint Online. It's readily available as a NuGet package to add to your projects.

For your requirment there is the EnsureFolderPath extension. This function will check if a folder exists, create it if needed and return the Microsoft.SharePoint.Client.Folder object.

Very easy to use:

```<code>var webRelativeUrlToFolder = "/doc_archive/K20170409-01"
var folder = cc.Web.EnsureFolderPath(webRelativeUrlToFolder);
cc.Load(folder);
cc.ExecuteQuery();
</code>```

Body:
I have a SharePoint Online where I can connect through my console application successfully:

private static ClientContext GetUserContext()
{
   var o365SecurePassword = new SecureString();

   foreach (char c in o365Password)
   {
       o365SecurePassword.AppendChar(c);
   }

   var o365Credentials = new SharePointOnlineCredentials(o365Username, o365SecurePassword);

   var o365Context = new ClientContext(o365SiteUrl);
   o365Context.Credentials = o365Credentials;

   return o365Context;
}

But what I need now to do is to go into my SharePoint Document Library named "doc_archive" and check if there exists a folder with name "K20170409-01".
If not create a new one.

Failed Attempt

ClientContext context = GetUserContext();

Web web = context.Web;
Web webroot = context.Site.RootWeb;
context.Load(web);
context.Load(webroot);

List list = webroot.GetList("doc_archive");
context.Load(list);

FolderCollection folders = list.RootFolder.Folders;
context.Load(folders);

IEnumerable<Folder> existingFolders = context.LoadQuery(
    folders.Include(
    folder => folder.Name)
);
context.ExecuteQuery();

What is the fastest ways to check and create a folder within a document library in SharePoint Online via CSOM (commandline application)?

Body:
If you are happy with using external libraries then the OfficeDevPnP.Core has some great CSOM extensions for SharePoint and SharePoint Online. It's readily available as a NuGet package to add to your projects.

For your requirment there is the EnsureFolderPath extension. This function will check if a folder exists, create it if needed and return the Microsoft.SharePoint.Client.Folder object.

Very easy to use:

var webRelativeUrlToFolder = "/doc_archive/K20170409-01"
var folder = cc.Web.EnsureFolderPath(webRelativeUrlToFolder);
cc.Load(folder);
cc.ExecuteQuery();


答:
You need to use addEventListener on elem[0] like

HTML

```<code><body ng-controller="MainCtrl">

 <audio controls audio-events autoplay>
  <source ng-src="{{url}}" type="audio/mp3">
 </audio>

</body>
</code>```

Controller

```<code>var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $sce) {
  $scope.url = $sce.trustAsResourceUrl("https://www.w3schools.com/tags/horse.mp3");
});

app.directive('audioEvents', function () {
    return function ($scope, $element) {
      $element[0].addEventListener("loadeddata", function () {
        console.log('loadeddata');
        // you can $rootScope.$broadcast...
      });

    }
});
</code>```

For you work around and further experiment here is the link to working PLUNKR

Title: How to use DOM event onloadeddata in HTML5 audio element through Angularjs?

Body:
You need to use addEventListener on elem[0] like

HTML

<body ng-controller="MainCtrl">

 <audio controls audio-events autoplay>
  <source ng-src="{{url}}" type="audio/mp3">
 </audio>

</body>

Controller

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $sce) {
  $scope.url = $sce.trustAsResourceUrl("https://www.w3schools.com/tags/horse.mp3");
});

app.directive('audioEvents', function () {
    return function ($scope, $element) {
      $element[0].addEventListener("loadeddata", function () {
        console.log('loadeddata');
        // you can $rootScope.$broadcast...
      });

    }
});

For you work around and further experiment here is the link to working PLUNKR


问:
rendering multiple elements after onClick event in React
I'm having problems trying to render two react elements inside a react component after a onClick event. Wondering if that's even possible? I'm sure I'm messing up the ternary operator, but I cannot think on another way to do what I'm trying to do ?

TL;DR: "When I click a button I see elementA and elementB"

Here is a snippet of the code:

```<code>import React, { Component } from 'react';

class MyComponent extends Component {
    constructor(props) {
    super(props)
    this.state = { showElement: true };
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
    this.setState(prevState => ({ showElement: !this.state.showElement }) );
  };

  elementA() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }

  elementB() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
          </button>
          { this.state.showElement
            ?
            null
            :
            this.elementA() && this.elementB()
          }
      </section>
    )
  }
}

export default MyComponent;
</code>```

答:
You just inattentive.

```<code>elementA() {
    return ( // You forget
        <div>
            <h1>
                some data
            </h1>
        </div>
    )
}
</code>```

And the same in element B.

And if You want to see both components you should change Your ternary to

```<code>{ this.state.showElement
            ?
            <div> {this.elementA()} {this.elementB()}</div>
            :
            null
          }
</code>```

Another "and", for toggling showElement in state just enough
this.setState({showElement: !this.state.showElement });

Body:
I'm having problems trying to render two react elements inside a react component after a onClick event. Wondering if that's even possible? I'm sure I'm messing up the ternary operator, but I cannot think on another way to do what I'm trying to do ?

TL;DR: "When I click a button I see elementA and elementB"

Here is a snippet of the code:

import React, { Component } from 'react';

class MyComponent extends Component {
    constructor(props) {
    super(props)
    this.state = { showElement: true };
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
    this.setState(prevState => ({ showElement: !this.state.showElement }) );
  };

  elementA() {

      some data

  }

  elementB() {

      some data

  }

  render() {
    return (

          <button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
          </button>
          { this.state.showElement
            ?
            null
            :
            this.elementA() && this.elementB()
          }

    )
  }
}

export default MyComponent;

Body:
You just inattentive.

elementA() {
    return ( // You forget
        <div>
            <h1>
                some data
            </h1>
        </div>
    )
}

And the same in element B.

And if You want to see both components you should change Your ternary to

{ this.state.showElement
            ?
            <div> {this.elementA()} {this.elementB()}</div>
            :
            null
          }

Another "and", for toggling showElement in state just enough
this.setState({showElement: !this.state.showElement });


问:
How to get the current time in the format `2010-12-20 06:32:48` with PHP?
Anyone knows how to do it?

What I know is time() but it's pure digits..

答:
To obtain a formatted date/timestamp use the date() function

```<code>$dt = date('Y-m-d H:i:s');
</code>```

Body:
To obtain a formatted date/timestamp use the date() function

$dt = date('Y-m-d H:i:s');


问:
Setting up Bluehost with Heroku and Google G-suite
I have my domain name purchased on Bluehost.  I have my website application hosted by Heroku. I have my email setup with Google G-suite.

I setup the 5 MX records in the Bluehost zone editor as per Google's instructions, however, I cannot receive any emails.  Google told me my nameservers are not active, however my domain name successfully directs to my Heroku app - so that's the first thing I don't understand.

Bluehost told me that I need to stop pointing at their nameservers and provide them with nameservers from Heroku but I cannot find this information.

Anyone know how to setup Bluehost to operate successfully with Heroku and Google mail?

答: Solved. Explanation to save others time (5 hrs chat / 2 hrs phone support): (1) Heroku does not supply nameservers. Therefore your DNS provider (or other company) needs to. (2) Even though the domain name successfully pointed to my Heroku app via the CNAME record, the Bluehost guy was surprised this worked at all without nameservers setup. (3) Solution: I needed to purchase the basic hosting plan from BH which activated the nameservers. My mails started to be received at Google mail. I had to re-enter the MX records for Google & the CNAME record for my Heroku app in the BH zone editor.</p>


问:
How to concatenate a series of variables in a calculated one without repetitions
I have a set of 6 variables for observation representing the Brand of tires in a truck. The brands could be different between tires but usually are all the same.
I need to create a summary variable that lists for each observation all the brands of the tires.

A simple SELECT CONCAT(BrandP1, ', ', BrandP2...) AS Brand usually gives a lot of repetitions.

I thought of concatenating the N variable only if the N-1 variables are different but i see it's quite ugly doing so. Is there an elegant way to summarize the content of 6 variables into one new calculated variable?

As requested an extract of the table:

```<code>ID_vehicle, BrandP1, BrandP2, BrandP3, BrandP4
----------------------------------------------
1    Dunlop    Dunlop    Riken    Riken
2    Dunlop    Dunlop    Dunlop   Dunlop
3    Riken     Dunlop    Toyo     Toyo
</code>```

What I'd like to obtain is

```<code>ID_vehicle, Brand
------------------
1   Dunlop, Riken
2   Dunlop
3   Riken, Dunlop, Toyo
</code>```

What I can get with CONCAT is

```<code>1   Dunlop, Dunlop, Riken, Riken
2   Dunlop, Dunlop, Dunlop, Dunlop
3   Riken, Dunlop, Toyo, Toyo
</code>```

答:
I figured it out, in part thanks to @a3r0, although I couldn't create a new table or changing the database schema.

So I went

```<code>SELECT ALL
    ID,
    GROUP_CONCAT( DISTINCT Brand SEPARATOR ', ') AS BrandP
FROM (
    SELECT ID, Wheel, Brand FROM (
        SELECT ID, 'BrandP1' Wheel, BrandP1 Brand FROM Pneumatici
        UNION ALL
        SELECT ID, 'BrandP2', BrandP2 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP3', BrandP3 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP4', BrandP4 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP5', BrandP5 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP6', BrandP6 FROM Cars
    ) AS y
    WHERE Brand != ''
) AS x
GROUP BY ID
</code>```

To transpose the variables I'm interested with
and then joined it with the original table matching by id.

Body:
I have a set of 6 variables for observation representing the Brand of tires in a truck. The brands could be different between tires but usually are all the same.
I need to create a summary variable that lists for each observation all the brands of the tires.

A simple SELECT CONCAT(BrandP1, ', ', BrandP2...) AS Brand usually gives a lot of repetitions.

I thought of concatenating the N variable only if the N-1 variables are different but i see it's quite ugly doing so. Is there an elegant way to summarize the content of 6 variables into one new calculated variable?

As requested an extract of the table:

ID_vehicle, BrandP1, BrandP2, BrandP3, BrandP4
----------------------------------------------
1    Dunlop    Dunlop    Riken    Riken
2    Dunlop    Dunlop    Dunlop   Dunlop
3    Riken     Dunlop    Toyo     Toyo

What I'd like to obtain is

ID_vehicle, Brand
------------------
1   Dunlop, Riken
2   Dunlop
3   Riken, Dunlop, Toyo

What I can get with CONCAT is

1   Dunlop, Dunlop, Riken, Riken
2   Dunlop, Dunlop, Dunlop, Dunlop
3   Riken, Dunlop, Toyo, Toyo

Body:
I figured it out, in part thanks to @a3r0, although I couldn't create a new table or changing the database schema.

So I went

SELECT ALL
    ID,
    GROUP_CONCAT( DISTINCT Brand SEPARATOR ', ') AS BrandP
FROM (
    SELECT ID, Wheel, Brand FROM (
        SELECT ID, 'BrandP1' Wheel, BrandP1 Brand FROM Pneumatici
        UNION ALL
        SELECT ID, 'BrandP2', BrandP2 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP3', BrandP3 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP4', BrandP4 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP5', BrandP5 FROM Cars
        UNION ALL
        SELECT ID, 'BrandP6', BrandP6 FROM Cars
    ) AS y
    WHERE Brand != ''
) AS x
GROUP BY ID

To transpose the variables I'm interested with
and then joined it with the original table matching by id.


问:
PostgreSQL: how to format date without using to_char()?
I have this PHP-script which I'd like to keep unchanged:

```<code>$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);
</code>```

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex

答:
If you don't want to change your PHP script, you can try adjusting datestyle configuration parameter.

I would recommend that you just change your PHP script though. Changing a global server configuration might affect other stuff currently running on your server.

Body:
I have this PHP-script which I'd like to keep unchanged:

$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
Do you have some limitations for T? If not you could use Non-Generic  IList:

```<code>public static string ToDisplay(this IList source, string seperator = ",")
{
    StringBuilder str = new StringBuilder();
    foreach (var o in source)
    {
        if (o != null)
        {
            if (str.Length > 0)
                str.Append(seperator);

            IList list = o as IList;
            if (list != null)
                str.Append(list.ToDisplay(seperator));
            else
                str.Append(o);
        }
    }
    return str.ToString().TrimEnd();
}
</code>```

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
Do you have some limitations for T? If not you could use Non-Generic  IList:

public static string ToDisplay(this IList source, string seperator = ",")
{
    StringBuilder str = new StringBuilder();
    foreach (var o in source)
    {
        if (o != null)
        {
            if (str.Length > 0)
                str.Append(seperator);

            IList list = o as IList;
            if (list != null)
                str.Append(list.ToDisplay(seperator));
            else
                str.Append(o);
        }
    }
    return str.ToString().TrimEnd();
}


问:
Xamarin Native iOS breakpoints not getting hit VS2017
I cannot hit a breakpoint in VS when debugging any native iOS app through VS2017 Pro. I have trawled the Xamarin/Stack forums and seen this has been a problem in the past and I have tried the suggestions but they relate to a 3.xxx version of Xamarin. Even an out-the-box new project untouched except for placing a breakpoint still does not hit, the build server pops up the simulator and runs as expected. Android is fine

This was working, I have recently downgraded from Enterprise to Pro but think this may be a red herring. I have 2015/13 pro installed with the same problem.

Is this an issue build server side or the windows side? I get the following generated in my bin App.app, App.exe, App.pdb but no app.mdb i do get the referenced dll.mdb files.

Current vs setup...

Microsoft Visual Studio Professional 2017  (2)
Version 15.1 (26403.7) Release
VisualStudio.15.Release/15.1.0+26403.7
Microsoft .NET Framework
Version 4.6.01586

Installed Version: Professional
...
Visual Studio Tools for Universal Windows Apps   15.0.26403.07
The Visual Studio Tools for Universal Windows apps allow you to build a single universal app experience that can reach every device running Windows 10: phone, tablet, PC, and more. It includes the Microsoft Windows 10 Software Development Kit.

Xamarin   4.4.0.34 (3f99c5a)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android SDK   7.2.0.7 (b16fb82)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK   10.8.0.174 (7656cc6)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

The Mac
Xamarin Studio 6.3
VS for Mac 7

答:
See this similar answer: Xamarin iOS debugger not hitting breakpoints

Also, make sure you don't have a firewall blocking Port 10000.


问:
Displaying Text View on top of Seekbar in Android
I am trying to implement a seek bar which has text 'Confirm to Slide' with a custom thumb. Using below code I am able to get custom thumb and seek bar. Please suggest me on how to display the text on top of seek bar with an example if possible. Below is my code

```<code><SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:progressDrawable="@drawable/background"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:thumb="@drawable/thumbsize"
        android:layout_height="wrap_content"
        android:minHeight="12dp"
        android:maxHeight="36dp"
        android:max="100"
        android:progress="80"
        android:paddingLeft="10dp"
        android:splitTrack="false"
        android:paddingRight="1dp"/>
</code>```

Thanks in advance

答:
You could do something like this using vertical LinearLayout:</p>

```<code><LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Some text goes here"/>

        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

Body:
I am trying to implement a seek bar which has text 'Confirm to Slide' with a custom thumb. Using below code I am able to get custom thumb and seek bar. Please suggest me on how to display the text on top of seek bar with an example if possible. Below is my code

<SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:progressDrawable="@drawable/background"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:thumb="@drawable/thumbsize"
        android:layout_height="wrap_content"
        android:minHeight="12dp"
        android:maxHeight="36dp"
        android:max="100"
        android:progress="80"
        android:paddingLeft="10dp"
        android:splitTrack="false"
        android:paddingRight="1dp"/>

Thanks in advance

Body:
You could do something like this using vertical LinearLayout:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Some text goes here"/>

        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>


答:
As you've said, you can get the current timestamp via the time function. You can then pass this timestamp to PHP's date function. (It'll use the current time if no timestamp is provided.)

The specific format you're after is:

```<code>date('Y-m-d H:i:s');
</code>```

Title: How to get the current time in the format `2010-12-20 06:32:48` with PHP?

Body:
Anyone knows how to do it?

What I know is time() but it's pure digits..

Body:
As you've said, you can get the current timestamp via the time function. You can then pass this timestamp to PHP's date function. (It'll use the current time if no timestamp is provided.)

The specific format you're after is:

date('Y-m-d H:i:s');