问:
Processing a string using as.yearqtr
Good morning,

Let's assume I have the following variable in R:

```<code>r <- c("Q412", "Q113", "Q213","Q313")
</code>```

To transform this into yearqtr, I would have thought that this would do the trick:

```<code>as.yearqtr(r, format = "Q%q%y")
</code>```

But, all I get is:

```<code>"NA QNA" "NA QNA" "NA QNA" "NA QNA"
</code>```

What's the best way to fix this? After some experimentation I also noticed:

```<code>> as.yearqtr(x = "14 Q2", format = "%y Q%q")
[1] "2014 Q2"
> as.yearqtr(x = "14Q2", format = "%yQ%q")
[1] "2014 Q2"
> as.yearqtr(x = "Q2 14", format = "Q%q %y")
[1] "2014 Q2"
> as.yearqtr(x = "Q214", format = "Q%q%y")
[1] "NA QNA"
</code>```

Any thoughts would be appreciated,

Philipp

---- Update:

```<code>> sessionInfo()

R version 3.0.3 (2014-03-06)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
 [1] gridExtra_0.9.1  ggplot2_0.9.3.1  lattice_0.20-27  xts_0.9-7
 [5] Haver_1.2        forecast_5.2     timeDate_3010.98 dyn_0.2-9
 [9] lubridate_1.3.3  markdown_0.6.4   gplots_2.12.1    reshape_0.8.4
[13] plyr_1.8.1       googleVis_0.4.7  zoo_1.7-11       shiny_0.9.1

loaded via a namespace (and not attached):
 [1] bitops_1.0-6              caTools_1.16
 [3] colorspace_1.2-4          dichromat_2.0-0
 [5] digest_0.6.4              fracdiff_1.4-2
 [7] gdata_2.13.2              gtable_0.1.2
 [9] gtools_3.3.1              httpuv_1.2.3
[11] KernSmooth_2.23-10        labeling_0.2
[13] MASS_7.3-29               memoise_0.1
[15] munsell_0.4.2             nnet_7.3-7
[17] parallel_3.0.3            proto_0.3-10
[19] quadprog_1.5-5            RColorBrewer_1.0-5
[21] Rcpp_0.11.1               RcppArmadillo_0.4.100.2.1
[23] reshape2_1.2.2            RJSONIO_1.0-3
[25] scales_0.2.3              stringr_0.6.2
[27] tools_3.0.3               tseries_0.10-32
[29] xtable_1.7-3
</code>```

答:
gsub comes in super handy if you would like to have such a regular string manipulation:

```<code>library('zoo')
r <- c("Q412", "Q113", "Q213","Q313")
as.yearqtr(
  gsub('(Q.)(.*)', '\\1-\\2', r), # Place a hyphen between the Q(char), & the rest of the string
  format='Q%q-%y')
</code>```

Title: Processing a string using as.yearqtr

Body:
Good morning,

Let's assume I have the following variable in R:

r <- c("Q412", "Q113", "Q213","Q313")

To transform this into yearqtr, I would have thought that this would do the trick:

as.yearqtr(r, format = "Q%q%y")

But, all I get is:

"NA QNA" "NA QNA" "NA QNA" "NA QNA"

What's the best way to fix this? After some experimentation I also noticed:

> as.yearqtr(x = "14 Q2", format = "%y Q%q")
[1] "2014 Q2"
> as.yearqtr(x = "14Q2", format = "%yQ%q")
[1] "2014 Q2"
> as.yearqtr(x = "Q2 14", format = "Q%q %y")
[1] "2014 Q2"
> as.yearqtr(x = "Q214", format = "Q%q%y")
[1] "NA QNA"

Any thoughts would be appreciated,

Philipp

---- Update:

> sessionInfo()

R version 3.0.3 (2014-03-06)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
 [1] gridExtra_0.9.1  ggplot2_0.9.3.1  lattice_0.20-27  xts_0.9-7
 [5] Haver_1.2        forecast_5.2     timeDate_3010.98 dyn_0.2-9
 [9] lubridate_1.3.3  markdown_0.6.4   gplots_2.12.1    reshape_0.8.4
[13] plyr_1.8.1       googleVis_0.4.7  zoo_1.7-11       shiny_0.9.1

loaded via a namespace (and not attached):
 [1] bitops_1.0-6              caTools_1.16
 [3] colorspace_1.2-4          dichromat_2.0-0
 [5] digest_0.6.4              fracdiff_1.4-2
 [7] gdata_2.13.2              gtable_0.1.2
 [9] gtools_3.3.1              httpuv_1.2.3
[11] KernSmooth_2.23-10        labeling_0.2
[13] MASS_7.3-29               memoise_0.1
[15] munsell_0.4.2             nnet_7.3-7
[17] parallel_3.0.3            proto_0.3-10
[19] quadprog_1.5-5            RColorBrewer_1.0-5
[21] Rcpp_0.11.1               RcppArmadillo_0.4.100.2.1
[23] reshape2_1.2.2            RJSONIO_1.0-3
[25] scales_0.2.3              stringr_0.6.2
[27] tools_3.0.3               tseries_0.10-32
[29] xtable_1.7-3

Body:
gsub comes in super handy if you would like to have such a regular string manipulation:

library('zoo')
r <- c("Q412", "Q113", "Q213","Q313")
as.yearqtr(
  gsub('(Q.)(.*)', '\\1-\\2', r), # Place a hyphen between the Q(char), & the rest of the string
  format='Q%q-%y')


来源: stackexchange

问:
Remove projectName from URL with REST with Jersey2 + Tomcat 8
I'm trying to build a simple REST service in Java (JDK 1.8.0.121) with IntelliJ IDEA, Jersey v2.25.1, Maven and Tomcat v8.0.14.

I've written a simple class with a GET method in the package com.example

```<code>package com.example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class HelloWorld {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getMessage() {
        return "Hello world!";
    }
}
</code>```

I've also created a main class that extends Application:

```<code>package com.example;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class MyApp extends Application {
    public MyApp(){
        System.out.println("Server Up");
    }
}
</code>```

My web.xml is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

When I run the application in my local Tomcat all works and the REST answers succesfully at http://localhost:8080/api/hello.

When I place the myproject-1.0-SNAPSHOP.war on my VPS, if I visit:
http://vps_public_address:8080/api/hello I get a 404 error

but if I visit:
http://vps_public_address:8080/myproject-1.0-SNAPSHOP/api/hello it works.

Why I have to write "myproject-1.0-SNAPSHOP" in the REST URL?

Is is possibile to avoid putting the war name in the request URL?

Thanks in advance :)

答:
Yes, just rename your war file to ROOT.war and it will work.

Another possibility is to use the maven-tomcat-plugin for the deployment and set the context path in the plugin configuration:

