问:
Android sockets: listening doesn't work through 4G
I'm learning Android and Java programming on my own. To practise, I've developed a couple of apps, and now I'm trying to write a chat-like application. So basically, I want to to something like WhatsApp. I have a server program also coded by me running in my computer, and it's what the chat in the Android system uses to communicate. So basically, everything is sent to the server and the server does what required to deliver the messages.

So here is what I have:

First, my app sends a "Hello" to my server (known IP and port)

The server stores the IP and the port (also the username) used by each user

When the server is asked to deliver a message to a user, it sends it to the IP and port stored

I use a socket for the "Hello", but I can't use the same one for sending back messages (because of how I programmed the server). But this is not the problem. When the server receives the "Hello", it's listening on the corresponding port. But when the server is the one who has to start the connection, it's the app the one who has to. In order to do this, the app must know on what port it must listen (it doesn't know because of NAT), and I tell it so sending back the port used through the first socket used for the "Hello" message. Despite this, my app is unable to receive messages and stays in the receive call.

Here you have the code:

Server:

```<code>    DatagramSocket client = new DatagramSocket(2048); //Predefined port
    DatagramPacket receivePacket;
    byte[] receiveData = new byte[1024];
    receivePacket = new DatagramPacket(receiveData,
            receiveData.length);
    System.out.println("Ready to receive");
    client.receive(receivePacket);
    System.out.println("Received successfuly");
    String receivedPort = String.valueOf(receivePacket.getPort());
    byte[] sendData = receivedPort.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
    client.send(sendPacket); //Send back the port used by the app
    System.out.println("Sent successfuly");
    client.close();
    Thread.sleep(1000); //To make sure the app is ready to listen
    DatagramSocket socket = new DatagramSocket();
    byte[] sendData2 = "Working like a charm".getBytes();
    InetAddress ip = receivePacket.getAddress();
    int port = receivePacket.getPort();
    System.out.println(ip + " " + port);
    DatagramPacket sendPacket2 = new DatagramPacket(sendData2, sendData2.length, ip, port);
    socket.send(sendPacket);
    System.out.println("Sent successfuly 2nd time");
    socket.close();
</code>```

Client (Android app):

```<code>EditText eT = (EditText) findViewById(R.id.messageText);
String message = eT.getText().toString();
DatagramSocket socket = new DatagramSocket();
byte[] sendData = message.getBytes();
InetAddress ip = InetAddress.getByName(MY_COMPUTER'S_IP);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 2048);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); //Receive the port used (and that must be opened and redirecting the traffic to this device due to NAT)
socket.close();
String receivedMessage = new String(receivePacket.getData());
String receivedData = new String(receivePacket.getData());
String actualData = receivedData.substring(0, receivePacket.getLength());
Log.d("Port", actualData);
int port = Integer.parseInt(actualData);
DatagramSocket socket2 = new DatagramSocket(port);
DatagramPacket receivePacket2;
byte[] receiveData2 = new byte[1024];
receivePacket2 = new DatagramPacket(receiveData2,
        receiveData2.length);
socket2.receive(receivePacket2); //Here is where it gets blocked
String data = new String(receivePacket2.getData());
Log.d("Finally received", data.substring(receivePacket2.getLength()));
socket2.close();
</code>```

Does anybody know why my messages aren't making it back through the second socket? I've checked and the IP and ports are correct.

Thanks in advance for answering, and I apologize for my formatting.

答:
First tell me is the device connected to the direct ip address or the subnet ? Is the device having some ip address like local ip 192.168 ..? and the is the NAT configured properly on the router to forward the packets to the respective port on the device ?

What i suspect is you device able to send because the server ip is going to be a static one. While receiving it might not reach the device... You tell me what is the ip address of the device and the server..

Once after ypu replied we can figure out the problem. In android its better if you use the websockets and send and receive the messages over wss connection. Also to reduce the power consumption try to use the google push notification service or the firebase messaging service to enable chat functionality.

Body:
I'm learning Android and Java programming on my own. To practise, I've developed a couple of apps, and now I'm trying to write a chat-like application. So basically, I want to to something like WhatsApp. I have a server program also coded by me running in my computer, and it's what the chat in the Android system uses to communicate. So basically, everything is sent to the server and the server does what required to deliver the messages.

So here is what I have:

First, my app sends a "Hello" to my server (known IP and port)

The server stores the IP and the port (also the username) used by each user

When the server is asked to deliver a message to a user, it sends it to the IP and port stored

I use a socket for the "Hello", but I can't use the same one for sending back messages (because of how I programmed the server). But this is not the problem. When the server receives the "Hello", it's listening on the corresponding port. But when the server is the one who has to start the connection, it's the app the one who has to. In order to do this, the app must know on what port it must listen (it doesn't know because of NAT), and I tell it so sending back the port used through the first socket used for the "Hello" message. Despite this, my app is unable to receive messages and stays in the receive call.

Here you have the code:

Server:

    DatagramSocket client = new DatagramSocket(2048); //Predefined port
    DatagramPacket receivePacket;
    byte[] receiveData = new byte[1024];
    receivePacket = new DatagramPacket(receiveData,
            receiveData.length);
    System.out.println("Ready to receive");
    client.receive(receivePacket);
    System.out.println("Received successfuly");
    String receivedPort = String.valueOf(receivePacket.getPort());
    byte[] sendData = receivedPort.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
    client.send(sendPacket); //Send back the port used by the app
    System.out.println("Sent successfuly");
    client.close();
    Thread.sleep(1000); //To make sure the app is ready to listen
    DatagramSocket socket = new DatagramSocket();
    byte[] sendData2 = "Working like a charm".getBytes();
    InetAddress ip = receivePacket.getAddress();
    int port = receivePacket.getPort();
    System.out.println(ip + " " + port);
    DatagramPacket sendPacket2 = new DatagramPacket(sendData2, sendData2.length, ip, port);
    socket.send(sendPacket);
    System.out.println("Sent successfuly 2nd time");
    socket.close();

Client (Android app):