```<code><project>
    ...
    <build>
    ...
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>
        ...
        </plugins>
    ...
    </build>
    ...
</project>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build a simple REST service in Java (JDK 1.8.0.121) with IntelliJ IDEA, Jersey v2.25.1, Maven and Tomcat v8.0.14.

I've written a simple class with a GET method in the package com.example

package com.example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class HelloWorld {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getMessage() {
        return "Hello world!";
    }
}

I've also created a main class that extends Application:

package com.example;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class MyApp extends Application {
    public MyApp(){
        System.out.println("Server Up");
    }
}

My web.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

When I run the application in my local Tomcat all works and the REST answers succesfully at http://localhost:8080/api/hello.

When I place the myproject-1.0-SNAPSHOP.war on my VPS, if I visit:
http://vps_public_address:8080/api/hello I get a 404 error

but if I visit:
http://vps_public_address:8080/myproject-1.0-SNAPSHOP/api/hello it works.

Why I have to write "myproject-1.0-SNAPSHOP" in the REST URL?

Is is possibile to avoid putting the war name in the request URL?

Thanks in advance :)

Body:
Yes, just rename your war file to ROOT.war and it will work.

Another possibility is to use the maven-tomcat-plugin for the deployment and set the context path in the plugin configuration:

<project>
    ...
    <build>
    ...
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.0-SNAPSHOT</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>
        ...
        </plugins>
    ...
    </build>
    ...
</project>


问:
How to find intersection of sublists of sublists in Python3.0?
Imagine a list like:

```<code>SuperList = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]
</code>```

As you can see I have a sublist inside a sublist.
How can I code it find the intersection of those sublists.?
In this case the answer is 1,3 and 4.
My goal is to append all elements that appear at least once in each sublist in a new list(it doesn't matter if it appears in all sublists of one sublist)

I tried with set.intersection, but constantly I get

```<code>'unhashable type: 'list''
</code>```

or while trying to unwind the list I get

```<code>'can't use the starred expression here'!
</code>```

答:
You can flatten the sublists and take their intersection using set.intersection:

```<code>>>> set.intersection(*[{x for lst in sub for x in lst} for sub in SuperList])
set([1, 3, 4])
</code>```

Body:
Imagine a list like:

SuperList = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]

As you can see I have a sublist inside a sublist.
How can I code it find the intersection of those sublists.?
In this case the answer is 1,3 and 4.
My goal is to append all elements that appear at least once in each sublist in a new list(it doesn't matter if it appears in all sublists of one sublist)

I tried with set.intersection, but constantly I get

'unhashable type: 'list''

or while trying to unwind the list I get

'can't use the starred expression here'!

Body:
You can flatten the sublists and take their intersection using set.intersection:

>>> set.intersection(*[{x for lst in sub for x in lst} for sub in SuperList])
set([1, 3, 4])


问:
Publishing a web application on Azure
I want to publish an web application on Azure market place.

I can create a Linux VM, install Java, Tomcat, SQL server and create an  image of it. But instead of that, is it possible to create a tomcat instance along with database on Azure portal, add it to a resource group and publish this resource group on market place?

Would this approach be more advantageous?
thanks

答:
As per the doc here:

https://learn.microsoft.com/en-us/azure/marketplace-publishing/marketplace-publishing-getting-started

Azure Marketplace offerings are based on Azure VM images or solution templates, your current solution would be the VM based route.  It sounds like you may want to look at the solution template route to leverage other capabilities such as Azure SQL Server.

Neither route enable "publish this resource group to the market place".  If that is the route you are aiming for that is essentially building out a multi-tenant application which is a bigger task and perhaps something like this link will help get you started:

https://azure.microsoft.com/en-gb/blog/with-newly-available-services-azure-continues-to-be-the-best-place-for-software-as-a-service-developers/

There are also other stackoverflow answers which may be of help:

Does a developer have to pay for publishing a SaaS app on Windows Azure Marketplace?

How can i publish my web solution to Marketplace

Title: Publishing a web application on Azure


问:
Can't use openssl extension for SSL/TLS protection
I am running Windows 10 working with Laravel 5.4, homestead 2.0, using VM and Vagrant. Everything works... Except when I am running "laravel new blog" I get:

```<code>  [Composer\Exception\NoSslException]
  The openssl extension is required for SSL/TLS protection but is not
  available. If you can not enable the openssl extension,
  you can disable this error, at your own risk, by setting the 'disable-tls'
  option to true.
</code>```

I know that there are some other questions regarding this but there seem yet not to have emerged a good answer for this. Also, most other questions regarding this is about WAMP... Therefor I think it is relevant to ask agiain when using VM.

I have removed the ; (semicolon) in front of extension=php_openssl.dll in my php.ini-development and php.ini-production. The error still remains.

When I check openssl version in comandline I have:
OpenSSL 1.0.2k  26 Jan 2017

答: ...This was due to something wrong with my PHP-install. What I finally did (which is a kinda bad solution) was to install xampp just to get a correct php version. Then I went to my PATH (winbtn + break(paus) ---> Advanced system settings ---> Environment Variables) and re-routed the php to the xampp php version and VOILA! It works. So either dig in to make a proper PHP install or YOLO like me and add xampp just to get a correct php and then it should work. GL HF!</p>

Body:
I am running Windows 10 working with Laravel 5.4, homestead 2.0, using VM and Vagrant. Everything works... Except when I am running "laravel new blog" I get:

  [Composer\Exception\NoSslException]
  The openssl extension is required for SSL/TLS protection but is not
  available. If you can not enable the openssl extension,
  you can disable this error, at your own risk, by setting the 'disable-tls'
  option to true.

I know that there are some other questions regarding this but there seem yet not to have emerged a good answer for this. Also, most other questions regarding this is about WAMP... Therefor I think it is relevant to ask agiain when using VM.

I have removed the ; (semicolon) in front of extension=php_openssl.dll in my php.ini-development and php.ini-production. The error still remains.

When I check openssl version in comandline I have:
OpenSSL 1.0.2k  26 Jan 2017


问:
Kendo UI Grid items per page dropdown dances/auto closes when the grid is displaying at the bottom of the page
The issue seems to be in the latest Kendo UI Grid Demo as well.
http://dojo.telerik.com/AJApA

The grid works in small screens like tablets.
Open the above demo link in large screen and it works fine.
Move the slider between the code and result window to the left to the maximum and try again. Upon clicking the dropdown, the dropdown list blinks and closes off.

答:
Sorry I can't add comments yet, but try to change the pageSize to number 5, it works this way, if you increases the number after 2 pages it will blinks again.

It is strange, but some how it works when it is 5.

```<code>$(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
                    },
                    pageSize: 5
                }
</code>```

instead of:

```<code>$(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
                    },
                    pageSize: 20
                }
</code>```

Body:
Sorry I can't add comments yet, but try to change the pageSize to number 5, it works this way, if you increases the number after 2 pages it will blinks again.

It is strange, but some how it works when it is 5.

$(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
                    },
                    pageSize: 5
                }

instead of:

$(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
                    },
                    pageSize: 20
                }


问:
How to speedup generating urls?
I have the following method that generates URLs for me:

```<code>async def get_url_for_ids(self, ids: List[int]) -> List[str]:
    urls = []
    async with self.session.create_client('s3', region_name=self.region_name) as s3:
        for id in ids:
            url = s3.generate_presigned_url(ClientMethod='get_object',
                  Params={'Bucket': self.bucket_with_videos,  'Key': '{}.mp4'.format(id)})
            urls.append(url)
    return urls
</code>```

This method is the slowest part in my app. Even query to the DB works much faster. get_url_for_ids works around 15 sec if ids contains for example 30,000 elements.

How to speed up it?

答:
Depending on what you are doing with your list of URLS one option could be to use a generator. This would mean the the whole list of URLs wouldn't need to be computed before you can start using them.

```<code>async def get_url_for_ids(self, ids: List[int]) -> List[str]:
    async with self.session.create_client('s3', region_name=self.region_name) as s3:
        for id in ids:
            url = s3.generate_presigned_url(ClientMethod='get_object',
                  Params={'Bucket': self.bucket_with_videos,  'Key': '{}.mp4'.format(id)})
            yield url
</code>```

To use this generator it must be in an async function, and the for loop is prefixed with async:

```<code>async def main():
    async for item in get_url_for_ids():
        #do something
</code>```

If you need the list pre-computed and available in memory, then I am not sure.

Title: How to speedup generating urls?

Body:
I have the following method that generates URLs for me:

async def get_url_for_ids(self, ids: List[int]) -> List[str]:
    urls = []
    async with self.session.create_client('s3', region_name=self.region_name) as s3:
        for id in ids:
            url = s3.generate_presigned_url(ClientMethod='get_object',
                  Params={'Bucket': self.bucket_with_videos,  'Key': '{}.mp4'.format(id)})
            urls.append(url)
    return urls

This method is the slowest part in my app. Even query to the DB works much faster. get_url_for_ids works around 15 sec if ids contains for example 30,000 elements.

How to speed up it?

Body:
Depending on what you are doing with your list of URLS one option could be to use a generator. This would mean the the whole list of URLs wouldn't need to be computed before you can start using them.

async def get_url_for_ids(self, ids: List[int]) -> List[str]:
    async with self.session.create_client('s3', region_name=self.region_name) as s3:
        for id in ids:
            url = s3.generate_presigned_url(ClientMethod='get_object',
                  Params={'Bucket': self.bucket_with_videos,  'Key': '{}.mp4'.format(id)})
            yield url

To use this generator it must be in an async function, and the for loop is prefixed with async:

async def main():
    async for item in get_url_for_ids():
        #do something

If you need the list pre-computed and available in memory, then I am not sure.


问:
c# Serialport data received event handler
I am currently reading data from serialport using WPF. I am able to read data from serialport & write it in File using Binarywriter.

What Problem I am facing right now is:
I want to Analyse this data. I have developed one function which contains Use case structures to split the data which i read in serialport datahandler. Purpose is to Analyse captured data. But my program is just hanging on in receiving data from Serialport. Its not approaching down to Analyse the data.

This are few Options which i read from some Posts which may be a solution for my problem:

Backgroundworker: If yes then how i can fetch in my current program?

Threading: I tried it but its not working. My program is handing on writing the Bytes in the file & not going down to start the thread which i declared.

So can anybody suggest me a better option?

My code:

```<code>private void port_DataReceived(Object sender, SerialDataReceivedEventArgs e) {
  BinaryWriter writer=new BinaryWriter(File.Open("c:\\temp\\lbus2snifflog1.txt", FileMode.Append));
  int bytes=comport.Read(buffer, 0, 4096);
  for (int i=0;
  i < bytes;
  i++) {
    //writer.Write(buffer, 0, bytes);             // Write the data to the file on temp folder
    data.Enqueue(buffer[i]); // Enqueue data from the buffer
    writer.Write(buffer, 0, bytes);
  }
  //writer.Write(buffer, 0, bytes);
  writer.Flush(); // Send all remaining data to the writer
  writer.Close(); // Close the writer
  /*Initilaise the Thread for the Analysis*/
  Thread Analyser=new Thread(datacollection);
  Analyser.Start();
}
</code>```

答:
I think you should run thread with setting IsBackground = true;
I use it like that

```<code>new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;
            //Do what you want to Run in background here
        }).Start();
</code>```

or maybe simple setting will do the job :

Analyser.IsBackground = true;
Analyser.Start();

Body:
I am currently reading data from serialport using WPF. I am able to read data from serialport & write it in File using Binarywriter.

What Problem I am facing right now is:
I want to Analyse this data. I have developed one function which contains Use case structures to split the data which i read in serialport datahandler. Purpose is to Analyse captured data. But my program is just hanging on in receiving data from Serialport. Its not approaching down to Analyse the data.

This are few Options which i read from some Posts which may be a solution for my problem:

Backgroundworker: If yes then how i can fetch in my current program?

Threading: I tried it but its not working. My program is handing on writing the Bytes in the file & not going down to start the thread which i declared.

So can anybody suggest me a better option?

My code:

private void port_DataReceived(Object sender, SerialDataReceivedEventArgs e) {
  BinaryWriter writer=new BinaryWriter(File.Open("c:\\temp\\lbus2snifflog1.txt", FileMode.Append));
  int bytes=comport.Read(buffer, 0, 4096);
  for (int i=0;
  i < bytes;
  i++) {
    //writer.Write(buffer, 0, bytes);             // Write the data to the file on temp folder
    data.Enqueue(buffer[i]); // Enqueue data from the buffer
    writer.Write(buffer, 0, bytes);
  }
  //writer.Write(buffer, 0, bytes);
  writer.Flush(); // Send all remaining data to the writer
  writer.Close(); // Close the writer
  /*Initilaise the Thread for the Analysis*/
  Thread Analyser=new Thread(datacollection);
  Analyser.Start();
}

Body:
I think you should run thread with setting IsBackground = true;
I use it like that

new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;
            //Do what you want to Run in background here
        }).Start();

or maybe simple setting will do the job :

Analyser.IsBackground = true;
Analyser.Start();


问:
UPDATE MySQL Query taking a long time to execute - ways to optimize
I have a doubt with the following query.

```<code>update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;
</code>```

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

```<code>src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+
</code>```

答:
First, you don't need the where clause.  Second, remove the index hints:

```<code>update src_woz_waardeklasse_2011 ww inner join
       waardeklasse_average wa
       on wa.waardeklasse_new = ww.waardeklasse
    set ww.woz_value = wb.average ;
</code>```

Then, try an index on src_woz_waardeklasse_2011(waardeklasse).  This should improve the execution plan.

You might also check that the 46 records in the second table actually correspond to 46 updates. If the join conditions are wrong, you could be updating all the records.

EDIT:

Indexes have nothing to do with your problem.  Updating 7 million records takes a long time.  You might consider creating the data you want in a temporary table and then truncating the original table and inserting the new rows into it.  Otherwise, batch the updates a few rows at a time.

Body:
I have a doubt with the following query.

update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+

Body:
First, you don't need the where clause.  Second, remove the index hints:

update src_woz_waardeklasse_2011 ww inner join
       waardeklasse_average wa
       on wa.waardeklasse_new = ww.waardeklasse
    set ww.woz_value = wb.average ;

Then, try an index on src_woz_waardeklasse_2011(waardeklasse).  This should improve the execution plan.

You might also check that the 46 records in the second table actually correspond to 46 updates. If the join conditions are wrong, you could be updating all the records.

EDIT:

Indexes have nothing to do with your problem.  Updating 7 million records takes a long time.  You might consider creating the data you want in a temporary table and then truncating the original table and inserting the new rows into it.  Otherwise, batch the updates a few rows at a time.


问:
laravel 5 update multiple columns in one line?
It's possible update multiple columns in one line with laravel 5.4?

I try to this

```<code>        DB::table('Home_Content')->where('id',1)->update(
        [$_POST['name'] => $_POST['content']],
        [$_POST['title'] => $_POST['titleMsg']]
        );
</code>```

only 1st part is work([$_POST['name'] => $_POST['content']])

server not return any error, but only 1st part is success.

答:
Update method syntax in Laravel is like so :

```<code>DB::table('users')
        ->where('id', 1)
        ->update(['options->enabled' => true]);
</code>```

Which means the values we want to update are inside an array, what I've seen is that you separated what you want to update into two arrays

```<code>DB::table('Home_Content')->where('id',1)->update(
    [$_POST['name'] => $_POST['content']],
    [$_POST['title'] => $_POST['titleMsg']]
    );
</code>```

so now you are out of the array

Your code should be like this

```<code>DB::table('Home_Content')->where('id',1)->update([
    $_POST['name'] => $_POST['content'],
    $_POST['title'] => $_POST['titleMsg']
]);
</code>```

Meaning each pair has a key and a value and separated with comma

Body:
It's possible update multiple columns in one line with laravel 5.4?

I try to this

        DB::table('Home_Content')->where('id',1)->update(
        [$_POST['name'] => $_POST['content']],
        [$_POST['title'] => $_POST['titleMsg']]
        );

only 1st part is work([$_POST['name'] => $_POST['content']])

server not return any error, but only 1st part is success.

Body:
Update method syntax in Laravel is like so :

DB::table('users')
        ->where('id', 1)
        ->update(['options->enabled' => true]);

Which means the values we want to update are inside an array, what I've seen is that you separated what you want to update into two arrays

DB::table('Home_Content')->where('id',1)->update(
    [$_POST['name'] => $_POST['content']],
    [$_POST['title'] => $_POST['titleMsg']]
    );

so now you are out of the array

Your code should be like this

DB::table('Home_Content')->where('id',1)->update([
    $_POST['name'] => $_POST['content'],
    $_POST['title'] => $_POST['titleMsg']
]);

Meaning each pair has a key and a value and separated with comma


问:
Java Removing Look and Feel
How can I remove any look and feel on my JFrame application to make the controls look like default windows controls ?

Screenshot of what I'm looking for

答:
You can specify the look and feel you want to use.  I personally prefer to default to the "system" look and feel, which defaults to the OS specific implementation (Windows on Windows)

```<code>EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }
    }
}
</code>```

Do this BEFORE you load any other UI elements

You should also have a look at How to Set the Look and Feel for more details

Title: Java Removing Look and Feel

Body:
You can specify the look and feel you want to use.  I personally prefer to default to the "system" look and feel, which defaults to the OS specific implementation (Windows on Windows)

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }
    }
}

Do this BEFORE you load any other UI elements

You should also have a look at How to Set the Look and Feel for more details


问:
Infinite scroll on already populated div
I have a div with large data (many sub-div),I want to implement a infinite scroll on this div, I tried with some jquery scripts which is available on internet for example :

JScroll

MetaFizzy Infinite Scroll

and many more which i could find on google.

Most of the scripts do ajax call to fetch data (but i already have data with me)

I am able to implement Custom Pagination with next and previous functionality
as used in this example
Custom Pagination with Next and Prev Button

But i want to implement a infinite scroll

Here's is div example

```<code><div class="InfiniteScroll">
  <div class="line-content">1 I have some content</div>
  <div class="line-content">2 I have some content</div>
  <div class="line-content">3 I have some content</div>
  <div class="line-content">4 I have some content</div>
  <div class="line-content">5 I have some content</div>
  <div class="line-content">6 I have some content</div>
  <div class="line-content">7 I have some content</div>
  <div class="line-content">8 I have some content</div>
  <div class="line-content">9 I have some content</div>
  <div class="line-content">10 I have some content</div>
  <div class="line-content">11 I have some content</div>
  ..
  ..
  ..
  ..
  ..
  ..
  ..
  <div>AND MANY MORE</div>
</div>
</code>```

Fiddle For Testing :   Fiddle For Test

答:
Used window scroll and window height offset worked for me </p>

<p>Code snippet  </p>

```<code>var $doc=$(document);
var $win=$(window);
var itemstoshow=5;