EditText eT = (EditText) findViewById(R.id.messageText);
String message = eT.getText().toString();
DatagramSocket socket = new DatagramSocket();
byte[] sendData = message.getBytes();
InetAddress ip = InetAddress.getByName(MY_COMPUTER'S_IP);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 2048);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); //Receive the port used (and that must be opened and redirecting the traffic to this device due to NAT)
socket.close();
String receivedMessage = new String(receivePacket.getData());
String receivedData = new String(receivePacket.getData());
String actualData = receivedData.substring(0, receivePacket.getLength());
Log.d("Port", actualData);
int port = Integer.parseInt(actualData);
DatagramSocket socket2 = new DatagramSocket(port);
DatagramPacket receivePacket2;
byte[] receiveData2 = new byte[1024];
receivePacket2 = new DatagramPacket(receiveData2,
        receiveData2.length);
socket2.receive(receivePacket2); //Here is where it gets blocked
String data = new String(receivePacket2.getData());
Log.d("Finally received", data.substring(receivePacket2.getLength()));
socket2.close();

Does anybody know why my messages aren't making it back through the second socket? I've checked and the IP and ports are correct.

Thanks in advance for answering, and I apologize for my formatting.


来源: stackexchange

问:
missingKeyMapError zk
Google maps do not load in zk. This is my .zul code

```<code><?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk xmlns:h="http://www.w3.org/1999/xhtml">
<script type="text/javascript" content="zk.googleAPIkey='AIzaSyBwAGLvnAYOtoRd32kkaqOxKuLyMAxcJTs'" />
<window >
    <div>
        <gmaps id="gmaps" width="520px" height="400px" protocol="https"/>
    </div>
</window>
</zk>
</code>```

Workspace configuration:JAVA 8 AND ZK 8.0.2.1

答:
Please upgrade to ZK Gmaps version 3.0.4 older versions don't transmit the key correctly (mentioned here):

Download or Maven Dependency:

```<code><dependency>
    <groupId>org.zkoss.zkforge</groupId>
    <artifactId>gmapsz</artifactId>
    <version>3.0.4</version>
</dependency>
</code>```

Robert

ContentLicense: CC BY-SA 3.0

Title: missingKeyMapError zk

Body:
Google maps do not load in zk. This is my .zul code

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk xmlns:h="http://www.w3.org/1999/xhtml">

Body:
Please upgrade to ZK Gmaps version 3.0.4 older versions don't transmit the key correctly (mentioned here):

Download or Maven Dependency:

<dependency>
    <groupId>org.zkoss.zkforge</groupId>
    <artifactId>gmapsz</artifactId>
    <version>3.0.4</version>
</dependency>

Robert


问:
Is it appropriate to return HTTP 503 in response to a database deadlock?
Is it appropriate for a server to return 503 ("Service Unavailable") when the requested operation resulted in a database deadlock?

Here is my reasoning:

Initially I tried avoiding database deadlocks, but I ran across https://stackoverflow.com/a/112256/14731

Next, I tried repeating the request on the server-side, but I ran across Java Servlets: How to repeat an HTTP request?. Technically speaking I can buffer the request entity but scalability will suffer and clients are more likely to see 503 Service Unavailable anyway.

Seeing as:

It's easier to ask clients to repeat the operation.

They need to be able to handle 503 Service Unavailable anyway.

Database deadlocks are rather rare.

I'm leaning towards this solution. What do you think?

UPDATE: I think returning 503 ("Service Unavailable") is still acceptable if you wish it, but I no longer think it is technically required. See https://stackoverflow.com/a/17960047/14731.

答:
I think semantically 409 Conflict is a better alternative - basically if you have a deadlock there's contention for some resource, and so the operation could not be completed.

Now depending on the reason for the deadlock, the request may not succeed if submitted a second time, but that's true for anything.

For a 503, as a client I'd implement some sort of back-away/circuit breaker operation as the system is rate limited, whereas 409 relates to the specific request.


问:
Check if object is not colliding with anything
Is there a way to detect if the collider on the player (with a rigidbody) object is not colliding with any other collider in a 2D environment?</p>

答:
Not per se, but there are two ways you can get the information. It's easiest to keep an int counter, and increment it in OnCollisionEnter and decrement in OnCollisionExit. When the counter is 0, there are no collisions.

Another way, which will tell you which colliders are overlapping but not necessarily if they are touching, is to use a physics function. Note which type of collider you have--sphere, capsule, box. Knowing the size/shape/position of the collider, you can call Physics.OverlapBox, Physics.OverlapCapsule, or Physics.OverlapSphere. Give the function the same shape as your collider, and it will return the colliders that overlap that space. (For 2D colliders, you can use the Physics2D.Overlap* functions.)


问:
Good resources for finding intents from strings using NLP
I am looking to decode intents from many strings from many conversations I have stored in a database, so I can use machine learning to create an intelligent chatbot. I have heard and tested tools like Amazon Lex, but I am looking to receive the intent from a string not create my own intents. Here is a sample starting question from the data I am working with:

Hi, can I please find out the location of the nearest Depot to Meadow Springs WA 6210?

Is there any chance we could get 34 cases from Melbourne to Sydney by Friday. I am hoping it will be a Sydney to Sydney tomorrow but if not can anyone do this by Friday from Melbourne?

can you tell me how the warranty claim is going on booking number 9528 thanks

答:
Intents are usually created for a specific application by providing examples. However, some services do provide pre-defined intents you can use.

LUIS provides prebuilt "domains" which include some place related queries

Snips has an "intents library" that you can use

That may be able to get you started. If that doesn't work, this guide to a from-scratch implementation may be useful.


问:
How to replace "if" statement with a ternary operator ( ? : )?
Based on the examples from this page, I wanted to convert the below if statement to a ternary operator.

Working code using if statement:

```<code>if (!empty($address['street2'])) echo $address['street2'].'<br />';
</code>```

I am not sure how this should be written using a ternary operator so that the echo works only if street2 exists in the array and is not an empty string.

答:
PHP 7+

As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :

```<code>echo $address['street2'] ?? 'Empty';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Based on the examples from this page, I wanted to convert the below if statement to a ternary operator.

Working code using if statement:

if (!empty($address['street2'])) echo $address['street2'].'
';

I am not sure how this should be written using a ternary operator so that the echo works only if street2 exists in the array and is not an empty string.

Body:
PHP 7+

As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :

echo $address['street2'] ?? 'Empty';


问:
C#: How to access a button outside the form class
I want to either enable or disable a button from another file,what should I do?

This is the form class declaration:

```<code>public partial class Form1 : Form
</code>```

I tried with

```<code>Form.btnName.enabled = false/true
</code>```

but there's no btnName member.

Thanks in advance!

答:
In Form1, create a object for external class(add button name in the parameter)

```<code>Class1 obj_Class1 = new Class1(btnName);
</code>```

In Class1 , create a private button

```<code>private System.Windows.Forms.Button btnName;
</code>```

In Class1 Construct

```<code> public Class1(System.Windows.Forms.Button btnName)
        {
            this. btnName = btnName;
        }
</code>```

then you can access your button like,

```<code>btnName.enabled = false/true;
</code>```

OwnerDisplayName: John

ContentLicense: CC BY-SA 2.5

Body:
I want to either enable or disable a button from another file,what should I do?

This is the form class declaration:

public partial class Form1 : Form

I tried with

Form.btnName.enabled = false/true

but there's no btnName member.

Thanks in advance!

LastEditorDisplayName: ScarletGarden

Body:
In Form1, create a object for external class(add button name in the parameter)

Class1 obj_Class1 = new Class1(btnName);

In Class1 , create a private button

private System.Windows.Forms.Button btnName;

In Class1 Construct

 public Class1(System.Windows.Forms.Button btnName)
        {
            this. btnName = btnName;
        }

then you can access your button like,

btnName.enabled = false/true;


问:
How to define in Eclipse Plugin WTP the context name of my app
I am working in Eclipse 4.2 and the WTP Plugin. I deployed my web-app on the integrated tomcat 7 server, but the context name is not as supposed. I want to name it moduleA but the current project name will be used as context name in the tomcat.

I already changed the Context-Root to moduleA in the Properties->Web Web Project Settings and I added

```<code><properties>
    <runtime.context>moduleA</runtime.context>
    <m2eclipse.wtp.contextRoot>moduleA</m2eclipse.wtp.contextRoot>
</properties>
</code>```

to my pom.xml

As I start my Tomcat it will always deploy it with the project name. Does someone know what the problem might be?

Thanks

答:
Hello if you are using pom.xml with maven 3.. version.
you can use eclipse plugin like given below

```<code><plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <wtpversion>2.0</wtpversion>
                <wtpContextName>moduleA</wtpContextName>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
                <classpathContainers>
                    <classpathContainer>org.eclipse.jst.j2ee.internal.web.container</classpathContainer>
                    <classpathContainer>org.eclipse.jst.j2ee.internal.module.container</classpathContainer>
                </classpathContainers>
            </configuration>
        </plugin>
</code>```

and give the desired context name in  tag.

Body:
I am working in Eclipse 4.2 and the WTP Plugin. I deployed my web-app on the integrated tomcat 7 server, but the context name is not as supposed. I want to name it moduleA but the current project name will be used as context name in the tomcat.

I already changed the Context-Root to moduleA in the Properties->Web Web Project Settings and I added

<properties>
    <runtime.context>moduleA</runtime.context>
    <m2eclipse.wtp.contextRoot>moduleA</m2eclipse.wtp.contextRoot>
</properties>

to my pom.xml

As I start my Tomcat it will always deploy it with the project name. Does someone know what the problem might be?

Thanks

Body:
Hello if you are using pom.xml with maven 3.. version.
you can use eclipse plugin like given below

<plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <wtpversion>2.0</wtpversion>
                <wtpContextName>moduleA</wtpContextName>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
                <classpathContainers>
                    <classpathContainer>org.eclipse.jst.j2ee.internal.web.container</classpathContainer>
                    <classpathContainer>org.eclipse.jst.j2ee.internal.module.container</classpathContainer>
                </classpathContainers>
            </configuration>
        </plugin>

and give the desired context name in  tag.


问:
How do I turn an image into a popup with only text
I'm trying to have a popup show when an image is clicked. All I can find is how to enlarge an image. Below is the code I have but it's not working. I'm not sure which part is wrong... Am I allowed to have a table in the span tag? </p>

```<code>.popup {
margin-top: 10%;
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

.popup .popuptext {
visibility: hidden;
width: 250px;
background-color: #5FACD7;
color: #000000;
text-align: center;
border-radius: 6px;
Padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;
</code>```

<p>}</p>

```<code>.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}

@-websit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

<div class="popup" onclick="popup1()">
<img src="../media/hours.jpg" alt="Hours of Operation" width="300"
height="200"/>
<span class="popuptext" id="myPopup">
    <table>
    <tr>
    <th>Day</th>
    <th>Times</th>
    </tr>
    <tr>
        <td> Monday - Wednesday</td>
        <td> Thursday</td>
        <td>Friday</td>
        <td>Saturday/Sunday</td>
    </tr>
    <tr>
        <td>9:00 a.m. - 6:00 p.m.</td>
        <td>9:00 a.m. - 9:00 p.m.</td>
        <td>9:00 a.m. - 8:00 p.m.</td>
        <td>10:00 a.m. - 6:00 p.m.</td>
    </tr>
    </table>
    </span>
</div>

<div class="popup" onClick="=popup2()">
<img src="../media/tickets.jpeg" alt="General Admission" width="300"
height="200"/>
<span class="popuptext" id="myPopup2">
<table>
    <tr>
    <th></th>
    <th>Prices</th>
    </tr>
    <tr>
        <td>Adults: </td>
        <td>Children (5-12): </td>
        <td>Seniors/Students with ID: </td>
        <td>Adult Members: </td>
        <td>Child Members: </td>
    </tr>
    <tr>
        <td>$12.00</td>
        <td>$6.00</td>
        <td>$8.00</td>
        <td>Free</td>
        <td>Free</td>
    </tr>
    </table>
    </span>
</div>
</code>```

答:
You can insert some text after the image after click;

```<code>  $('<span class="absolute">Test</span>').insertAfter(this);
</code>```

And make wrap it in a div the same height and width of the image, and make it position: relative;
and then absolutely position it above the image.

```<code>.absolute {
  position: absolute;
  left: 50%;
  top: 50%;
  transform:translate(-50%,-50%)
}
</code>```

Here is an example:

$('.click-text').click(function() {
  if (!$(this).next('span.absolute').length) {
    $('Test').insertAfter(this);
  } else {
    $(this).next('span.absolute').remove();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.img-container {
  height: 100px;
  width: 100px;
  position: relative;
}
.absolute {
  position: absolute;
  left: 50%;
  top: 50%;
  transform:translate(-50%,-50%)
}</code>```

```

Body:
I'm trying to have a popup show when an image is clicked. All I can find is how to enlarge an image. Below is the code I have but it's not working. I'm not sure which part is wrong... Am I allowed to have a table in the span tag?

.popup {
margin-top: 10%;
position: relative;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

.popup .popuptext {
visibility: hidden;
width: 250px;
background-color: #5FACD7;
color: #000000;
text-align: center;
border-radius: 6px;
Padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;

}

.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}

@-websit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}

    Day
    Times

         Monday - Wednesday
         Thursday
        Friday
        Saturday/Sunday

        9:00 a.m. - 6:00 p.m.
        9:00 a.m. - 9:00 p.m.
        9:00 a.m. - 8:00 p.m.
        10:00 a.m. - 6:00 p.m.

    Prices

        Adults:
        Children (5-12):
        Seniors/Students with ID:
        Adult Members:
        Child Members:

        $12.00
        $6.00
        $8.00
        Free
        Free

Body:
You can insert some text after the image after click;

  $('<span class="absolute">Test</span>').insertAfter(this);

And make wrap it in a div the same height and width of the image, and make it position: relative;
and then absolutely position it above the image.

.absolute {
  position: absolute;
  left: 50%;
  top: 50%;
  transform:translate(-50%,-50%)
}

Here is an example:

$('.click-text').click(function() {
  if (!$(this).next('span.absolute').length) {
    $('<span class="absolute">Test</span>').insertAfter(this);
  } else {
    $(this).next('span.absolute').remove();
  }
});

.img-container {
  height: 100px;
  width: 100px;
  position: relative;
}
.absolute {
  position: absolute;
  left: 50%;
  top: 50%;
  transform:translate(-50%,-50%)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="img-container">
  <img src="http://via.placeholder.com/100x100" class="click-text">
</div>


问:
Filling missing values with distribution
So i have 2 dataset.

On the first one i have values for each hour of a day. Example:

```<code>Date                 Value
05/07/2017 01:00     5
05/07/2017 02:00     10
05/07/2017 03:00     5
</code>```

In the second dataset i only have the total of each day

```<code>Date                 Value
05/07/2017           40
</code>```

So i want to distribute the total of the second dataset by the same distribution of the first dataset. Something like this:

```<code>Date                 Value
05/07/2017 01:00     10
05/07/2017 02:00     20
05/07/2017 03:00     10
</code>```

How can i do this? I'm using R and created a time series for the first dataset.

答:
You may want to check the mice package for R which specialises in missing data imputation. In your case probably a knn method which would impute the missing values by regarding similar (times) attribute-wise samples might do the trick.

Having a second look, maybe a bit more sophisticated procedure would be possible to bootstrap the values across the different times and then to fill the missing value you would have to find a random (times) combination (assuming that you use a random sample of each time specific time pool or distribution) of these which would total to the sum that you have.

Body:
So i have 2 dataset.

On the first one i have values for each hour of a day. Example:

Date                 Value
05/07/2017 01:00     5
05/07/2017 02:00     10
05/07/2017 03:00     5

In the second dataset i only have the total of each day

Date                 Value
05/07/2017           40

So i want to distribute the total of the second dataset by the same distribution of the first dataset. Something like this:

Date                 Value
05/07/2017 01:00     10
05/07/2017 02:00     20
05/07/2017 03:00     10

How can i do this? I'm using R and created a time series for the first dataset.

OwnerDisplayName: Philip C.


问:
Spring JPA - Data fetching selected columns
Am using Spring JPA repository

```<code>public String getNextULAID();
 // Selecting particular columns from a table
  @Query(value="select dbts,firstName from user_details
  where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)

  public UserDetails fetchUser(@Param("ulaID")String ulaId);
}
</code>```

Throws error

```<code>{
    "timestamp": 1499336001602,
    "status": 500,
    "error": "Internal Server Error",

    "exception": "org.springframework.dao.InvalidDataAccessResourceUsageException",

    "message": "could not extract ResultSet; SQL [n/a];
    nested exception is org.hibernate.exception.SQLGrammarException:
    could not extract ResultSet",

    "path": "/viewProfile/1"
}
</code>```

But if I select all data from the database,then its working perfectly

```<code>public String getNextULAID();
  // selecting all records
  @Query(value="select * from user_details
  where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)
  public UserDetails fetchUser(@Param("ulaID")String ulaId);

}
</code>```

Here is my entity...

```<code>import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// End of user code

 @Entity
 @Table(name="user_details")
 public class UserDetails {
/**
 * Description of the property dbts.
 */
private Integer dbts;

/**
 * Description of the property ulaId.
 */
@Id
private String ulaId = "";

/**
 * Description of the property firstName.
 */
private String firstName = "";

/**
 * Description of the property lastName.
 */
private String lastName = "";

/**
 * Description of the property emailId.
 */
private String emailId = "";

/**
 * Description of the property mobileNo.
 */
private String mobileNo = "";

/**
 * Description of the property gender.
 */
private String gender = "";

/**
 * Description of the property dateOfBirth.
 */
private String dateOfBirth = "";

/**
 * Description of the property address1.
 */
private String address1 = "";

/**
 * Description of the property address2.
 */
private String address2 = "";

/**
 * Description of the property city.
 */
private String city = "";

/**
 * Description of the property state.
 */
private String state = "";

/**
 * Description of the property country.
 */
private String country = "";

/**
 * Description of the property pincode.
 */
private String pincode = "";

/**
 * Description of the property profileGroup.
 */
private String profileGroup = "";

/**
 * Description of the property delFlg.
 */
private String delFlg = "";

/**
 * Description of the property remarks.
 */
private String remarks = "";

/**
 * Description of the property rCreTime.
 */
private String rCreTime = "";

/**
 * Description of the property rModTime.
 */
private String rModTime = "";

// Start of user code (user defined attributes for UserDetails)

// End of user code

/**
 * The constructor.
 */
public UserDetails() {
    // Start of user code constructor for UserDetails)
    super();
    // End of user code
}

// Start of user code (user defined methods for UserDetails)

// End of user code
/**
 * Returns dbts.
 * @return dbts
 */
public Integer getDbts() {
    return this.dbts;
}

/**
 * Sets a value to attribute dbts.
 * @param newDbts
 */
public void setDbts(Integer newDbts) {
    this.dbts = newDbts;
}

/**
 * Returns ulaId.
 * @return ulaId
 */
public String getUlaId() {
    return this.ulaId;
}

/**
 * Sets a value to attribute ulaId.
 * @param newUlaId
 */
public void setUlaId(String newUlaId) {
    this.ulaId = newUlaId;
}

/**
 * Returns firstName.
 * @return firstName
 */
public String getFirstName() {
    return this.firstName;
}

/**
 * Sets a value to attribute firstName.
 * @param newFirstName
 */
public void setFirstName(String newFirstName) {
    this.firstName = newFirstName;
}

/**
 * Returns lastName.
 * @return lastName
 */
public String getLastName() {
    return this.lastName;
}

/**
 * Sets a value to attribute lastName.
 * @param newLastName
 */
public void setLastName(String newLastName) {
    this.lastName = newLastName;
}

/**
 * Returns emailId.
 * @return emailId
 */
public String getEmailId() {
    return this.emailId;
}

/**
 * Sets a value to attribute emailId.
 * @param newEmailId
 */
public void setEmailId(String newEmailId) {
    this.emailId = newEmailId;
}

/**
 * Returns mobileNo.
 * @return mobileNo
 */
public String getMobileNo() {
    return this.mobileNo;
}

/**
 * Sets a value to attribute mobileNo.
 * @param newMobileNo
 */
public void setMobileNo(String newMobileNo) {
    this.mobileNo = newMobileNo;
}

/**
 * Returns gender.
 * @return gender
 */
public String getGender() {
    return this.gender;
}

/**
 * Sets a value to attribute gender.
 * @param newGender
 */
public void setGender(String newGender) {
    this.gender = newGender;
}

/**
 * Returns dateOfBirth.
 * @return dateOfBirth
 */
public String getDateOfBirth() {
    return this.dateOfBirth;
}

/**
 * Sets a value to attribute dateOfBirth.
 * @param newDateOfBirth
 */
public void setDateOfBirth(String newDateOfBirth) {
    this.dateOfBirth = newDateOfBirth;
}

/**
 * Returns address1.
 * @return address1
 */
public String getAddress1() {
    return this.address1;
}

/**
 * Sets a value to attribute address1.
 * @param newAddress1
 */
public void setAddress1(String newAddress1) {
    this.address1 = newAddress1;
}

/**
 * Returns address2.
 * @return address2
 */
public String getAddress2() {
    return this.address2;
}

/**
 * Sets a value to attribute address2.
 * @param newAddress2
 */
public void setAddress2(String newAddress2) {
    this.address2 = newAddress2;
}

/**
 * Returns city.
 * @return city
 */
public String getCity() {
    return this.city;
}

/**
 * Sets a value to attribute city.
 * @param newCity
 */
public void setCity(String newCity) {
    this.city = newCity;
}

/**
 * Returns state.
 * @return state
 */
public String getState() {
    return this.state;
}

/**
 * Sets a value to attribute state.
 * @param newState
 */
public void setState(String newState) {
    this.state = newState;
}

/**
 * Returns country.
 * @return country
 */
public String getCountry() {
    return this.country;
}

/**
 * Sets a value to attribute country.
 * @param newCountry
 */
public void setCountry(String newCountry) {
    this.country = newCountry;
}

/**
 * Returns pincode.
 * @return pincode
 */
public String getPincode() {
    return this.pincode;
}

/**
 * Sets a value to attribute pincode.
 * @param newPincode
 */
public void setPincode(String newPincode) {
    this.pincode = newPincode;
}

/**
 * Returns profileGroup.
 * @return profileGroup
 */
public String getProfileGroup() {
    return this.profileGroup;
}

/**
 * Sets a value to attribute profileGroup.
 * @param newProfileGroup
 */
public void setProfileGroup(String newProfileGroup) {
    this.profileGroup = newProfileGroup;
}

/**
 * Returns delFlg.
 * @return delFlg
 */
public String getDelFlg() {
    return this.delFlg;
}

/**
 * Sets a value to attribute delFlg.
 * @param newDelFlg
 */
public void setDelFlg(String newDelFlg) {
    this.delFlg = newDelFlg;
}

/**
 * Returns remarks.
 * @return remarks
 */
public String getRemarks() {
    return this.remarks;
}

/**
 * Sets a value to attribute remarks.
 * @param newRemarks
 */
public void setRemarks(String newRemarks) {
    this.remarks = newRemarks;
}

/**
 * Returns rCreTime.
 * @return rCreTime
 */
public String getRCreTime() {
    return this.rCreTime;
}

/**
 * Sets a value to attribute rCreTime.
 * @param newRCreTime
 */
public void setRCreTime(String newRCreTime) {
    this.rCreTime = newRCreTime;
}

/**
 * Returns rModTime.
 * @return rModTime
 */
public String getRModTime() {
    return this.rModTime;
}

/**
 * Sets a value to attribute rModTime.
 * @param newRModTime
 */
public void setRModTime(String newRModTime) {
    this.rModTime = newRModTime;
}
</code>```

}

What changes i have to do, to get specific columns from multiple data.

Thanks in advance.

答:
You should return List<Object[]> instead of UserDetails in case of native query.

Another way is to create projection. You can use projections from Spring Data JPA http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.

Body:
Am using Spring JPA repository

public String getNextULAID();
 // Selecting particular columns from a table
  @Query(value="select dbts,firstName from user_details
  where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)

  public UserDetails fetchUser(@Param("ulaID")String ulaId);
}

Throws error

{
    "timestamp": 1499336001602,
    "status": 500,
    "error": "Internal Server Error",

    "exception": "org.springframework.dao.InvalidDataAccessResourceUsageException",

    "message": "could not extract ResultSet; SQL [n/a];
    nested exception is org.hibernate.exception.SQLGrammarException:
    could not extract ResultSet",

    "path": "/viewProfile/1"
}

But if I select all data from the database,then its working perfectly

public String getNextULAID();
  // selecting all records
  @Query(value="select * from user_details
  where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)
  public UserDetails fetchUser(@Param("ulaID")String ulaId);

}

Here is my entity...

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// End of user code

 @Entity
 @Table(name="user_details")
 public class UserDetails {
/**
 * Description of the property dbts.
 */
private Integer dbts;

/**
 * Description of the property ulaId.
 */
@Id
private String ulaId = "";

/**
 * Description of the property firstName.
 */
private String firstName = "";

/**
 * Description of the property lastName.
 */
private String lastName = "";

/**
 * Description of the property emailId.
 */
private String emailId = "";

/**
 * Description of the property mobileNo.
 */
private String mobileNo = "";

/**
 * Description of the property gender.
 */
private String gender = "";

/**
 * Description of the property dateOfBirth.
 */
private String dateOfBirth = "";

/**
 * Description of the property address1.
 */
private String address1 = "";

/**
 * Description of the property address2.
 */
private String address2 = "";

/**
 * Description of the property city.
 */
private String city = "";

/**
 * Description of the property state.
 */
private String state = "";

/**
 * Description of the property country.
 */
private String country = "";

/**
 * Description of the property pincode.
 */
private String pincode = "";

/**
 * Description of the property profileGroup.
 */
private String profileGroup = "";

/**
 * Description of the property delFlg.
 */
private String delFlg = "";

/**
 * Description of the property remarks.
 */
private String remarks = "";

/**
 * Description of the property rCreTime.
 */
private String rCreTime = "";

/**
 * Description of the property rModTime.
 */
private String rModTime = "";

// Start of user code (user defined attributes for UserDetails)

// End of user code

/**
 * The constructor.
 */
public UserDetails() {
    // Start of user code constructor for UserDetails)
    super();
    // End of user code
}

// Start of user code (user defined methods for UserDetails)

// End of user code
/**
 * Returns dbts.
 * @return dbts
 */
public Integer getDbts() {
    return this.dbts;
}

/**
 * Sets a value to attribute dbts.
 * @param newDbts
 */
public void setDbts(Integer newDbts) {
    this.dbts = newDbts;
}

/**
 * Returns ulaId.
 * @return ulaId
 */
public String getUlaId() {
    return this.ulaId;
}

/**
 * Sets a value to attribute ulaId.
 * @param newUlaId
 */
public void setUlaId(String newUlaId) {
    this.ulaId = newUlaId;
}

/**
 * Returns firstName.
 * @return firstName
 */
public String getFirstName() {
    return this.firstName;
}

/**
 * Sets a value to attribute firstName.
 * @param newFirstName
 */
public void setFirstName(String newFirstName) {
    this.firstName = newFirstName;
}

/**
 * Returns lastName.
 * @return lastName
 */
public String getLastName() {
    return this.lastName;
}

/**
 * Sets a value to attribute lastName.
 * @param newLastName
 */
public void setLastName(String newLastName) {
    this.lastName = newLastName;
}

/**
 * Returns emailId.
 * @return emailId
 */
public String getEmailId() {
    return this.emailId;
}

/**
 * Sets a value to attribute emailId.
 * @param newEmailId
 */
public void setEmailId(String newEmailId) {
    this.emailId = newEmailId;
}

/**
 * Returns mobileNo.
 * @return mobileNo
 */
public String getMobileNo() {
    return this.mobileNo;
}

/**
 * Sets a value to attribute mobileNo.
 * @param newMobileNo
 */
public void setMobileNo(String newMobileNo) {
    this.mobileNo = newMobileNo;
}

/**
 * Returns gender.
 * @return gender
 */
public String getGender() {
    return this.gender;
}

/**
 * Sets a value to attribute gender.
 * @param newGender
 */
public void setGender(String newGender) {
    this.gender = newGender;
}

/**
 * Returns dateOfBirth.
 * @return dateOfBirth
 */
public String getDateOfBirth() {
    return this.dateOfBirth;
}

/**
 * Sets a value to attribute dateOfBirth.
 * @param newDateOfBirth
 */
public void setDateOfBirth(String newDateOfBirth) {
    this.dateOfBirth = newDateOfBirth;
}

/**
 * Returns address1.
 * @return address1
 */
public String getAddress1() {
    return this.address1;
}

/**
 * Sets a value to attribute address1.
 * @param newAddress1
 */
public void setAddress1(String newAddress1) {
    this.address1 = newAddress1;
}

/**
 * Returns address2.
 * @return address2
 */
public String getAddress2() {
    return this.address2;
}

/**
 * Sets a value to attribute address2.
 * @param newAddress2
 */
public void setAddress2(String newAddress2) {
    this.address2 = newAddress2;
}

/**
 * Returns city.
 * @return city
 */
public String getCity() {
    return this.city;
}

/**
 * Sets a value to attribute city.
 * @param newCity
 */
public void setCity(String newCity) {
    this.city = newCity;
}

/**
 * Returns state.
 * @return state
 */
public String getState() {
    return this.state;
}

/**
 * Sets a value to attribute state.
 * @param newState
 */
public void setState(String newState) {
    this.state = newState;
}

/**
 * Returns country.
 * @return country
 */
public String getCountry() {
    return this.country;
}

/**
 * Sets a value to attribute country.
 * @param newCountry
 */
public void setCountry(String newCountry) {
    this.country = newCountry;
}

/**
 * Returns pincode.
 * @return pincode
 */
public String getPincode() {
    return this.pincode;
}

/**
 * Sets a value to attribute pincode.
 * @param newPincode
 */
public void setPincode(String newPincode) {
    this.pincode = newPincode;
}

/**
 * Returns profileGroup.
 * @return profileGroup
 */
public String getProfileGroup() {
    return this.profileGroup;
}

/**
 * Sets a value to attribute profileGroup.
 * @param newProfileGroup
 */
public void setProfileGroup(String newProfileGroup) {
    this.profileGroup = newProfileGroup;
}

/**
 * Returns delFlg.
 * @return delFlg
 */
public String getDelFlg() {
    return this.delFlg;
}

/**
 * Sets a value to attribute delFlg.
 * @param newDelFlg
 */
public void setDelFlg(String newDelFlg) {
    this.delFlg = newDelFlg;
}

/**
 * Returns remarks.
 * @return remarks
 */
public String getRemarks() {
    return this.remarks;
}

/**
 * Sets a value to attribute remarks.
 * @param newRemarks
 */
public void setRemarks(String newRemarks) {
    this.remarks = newRemarks;
}

/**
 * Returns rCreTime.
 * @return rCreTime
 */
public String getRCreTime() {
    return this.rCreTime;
}

/**
 * Sets a value to attribute rCreTime.
 * @param newRCreTime
 */
public void setRCreTime(String newRCreTime) {
    this.rCreTime = newRCreTime;
}

/**
 * Returns rModTime.
 * @return rModTime
 */
public String getRModTime() {
    return this.rModTime;
}

/**
 * Sets a value to attribute rModTime.
 * @param newRModTime
 */
public void setRModTime(String newRModTime) {
    this.rModTime = newRModTime;
}

}

What changes i have to do, to get specific columns from multiple data.

Thanks in advance.


问:
CSS Table frozen first column is not the same height as row
Trying to freeze the first column of a table, I've managed to do so but i can't seem to align the height of the first cell and the rest of the row,
as shown here

here is a jsfiddle

```<code>.headcol {
    position: absolute;
    width: 5em;
    left: 0;
    top: auto;
    border-top-width: 1px;
    /*only relevant for first row*/
    margin-top: -1px;
    /*compensate for top border*/
    background: white;
    border-right: 4px solid black;

}
</code>```

答:
Your problem was the different height of the column and the fixed rowhead.

HTML-Elements with position-absolut only getting the height of the innerHTML.

Consquently i added a min-height to your columns & headers. As well as a min-width for a better style. You can change the JSFiddle here.

.grades-table {
  overflow-x:scroll;
  overflow-y:visible;
  margin-left: 5em;
}

.grades-header,
.grades-column {
  min-width: 150px;
  min-height: 38px;
  text-align: center;
}

.headcol {
  position: absolute;
  width: 5em;
  min-height: 38px;
  left: 0;
  top: auto;
  border-top-width: 1px;
  margin-top: -1px;
  background: white;
  border-right: 4px solid black;
}

.headcol-text {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grades-table">
<table>
  <thead>
    <tr>
      <th class="headcol">students</th>
      <th class="grades-header">01_getting_started</th>
      <th class="grades-header">02_courses</th>
      <th class="grades-header">03_tasks</th>
      <th class="grades-header">04_run_student</th>
      <th class="grades-header">05_fetching_input</th>
      <th class="grades-header">06_feedback</th>
      <th class="grades-header">07_advance_feedback</th>
      <th class="grades-header">08_archive</th>
      <th class="grades-header">09_ssh_debug</th>
      <th class="grades-header">10_environments</th>
    </tr>
  </thead>
  <tbody>
    <tr class="grades-row">
      <th class="headcol">
        <div class="headcol-text">
          student1
        </div>
      </th>
      <td class="grades-column">01<br>X days ago</td>
      <td class="grades-column">02<br>X days ago</td>
      <td class="grades-column">03<br>X days ago</td>
      <td class="grades-column">04<br>X days ago</td>
      <td class="grades-column">05<br>X days ago</td>
      <td class="grades-column">06<br>X days ago</td>
      <td class="grades-column">07<br>X days ago</td>
      <td class="grades-column">08<br>X days ago</td>
      <td class="grades-column">09<br>X days ago</td>
      <td class="grades-column">10<br>X days ago</td>
    </tr>
  </tbody>
</table>
</div></code>```

Body:
Trying to freeze the first column of a table, I've managed to do so but i can't seem to align the height of the first cell and the rest of the row,
as shown here

here is a jsfiddle

.headcol {
    position: absolute;
    width: 5em;
    left: 0;
    top: auto;
    border-top-width: 1px;
    /*only relevant for first row*/
    margin-top: -1px;
    /*compensate for top border*/
    background: white;
    border-right: 4px solid black;

}

Body:
Your problem was the different height of the column and the fixed rowhead.

HTML-Elements with position-absolut only getting the height of the innerHTML.

Consquently i added a min-height to your columns & headers. As well as a min-width for a better style. You can change the JSFiddle here.

.grades-table {
  overflow-x:scroll;
  overflow-y:visible;
  margin-left: 5em;
}

.grades-header,
.grades-column {
  min-width: 150px;
  min-height: 38px;
  text-align: center;
}

.headcol {
  position: absolute;
  width: 5em;
  min-height: 38px;
  left: 0;
  top: auto;
  border-top-width: 1px;
  margin-top: -1px;
  background: white;
  border-right: 4px solid black;
}

.headcol-text {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

<div class="grades-table">
<table>
  <thead>
    <tr>
      <th class="headcol">students</th>
      <th class="grades-header">01_getting_started</th>
      <th class="grades-header">02_courses</th>
      <th class="grades-header">03_tasks</th>
      <th class="grades-header">04_run_student</th>
      <th class="grades-header">05_fetching_input</th>
      <th class="grades-header">06_feedback</th>
      <th class="grades-header">07_advance_feedback</th>
      <th class="grades-header">08_archive</th>
      <th class="grades-header">09_ssh_debug</th>
      <th class="grades-header">10_environments</th>
    </tr>
  </thead>
  <tbody>
    <tr class="grades-row">
      <th class="headcol">
        <div class="headcol-text">
          student1
        </div>
      </th>
      <td class="grades-column"><a href="#">01</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">02</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">03</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">04</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">05</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">06</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">07</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">08</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">09</a><br><a href="#">X days ago</a></td>
      <td class="grades-column"><a href="#">10</a><br><a href="#" href="#">X days ago</a></td>
    </tr>
  </tbody>
</table>
</div>


问:
Adding gradle task to a subproject in method
I have a project with a bunch of subprojects. Some of the subprojects are utility projects, and some of the projects are actual applications.

The "application" subprojects should all produce a jar file with a given main class etc. To solve this I've put the following in the parent build.gradle:

```<code>def configureApplication(project, mainClass) {
    project.jar { ... }
}
</code>```

and from each subproject's build.gradle, I call configureApplication(project, "my.main.Class")

Now I want to add a deploy task to all application subproject's so that I can deploy all applications using ./gradlew deploy. I've tried to mimic the above approach by putting this in the parent build.gradle:

```<code>def configureDeploy(project) {
    project {
        task deploy {
            println "Deploying!"
        }
    }
}
</code>```

But I'm running in to:

```<code>Could not find method call() for arguments [build_51pn93...closure3@334ebcaa] on project ':subproj'.
</code>```

I've tried about a hundred other variations for the past hour without success.

Question: How do add tasks to some of the subprojects without repeating myself in each subproject's build.gradle? (Also, is using methods in the parent build.gradle a reasonable way of achieving this, or is there a more gradle idiomatic way of doing it?)

答:
I read the previous answers and their comments, especially the following statement:

I would very much like to add the deploy task to each relevant subproject through the subprojects build.gradle (while keeping code duplication to a minimum).

This sounds to me like the perfect use case for plugins. Gradle allows you to define plugins in the buildSrc subproject of your root project. Just place your plugin source code in <rootProjectDir>/buildSrc/src/main/groovy. You can find additional details in the docs.

An example plugin for your use case could look like this:

```<code>class MyDeployPlugin implements Plugin<Project> {
    void apply(Project project) {
        // you can access the project instance this plugin is applied to
        project.task('deploy') {
            // configure your task
        }
    }
}
</code>```

Now you can apply the plugin in your subproject build.gradle files:

```<code>apply plugin: MyDeployPlugin

deploy {
     // configure your task project-specific
}
</code>```

One last advice: People who work a lot with both Maven and Gradle, often state, that Gradle's flexibility through scripting is both the biggest advantage and the biggest disadvantage. In Maven, if you want to add or alter functionality, you often have to write a plugin. In Gradle, you can simply script the functionality, but if this happens to often, it will produce clusterfuck and unreusable code. So, whenever you need to add the same functionality to multiple (sub-)projects, use plugins. You can even publish plugins to Maven or your own repository.

Body:
I have a project with a bunch of subprojects. Some of the subprojects are utility projects, and some of the projects are actual applications.

The "application" subprojects should all produce a jar file with a given main class etc. To solve this I've put the following in the parent build.gradle:

def configureApplication(project, mainClass) {
    project.jar { ... }
}

and from each subproject's build.gradle, I call configureApplication(project, "my.main.Class")

Now I want to add a deploy task to all application subproject's so that I can deploy all applications using ./gradlew deploy. I've tried to mimic the above approach by putting this in the parent build.gradle:

def configureDeploy(project) {
    project {
        task deploy {
            println "Deploying!"
        }
    }
}

But I'm running in to:

Could not find method call() for arguments [build_51pn93...closure3@334ebcaa] on project ':subproj'.

I've tried about a hundred other variations for the past hour without success.

Question: How do add tasks to some of the subprojects without repeating myself in each subproject's build.gradle? (Also, is using methods in the parent build.gradle a reasonable way of achieving this, or is there a more gradle idiomatic way of doing it?)

Body:
I read the previous answers and their comments, especially the following statement:

I would very much like to add the deploy task to each relevant subproject through the subprojects build.gradle (while keeping code duplication to a minimum).

This sounds to me like the perfect use case for plugins. Gradle allows you to define plugins in the buildSrc subproject of your root project. Just place your plugin source code in <rootProjectDir>/buildSrc/src/main/groovy. You can find additional details in the docs.

An example plugin for your use case could look like this:

class MyDeployPlugin implements Plugin<Project> {
    void apply(Project project) {
        // you can access the project instance this plugin is applied to
        project.task('deploy') {
            // configure your task
        }
    }
}

Now you can apply the plugin in your subproject build.gradle files:

apply plugin: MyDeployPlugin

deploy {
     // configure your task project-specific
}

One last advice: People who work a lot with both Maven and Gradle, often state, that Gradle's flexibility through scripting is both the biggest advantage and the biggest disadvantage. In Maven, if you want to add or alter functionality, you often have to write a plugin. In Gradle, you can simply script the functionality, but if this happens to often, it will produce clusterfuck and unreusable code. So, whenever you need to add the same functionality to multiple (sub-)projects, use plugins. You can even publish plugins to Maven or your own repository.


问:
Find large number of consecutive values fulfilling condition in a numpy array
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

```<code>values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here
</code>```

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

答:
I haven't tested this but you it should be close to what you are looking for.  Slightly more lines of code but should be more efficient, readable, and it doesn't abuse regular expressions :-)</p>

```<code>def find_silent(samples):
    num_silent = 0
    start = 0
    for index in range(0, len(samples)):
        if abs(samples[index]) < SILENCE_THRESHOLD:
            if num_silent == 0:
                start = index
            num_silent += 1
        else:
            if num_silent > MIN_SILENCE:
                yield samples[start:index]
            num_silent = 0
    if num_silent > MIN_SILENCE:
        yield samples[start:]

for match in find_silent(samples):
    # code goes here
</code>```

Body:
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

Body:
I haven't tested this but you it should be close to what you are looking for.  Slightly more lines of code but should be more efficient, readable, and it doesn't abuse regular expressions :-)