$('.infinite').filter(function(index){
    return (($(this).offset().top) > $win.height());
}).hide();

$(window).scroll(function(){
    if ($doc.height()-$win.height()-$(this).scrollTop() == 0) {
        $('.infinite:hidden:lt('+itemstoshow+')').show();
    }
});
</code>```

Body:
I have a div with large data (many sub-div),I want to implement a infinite scroll on this div, I tried with some jquery scripts which is available on internet for example :

JScroll

MetaFizzy Infinite Scroll

and many more which i could find on google.

Most of the scripts do ajax call to fetch data (but i already have data with me)

I am able to implement Custom Pagination with next and previous functionality
as used in this example
Custom Pagination with Next and Prev Button

But i want to implement a infinite scroll

Here's is div example

1 I have some content

2 I have some content

3 I have some content

4 I have some content

5 I have some content

6 I have some content

7 I have some content

8 I have some content

9 I have some content

10 I have some content

11 I have some content

  ..
  ..
  ..
  ..
  ..
  ..
  ..

AND MANY MORE

Fiddle For Testing :   Fiddle For Test

Body:
Used window scroll and window height offset worked for me

Code snippet

var $doc=$(document);
var $win=$(window);
var itemstoshow=5;

$('.infinite').filter(function(index){
    return (($(this).offset().top) > $win.height());
}).hide();

$(window).scroll(function(){
    if ($doc.height()-$win.height()-$(this).scrollTop() == 0) {
        $('.infinite:hidden:lt('+itemstoshow+')').show();
    }
});


问:
Replace all td's tags by th in a java String
I want to replace replace all "td" by "th" in this String

```<code>String head = "<tr>\n<td> </td>\n<td> </td>\n<td>Libelle</td>\n"
                      + "<td>Nom Table</td>\n<td>Groupe</td>\n<td> </td>\n</tr>\n"
</code>```

I tried to use :

```<code>head.replace("<td>", "<th>");
head.replace("</td>", "</th>");
</code>```

but it doesn't working.

Can you help me ?

答:
replace methods returns a new string.

String s= "hi hi hi";

String f= s.replace("hi", "bye");

System.out.println(s+ "----" + f);

prints: hi hi hi----bye bye bye

Body:
I want to replace replace all "td" by "th" in this String

String head = "
\n 	\n 	\nLibelle	\n"
                      + "Nom Table	\nGroupe	\n 	\n
\n"

I tried to use :

head.replace("", "");
head.replace("	", "	");

but it doesn't working.

Can you help me ?


问:
how can I use FirstOrDefault()?
I have this code and I want to set a value to Viewdate when the expression returns no data:

```<code>ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;
</code>```

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

答:
Default will return the default for the data type.  If the data type in that place is a reference type (e.g. string) the default value will always be null, and therefore the following .NumsCoefficientFix member will throw a NullReferenceException.

The default value is built into .NET and not changeable, and is always given if the result set contains no value.

@Mikey has already given the code sample in his answer that I would suggest.

ContentLicense: CC BY-SA 2.5

Title: how can I use FirstOrDefault()?

Body:
I have this code and I want to set a value to Viewdate when the expression returns no data:

ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.


答: The class JFrame belongs to the Swing Framework (so what you are creating actually is a "Swing Application" not a "JFrame Application") and seeing that you attached the nimbus tag you seem to have activated the Nimbus Look and Feel. If you want to achieve a native look, you need to set the system look and feel (see MadProgrammers answer written in the meantime).</p>

Title: Java Removing Look and Feel

Body:
How can I remove any look and feel on my JFrame application to make the controls look like default windows controls ?

Screenshot of what I'm looking for


答:
You can customize the Look & Feel using

UIManager.setLookAndFeel("path.to.lookAndFeel");

Optionally, you can also retrieve the Look & Feel from the system your program is operating on:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

I haven't tested it yet, but if the default Windows Look & Feel is what you want to achieve, I'd recommend trying
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

Exceptions included, the full code would be

```<code> try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
    }
    catch (UnsupportedLookAndFeelException e) {
       // handle exception
    }
    catch (ClassNotFoundException e) {
       // handle exception
    }
    catch (InstantiationException e) {
       // handle exception
    }
    catch (IllegalAccessException e) {
       // handle exception
    }
</code>```

(In case the above doesn't work, you might want to check what's installed, using

public static UIManager.LookAndFeelInfo[] getInstalledLookAndFeels())

Title: Java Removing Look and Feel

Body:
You can customize the Look & Feel using

UIManager.setLookAndFeel("path.to.lookAndFeel");

Optionally, you can also retrieve the Look & Feel from the system your program is operating on:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

I haven't tested it yet, but if the default Windows Look & Feel is what you want to achieve, I'd recommend trying
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

Exceptions included, the full code would be

 try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
    }
    catch (UnsupportedLookAndFeelException e) {
       // handle exception
    }
    catch (ClassNotFoundException e) {
       // handle exception
    }
    catch (InstantiationException e) {
       // handle exception
    }
    catch (IllegalAccessException e) {
       // handle exception
    }

(In case the above doesn't work, you might want to check what's installed, using

public static UIManager.LookAndFeelInfo[] getInstalledLookAndFeels())


问:
Composer autoload - load class from parent directory
I'm currently working on a Laravel project that needs to access classes from its parent directory.

composer.json > PSR-4:

```<code>    "psr-4": {
        ...
        "ModuleA\\": "../ModuleA/baseObjects",
        "ModuleB\\": "../ModuleB/baseObjects"
    }
</code>```

Example file structure:

```<code>/var/www
 +- /xxx (project)
     +- /ModuleA
        +- /baseObjects
            - configClass.inc
     +- /ModuleB
        +- /baseObjects
            - configClass.inc
     +- /laravel
        - composer.json