def find_silent(samples):
    num_silent = 0
    start = 0
    for index in range(0, len(samples)):
        if abs(samples[index]) < SILENCE_THRESHOLD:
            if num_silent == 0:
                start = index
            num_silent += 1
        else:
            if num_silent > MIN_SILENCE:
                yield samples[start:index]
            num_silent = 0
    if num_silent > MIN_SILENCE:
        yield samples[start:]

for match in find_silent(samples):
    # code goes here


问:
How to input large data into python pandas using looping or parallel computing?
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

```<code>file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)
</code>```

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

```<code>id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.
</code>```

答: You also might want to use the das framework and it's built in dask.dataframe. Essentially, the csv file is transformed into multiple pandas dataframes, each read in when necessary. However, not every pandas command is avaialble within dask.</p>

Body:
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.


问:
Python in-memory zip library
Is there a Python library that allows manipulation of zip archives in memory, without having to use actual disk files?

The ZipFile library does not allow you to update the archive. The only way seems to be to extract it to a directory, make your changes, and create a new zip from that directory. I want to modify zip archives without disk access, because I'll be downloading them, making changes, and uploading them again, so I have no reason to store them.

Something similar to Java's ZipInputStream/ZipOutputStream would do the trick, although any interface at all that avoids disk access would be fine.