</code>```

I run composer dump-autoload but the project still can't find ModuleA\configClass neither ModuleB\configClass.

Furthermore, inside my autoload_psr4.php, the above gets referenced as following:

```<code>'MobuleA\\' => array($baseDir . '/../MobuleA/baseObjects')
'MobuleB\\' => array($baseDir . '/../MobuleB/baseObjects')
</code>```

答:
try it：</p>

```<code>"psr-4": {
        ...
        "ModuleA\\": "ModuleA/baseObjects",
        "ModuleB\\": "ModuleB/baseObjects"
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently working on a Laravel project that needs to access classes from its parent directory.

composer.json > PSR-4:

    "psr-4": {
        ...
        "ModuleA\\": "../ModuleA/baseObjects",
        "ModuleB\\": "../ModuleB/baseObjects"
    }

Example file structure:

/var/www
 +- /xxx (project)
     +- /ModuleA
        +- /baseObjects
            - configClass.inc
     +- /ModuleB
        +- /baseObjects
            - configClass.inc
     +- /laravel
        - composer.json

I run composer dump-autoload but the project still can't find ModuleA\configClass neither ModuleB\configClass.

Furthermore, inside my autoload_psr4.php, the above gets referenced as following:

'MobuleA\\' => array($baseDir . '/../MobuleA/baseObjects')
'MobuleB\\' => array($baseDir . '/../MobuleB/baseObjects')

Body:
try it：

"psr-4": {
        ...
        "ModuleA\\": "ModuleA/baseObjects",
        "ModuleB\\": "ModuleB/baseObjects"
 }


问:
Java Regex capture nested matches
I am having trouble with regex here.

Say i have this input:

```<code>608094.21.1.2014.TELE.&BIG00Z.1.1.GBP
</code>```

My regex looks like this

```<code>(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)
</code>```

I want to extract the date 21.1.2014 out of the string, but all i get is

```<code>8094.21.1
</code>```

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

答:
If the date is always surrounded by dot:</p>

```<code>\.(\d\d\d\d\.\d?\d\.\d?\d|\d?\d\.\d?\d\.\d?\d?\d\d)\.
</code>```

Title: Java Regex capture nested matches

Body:
I am having trouble with regex here.

Say i have this input:

608094.21.1.2014.TELE.&BIG00Z.1.1.GBP

My regex looks like this

(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)

I want to extract the date 21.1.2014 out of the string, but all i get is

8094.21.1

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

Body:
If the date is always surrounded by dot:

\.(\d\d\d\d\.\d?\d\.\d?\d|\d?\d\.\d?\d\.\d?\d?\d\d)\.


问:
Can we able to access tables from two different hive2 servers using multiple sparksessions
Can we able to access tables from two different hive2 servers using two SparkSessions like below:

```<code>val spark = SparkSession.builder().master("local")
  .appName("spark remote")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.160:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.160:9083")
  .enableHiveSupport()
  .getOrCreate()

val sparkdestination = SparkSession.builder().master("local") .appName("spark remote2")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.42:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.42:9083")
  .enableHiveSupport()
  .getOrCreate()

import spark.implicits._
import spark.sql
val source = spark.sql("SELECT * from sample.source limit 20")

import sparkdestination.implicits._
import sparkdestination.sql
val destination = sparkdestination.sql("select * from sample.destination  limit 20")
</code>```

Or is there is any possible way we can able to access two different database tables like mysql-hive for comaparison using multiple sparksessions.

Thank you

答:
Finally I found the solution for my concern of how to use multiple SparkSession, its achieved by:

```<code>SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()
</code>```

After clearing the sessions we can reassign it with different values.

Body:
Can we able to access tables from two different hive2 servers using two SparkSessions like below:

val spark = SparkSession.builder().master("local")
  .appName("spark remote")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.160:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.160:9083")
  .enableHiveSupport()
  .getOrCreate()

val sparkdestination = SparkSession.builder().master("local") .appName("spark remote2")
  .config("javax.jdo.option.ConnectionURL", "jdbc:mysql://192.168.175.42:3306/metastore?useSSL=false")
  .config("javax.jdo.option.ConnectionUserName", "hiveroot")
  .config("javax.jdo.option.ConnectionPassword", "hivepassword")
  .config("hive.exec.scratchdir", "/tmp/hive/${user.name}")
  .config("hive.metastore.uris", "thrift://192.168.175.42:9083")
  .enableHiveSupport()
  .getOrCreate()

import spark.implicits._
import spark.sql
val source = spark.sql("SELECT * from sample.source limit 20")

import sparkdestination.implicits._
import sparkdestination.sql
val destination = sparkdestination.sql("select * from sample.destination  limit 20")

Or is there is any possible way we can able to access two different database tables like mysql-hive for comaparison using multiple sparksessions.

Thank you

Body:
Finally I found the solution for my concern of how to use multiple SparkSession, its achieved by:

SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()

After clearing the sessions we can reassign it with different values.


问:
Visual Studio Code SQL results dock to bottom
I'm trying to dock the SQL queries results to bottom in VS Code, as we see at SSMS. In old versions of VS Code I could do it, but I don't know what happened. The results can be moved only to left/right of window now, and the results view are awful in this way.

I want to make the VS Code SQL results disposed like this:

But I have only this on VS Code:

Any help will be appreciated.

答:
Go to View -> Toggle Editor Group Layout

https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-develop-use-vscode


问:
J2EE redirect to an external URL
I am developing a web application in which the servlet takes informaiton from index.jsp and does some data processing. After that, I want my application to redirect the user to an external url.

How can I do that? Should I redirect in the servlet or make the servlet call a jsp page which calls the url? and how to do that explicitly?

Thank you in advance!

答:
There is no need for creating a seperate jsp for url redirection. After performing the required operations in the servlet, simply call sendredirect method of the response object.
'reponse.sendRedirect(url)' will do.

Title: J2EE redirect to an external URL


问:
Camel blueprint: enums value in header
I'm trying to set an header using a Java Enum object, but in Camel blueprint it is automatically converted in a string instead of been used as Enum object.
In the blueprint I have this route:

```<code>    <route id="doOperationARoute">
        <from uri="timer://MNG?delay=5s&repeatCount=1" />
        <setHeader headerName="operationName">
            <simple>${type:my.pkg.EnumOperations.OP_A}</simple>
        </setHeader>
        <log message="${headers}" />
        <to uri="bean:myProcessor" />
    </route>
</code>```

The Java enum:

```<code> package my.pkg;
 public enum EnumOperations{
    OP_A
 }
</code>```

The processor:

```<code>public class MyProcessor implements Processor{
    @Override
    public void process(Exchange exc) throws Exception {

        //HERE I RECEIVE THE CAST ERROR (String cannot be casted to EnumOperation)
        EnumOperations operation=(EnumOperations)exc.getIn().getHeader("operationName");

        switch (operation) {
        case OP_A:
            break;
        default:
            break;
        }
    }
}
</code>```

I searched in the simple documentation, but nothing found. Any idea?

答:
You can do this in 2 ways:

1) In your proccessor get the headr with the class type

```<code>EnumOperations operation = exc.getIn().getHeader("operationName", EnumOperations.class);
</code>```

2) Use a bean instead if a Camel Proccessor and pass the enum with the @header

```<code>class Bean {

   public void methodName (@Header("operationName") EnumOperations operation){
     switch (operation) {
        case OP_A:
            break;
        default:
            break;
        }
   }
</code>```

}

Title: Camel blueprint: enums value in header

Body:
I'm trying to set an header using a Java Enum object, but in Camel blueprint it is automatically converted in a string instead of been used as Enum object.
In the blueprint I have this route:

    <route id="doOperationARoute">
        <from uri="timer://MNG?delay=5s&repeatCount=1" />
        <setHeader headerName="operationName">
            <simple>${type:my.pkg.EnumOperations.OP_A}</simple>
        </setHeader>
        <log message="${headers}" />
        <to uri="bean:myProcessor" />
    </route>

The Java enum:

 package my.pkg;
 public enum EnumOperations{
    OP_A
 }

The processor:

public class MyProcessor implements Processor{
    @Override
    public void process(Exchange exc) throws Exception {

        //HERE I RECEIVE THE CAST ERROR (String cannot be casted to EnumOperation)
        EnumOperations operation=(EnumOperations)exc.getIn().getHeader("operationName");

        switch (operation) {
        case OP_A:
            break;
        default:
            break;
        }
    }
}

I searched in the simple documentation, but nothing found. Any idea?

Body:
You can do this in 2 ways:

1) In your proccessor get the headr with the class type

EnumOperations operation = exc.getIn().getHeader("operationName", EnumOperations.class);

2) Use a bean instead if a Camel Proccessor and pass the enum with the @header

class Bean {

   public void methodName (@Header("operationName") EnumOperations operation){
     switch (operation) {
        case OP_A:
            break;
        default:
            break;
        }
   }

}


问:
Highcharts - handle click on overlapping areaspline point
I need to get the point details every time I click on a certain point of a series, but clicking on a areaspline overlapped point doesn't trigger the 'click' event. It triggers only if the points of the series are in front.

```<code>        plotOptions: {
            series: {
                events: {
                    click: function(event) {
                        alert(this.name);
                    }
                }
            }
        },
</code>```

I made a small fiddle showing it.

Thanks.

答:
If you set trackByArea option to true it will enable catching click events even if the series is behind another series.

```<code> plotOptions: {
            series: {
              trackByArea: true,
                events: {
                    click: function(event) {
                        alert(this.name);
                    }
                }
            }
        },
</code>```

example: http://jsfiddle.net/83x6L69x/

However, this will catch events even when you click not exactly on the point. To avoid it, you can check if the click event was done inside the point's marker:

```<code>      plotOptions: {
        series: {
          trackByArea: true,
          point: {
            events: {
              click: function(e) {
                console.log(this)
                const group = this.series.group
                const x = e.chartX - this.plotX - group.translateX
                const y = e.chartY - this.plotY - group.translateY
                const d = (x * x + y * y)

                const rPlus = this.graphic.states.hover.radiusPlus // it is an additional radius when the point is hovered
                const r = this.graphic.radius + (rPlus || 0)

                if (x * x + y * y <= r * r) {
                  alert(this.series.name)
                }
              }
            }
          }
        }
      },
</code>```

example: http://jsfiddle.net/dh4zn6h4/

Body:
I need to get the point details every time I click on a certain point of a series, but clicking on a areaspline overlapped point doesn't trigger the 'click' event. It triggers only if the points of the series are in front.

        plotOptions: {
            series: {
                events: {
                    click: function(event) {
                        alert(this.name);
                    }
                }
            }
        },

I made a small fiddle showing it.

Thanks.

Body:
If you set trackByArea option to true it will enable catching click events even if the series is behind another series.

 plotOptions: {
            series: {
              trackByArea: true,
                events: {
                    click: function(event) {
                        alert(this.name);
                    }
                }
            }
        },

example: http://jsfiddle.net/83x6L69x/

However, this will catch events even when you click not exactly on the point. To avoid it, you can check if the click event was done inside the point's marker:

      plotOptions: {
        series: {
          trackByArea: true,
          point: {
            events: {
              click: function(e) {
                console.log(this)
                const group = this.series.group
                const x = e.chartX - this.plotX - group.translateX
                const y = e.chartY - this.plotY - group.translateY
                const d = (x * x + y * y)

                const rPlus = this.graphic.states.hover.radiusPlus // it is an additional radius when the point is hovered
                const r = this.graphic.radius + (rPlus || 0)

                if (x * x + y * y <= r * r) {
                  alert(this.series.name)
                }
              }
            }
          }
        }
      },