答:
PYTHON 3

```<code>import io
import zipfile

zip_buffer = io.BytesIO()

with zipfile.ZipFile(zip_buffer, "a",
                     zipfile.ZIP_DEFLATED, False) as zip_file:
    for file_name, data in [('1.txt', io.BytesIO(b'111')),
                            ('2.txt', io.BytesIO(b'222'))]:
        zip_file.writestr(file_name, data.getvalue())

with open('C:/1.zip', 'wb') as f:
    f.write(zip_buffer.getvalue())
</code>```

Title: Python in-memory zip library

Body:
PYTHON 3

import io
import zipfile

zip_buffer = io.BytesIO()

with zipfile.ZipFile(zip_buffer, "a",
                     zipfile.ZIP_DEFLATED, False) as zip_file:
    for file_name, data in [('1.txt', io.BytesIO(b'111')),
                            ('2.txt', io.BytesIO(b'222'))]:
        zip_file.writestr(file_name, data.getvalue())

with open('C:/1.zip', 'wb') as f:
    f.write(zip_buffer.getvalue())


问:
Streaming segmented data with decryption in iOS
I am creating an application in which i have a requirement to download encrypted Mpeg segment and play the video in player after decryption using a key downloaded from server. I don't know from where to start. I got some help from here and working on it, Till time if anyone have ever build or created such feature then please let me know. </p>

答:
The usual way to do this on an iOS device if you need DRM level protection is to use Apples FairPlay DRM solution.

There is documentation, SDK and a sample app available if you have an apple developer id: https://developer.apple.com/streaming/fps/

Note, however, to actually deploy it you have to be a 'licensed content owner' and I think this is largely aimed at larger operators and content owners so it would be important to check if you fall into their definition of this first:

Request Deployment Package

If you're a licensed content owner ready to deploy your implementation of FairPlay Streaming to a production environment, request the FPS Deployment Package. Please note that you must be the Team Agent of a development team that is a licensed content owner. The FPS Deployment Package is not available to third parties acting on behalf of licensed content owners.

If you can live with a lower level of protection then AES encrypted HLS may be enough for you - the actual video encryption is pretty much the same as with DRM, but the key itself is not encrypted.

You can use ffmpeg and openssl to create an AES encrypted HLS stream - the ffmpeg documentation (http://ffmpeg.org/ffmpeg-all.html#Options-34) includes this example script:

#!/bin/sh
BASE_URL=${1:-'.'}
openssl rand 16 > file.key
echo $BASE_URL/file.key > file.keyinfo
echo file.key >> file.keyinfo
echo $(openssl rand -hex 16) >> file.keyinfo
ffmpeg -f lavfi -re -i testsrc -c:v h264 -hls_flags delete_segments \
  -hls_key_info_file file.keyinfo out.m3u8
```


问:
edit docx file using phpword
is it possible to edit existing docx file using phpword?

i want to add footer text to my existing docx file.

there are lot of examples but those examples are creating the doc file from scratch not editing the file
can someone link to me an example? thank you

just like this.

```<code><?php
require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));
// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
// Write some text
$section->addTextBreak();
$section->addText('Some text...');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>
</code>```

答:
In the footer of your file(template) docx, you can put a variable like this ${var1}.

Open a file as template with "TemplateProcessor".

```<code>$templateObject = new TemplateProcessor($filename);
</code>```

Replace var1 variable in your file

```<code>$templateObject->setValue('var1', 'test');
</code>```

Transform your template into a PhpWord

```<code>$fileName = $templateObject->save();
$phpWordObject = IOFactory::load($fileName);
unlink($fileName);
return $phpWordObject;
</code>```

Save/Render your phpWord instance

```<code>// create the writer
$writer = $this->wordService->createWriter($phpWordObject, 'Word2007');
// create the response
$response = $this->wordService->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'export.docx'
);
$response->headers->set('Content-Type', 'application/msword');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
</code>```

Title: edit docx file using phpword

Body:
is it possible to edit existing docx file using phpword?

i want to add footer text to my existing docx file.

there are lot of examples but those examples are creating the doc file from scratch not editing the file
can someone link to me an example? thank you

just like this.

<?php
require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));
// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
// Write some text
$section->addTextBreak();
$section->addText('Some text...');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>

Body:
In the footer of your file(template) docx, you can put a variable like this ${var1}.

Open a file as template with "TemplateProcessor".

$templateObject = new TemplateProcessor($filename);

Replace var1 variable in your file

$templateObject->setValue('var1', 'test');

Transform your template into a PhpWord

$fileName = $templateObject->save();
$phpWordObject = IOFactory::load($fileName);
unlink($fileName);
return $phpWordObject;

Save/Render your phpWord instance

// create the writer
$writer = $this->wordService->createWriter($phpWordObject, 'Word2007');
// create the response
$response = $this->wordService->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'export.docx'
);
$response->headers->set('Content-Type', 'application/msword');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);


问:
How come my order by section gives a 'not a group by' error
My SQL-query works fine until I add in the 'order by' clause.
I receive a 'not a group by expression' error
I thought you were supposed to put an exact copy of the column in the 'select' clause ,in the 'order by' clause if you wish to edit the order of said column in your table...

```<code>select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by case when latitude between -18 and 18 then 5
 when latitude between -36 and 36 then 4
 when latitude between -54 and 54 then 3
 when latitude between -72 and 72 then 2
 else 1 end