example: http://jsfiddle.net/dh4zn6h4/


问:
Set Gradient as Button Color Renderer
I'm using Xamarin.Forms and I'm trying to set a gradient as a button color.
I have the exactly same problem as this guy: Gradient Layer form as the form of a button in Xamarin.Forms Android

But the given answer is not quite what I'm looking for.

The answer is successful but it set all the button as the gradient.

I.E.: The guy had a problem that only the background was painted, the given answer sets the whole button, I want to set the color of the button itself and keep the padding.

Here I probably have why the code it's not working, how to use the answer and and make this work??
Edit:
Here is my code:

```<code>public class GenericButton:Button
{
    public Xamarin.Forms.Color StartColor { get; set; }
    public Xamarin.Forms.Color EndColor { get; set; }
}
</code>```

With this code I get the backround beyond the button:

```<code>public class GenericButtonRenderer :ButtonRenderer
{
    private Xamarin.Forms.Color StartColor { get; set; }
    private Xamarin.Forms.Color EndColor { get; set; }

    protected override void DispatchDraw(Canvas canvas)
    {
        var gradient = new Android.Graphics.LinearGradient(0, 0, Width, Height,
            this.StartColor.ToAndroid(),
            this.EndColor.ToAndroid(),
            Android.Graphics.Shader.TileMode.Clamp);
        var paint = new Android.Graphics.Paint()
        {
            Dither = true,
        };
        paint.SetShader(gradient);
        canvas.DrawPaint(paint);
        base.DispatchDraw(canvas);
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement != null || Element == null)
        {
            return;
        }
        try
        {
            var btn = e.NewElement as GenericButton;
            this.StartColor = btn.StartColor;
            this.EndColor = btn.EndColor;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"          ERROR: ", ex.Message);
        }
    }
}//See result here: http://i.stack.imgur.com/3ZpuX.png
</code>```

The second thing I tried, with this I get the gradient correct but the button loses its layout:

```<code>public class GenericButtonRenderer :ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement != null || Element == null)
        {
            return;
        }
        try
        {
            var btn = e.NewElement as GenericButton;
            var gradient = new GradientDrawable(GradientDrawable.Orientation.TopBottom, new[] {
            btn.StartColor.ToAndroid().ToArgb(),
           btn.EndColor.ToAndroid().ToArgb()
        });
            Control.Background=gradient;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"          ERROR: ", ex.Message);
        }
    }
}//See result here: http://i.stack.imgur.com/4CDtG.png
</code>```

答:
You need to extend ButtonRenderer and customize the Background property of native control.</p>

```<code>/// <summary>
    /// Extends <see cref="Xamarin.Forms.Button"/>.
    /// </summary>
    public class ExtendedButton : Button
    {
        /// <summary>
        /// Bindable property for button background gradient start color
        /// </summary>
        public static readonly BindableProperty StartColorProperty =
            BindableProperty.Create("StartColor", typeof(Color), typeof(ExtendedButton), Color.Gray);

        /// <summary>
        /// Gets or sets the background gradient start color
        /// </summary>
        public Color StartColor
        {
            get { return (Color)this.GetValue(StartColorProperty); }
            set { this.SetValue(StartColorProperty, value); }
        }

        /// <summary>
        /// Bindable property for button background gradient end color
        /// </summary>
        public static readonly BindableProperty EndColorProperty =
            BindableProperty.Create("EndColor", typeof(Color), typeof(ExtendedButton), Color.Black);

        /// <summary>
        /// Gets or sets the background gradient end color
        /// </summary>
        public Color EndColor
        {
            get { return (Color)this.GetValue(EndColorProperty); }
            set { this.SetValue(EndColorProperty, value); }
        }
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

using NewHelloWorld.Droid.Renderers;
using NewHelloWorld;

[assembly: ExportRenderer(typeof(ExtendedButton), typeof(ExtendedButtonRenderer))]
namespace NewHelloWorld.Droid.Renderers
{
    /// <summary>
    /// Class ExtendedButtonRenderer.
    /// </summary>
    public class ExtendedButtonRenderer : ButtonRenderer
    {
        /// <summary>
        /// Called when [element changed].
        /// </summary>
        /// <param name="e">The e.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            UpdateGradientBackground();
        }

        /// <summary>
        /// Handles the <see cref="E:ElementPropertyChanged" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == ExtendedButton.StartColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.EndColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderRadiusProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderWidthProperty.PropertyName)
            {
                UpdateGradientBackground();
            }

            base.OnElementPropertyChanged(sender, e);
        }

        //Called
        protected override void UpdateBackgroundColor()
        {
            base.UpdateBackgroundColor();

            UpdateGradientBackground();
        }

        //Sets the background gradient color
        private void UpdateGradientBackground()
        {
            var button = this.Element as ExtendedButton;
            if (button != null)
            {
                int[] colors = new int[] { button.StartColor.ToAndroid(), button.EndColor.ToAndroid() };
                var gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TopBottom, colors);
                gradientDrawable.SetGradientType(GradientType.LinearGradient);
                gradientDrawable.SetShape(ShapeType.Rectangle);
                gradientDrawable.SetCornerRadius(button.BorderRadius);
                gradientDrawable.SetStroke((int)button.BorderWidth, button.BorderColor.ToAndroid());
                this.Control.Background = gradientDrawable;
            }
        }
    }
}
</code>```

Title: Set Gradient as Button Color Renderer

Body:
I'm using Xamarin.Forms and I'm trying to set a gradient as a button color.
I have the exactly same problem as this guy: Gradient Layer form as the form of a button in Xamarin.Forms Android

But the given answer is not quite what I'm looking for.

The answer is successful but it set all the button as the gradient.

I.E.: The guy had a problem that only the background was painted, the given answer sets the whole button, I want to set the color of the button itself and keep the padding.

Here I probably have why the code it's not working, how to use the answer and and make this work??
Edit:
Here is my code:

public class GenericButton:Button
{
    public Xamarin.Forms.Color StartColor { get; set; }
    public Xamarin.Forms.Color EndColor { get; set; }
}

With this code I get the backround beyond the button:

public class GenericButtonRenderer :ButtonRenderer
{
    private Xamarin.Forms.Color StartColor { get; set; }
    private Xamarin.Forms.Color EndColor { get; set; }

    protected override void DispatchDraw(Canvas canvas)
    {
        var gradient = new Android.Graphics.LinearGradient(0, 0, Width, Height,
            this.StartColor.ToAndroid(),
            this.EndColor.ToAndroid(),
            Android.Graphics.Shader.TileMode.Clamp);
        var paint = new Android.Graphics.Paint()
        {
            Dither = true,
        };
        paint.SetShader(gradient);
        canvas.DrawPaint(paint);
        base.DispatchDraw(canvas);
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement != null || Element == null)
        {
            return;
        }
        try
        {
            var btn = e.NewElement as GenericButton;
            this.StartColor = btn.StartColor;
            this.EndColor = btn.EndColor;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"          ERROR: ", ex.Message);
        }
    }
}//See result here: http://i.stack.imgur.com/3ZpuX.png

The second thing I tried, with this I get the gradient correct but the button loses its layout:

public class GenericButtonRenderer :ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement != null || Element == null)
        {
            return;
        }
        try
        {
            var btn = e.NewElement as GenericButton;
            var gradient = new GradientDrawable(GradientDrawable.Orientation.TopBottom, new[] {
            btn.StartColor.ToAndroid().ToArgb(),
           btn.EndColor.ToAndroid().ToArgb()
        });
            Control.Background=gradient;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"          ERROR: ", ex.Message);
        }
    }
}//See result here: http://i.stack.imgur.com/4CDtG.png

Body:
You need to extend ButtonRenderer and customize the Background property of native control.

/// <summary>
    /// Extends <see cref="Xamarin.Forms.Button"/>.
    /// </summary>
    public class ExtendedButton : Button
    {
        /// <summary>
        /// Bindable property for button background gradient start color
        /// </summary>
        public static readonly BindableProperty StartColorProperty =
            BindableProperty.Create("StartColor", typeof(Color), typeof(ExtendedButton), Color.Gray);

        /// <summary>
        /// Gets or sets the background gradient start color
        /// </summary>
        public Color StartColor
        {
            get { return (Color)this.GetValue(StartColorProperty); }
            set { this.SetValue(StartColorProperty, value); }
        }

        /// <summary>
        /// Bindable property for button background gradient end color
        /// </summary>
        public static readonly BindableProperty EndColorProperty =
            BindableProperty.Create("EndColor", typeof(Color), typeof(ExtendedButton), Color.Black);

        /// <summary>
        /// Gets or sets the background gradient end color
        /// </summary>
        public Color EndColor
        {
            get { return (Color)this.GetValue(EndColorProperty); }
            set { this.SetValue(EndColorProperty, value); }
        }
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

using NewHelloWorld.Droid.Renderers;
using NewHelloWorld;

[assembly: ExportRenderer(typeof(ExtendedButton), typeof(ExtendedButtonRenderer))]
namespace NewHelloWorld.Droid.Renderers
{
    /// <summary>
    /// Class ExtendedButtonRenderer.
    /// </summary>
    public class ExtendedButtonRenderer : ButtonRenderer
    {
        /// <summary>
        /// Called when [element changed].
        /// </summary>
        /// <param name="e">The e.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            UpdateGradientBackground();
        }

        /// <summary>
        /// Handles the <see cref="E:ElementPropertyChanged" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == ExtendedButton.StartColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.EndColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderColorProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderRadiusProperty.PropertyName ||
                e.PropertyName == ExtendedButton.BorderWidthProperty.PropertyName)
            {
                UpdateGradientBackground();
            }

            base.OnElementPropertyChanged(sender, e);
        }

        //Called
        protected override void UpdateBackgroundColor()
        {
            base.UpdateBackgroundColor();

            UpdateGradientBackground();
        }

        //Sets the background gradient color
        private void UpdateGradientBackground()
        {
            var button = this.Element as ExtendedButton;
            if (button != null)
            {
                int[] colors = new int[] { button.StartColor.ToAndroid(), button.EndColor.ToAndroid() };
                var gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TopBottom, colors);
                gradientDrawable.SetGradientType(GradientType.LinearGradient);
                gradientDrawable.SetShape(ShapeType.Rectangle);
                gradientDrawable.SetCornerRadius(button.BorderRadius);
                gradientDrawable.SetStroke((int)button.BorderWidth, button.BorderColor.ToAndroid());
                this.Control.Background = gradientDrawable;
            }
        }
    }
}


问:
Return vue instance from vue.js filter (Vue.js 2)
I'm using filter function for internationalization like this:

```<code><div>{{ "hello" | message }}<div>
</code>```

message is a filter function that depends on global Vue.config.lang variable.

It works great, but if I change Vue.config.lang, message doesn't rerender.

I wanted to make message rerender anytime Vue.config.lang changes, so I changed my filter function from

```<code>message => locale_messages[Vue.config.lang][message]
</code>```

to

```<code>message => new Vue({
  template: '{{ message }}',
  computed: {
    message() { return locale_messages[Vue.config.lang][message]; }
  }
})
</code>```

But it doesn't work. Getting this error:

```<code>Uncaught TypeError: Converting circular structure to JSON
    at Object.stringify (<anonymous>)
    ....
</code>```

Is there anything I can do to make it work? I'm new to Vue.js and can't find a working solution.

答:
New to Vue myself, so not quite sure how global variables work, but you can definitely pass params to a custom filter - even a Vue reference. You can do this: </p>

```<code><!-- this = a reference to the vue instance -->
<span class="display-3">{{value|FormatValue(this)}}</span>

[...]

props: ["aIsPercentNeeded"],

[...]

Vue.filter("FormatValue", function (aValue, aVueInstance)
{
  if (!aVueInstance["aIsPercentNeeded"])
  {
    return aValue;
  }

  return aValue + "%";
});
</code>```

Body:
I'm using filter function for internationalization like this:

{{ "hello" | message }}

message is a filter function that depends on global Vue.config.lang variable.

It works great, but if I change Vue.config.lang, message doesn't rerender.

I wanted to make message rerender anytime Vue.config.lang changes, so I changed my filter function from

message => locale_messages[Vue.config.lang][message]

to

message => new Vue({
  template: '{{ message }}',
  computed: {
    message() { return locale_messages[Vue.config.lang][message]; }
  }
})

But it doesn't work. Getting this error:

Uncaught TypeError: Converting circular structure to JSON
    at Object.stringify (<anonymous>)
    ....

Is there anything I can do to make it work? I'm new to Vue.js and can't find a working solution.

Body:
New to Vue myself, so not quite sure how global variables work, but you can definitely pass params to a custom filter - even a Vue reference. You can do this:

<!-- this = a reference to the vue instance -->
<span class="display-3">{{value|FormatValue(this)}}</span>

[...]

props: ["aIsPercentNeeded"],

[...]

Vue.filter("FormatValue", function (aValue, aVueInstance)
{
  if (!aVueInstance["aIsPercentNeeded"])
  {
    return aValue;
  }

  return aValue + "%";
});


问:
How can I create an editable combobox?
I need to populate the combo box Items from a database query (this part is no problem).
Then if the user does not find an option, they can enter their own text and store in Db with index..
       Add new item to store in Db with index value and display the value from db with index and value.

using jquery or javascript...

Help plz..

答:
Actually there is a plugin called jEC

Product Page

Demo

jEC on Google Code

Title: How can I create an editable combobox?


问:
CAGradientLayer, not resizing nicely, tearing on rotation
I'm trying to get my CAGradientLayers, that i'm using to create nice gradient backgrounds, to resize nicely on rotation and modal view presentation, but they will not play ball.

Here is a video I just created showing my problem: Notice the tearing on rotation.

Also please note this video was created by filming the iPhone Simulator on OS X. I have slowed down the animations in the video to highlight my issue.

Video of Problem...

Here is an Xcode project which I just created (which is the source for the app shown in the video), basically as illustrated the issue occurs on rotation and especially when views are presented modally:

Xcode Project, modally presenting views with CAGradientLayer backgrounds...

For what it's worth I understand that using:

```<code>    [[self view] setBackgroundColor:[UIColor blackColor]];
</code>```

does a reasonable job of making the transitions a bit more seamless and less jarring, but if you look at the video when I, whilst currently in landscape mode, modally present a view, you will see why the above code will not help.

Any ideas what I can do to sort this out?

John

答:
Info

Use as one line solution

Replacing gradient when you add it to the view again (to use in reusables)

Automatically transiting

Automatically removing

Details

Swift 3.1, xCode 8.3.3

Solution

```<code>import UIKit

extension UIView {

    func addGradient(colors: [UIColor], locations: [NSNumber]) {
        addSubview(ViewWithGradient(addTo: self, colors: colors, locations: locations))
    }
}

class ViewWithGradient: UIView {

    private var gradient = CAGradientLayer()

    init(addTo parentView: UIView, colors: [UIColor], locations: [NSNumber]){

        super.init(frame: CGRect(x: 0, y: 0, width: 1, height: 2))
        restorationIdentifier = "__ViewWithGradient"

        for subView in parentView.subviews {
            if let subView = subView as? ViewWithGradient {
                if subView.restorationIdentifier == restorationIdentifier {
                    subView.removeFromSuperview()
                    break
                }
            }
        }

        let cgColors = colors.map { (color) -> CGColor in
            return color.cgColor
        }

        gradient.frame = parentView.frame
        gradient.colors = cgColors
        gradient.locations = locations
        backgroundColor = .clear

        parentView.addSubview(self)
        parentView.layer.insertSublayer(gradient, at: 0)
        parentView.backgroundColor = .clear
        autoresizingMask = [.flexibleWidth, .flexibleHeight]

        clipsToBounds = true
        parentView.layer.masksToBounds = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        if let parentView = superview {
            gradient.frame = parentView.bounds
        }
    }

    override func removeFromSuperview() {
        super.removeFromSuperview()
        gradient.removeFromSuperlayer()
    }
}
</code>```

Usage

```<code>viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])
</code>```

Using StoryBoard

ViewController

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var viewWithGradient: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])
    }
}
</code>```

StoryBoard

```<code><?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
        <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_17555986" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="uii-31-sl9">
                                <rect key="frame" x="66" y="70" width="243" height="547"/>
                                <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                            </view>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="wfy-db-euE" firstAttribute="top" secondItem="uii-31-sl9" secondAttribute="bottom" constant="50" id="a7J-Hq-IIq"/>
                            <constraint firstAttribute="trailingMargin" secondItem="uii-31-sl9" secondAttribute="trailing" constant="50" id="i9v-hq-4tD"/>
                            <constraint firstItem="uii-31-sl9" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="50" id="wlO-83-8FY"/>
                            <constraint firstItem="uii-31-sl9" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" constant="50" id="zb6-EH-j6p"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="viewWithGradient" destination="uii-31-sl9" id="FWB-7A-MaH"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
        </scene>
    </scenes>