</code>```

EDIT: To clarify , I am not necessarily looking for a solution to this problem but rather an explanation on why this particular piece of code doesn't work

答:
Basically, with your CASE
 you create just one column.  In order by you can specify only column usually by name, but you can use number (position of the column in the select list).

Try

```<code>select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by 1;
</code>```

I did a test in mysql: it seems it works this too (for semplicity I just removed your AND niveau=0)

```<code>select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1) AS RC
from regios
WHERE latitude is not null
group by klimaat
order by klimaat;
</code>```

Sample data:

```<code>create table regios (latitude integer, test varchar(100));
insert into regios value (15, 'aaa');
insert into regios value (37, 'bbb');
insert into regios value (55, 'ccc');
insert into regios value (84, 'ddd');
</code>```

Output:

```<code>klimaat RC
1   average 1
2   polar   1
3   subpolar    1
4   tropical    1
</code>```

If next time you post script to create table, sample data and obtained and expected results (in text form) all member of SO can help you better and faster.

Body:
My SQL-query works fine until I add in the 'order by' clause.
I receive a 'not a group by expression' error
I thought you were supposed to put an exact copy of the column in the 'select' clause ,in the 'order by' clause if you wish to edit the order of said column in your table...

select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by case when latitude between -18 and 18 then 5
 when latitude between -36 and 36 then 4
 when latitude between -54 and 54 then 3
 when latitude between -72 and 72 then 2
 else 1 end

EDIT: To clarify , I am not necessarily looking for a solution to this problem but rather an explanation on why this particular piece of code doesn't work

Body:
Basically, with your CASE
 you create just one column.  In order by you can specify only column usually by name, but you can use number (position of the column in the select list).

Try

select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by 1;

I did a test in mysql: it seems it works this too (for semplicity I just removed your AND niveau=0)

select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1) AS RC
from regios
WHERE latitude is not null
group by klimaat
order by klimaat;

Sample data:

create table regios (latitude integer, test varchar(100));
insert into regios value (15, 'aaa');
insert into regios value (37, 'bbb');
insert into regios value (55, 'ccc');
insert into regios value (84, 'ddd');

Output:

klimaat RC
1   average 1
2   polar   1
3   subpolar    1
4   tropical    1

If next time you post script to create table, sample data and obtained and expected results (in text form) all member of SO can help you better and faster.


问:
Django custom save and update
I have a custom save method for a model.

```<code>class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()
</code>```

In the view I would like to update multiple Ticket objects:

```<code>Ticket.objects.filter(ref='ref').update(paid=True)
</code>```

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?

答:
Quote from docs:

Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn’t run any save() methods on your models, or emit the pre_save or post_save signals (which are a consequence of calling save()), or honor the auto_now field option. If you want to save every item in a QuerySet and make sure that the save() method is called on each instance, you don’t need any special function to handle that. Just loop over them and call save().

So you need to iterate over queryset and call save() method for each element.

Title: Django custom save and update

Body:
I have a custom save method for a model.

class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()

In the view I would like to update multiple Ticket objects:

Ticket.objects.filter(ref='ref').update(paid=True)

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?


问:
how to set the Caps Lock warning balloon in meanstack
I want to set the caps lock warning balloon message in meanstack.

is it possible to do in mean stack. if yes mean can anybody give some example.

thanks

vinoth

答:
You can capture the keydown event on the input field in angular and then use event.getModifierState( 'CapsLock' ) to check the capslock state.

Here's an example:

```<code>app.controller('MainCtrl', function() {
    var ctrl = this;

    ctrl.keydown = function(e){
        ctrl.capsLockOn = e.getModifierState( 'CapsLock' );
    }
});
</code>```

and then in your view:

```<code><div ng-controller="MainCtrl as vm">
    <input ng-keydown="vm.keydown($event)" />
    <p>Is capslock on? {{vm.capsLockOn}}</p>
</div>
</code>```

Beware, event.getModifierState(..) might not work in all browsers.

Here's a plunker to show it in action

Body:
You can capture the keydown event on the input field in angular and then use event.getModifierState( 'CapsLock' ) to check the capslock state.

Here's an example:

app.controller('MainCtrl', function() {
    var ctrl = this;

    ctrl.keydown = function(e){
        ctrl.capsLockOn = e.getModifierState( 'CapsLock' );
    }
});

and then in your view:

<div ng-controller="MainCtrl as vm">
    <input ng-keydown="vm.keydown($event)" />
    <p>Is capslock on? {{vm.capsLockOn}}</p>
</div>

Beware, event.getModifierState(..) might not work in all browsers.

Here's a plunker to show it in action


问:
How to stop property onclick undefined
I followed a tutorial to add a modal image on my website.
https://www.w3schools.com/howto/howto_css_modal_images.asp

But as I have multiple images, i followed what this guy tell on this question
Modal image galleries - multiple images

And it still doesn't work.

Here is my javascript:
It tells me "Uncaught TypeError: Cannot set property 'onclick' of undefined"
for my var "span"

```<code>var modal = document.getElementById('myModal');
var img = $('.myImg');
var modalImg = $("#img01");
var captionText = document.getElementById("caption");
$('.myImg').click(function(){
modal.style.display = "block";
var newSrc = this.src;
modalImg.attr('src', newSrc);
captionText.innerHTML = this.alt;
});
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
</code>```

And here is my html that i generate with a script :

```<code><script id="mapListDetailTemplate" type="text/x-jQuery-tmpl">
<div class="result_item_detail">
<a href="#" class="map_details_close"><img src="src/close.png" alt="Close"></a>
<h3>${name}</h3>
<div class="result_item_detail_info">
    <div class="info">
        <ul class="list-unstyled">
            <li><b>Adresse</b>: ${address}</li>
        </ul>
    </div>
</div>
<div class="result_item_detail_info">
<h4>Description</h4>
${about}
</div>
<div class="result_item_detail_info">
<h4>Image</h4>
    <div class="slider_container">
        <div style="display: inline-block;">
              <img class="myImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg" alt="Trolltunga, Norway" width="300" height="200"/>
        </div>
    </div>
</div>
<div class="result_item_detail_info">
<h4>Aujourdhui</h4>
    <div id="pano"> </div>
</div>
</div>
<div id="myModal" class="modal">
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
</script>
</code>```

And here is the CSS

```<code>/* Style the Image Used to Trigger the Modal */
.myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}

.myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}

@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}

/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}

.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
.modal-content {
    width: 100%;
}
}
</code>```

You know why I have this error? Is it because my html is into a script??

答:
As mentioned in the comments, it appears the HTML structure is a modal in a modal, which might be an UX/UI issue but could be done. Ignoring that, here's a basic working example. A few changes from what you had.

the jQuery template script needs to be loaded since you're using a template

then .tmpl() needs to be called on the template, along with some data

the onClick needs to be added after the templates have been created

$(document).ready(function() {
  var items = [
    {name: 'Name 1', address: 'Address 1', about: 'About 1'}
  ];

  // Render the item using the template
  $("#mapListDetailTemplate").tmpl(items).appendTo("#container");

  var modal = document.getElementById('myModal');
  var modalImg = $("#img01");
  var captionText = document.getElementById("caption");
  $('.myImg').on('click', function() {
    modal.style.display = "block";
    var newSrc = this.src;
    modalImg.attr('src', newSrc);
    captionText.innerHTML = this.alt;
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Style the Image Used to Trigger the Modal */

.myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

.myImg:hover {
  opacity: 0.7;
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.9);
  /* Black w/ opacity */
}

/* Modal Content (Image) */

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */

#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation - Zoom in the Modal */

.modal-content,
#caption {
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {
    -webkit-transform: scale(0)
  }
  to {
    -webkit-transform: scale(1)
  }
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}

/* The Close Button */

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */

@media only screen and (max-width: 700px) {
  .modal-content {
    width: 100%;
  }
}</code>```