</document>
</code>```

Programmatically

```<code>import UIKit

class ViewController2: UIViewController {

    @IBOutlet weak var viewWithGradient: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let viewWithGradient = UIView(frame: CGRect(x: 10, y: 20, width: 30, height: 40))
        view.addSubview(viewWithGradient)

        viewWithGradient.translatesAutoresizingMaskIntoConstraints = false
        let constant:CGFloat = 50.0

        NSLayoutConstraint(item: viewWithGradient, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1.0, constant: constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin
                    , multiplier: 1.0, constant: -1*constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottomMargin
            , multiplier: 1.0, constant: -1*constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin
            , multiplier: 1.0, constant: constant).isActive = true

        viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])
    }
}
</code>```

Body:
I'm trying to get my CAGradientLayers, that i'm using to create nice gradient backgrounds, to resize nicely on rotation and modal view presentation, but they will not play ball.

Here is a video I just created showing my problem: Notice the tearing on rotation.

Also please note this video was created by filming the iPhone Simulator on OS X. I have slowed down the animations in the video to highlight my issue.

Video of Problem...

Here is an Xcode project which I just created (which is the source for the app shown in the video), basically as illustrated the issue occurs on rotation and especially when views are presented modally:

Xcode Project, modally presenting views with CAGradientLayer backgrounds...

For what it's worth I understand that using:

    [[self view] setBackgroundColor:[UIColor blackColor]];

does a reasonable job of making the transitions a bit more seamless and less jarring, but if you look at the video when I, whilst currently in landscape mode, modally present a view, you will see why the above code will not help.

Any ideas what I can do to sort this out?

John

Body:
Info

Use as one line solution

Replacing gradient when you add it to the view again (to use in reusables)

Automatically transiting

Automatically removing

Details

Swift 3.1, xCode 8.3.3

Solution

import UIKit

extension UIView {

    func addGradient(colors: [UIColor], locations: [NSNumber]) {
        addSubview(ViewWithGradient(addTo: self, colors: colors, locations: locations))
    }
}

class ViewWithGradient: UIView {

    private var gradient = CAGradientLayer()

    init(addTo parentView: UIView, colors: [UIColor], locations: [NSNumber]){

        super.init(frame: CGRect(x: 0, y: 0, width: 1, height: 2))
        restorationIdentifier = "__ViewWithGradient"

        for subView in parentView.subviews {
            if let subView = subView as? ViewWithGradient {
                if subView.restorationIdentifier == restorationIdentifier {
                    subView.removeFromSuperview()
                    break
                }
            }
        }

        let cgColors = colors.map { (color) -> CGColor in
            return color.cgColor
        }

        gradient.frame = parentView.frame
        gradient.colors = cgColors
        gradient.locations = locations
        backgroundColor = .clear

        parentView.addSubview(self)
        parentView.layer.insertSublayer(gradient, at: 0)
        parentView.backgroundColor = .clear
        autoresizingMask = [.flexibleWidth, .flexibleHeight]

        clipsToBounds = true
        parentView.layer.masksToBounds = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        if let parentView = superview {
            gradient.frame = parentView.bounds
        }
    }

    override func removeFromSuperview() {
        super.removeFromSuperview()
        gradient.removeFromSuperlayer()
    }
}

Usage

viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])

Using StoryBoard

ViewController

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var viewWithGradient: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])
    }
}

StoryBoard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
        <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_17555986" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="uii-31-sl9">
                                <rect key="frame" x="66" y="70" width="243" height="547"/>
                                <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                            </view>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="wfy-db-euE" firstAttribute="top" secondItem="uii-31-sl9" secondAttribute="bottom" constant="50" id="a7J-Hq-IIq"/>
                            <constraint firstAttribute="trailingMargin" secondItem="uii-31-sl9" secondAttribute="trailing" constant="50" id="i9v-hq-4tD"/>
                            <constraint firstItem="uii-31-sl9" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="50" id="wlO-83-8FY"/>
                            <constraint firstItem="uii-31-sl9" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" constant="50" id="zb6-EH-j6p"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="viewWithGradient" destination="uii-31-sl9" id="FWB-7A-MaH"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
        </scene>
    </scenes>
</document>

Programmatically

import UIKit

class ViewController2: UIViewController {

    @IBOutlet weak var viewWithGradient: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let viewWithGradient = UIView(frame: CGRect(x: 10, y: 20, width: 30, height: 40))
        view.addSubview(viewWithGradient)

        viewWithGradient.translatesAutoresizingMaskIntoConstraints = false
        let constant:CGFloat = 50.0

        NSLayoutConstraint(item: viewWithGradient, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1.0, constant: constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin
                    , multiplier: 1.0, constant: -1*constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottomMargin
            , multiplier: 1.0, constant: -1*constant).isActive = true
        NSLayoutConstraint(item: viewWithGradient, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin
            , multiplier: 1.0, constant: constant).isActive = true

        viewWithGradient.addGradient(colors: [.blue, .green, .orange], locations: [0.1, 0.3, 1.0])
    }
}


问:
Aurelia - how send object or parameter to viewmodel?
I use Kendo multiselect:

```<code><ak-multiselect k-data-text-field="name"
  k-data-value-field="id"
  id="selectCorporateGroup"
  k-data-source.bind="corporateGroupDataSource"
  k-on-change.delegate="SetGroupFilter(???)"
  data-placeholder="Select corporate group...">
</ak-multiselect>
</code>```

in ts-file I have the following description for SetGroupFilter:

```<code>SetGroupFilter(select)
    {
        var multiselect = select.data("kendoMultiSelect");
        var selectedItems = multiselect.dataItems();

        var filters = this.buildFilters(selectedItems , "GroupId");
        this.merchantDataSource.filter(filters);
    }
</code>```

Before I had the following SetGroupFilter function:

```<code>export class TransactionComponent {
        SetGroupFilter()
            {
                var multiselect = $("#selectCorporateGroup").data("kendoMultiSelect");
                var dataItem = multiselect.dataItems();

                var filters = this.buildFilters(dataItem, "GroupId");
                this.merchantDataSource.filter(filters);
            }
    }
</code>```

But now I have a task to divide model & viewmodel. So I can't use id for my multiselect in ts-file.

But how I can send the necessary information to viewmodel? I want to sent my multiselect as object.

If I use k-on-change.delegate="SetGroupFilter($this)", I get select = TransactionComponent

If I use k-on-change.delegate="SetGroupFilter(this)" I get select = undefined

How I can fixed it?

答:
I have found the decision!

I have used the following expression:

```<code>k-on-change.delegate="SetGroupFilter($event)"
</code>```

And in viewmodel:

```<code>var multiselect = select.detail.sender;

var dataItem = select.detail.sender.dataItems();
</code>```

It works fine!

Body:
I use Kendo multiselect:

<ak-multiselect k-data-text-field="name"
  k-data-value-field="id"
  id="selectCorporateGroup"
  k-data-source.bind="corporateGroupDataSource"
  k-on-change.delegate="SetGroupFilter(???)"
  data-placeholder="Select corporate group...">
</ak-multiselect>

in ts-file I have the following description for SetGroupFilter:

SetGroupFilter(select)
    {
        var multiselect = select.data("kendoMultiSelect");
        var selectedItems = multiselect.dataItems();

        var filters = this.buildFilters(selectedItems , "GroupId");
        this.merchantDataSource.filter(filters);
    }

Before I had the following SetGroupFilter function:

export class TransactionComponent {
        SetGroupFilter()
            {
                var multiselect = $("#selectCorporateGroup").data("kendoMultiSelect");
                var dataItem = multiselect.dataItems();

                var filters = this.buildFilters(dataItem, "GroupId");
                this.merchantDataSource.filter(filters);
            }
    }

But now I have a task to divide model & viewmodel. So I can't use id for my multiselect in ts-file.

But how I can send the necessary information to viewmodel? I want to sent my multiselect as object.

If I use k-on-change.delegate="SetGroupFilter($this)", I get select = TransactionComponent

If I use k-on-change.delegate="SetGroupFilter(this)" I get select = undefined

How I can fixed it?

Body:
I have found the decision!

I have used the following expression:

k-on-change.delegate="SetGroupFilter($event)"

And in viewmodel:

var multiselect = select.detail.sender;

var dataItem = select.detail.sender.dataItems();

It works fine!