```

Title: How to stop property onclick undefined

Body:
I followed a tutorial to add a modal image on my website.
https://www.w3schools.com/howto/howto_css_modal_images.asp

But as I have multiple images, i followed what this guy tell on this question
Modal image galleries - multiple images

And it still doesn't work.

Here is my javascript:
It tells me "Uncaught TypeError: Cannot set property 'onclick' of undefined"
for my var "span"

var modal = document.getElementById('myModal');
var img = $('.myImg');
var modalImg = $("#img01");
var captionText = document.getElementById("caption");
$('.myImg').click(function(){
modal.style.display = "block";
var newSrc = this.src;
modalImg.attr('src', newSrc);
captionText.innerHTML = this.alt;
});
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}

And here is my html that i generate with a script :

And here is the CSS

/* Style the Image Used to Trigger the Modal */
.myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}

.myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (Image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}

/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}

@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}

/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}

.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
.modal-content {
    width: 100%;
}
}

You know why I have this error? Is it because my html is into a script??

Body:
As mentioned in the comments, it appears the HTML structure is a modal in a modal, which might be an UX/UI issue but could be done. Ignoring that, here's a basic working example. A few changes from what you had.

the jQuery template script needs to be loaded since you're using a template

then .tmpl() needs to be called on the template, along with some data

the onClick needs to be added after the templates have been created

$(document).ready(function() {
  var items = [
    {name: 'Name 1', address: 'Address 1', about: 'About 1'}
  ];

  // Render the item using the template
  $("#mapListDetailTemplate").tmpl(items).appendTo("#container");

  var modal = document.getElementById('myModal');
  var modalImg = $("#img01");
  var captionText = document.getElementById("caption");
  $('.myImg').on('click', function() {
    modal.style.display = "block";
    var newSrc = this.src;
    modalImg.attr('src', newSrc);
    captionText.innerHTML = this.alt;
  });

});

/* Style the Image Used to Trigger the Modal */

.myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

.myImg:hover {
  opacity: 0.7;
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.9);
  /* Black w/ opacity */
}

/* Modal Content (Image) */

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image (Image Text) - Same Width as the Image */

#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation - Zoom in the Modal */

.modal-content,
#caption {
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {
    -webkit-transform: scale(0)
  }
  to {
    -webkit-transform: scale(1)
  }
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}

/* The Close Button */

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */

@media only screen and (max-width: 700px) {
  .modal-content {
    width: 100%;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<div id="container"></div>
<script id="mapListDetailTemplate" type="text/x-jQuery-tmpl">
  <div class="result_item_detail">
    <a href="#" class="map_details_close"><img src="src/close.png" alt="Close"></a>
    <h3>${name}</h3>
    <div class="result_item_detail_info">
      <div class="info">
        <ul class="list-unstyled">
          <li><b>Adresse</b>: ${address}</li>
        </ul>
      </div>
    </div>
    <div class="result_item_detail_info">
      <h4>Description</h4>
      ${about}
    </div>
    <div class="result_item_detail_info">
      <h4>Image</h4>
      <div class="slider_container">
        <div style="display: inline-block;">
          <img class="myImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg" alt="Trolltunga, Norway" width="300" height="200" />
        </div>
      </div>
    </div>
    <div class="result_item_detail_info">
      <h4>Aujourdhui</h4>
      <div id="pano"> </div>
    </div>
  </div>
  <div id="myModal" class="modal">
    <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>
    <img class="modal-content" id="img01">
    <div id="caption"></div>
  </div>
</script>


问:
TIZEN for SamsungTV app - Common is not defined
I'm getting this "Warning" in mi js file, and because of this my code is not working (downloaded for the sample here: http://developer.samsung.com/tv/develop/legacy-platform-library/tut00055/index )

It seems that the Widget.js file cannot be found (and then the Widget class cannot be instantiated)

this is mi Main.js file:

```<code>var widgetAPI = new Common.API.Widget();
var    tvKey = new Common.API.TVKeyValue();
var    Main = {};

Main.onLoad = function() {
    console.log("antes del alert");
    alert("Main.onLoad()");
    console.log("despues del alert");
    this.enableKeys();
    widgetAPI.sendReadyEvent();
};
</code>```

and this mi index.html file:

```<code><!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
    <!-- Common widget API -->
    <script type='text/javascript' language='javascript' src='Common/API/Widget.js'></script>
        <script type='text/javascript' language='javascript' src='Common/API/TVKeyValue.js'></script>

        <!-- Widget code -->
        <script language="javascript" type="text/javascript" src="Javascript/Main.js"></script>

        <link rel="stylesheet" href="CSS/Main.css" type="text/css">
    </head>
    <body onload="Main.onLoad();" onunload="Main.onUnload();">
    </body>
</html>
</code>```

As the tutorial Says, I also tried with this url: $MANAGER_WIDGET/Common/API/Widget.js but the Warning still showing and the class is not being instantiated.

答: Simulator doesn't have webapis.js and doesn't support APIs in webapis.js If you use emulator or actual device. there may be no problem.</p>

Body:
I'm getting this "Warning" in mi js file, and because of this my code is not working (downloaded for the sample here: http://developer.samsung.com/tv/develop/legacy-platform-library/tut00055/index )

It seems that the Widget.js file cannot be found (and then the Widget class cannot be instantiated)

this is mi Main.js file:

var widgetAPI = new Common.API.Widget();
var    tvKey = new Common.API.TVKeyValue();
var    Main = {};

Main.onLoad = function() {
    console.log("antes del alert");
    alert("Main.onLoad()");
    console.log("despues del alert");
    this.enableKeys();
    widgetAPI.sendReadyEvent();
};

and this mi index.html file:

<!DOCTYPE html>

<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>

        <link rel="stylesheet" href="CSS/Main.css" type="text/css">

As the tutorial Says, I also tried with this url: $MANAGER_WIDGET/Common/API/Widget.js but the Warning still showing and the class is not being instantiated.


问:
How to explain the code output of this multi-threading program in Java?
I am studying multi-threading in java and wrote the following code.

```<code>    public class MulThread extends Thread
{
    public void run()
    {
        for(int i=1; i<5;i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(Exception e){ System.out.println(e);}
            System.out.println(i);
        }
    }

public static void main(String [] args)
{
    MulThread t1 = new MulThread();
    MulThread t2 = new MulThread();
    MulThread t3 = new MulThread();

    t1.start();
    t1.run();
    t2.start();
    t2.run();

    t3.start();
    t3.run();

}
}
</code>```

I discussed this with some friends, and I came to the conclusion that the output should be a complete mess. But for some reason, the compiler always produces the following output:

```<code>1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
</code>```

Can someone explain what exactly is happening here when the threads reach the scheduler? Why isn't the output a mess of 1, 2, 3, and 4, each repeated 6 times in a random soup?

A few of my mentors tell me it's just a coincidence, and it depends on my OS or something, but I'm skeptical about that. I've run the code over 10 times, and it always produces the same results.

答:
This:

```<code>t1.start();
</code>```

starts the thread as you would want. The threading mechanism will call run() under the covers.

But you then call this:

```<code>t1.run();
</code>```

which calls the run() method directly and block your main thread whilst it runs (since you're simply calling a blocking method). You don't need this. Simply start() and your new thread will run as you expect (separate to your main thread).

Note that calling run() directly in these circumstances is often unusual and an indication of confusion!

It's useful to print the thread name in these circumstances (via Thread.currentThread().getName()) to see what's going on (and perhaps naming your threads too, via a different Thread constructor)

Body:
I am studying multi-threading in java and wrote the following code.

    public class MulThread extends Thread
{
    public void run()
    {
        for(int i=1; i<5;i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(Exception e){ System.out.println(e);}
            System.out.println(i);
        }
    }

public static void main(String [] args)
{
    MulThread t1 = new MulThread();
    MulThread t2 = new MulThread();
    MulThread t3 = new MulThread();

    t1.start();
    t1.run();
    t2.start();
    t2.run();

    t3.start();
    t3.run();

}
}

I discussed this with some friends, and I came to the conclusion that the output should be a complete mess. But for some reason, the compiler always produces the following output:

1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4
1
1
2
2
3
3
4
4

Can someone explain what exactly is happening here when the threads reach the scheduler? Why isn't the output a mess of 1, 2, 3, and 4, each repeated 6 times in a random soup?

A few of my mentors tell me it's just a coincidence, and it depends on my OS or something, but I'm skeptical about that. I've run the code over 10 times, and it always produces the same results.

Body:
This:

t1.start();

starts the thread as you would want. The threading mechanism will call run() under the covers.

But you then call this:

t1.run();

which calls the run() method directly and block your main thread whilst it runs (since you're simply calling a blocking method). You don't need this. Simply start() and your new thread will run as you expect (separate to your main thread).

Note that calling run() directly in these circumstances is often unusual and an indication of confusion!

It's useful to print the thread name in these circumstances (via Thread.currentThread().getName()) to see what's going on (and perhaps naming your threads too, via a different Thread constructor)