问:
WPF - Adding a handler for PreviewMouseLeftButtonDown suppresses click event
Just adding a handler for PreviewMouseLeftButtonDown seems to suppress the button's click event. Is this to be expected? My understanding was that this would only happened if marked the PreviewMouseLeftButtonDown event args as handled then further handlers wouldn't be invoked but I haven't done that. I checked the value of e.Handled in the handler for PreviewMouseLeftButtonDown and it's false. What's going on here?</p>

```<code><Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="169.604" Width="233.59">
      <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="10,44,0,0" VerticalAlignment="Top" Width="75" PreviewMouseLeftButtonDown="button_PreviewMouseLeftButtonDown" Click="button_Click"/>
        <Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="119,44,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Click event");
        }

        private void button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("PreviewMouseLeftButtonDown event");
        }
    }
}
</code>```

答:
PreviewMouseLeftButtonDown does not supress Click event. It's what you are doing inside that handler can supress Click event under certain conditions. Button has ClickMode property with possible options Release, Press and Hover. Default one is Release. For Click event to fire in Release mode mouse should press the button (mouse down) and release (mouse up). In your case button is pressed but then message box appears, button loses mouse capture and no "mouse up" event is registered. Without "mouse up" event (for which MouseLeftButtonUp is handler) - Click event is not registered in Release mode. If you replace MessageBox.Show with something that does not grabs focus (like Console.WriteLine) or change button ClickMode to Press - code will work as expected.

Ensure also that you don't have breakpoints in PreviewMouseLeftButtonDown event handler also - because breaking on it will bring focus to visual studio and click event will not work again.

Body:
Just adding a handler for PreviewMouseLeftButtonDown seems to suppress the button's click event. Is this to be expected? My understanding was that this would only happened if marked the PreviewMouseLeftButtonDown event args as handled then further handlers wouldn't be invoked but I haven't done that. I checked the value of e.Handled in the handler for PreviewMouseLeftButtonDown and it's false. What's going on here?

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="169.604" Width="233.59">
      <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="10,44,0,0" VerticalAlignment="Top" Width="75" PreviewMouseLeftButtonDown="button_PreviewMouseLeftButtonDown" Click="button_Click"/>
        <Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="119,44,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication2
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Click event");
        }

        private void button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("PreviewMouseLeftButtonDown event");
        }
    }
}


来源: stackexchange

问:
Can I clear headers that sent? on ASP.NET
For example

```<code> Response.Write("<div id='divTitle'>Loading</div>");
 Response.Flush();
 ....
 ....
 Response.Redirect("home.aspx", false);
</code>```

I got the following error:

Cannot redirect after HTTP headers have been sent.

Please help.

答:
Actually the message is clear. You sent headers with Response.Flush();. You are trying both  to send content and redirect request. Why?

UPDATE:

```<code>Response.Buffer =false;
Response.Write("<div id='divTitle'>Loading</div>");
Response.Flush();

// do something

Response.Write("<script type='text/javascript'>window.location = 'home.aspx' </script>");
Response.Flush();
Response.End();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example

 Response.Write("
Loading
");
 Response.Flush();
 ....
 ....
 Response.Redirect("home.aspx", false);

I got the following error:

Cannot redirect after HTTP headers have been sent.

Please help.

Body:
Actually the message is clear. You sent headers with Response.Flush();. You are trying both  to send content and redirect request. Why?

UPDATE:

Response.Buffer =false;
Response.Write("<div id='divTitle'>Loading</div>");
Response.Flush();

// do something

Response.Write("<script type='text/javascript'>window.location = 'home.aspx' </script>");
Response.Flush();
Response.End();


问:
NSMutableDictionary returning null
I created an NSMutableDictionary in NSObject class like

```<code>@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments;
</code>```

and saved the data in this variable when comes through API.

But when I am sending the key to get the value it is returning null every time.

To get the value I am doing like this

```<code>NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]);
// serviceRequest.RequestId is returning NSNumber.
</code>```

the output I'm getting is "(null)"

if I use to like this then it returns a value

```<code>NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);
</code>```

Why it is returning null in the above case.

答:
Because you declared requestComment to be aNSDictionary which keys are NSNumbers and values are NSString doesn't oblige it to respect it.

Sample:

```<code>_requestComments = [[NSMutableDictionary alloc] init];

[_requestComments setObject:[NSNumber numberWithInt:34] forKey:@"54"]; // => Warning: Incompatible pointer types sending 'NSNumber * _Nonnull' to parameter of type 'NSString * _Nonnull'

id obj = [NSNumber numberWithInt:35];
id key = @"55";
[_requestComments setObject:obj forKey:key];

NSLog(@"[_requestComments objectForKey:@\"55\"]: %@", [_requestComments objectForKey:@"55"]); //Warning: Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber * _Nonnull'
NSLog(@"[_requestComments objectForKey:@(55)]: %@", [_requestComments objectForKey:@(55)]);
</code>```

Logs:

```<code>$>[_requestComments objectForKey:@"55"]: 35
$>[_requestComments objectForKey:@(55)]: (null)
</code>```

Okay, I used id to lure the compiler, but id is a common returned "class", in objectAtIndex:, etc. It's common in JSON parsing when you think a object will be a NSString but is in fact a NSNumber of (inverse).

Before doing requestComments[serviceRequest.RequestId], enumerate ALL the keys value & class and ALL objects value & class. You can check it like this:

```<code>for (id aKey in _requestComments)
{
    id aValue = _requestComments[aKey];
    NSLog(@"aKey %@ of class %@\naValue %@ of class %@", aKey, NSStringFromClass([aKey class]),aValue, NSStringFromClass([aValue class]));
}
</code>```

Then you can try to track where you put a wrong key (class).

Title: NSMutableDictionary returning null

Body:
I created an NSMutableDictionary in NSObject class like

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments;

and saved the data in this variable when comes through API.

But when I am sending the key to get the value it is returning null every time.

To get the value I am doing like this

NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]);
// serviceRequest.RequestId is returning NSNumber.

the output I'm getting is "(null)"

if I use to like this then it returns a value

NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);

Why it is returning null in the above case.

Body:
Because you declared requestComment to be aNSDictionary which keys are NSNumbers and values are NSString doesn't oblige it to respect it.

Sample:

_requestComments = [[NSMutableDictionary alloc] init];

[_requestComments setObject:[NSNumber numberWithInt:34] forKey:@"54"]; // => Warning: Incompatible pointer types sending 'NSNumber * _Nonnull' to parameter of type 'NSString * _Nonnull'

id obj = [NSNumber numberWithInt:35];
id key = @"55";
[_requestComments setObject:obj forKey:key];

NSLog(@"[_requestComments objectForKey:@\"55\"]: %@", [_requestComments objectForKey:@"55"]); //Warning: Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber * _Nonnull'
NSLog(@"[_requestComments objectForKey:@(55)]: %@", [_requestComments objectForKey:@(55)]);

Logs:

$>[_requestComments objectForKey:@"55"]: 35
$>[_requestComments objectForKey:@(55)]: (null)

Okay, I used id to lure the compiler, but id is a common returned "class", in objectAtIndex:, etc. It's common in JSON parsing when you think a object will be a NSString but is in fact a NSNumber of (inverse).

Before doing requestComments[serviceRequest.RequestId], enumerate ALL the keys value & class and ALL objects value & class. You can check it like this:

for (id aKey in _requestComments)
{
    id aValue = _requestComments[aKey];
    NSLog(@"aKey %@ of class %@\naValue %@ of class %@", aKey, NSStringFromClass([aKey class]),aValue, NSStringFromClass([aValue class]));
}

Then you can try to track where you put a wrong key (class).


问:
Align leged text in figure caption Sphinx
I cannot choose to align the legend text of a figure in sphinx.

```<code>.. figure:: check_validity.png
   :align: center

   ..

   Left: the source layer

   Right: in blue the valid layer, in green the invalid layer and in red the error
   layer
</code>```

This the result:

But I would like to have both caption aligned left. Is this possible without using tables?

答:
Yes, but it is very kludgy, requiring custom CSS to account for each image's width.

Here's the HTML that Sphinx generates for me:

```<code><div class="figure align-center">
    <img src="check_validity.png" />
    <div class="legend">
        <p>Some text</p>
        <p>Another sentence</p>
    </div>
</div>
</code>```

Depending on your theme, you would need to:

get the width of the image (WI)

get the width of the content area (WCA), which might be impossible if it is a fluid, variable width area

calculate the left margin: LM = (WCA - WI)/2

apply LM as the left margin to the paragraph block with a CSS selector

It's far easier to just use tables. Welcome to the 1990s!

Here's the reST markup:

```<code>.. rst-class:: table-center

+--------------------------------+
| .. figure:: check_validity.png |
|                                |
|   ..                           |
|                                |
|   Left: the source layer       |
|                                |
|   Right: in blue the valid     |
|   layer, in green the invalid  |
|   layer and in red the error   |
|   layer                        |
+--------------------------------+
</code>```

And you will need to add a custom style to your CSS file:

```<code>table.table-center {
    margin-left: auto;
    margin-right: auto;
}
</code>```

Body:
I cannot choose to align the legend text of a figure in sphinx.

.. figure:: check_validity.png
   :align: center

   ..

   Left: the source layer

   Right: in blue the valid layer, in green the invalid layer and in red the error
   layer

This the result:

But I would like to have both caption aligned left. Is this possible without using tables?

Body:
Yes, but it is very kludgy, requiring custom CSS to account for each image's width.

Here's the HTML that Sphinx generates for me:

<div class="figure align-center">
    <img src="check_validity.png" />
    <div class="legend">
        <p>Some text</p>
        <p>Another sentence</p>
    </div>
</div>

Depending on your theme, you would need to:

get the width of the image (WI)

get the width of the content area (WCA), which might be impossible if it is a fluid, variable width area

calculate the left margin: LM = (WCA - WI)/2

apply LM as the left margin to the paragraph block with a CSS selector

It's far easier to just use tables. Welcome to the 1990s!

Here's the reST markup:

.. rst-class:: table-center

+--------------------------------+
| .. figure:: check_validity.png |
|                                |
|   ..                           |
|                                |
|   Left: the source layer       |
|                                |
|   Right: in blue the valid     |
|   layer, in green the invalid  |
|   layer and in red the error   |
|   layer                        |
+--------------------------------+

And you will need to add a custom style to your CSS file:

table.table-center {
    margin-left: auto;
    margin-right: auto;
}


问:
bzImage and grub config not installed to .dsk in yocto dsk build
I am building yocto image with bitbake, with image type dsk (default had been wic which I changed to dsk in local.conf). It generates bzImage, boot/grub/grub.conf. But these are not installed in dsk.

As in .dsk format, I have two partitions holding identical EFI and the third partition as OS root file system.

In 1st two partitions tree are like,

```<code>├── EFI
│   └── BOOT
│       └── bootia32.efi
├── EFI_internal_storage
│   └── BOOT
│       └── bootia32.efi
├── emmc-partitions-data
└── rmc.db
</code>```

So, there is no kernel and grub config here. How to install kernel and grub images to this partition as part of dsk image?

My another question is, what is the significance of having two identical partitions holding EFI?

答:
After exploring around, I ended up finding that vmlinuz has to be renamed form of bzImage and initrd renamed form of .cpio archive. Nothing much technical as such.

We have to install grub config separately through installation script by putting in bbclass of bbappend (based on scope of use across the target) of image creating script. Seems like this is not generic requirement, not sure.

INST_LOC=${IMAGE_ROOTFS}/boot
install -d ${INST_LOC}/boot/grub
install -m 0644 ${DEPLOY_DIR_IMAGE}/boot/grub/grub.conf
${INST_LOC}/boot/grub/grub.conf

Body:
I am building yocto image with bitbake, with image type dsk (default had been wic which I changed to dsk in local.conf). It generates bzImage, boot/grub/grub.conf. But these are not installed in dsk.

As in .dsk format, I have two partitions holding identical EFI and the third partition as OS root file system.

In 1st two partitions tree are like,

├── EFI
│   └── BOOT
│       └── bootia32.efi
├── EFI_internal_storage
│   └── BOOT
│       └── bootia32.efi
├── emmc-partitions-data
└── rmc.db

So, there is no kernel and grub config here. How to install kernel and grub images to this partition as part of dsk image?

My another question is, what is the significance of having two identical partitions holding EFI?


问:
Pyparsing: How can I parse data and then edit a specific value in a .txt file?
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

```<code>from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value
</code>```

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

答:
Actually, you should have a look at the config parser module
Which parses exactly your syntax (you need only to add [section] at the beginning).

If you insist on your implementation, you can create a dictionary :

```<code>dictt = {}
for t,s,e in macroDef.scanString(src):
   dictt[t.name]= t.value
dictt[variable]=new_value
</code>```

ContentLicense: CC BY-SA 2.5

Body:
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

Body:
Actually, you should have a look at the config parser module
Which parses exactly your syntax (you need only to add [section] at the beginning).

If you insist on your implementation, you can create a dictionary :

dictt = {}
for t,s,e in macroDef.scanString(src):
   dictt[t.name]= t.value
dictt[variable]=new_value


问:
Publish to Azure EventHub from AWS
I am working on a use case wherein we collect data from multiple entities thru REST APIs and persist the on an RDBMS; this is an existing system. This stack is running on Windows Services on AWS (EC2 instances).

Now, we want to publish this data that is being persisted onto an Azure EventHub. A traditional way will be to use the Azure EventHub REST endpoint to publish the data from a Windows Service.

I do understand that Azure EventHub supports throughput of 1 MB/s Ingress. With the throughput that we are forecasting (~0.5 to 0.75 MB/s), we may not be using EventHub to its fullest capacity. Are there any other mechanisms that we can use for the above use case?

答:
It sounds like the REST API on to Event Hub would be an adequate solution. Only when you go above the limits of the service does it become a problem from a scalability perspective. It is fine to have an Event Hub that is underutilised, even at 0.0001 MB/s. Note that you only get billed for the capacity you use, not for the service as a whole.

You do have some alternative options for ingesting the data, depending on what features the RDBMS has. Alternatively, your could push your incoming data on to a service bus (like Amazon SQS) and have it route to your Event Hub and to the RDBMS.

Crossing cloud providers in a high volume scenario may become expensive since you are paying for the ingress and egress out of the cloud data centres. If you could stick with one cloud provider you could save those costs.

Title: Publish to Azure EventHub from AWS


问:
How do I enable certificate based authentication when creating a cluster with kops?
I am creating Kubernetes clusters on AWS with the help of the kops tool. I would like to require authentication with client certificates in order to connect to the cluster API, how can I enable this when creating a cluster with kops create cluster?.

My cluster creation command looks as follows, I would like to know how to modify it in order to enable client certificate authentication:

```<code>kops --state s3://example.com create cluster \
--zones eu-central-1a,eu-central-1b,eu-central-1c \
--master-zones eu-central-1a,eu-central-1b,eu-central-1c \
--topology private --networking flannel --master-size m4.large \
--node-size m4.large --node-count 2 --bastion --cloud aws \
--ssh-public-key id_rsa.pub --yes example.com
</code>```

答: Certificate based authentication is enabled by default in the Kubernetes API, the kubectl tool typically uses a certificate from its configuration file in order to authenticate the user. In order to create certificates to authenticate individual users, you need to get hold of the certificate authority key and certificate files belonging to the cluster, and sign new certificates with them.</p>

Body:
I am creating Kubernetes clusters on AWS with the help of the kops tool. I would like to require authentication with client certificates in order to connect to the cluster API, how can I enable this when creating a cluster with kops create cluster?.

My cluster creation command looks as follows, I would like to know how to modify it in order to enable client certificate authentication:

kops --state s3://example.com create cluster \
--zones eu-central-1a,eu-central-1b,eu-central-1c \
--master-zones eu-central-1a,eu-central-1b,eu-central-1c \
--topology private --networking flannel --master-size m4.large \
--node-size m4.large --node-count 2 --bastion --cloud aws \
--ssh-public-key id_rsa.pub --yes example.com


问:
Include functions
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

```<code><?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
</code>```

Header.php

```<code>function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
</code>```

Any idea why this won't work? I'm getting a blank white screen right now.

答:
I think you are missing the core understanding of what a function is. Variables inside one function cannot be accessed by another function unless passed into the function.

Also you can not start a procedural statement (while loop) in one function and end it within another function.

Title: Include functions

Body:
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

<?php include 'includes/header.php'; ?>
<?php getPosts();?>

Some HTML Code

<?php endPosts(); ?>

Header.php

function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};

Any idea why this won't work? I'm getting a blank white screen right now.


问:
Android Share data between two Fragment
I am new developer of Android.How we can share the data between two fragment.
Any idea for this problem.i have make the orderFragment and itemfragment user select the item on item screen and press submit the screen redirct to orders screen user have multiple order.if we redirect the screen the data not send to the orders screen</p>

答:
For Send data between two fragment try below code

```<code>YourSubmitButton.setOnClickListener(new View.OnClickListener(){
 public void onClick(View v){
   Bundle bundle = new Bundle();
   bundle.putString = ("KEY",value)  //Here if you want to send Integer value then write putInt
   YourItemFragment.setArguments(bundle);
 }
}
</code>```

In ItemFragment try below code

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_order, container, false);
    String YourItem = getArguments.getString("KEY");
    return view;
}
</code>```

Title: Android Share data between two Fragment

Body:
For Send data between two fragment try below code

YourSubmitButton.setOnClickListener(new View.OnClickListener(){
 public void onClick(View v){
   Bundle bundle = new Bundle();
   bundle.putString = ("KEY",value)  //Here if you want to send Integer value then write putInt
   YourItemFragment.setArguments(bundle);
 }
}

In ItemFragment try below code

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_order, container, false);
    String YourItem = getArguments.getString("KEY");
    return view;
}


问:
Multiple aggregate functions in Java 8 Stream API
I have a class defined like

```<code>public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}
</code>```

I would like to perform the following SQL statement using Java 8 Stream API.

```<code>SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate
</code>```

I tried :

```<code>Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....
</code>```

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

答:
To do it without a custom Collector (not streaming again on the result), you could do it like this. It's a bit dirty, since it is first collecting to Map<String, List<TimePeriodCalc>> and then streaming that list and get the average double.

Since you need two averages, they are collected to a Holder or a Pair, in this case I'm using AbstractMap.SimpleEntry

```<code>  Map<String, SimpleEntry<Double, Double>> map = Stream.of(new TimePeriodCalc(12d, 10d, "A"), new TimePeriodCalc(2d, 16d, "A"))
            .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
                    Collectors.collectingAndThen(Collectors.toList(), list -> {
                        double occupancy = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getOccupancy));
                        double efficiency = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getEfficiency));
                        return new AbstractMap.SimpleEntry<>(occupancy, efficiency);
                    })));

    System.out.println(map);
</code>```

Body:
I have a class defined like

public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}

I would like to perform the following SQL statement using Java 8 Stream API.

SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate

I tried :

Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

Body:
To do it without a custom Collector (not streaming again on the result), you could do it like this. It's a bit dirty, since it is first collecting to Map<String, List<TimePeriodCalc>> and then streaming that list and get the average double.

Since you need two averages, they are collected to a Holder or a Pair, in this case I'm using AbstractMap.SimpleEntry

  Map<String, SimpleEntry<Double, Double>> map = Stream.of(new TimePeriodCalc(12d, 10d, "A"), new TimePeriodCalc(2d, 16d, "A"))
            .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
                    Collectors.collectingAndThen(Collectors.toList(), list -> {
                        double occupancy = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getOccupancy));
                        double efficiency = list.stream().collect(
                                Collectors.averagingDouble(TimePeriodCalc::getEfficiency));
                        return new AbstractMap.SimpleEntry<>(occupancy, efficiency);
                    })));

    System.out.println(map);


问:
TYPO3 Extbase - Download file is cut off to 40 KB if user is not logged in to the front end
I created a duplicate of a download extension from my colleague which is basically an extension which just provides files to download in the back end.

Problem:

If i try to download a file while the extension is only accessible after login to the back end, then it works perfectly fine

however if I open a private browser window where I am not logged in to the back end, then it always cuts off the file and only download the first 40 KB ... even though it is normally 10 MB. Why is the file cut off?

I can download small files ( < 40KB ) perfectly without them getting cutted off.

NOTE:

Before I edited the extension, the download worked perfectly, even if not logged in to the back end! And the download was triggered the same way

Currently I am comparing the code, but from the logic it looks ok, since I did not changed much (added a new model, renamed the extension and some other stuff)

Does someone have a clue what can lead to this problem?

This is the relevant part in my download controller where I first get the public url of the file by passing the fid of the file  and then trigger the download by sending headers.

```<code>...
if ($this->request->hasArgument('fid')) {
    $this->fid = $this->request->getArgument('fid');
}
if ($this->request->hasArgument('cid')) {
    $this->cid = $this->request->getArgument('cid');
}

$fileobj = $this->fileRepository->findByUid($this->fid);

if ($fileobj->getFile() !== null) {
    $downloadFilePath = $fileobj->getFile()->getOriginalResource()->getPublicUrl();

    if (file_exists($downloadFilePath)) {
        $fileCounter = (int)$fileobj->getCounter();
        $fileobj->setCounter(++$fileCounter);
        $oldChecksum = $fileobj->getChecksume();
        $groesse = filesize($downloadFilePath);

        if (isset($oldChecksum)) {
            $checksum = sha1_file($downloadFilePath);
            $fileobj->setChecksume($checksum);
        }

        // update fileobj
        $this->fileRepository->update($fileobj);

        // Unset fileobj before persists, otherwise there will be also changes
        $this->persistenceManager->persistAll();

        // If file exists, force download
        $fileName = basename($downloadFilePath);

        $this->response->setHeader('Content-Type', "application/force-download", TRUE);
        $this->response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName, TRUE);
        $this->response->setHeader('Content-Length', $groesse, TRUE);

        @readfile($downloadFilePath);
        $this->response->sendHeaders();
        return true; //i can also delete this line, since it is never reached.

    } else {
        //send emails to everyone who is entered in the address list in the extension configuration.
        $this->sendEmails('missing_file', $fileobj);
        $this->redirect(
            'list',
            'Category',
            NULL,
            array(
                'missing' => array(
                    'fileId' => $this->fid,
                    'category' => $this->cid
                )
            )
        );
    }
}
</code>```

The 40 KB file does not contain anything that shouldn't be there, it is just cut off. I tested it by writing alot of numbers in a file line by line and download it, result: only a couple thousand numbers are in the file instead of all numbers.

I tried it with both, files stored at a FTP Server and files stored in user_upload, same result.

Here you can see the 40 KB file:
http://pasteall.org/459911

Snippet (in case if the link is down):

```<code><ul>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
</code>```

//Cut because stackoverflow does not allow me to post such big texts
            ...

```<code>        <li>3183</li>
        <li>3184</li>
        <li>3185</li>
        <li>3186</li>
        <li
</code>```

You can see that it stops downloading the rest, the question is: why?

UPDATE:

I changed it to this:

```<code>    // If file exists, force download
    $fileName = basename($downloadFilePath);

    $this->response->setHeader('Content-Type', "application/force-download", TRUE);
    $this->response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName, TRUE);
    $this->response->setHeader('Content-Length', $groesse, TRUE);

    ob_start();
    ob_flush();
    flush();
    $content = file_get_contents($downloadFilePath);

    $this->response->setContent($content);
    $this->response->sendHeaders();
    return true; //i can also delete this line, since it is never reached.
</code>```

Now the file is downloaded completly, but the file is now wrapped inside the html from the template. it gets rendered inside the fluid variable mainContent.

Like this:

```<code>...

<!--TYPO3SEARCH_begin-->
<div class="clearfix col-sm-{f:if(condition:'{data.backend_layout} == 4',then:'12',else:'9')} col-md-{f:if(condition:'{data.backend_layout} == 4',then:'9',else:'6')} col-lg-{f:if(condition:'{data.backend_layout} == 4',then:'10',else:'8')} mainContent">
    <f:format.raw>{mainContent}</f:format.raw>
</div>
<!--TYPO3SEARCH_end-->

...
</code>```

It gets weirder and weirder...

答:
I finally solved the problem. I just had to execute exit or die  after sending the headers:

```<code>@readfile($downloadFilePath);
$this->response->sendHeaders();
exit;
</code>```

NOTE: If you exit your code with exit or die then typo3 session set with e.g. $GLOBALS['TSFE']->fe_user->setKey("ses", "token", DownloadUtility::getToken(32)); won't work anymore if not logged in to the backend! Use $GLOBALS['TSFE']->fe_user->setAndSaveSessionData("token", DownloadUtility::getToken(32)); in this case if no log in should be required.

Now it works even if not logged in to the front end.

But I still don't know why the download worked without being cut off while being logged in to the backend, even though the exit statement was missing. Thats extremly weird and we have no explanation.

Body:
I created a duplicate of a download extension from my colleague which is basically an extension which just provides files to download in the back end.

Problem:

If i try to download a file while the extension is only accessible after login to the back end, then it works perfectly fine

however if I open a private browser window where I am not logged in to the back end, then it always cuts off the file and only download the first 40 KB ... even though it is normally 10 MB. Why is the file cut off?

I can download small files ( < 40KB ) perfectly without them getting cutted off.

NOTE:

Before I edited the extension, the download worked perfectly, even if not logged in to the back end! And the download was triggered the same way

Currently I am comparing the code, but from the logic it looks ok, since I did not changed much (added a new model, renamed the extension and some other stuff)

Does someone have a clue what can lead to this problem?

This is the relevant part in my download controller where I first get the public url of the file by passing the fid of the file  and then trigger the download by sending headers.

...
if ($this->request->hasArgument('fid')) {
    $this->fid = $this->request->getArgument('fid');
}
if ($this->request->hasArgument('cid')) {
    $this->cid = $this->request->getArgument('cid');
}

$fileobj = $this->fileRepository->findByUid($this->fid);

if ($fileobj->getFile() !== null) {
    $downloadFilePath = $fileobj->getFile()->getOriginalResource()->getPublicUrl();

    if (file_exists($downloadFilePath)) {
        $fileCounter = (int)$fileobj->getCounter();
        $fileobj->setCounter(++$fileCounter);
        $oldChecksum = $fileobj->getChecksume();
        $groesse = filesize($downloadFilePath);

        if (isset($oldChecksum)) {
            $checksum = sha1_file($downloadFilePath);
            $fileobj->setChecksume($checksum);
        }

        // update fileobj
        $this->fileRepository->update($fileobj);

        // Unset fileobj before persists, otherwise there will be also changes
        $this->persistenceManager->persistAll();

        // If file exists, force download
        $fileName = basename($downloadFilePath);

        $this->response->setHeader('Content-Type', "application/force-download", TRUE);
        $this->response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName, TRUE);
        $this->response->setHeader('Content-Length', $groesse, TRUE);

        @readfile($downloadFilePath);
        $this->response->sendHeaders();
        return true; //i can also delete this line, since it is never reached.

    } else {
        //send emails to everyone who is entered in the address list in the extension configuration.
        $this->sendEmails('missing_file', $fileobj);
        $this->redirect(
            'list',
            'Category',
            NULL,
            array(
                'missing' => array(
                    'fileId' => $this->fid,
                    'category' => $this->cid
                )
            )
        );
    }
}

The 40 KB file does not contain anything that shouldn't be there, it is just cut off. I tested it by writing alot of numbers in a file line by line and download it, result: only a couple thousand numbers are in the file instead of all numbers.

I tried it with both, files stored at a FTP Server and files stored in user_upload, same result.

Here you can see the 40 KB file:
http://pasteall.org/459911

Snippet (in case if the link is down):

0

1

2

3

4

5

6

7

8

9

//Cut because stackoverflow does not allow me to post such big texts
            ...

3183

3184

3185

3186

        <li

You can see that it stops downloading the rest, the question is: why?

UPDATE:

I changed it to this:

    // If file exists, force download
    $fileName = basename($downloadFilePath);

    $this->response->setHeader('Content-Type', "application/force-download", TRUE);
    $this->response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName, TRUE);
    $this->response->setHeader('Content-Length', $groesse, TRUE);

    ob_start();
    ob_flush();
    flush();
    $content = file_get_contents($downloadFilePath);

    $this->response->setContent($content);
    $this->response->sendHeaders();
    return true; //i can also delete this line, since it is never reached.

Now the file is downloaded completly, but the file is now wrapped inside the html from the template. it gets rendered inside the fluid variable mainContent.

Like this:

...

    <f:format.raw>{mainContent}</f:format.raw>

...

It gets weirder and weirder...

Body:
I finally solved the problem. I just had to execute exit or die  after sending the headers:

@readfile($downloadFilePath);
$this->response->sendHeaders();
exit;

NOTE: If you exit your code with exit or die then typo3 session set with e.g. $GLOBALS['TSFE']->fe_user->setKey("ses", "token", DownloadUtility::getToken(32)); won't work anymore if not logged in to the backend! Use $GLOBALS['TSFE']->fe_user->setAndSaveSessionData("token", DownloadUtility::getToken(32)); in this case if no log in should be required.

Now it works even if not logged in to the front end.

But I still don't know why the download worked without being cut off while being logged in to the backend, even though the exit statement was missing. Thats extremly weird and we have no explanation.


问:
Bottom div alignment issue if upper have boder on hover
The issue when adding border property on hover the below div alignment is getting distorted. I know it is because it increase the height of hovered div which cause. Is there any work around.

The box height is depend on content inside it so we cant fix it. fiddle

.col {
  width: 20%;
  padding: 10px;
  float: left;
  box-sizing: border-box
}

.col:hover {
  border: solid 1px red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
  <div class="col">4</div>
  <div class="col">5</div>
  <div class="col">6</div>
  <div class="col">7</div>
  <div class="col">8</div>
</div></code>```

Edit

I have added the hover property to top most parent div which add transparent border to all the div. which fix this issue but it does not seem good approach because user can see something moving when hover

答:
Don't worry

It is easy, you can use outline:1px solid red;insted of border

That is because , You have given 20% width for each column, totally 5 divs can fit on screen.
Once you hover you are adding a border. it will increase width 20%+border width. since you are getting this issue.

See fiddle link https://jsfiddle.net/nmxzzvk5/7/

Body:
The issue when adding border property on hover the below div alignment is getting distorted. I know it is because it increase the height of hovered div which cause. Is there any work around.

The box height is depend on content inside it so we cant fix it. fiddle

.col {
  width: 20%;
  padding: 10px;
  float: left;
  box-sizing: border-box
}

.col:hover {
  border: solid 1px red
}

1

2

3

4

5

6

7

8

Edit

I have added the hover property to top most parent div which add transparent border to all the div. which fix this issue but it does not seem good approach because user can see something moving when hover


问:
Stuck on developing a combat function
basically im learning to code and saw this nice dragon realm example task. Everything was fine until i reached the stage where i want to engage in combat.

```<code>    def cave_2_fight():
        def monster_hit():
            m_hit = random.randint(1, 11)
            return m_hit

        def player_hit():
            p_hit = random.randint(1, 11)
            return p_hit

        monster_hp = random.randint(1, 101)
        player_hp = 100
        print("You are being attacked by a goblin with {} hp".format(monster_hp))
        print("Getting ready text")
        while monster_hp != 0 or player_hp != 0:
            attack_area = input("Where do you want to hit him[top or mid or bot]: ")
            if attack_area == 'top':
                p_dmg = player_hit()
                m_dmg = monster_hit()
                print('You hit goblin for {} and he hits you for {}'.format(p_dmg, m_dmg))
                player_hp = player_hp - m_dmg
                monster_hp = monster_hp - p_dmg
                return player_hp, monster_hp

            elif attack_area == "mid":
                p_dmg = player_hit()
                m_dmg = monster_hit()
                print('You hit goblin for {} and he hits you for {}'.format(p_dmg, m_dmg))
                player_hp = player_hp - m_dmg
                monster_hp = monster_hp - p_dmg
</code>```

I want it to be random a bit, and im really stuck in returning to choosing attack_area after i negaged for the first time. Thanks in advance

答:
```<code>                return player_hp, monster_hp
</code>```

exits the function. You should take out this line - monster_hp and player_hp will get updated without it.

Also, you should probably change

```<code>    while monster_hp != 0 or player_hp != 0:
</code>```

to

```<code>    while monster_hp > 0 or player_hp > 0:
</code>```

since it's possible that someone's hp will go negative. If you want the game to end whenever either player dies, change the "or" to "and" (this will require them both to be alive.)

You're probably getting downvoted because a) it's not at all clear what your problem with your code is (I guessed), and b) the code you posted isn't an MCVE: the first line will give a syntax error (I think this is just an indentation problem with the copy-pasting.)

Title: Stuck on developing a combat function

Body:
basically im learning to code and saw this nice dragon realm example task. Everything was fine until i reached the stage where i want to engage in combat.

    def cave_2_fight():
        def monster_hit():
            m_hit = random.randint(1, 11)
            return m_hit

        def player_hit():
            p_hit = random.randint(1, 11)
            return p_hit

        monster_hp = random.randint(1, 101)
        player_hp = 100
        print("You are being attacked by a goblin with {} hp".format(monster_hp))
        print("Getting ready text")
        while monster_hp != 0 or player_hp != 0:
            attack_area = input("Where do you want to hit him[top or mid or bot]: ")
            if attack_area == 'top':
                p_dmg = player_hit()
                m_dmg = monster_hit()
                print('You hit goblin for {} and he hits you for {}'.format(p_dmg, m_dmg))
                player_hp = player_hp - m_dmg
                monster_hp = monster_hp - p_dmg
                return player_hp, monster_hp

            elif attack_area == "mid":
                p_dmg = player_hit()
                m_dmg = monster_hit()
                print('You hit goblin for {} and he hits you for {}'.format(p_dmg, m_dmg))
                player_hp = player_hp - m_dmg
                monster_hp = monster_hp - p_dmg

I want it to be random a bit, and im really stuck in returning to choosing attack_area after i negaged for the first time. Thanks in advance

Body:
                return player_hp, monster_hp

exits the function. You should take out this line - monster_hp and player_hp will get updated without it.

Also, you should probably change

    while monster_hp != 0 or player_hp != 0:

to

    while monster_hp > 0 or player_hp > 0:

since it's possible that someone's hp will go negative. If you want the game to end whenever either player dies, change the "or" to "and" (this will require them both to be alive.)

You're probably getting downvoted because a) it's not at all clear what your problem with your code is (I guessed), and b) the code you posted isn't an MCVE: the first line will give a syntax error (I think this is just an indentation problem with the copy-pasting.)


问:
How can i deploy kubernetes for trial purpose? (sandbox kind of environment)
Links suggested i use minikube to install kubernetes. However i am confused if i should install this on my ubuntu host machine or on the vm provisioned with virtual box running on this host machine.
I want to know the pre-requisites for the install and how to go about it.
I am a newbie to kubernetes and pretty confused on how to go about it.</p>

答: Minikube already provides a VM with K8s installed. In this sense, with Minikube, you do not need to install anything. If your aim is to test how to work with Kubernetes (i.e. deploying pods, services, volumes...), then Minikube is for you. If, on the contrary, you want to experiment how to actually install Kubernetes (i.e. install kubelet, the API server...) then you will need to find another alternative, like for example sinning up several Ubuntu VMs and follow the installation documentation (https://kubernetes.io/docs/setup/pick-right-solution/)</p>


问:
Python checking if string in list to list
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

```<code>list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)
</code>```

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.

答:
Use Set for this .

set(list2)-set(list1)

Check with python set

Body:
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.


问:
Architectural and design question about uploading photos from iPhone app and S3
I want to allow users of an iPhone app to upload photos and use Amazon S3.  There are 2 ways I see going about this:

Upload from iPhone to my server, which proxies it then to Amazon S3.

Upload from iPhone direct to S3

For option 1, the security is straightforward. I don't ever have to tell the iPhone my S3 secret. Downside is that everything is proxied through our server for uploads which sort of defeats the purpose of going to S3.

For option 2, in theory it's better but the issue is how do you enable the iPhone (or any mobile app on a different platform) to write into my S3 bucket without giving it my secret?  Additionally, I'm not sure if this is a good design or not because the flow would be: iphone uploads to S3, gets the URL, then tells the server what the URL is so it can add it to our database to reference in the future. However, since the communication is separated into 2 legs (iphone->S3 vs iPhone->My-Server) it leaves it fragile as a non-atomic operation.

I've found some older info that references using Browser-based Uploads using POST but unsure if that is still the recommended approach. I'm hoping for a better solution where we can just use the REST APIs rather than relying on POST.  I've also see the AWS iOS Beta SDK, but their docs didn't help much and I found an Amazon article that was equally unhelpful as it cautions you on what not to do, but doesn't tell you an alternative approach:

The mobile AWS SDKs sign the API
  requests sent to Amazon Web Services
  (AWS) in order to validate the
  identity of the AWS account making the
  request. Otherwise, a malicious
  developer could easily make requests
  to another developer's infrastructure.
  The requests are signed using an AWS
  Access Key ID and a Secret Access Key
  that AWS provides. The Secret Access
  Key is similar to a password, and it
  is extremely important to keep secret.

Tip: You can view all your AWS
  security credentials, including Access
  Key ID and Secret Access Key, on the
  AWS web site at
  http://aws.amazon.com/security-credentials.

Embedding credentials in source code
  is problematic for software, including
  mobile applications, because malicious
  users can de-compile the software or
  view the source code to retrieve the
  Secret Access Key.

Does anyone have any advice on the best architectural design and flow for this?

Update: The more I dig into this, it seems that a bunch of pople recommend using the HTTP POST method with the json policy file as described here: http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/index.html?UsingHTTPPOST.html.

With this, the flow would be something like (1) iPhone makes request to my server, asking for policy file (2) server generates json policy file and gives back to client (3) iPhone does HTTP POST of photo + json policy to S3.  I hate that I'm using HTTP POST in an apparently kludgy way but it appears to be better because it removes the need for my server to store the photo at all.

答: I m confused. Why would amazon come up w/ the ios sdk to upload data to s3 then tell us not to use it (Embedding credentials in source code is problematic for software, including mobile applications, because malicious users can de-compile the software or view the source code to retrieve the Secret Access Key)???


问:
XPATH: exclude elements which which has a specific child
```<code><ul>
  <li><a></li>
  <li><a></li>
  <li>
    <div>
      <a>
    </div>
  </li>
</ul>
</code>```

How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

```<code>./li[not(contains(descendant::div]
</code>```

But obviously that didn't work

答:
Xpath that searches for li tags that has not div child:

```<code>//li[not(descendant::div)]
</code>```

another option:

```<code>//li[not(.//div)]
</code>```

To exclude some elements from selection - use not() method like locator[not(condition)]

Some more complex example on this table https://www.w3schools.com/css/css_table.asp:
here is locator that gets row that has not elements inside with text that starts with "C"

```<code>//table[@id='customers']//tr[not(.//*[starts-with(text(),'C')])]
</code>```

explanation:

//table[@id='customers']//tr - get all rows

[not(.//*[...])] - not containing element with specific attribute

[starts-with(text(),'C')] - and that the described attribute

ContentLicense: CC BY-SA 4.0

Body:
How can I select only first 2 li items and exclude li that contains div inside?

Considering ul is set as parent, I've tried

./li[not(contains(descendant::div]

But obviously that didn't work

Body:
Xpath that searches for li tags that has not div child:

//li[not(descendant::div)]

another option:

//li[not(.//div)]

To exclude some elements from selection - use not() method like locator[not(condition)]

Some more complex example on this table https://www.w3schools.com/css/css_table.asp:
here is locator that gets row that has not elements inside with text that starts with "C"

//table[@id='customers']//tr[not(.//*[starts-with(text(),'C')])]

explanation:

//table[@id='customers']//tr - get all rows

[not(.//*[...])] - not containing element with specific attribute

[starts-with(text(),'C')] - and that the described attribute


问:
JOIN query to retrieve multiple column referencing to a single column from another table
Below is my database diagram which includes three tables and their relations -  PersonalInfo,Subjects,Students

Currently, Students table have below values.

I'm trying to query data to be displayed as below.

What I tried

```<code>SELECT FullName, SubjectName AS 'Subject1', SubjectName AS 'Subject2',
SubjectName AS 'Subject3', SubjectName AS 'Subject4',SubjectName AS 'Subject5'
FROM Subjects JOIN Students ON Students.Subject1 =Subjects.Id
JOIN PersonalInfo ON PersonalInfo.Id=Students.StudId
</code>```

Getting below output which is wrong. It's showing only name of the first subject.

Could anyone guide me the right way.

答:
Working query

```<code>SELECT FullName,
sb.SubjectName AS 'Subject1',
sb2.SubjectName AS 'Subject2',
sb3.SubjectName AS 'Subject3',
sb4.SubjectName AS 'Subject4',
sb5.SubjectName AS 'Subject5'
FROM Students s
JOIN PersonalInfo ON PersonalInfo.Id=s.StudId
JOIN Subjects sb ON s.Subject1 =sb.Id
JOIN Subjects sb2 ON s.Subject2 =sb2.Id
JOIN Subjects sb3 ON s.Subject3 =sb3.Id
JOIN Subjects sb4 ON s.Subject4 =sb4.Id
JOIN Subjects sb5 ON s.Subject5 =sb5.Id
</code>```

Result

Body:
Below is my database diagram which includes three tables and their relations -  PersonalInfo,Subjects,Students

Currently, Students table have below values.

I'm trying to query data to be displayed as below.

What I tried

SELECT FullName, SubjectName AS 'Subject1', SubjectName AS 'Subject2',
SubjectName AS 'Subject3', SubjectName AS 'Subject4',SubjectName AS 'Subject5'
FROM Subjects JOIN Students ON Students.Subject1 =Subjects.Id
JOIN PersonalInfo ON PersonalInfo.Id=Students.StudId

Getting below output which is wrong. It's showing only name of the first subject.

Could anyone guide me the right way.

Body:
Working query

SELECT FullName,
sb.SubjectName AS 'Subject1',
sb2.SubjectName AS 'Subject2',
sb3.SubjectName AS 'Subject3',
sb4.SubjectName AS 'Subject4',
sb5.SubjectName AS 'Subject5'
FROM Students s
JOIN PersonalInfo ON PersonalInfo.Id=s.StudId
JOIN Subjects sb ON s.Subject1 =sb.Id
JOIN Subjects sb2 ON s.Subject2 =sb2.Id
JOIN Subjects sb3 ON s.Subject3 =sb3.Id
JOIN Subjects sb4 ON s.Subject4 =sb4.Id
JOIN Subjects sb5 ON s.Subject5 =sb5.Id

Result


问:
TextInput OnChange in React native
Please help me. I have a TextInput, my problem is when I type the numeric value, that value going to multiply with some number. When I type 1000, this will get saved to state as 1000, but it saves to store as 100. The results differ.

```<code> <TextInput
  onChangeText={this.handle_bill_Amount}
  style={styles.input}
  placeholder="Amount"
  value={this.state.Amount}
  keyboardType = 'numeric'
  enablesReturnKeyAutomatically={true}
  placeholderTextColor = "#824242"
  underlineColorAndroid="transparent">
 </TextInput>

  handle_bill_Amount = Amount => {
  this.setState({ Amount})
  let billamt = this.state.Amount;
  console.log(billamt);
  }

 constructor(props) {
    super(props);
    this.state = {
    Amount: '',
    }
    this.handle_bill_Amount = this.handle_bill_Amount.bind(this);
}
</code>```

Guys help me please!

答:
this.setState is async in nature, hence non-deterministic in the next statement. So, when you are logging the value, state might not yet have the updated value.
So for deterministic behavior, it is advised that you use the second argument, which is a callback, to get the correct state. It is invoked when setState is executed.

```<code>this.setState({Amount}, () => console.log(this.state.Amount))
</code>```

Title: TextInput OnChange in React native

Body:
Please help me. I have a TextInput, my problem is when I type the numeric value, that value going to multiply with some number. When I type 1000, this will get saved to state as 1000, but it saves to store as 100. The results differ.

 <TextInput
  onChangeText={this.handle_bill_Amount}
  style={styles.input}
  placeholder="Amount"
  value={this.state.Amount}
  keyboardType = 'numeric'
  enablesReturnKeyAutomatically={true}
  placeholderTextColor = "#824242"
  underlineColorAndroid="transparent">
 </TextInput>

  handle_bill_Amount = Amount => {
  this.setState({ Amount})
  let billamt = this.state.Amount;
  console.log(billamt);
  }

 constructor(props) {
    super(props);
    this.state = {
    Amount: '',
    }
    this.handle_bill_Amount = this.handle_bill_Amount.bind(this);
}

Guys help me please!

Body:
this.setState is async in nature, hence non-deterministic in the next statement. So, when you are logging the value, state might not yet have the updated value.
So for deterministic behavior, it is advised that you use the second argument, which is a callback, to get the correct state. It is invoked when setState is executed.

this.setState({Amount}, () => console.log(this.state.Amount))


问:
Stylesheet is not working with bootstrap 4 CDN link?
Javascript is working fine alongside my bootstrap cdn but my css file seems to be overridden by default bootstrap cdn, need help in adding the !important tag to my css file.

I have tried almost every possible event but none helping

My code snippet is as follows:

var nodes = document.querySelectorAll('li'),
  _nodes = [].slice.call(nodes, 0);

var getDirection = function(ev, obj) {
  var w = obj.offsetWidth,
    h = obj.offsetHeight,
    x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
    y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
    d = Math.round(Math.atan2(y, x) / 1.57079633 + 5) % 4;

  return d;
};

var addClass = function(ev, obj, state) {
  var direction = getDirection(ev, obj),
    class_suffix = "";

  obj.className = "";

  switch (direction) {
    case 0:
      class_suffix = '-top';
      break;
    case 1:
      class_suffix = '-right';
      break;
    case 2:
      class_suffix = '-bottom';
      break;
    case 3:
      class_suffix = '-left';
      break;
  }

  obj.classList.add(state + class_suffix);
};

_nodes.forEach(function(el) {
  el.addEventListener('mouseover', function(ev) {
    addClass(ev, this, 'in');
  }, false);

  el.addEventListener('mouseout', function(ev) {
    addClass(ev, this, 'out');
  }, false);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  -webkit-perspective: 400px;
  perspective: 400px;
}

.info {
  -webkit-transform: rotate3d(1, 0, 0, 90deg);
  transform: rotate3d(1, 0, 0, 90deg);
  width: 100%;
  height: 100%;
  padding: 50px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border-radius: 4px;
  pointer-events: none;
  background-color: rgba(26, 188, 156, 0.9);
}

.in-top .info {
  -webkit-transform-origin: 50% 0%;
  transform-origin: 50% 0%;
  -webkit-animation: in-top 300ms ease 0ms 1 forwards;
  animation: in-top 300ms ease 0ms 1 forwards;
}

.out-top .info {
  -webkit-transform-origin: 50% 0%;
  transform-origin: 50% 0%;
  -webkit-animation: out-top 300ms ease 0ms 1 forwards;
  animation: out-top 300ms ease 0ms 1 forwards;
}

@-webkit-keyframes in-top {
  from {
    -webkit-transform: rotate3d(-1, 0, 0, 90deg);
    transform: rotate3d(-1, 0, 0, 90deg);
  }
  to {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
}

@keyframes in-top {
  from {
    -webkit-transform: rotate3d(-1, 0, 0, 90deg);
    transform: rotate3d(-1, 0, 0, 90deg);
  }
  to {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
}

@-webkit-keyframes out-top {
  from {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
  to {
    -webkit-transform: rotate3d(-1, 0, 0, 104deg);
    transform: rotate3d(-1, 0, 0, 104deg);
  }
}

@keyframes out-top {
  from {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
  to {
    -webkit-transform: rotate3d(-1, 0, 0, 104deg);
    transform: rotate3d(-1, 0, 0, 104deg);
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Direction-aware 3D hover effect (Concept)</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Direction-aware hover effect

CSS & bits of JS

          <svg viewBox='0 0 80 76' x='0px' y='0px'>
                   <g>
                      <path d='M 68.9708 24.8623 L 60.4554 2.3018 C 59.9641 0.7017 58.1628 -0.2583 56.5252 0.3817 L 1.9822 20.2222 C 0.3822 20.7022 -0.4179 22.6222 0.2222 24.2223 L 8.8624 47.7797 L 8.8624 35.1484 C 8.8624 29.5024 13.3425 24.8623 18.8857 24.8623 L 32.9442 24.8623 L 50.63 12.862 L 60.7829 24.8623 L 68.9708 24.8623 L 68.9708 24.8623 ZM 77.098 32.0625 L 18.8857 32.0625 C 17.2512 32.0625 16.0625 33.4511 16.0625 35.1484 L 16.0625 72.8491 C 16.0625 74.5477 17.2512 75.9375 18.8857 75.9375 L 77.098 75.9375 C 78.742 75.9375 79.9376 74.5477 79.9376 72.8491 L 79.9376 35.1484 C 79.9376 33.4511 78.742 32.0625 77.098 32.0625 L 77.098 32.0625 ZM 73.0626 68.0625 L 23.9375 68.0625 L 23.9375 61.0852 L 31.4704 43.7232 L 42.7696 57.6777 L 53.4138 46.8062 L 67.1695 41.9375 L 73.0626 55.0815 L 73.0626 68.0625 L 73.0626 68.0625 Z'></path>
                   </g>
                </svg>

Single-origin coffee whatever

Williamsburg tofu polaroid, 90's Bushwick irony locavore ethnic meh messenger bag Truffaut jean shorts.

```

My default stylesheet is overriden by BootStrap CSS. How to use !important exception

答:
Load your custom css after the Bootstrap CSS, the order of the items you load in matters. In your current order, your CSS loads and then the Bootstrap does, overriding your styles. </p>

<p>To fix simply place your custom CSS after the Bootstrap load. </p>

```<code><head>
<meta charset="UTF-8">
<title>Direction-aware 3D hover effect (Concept)</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
</code>```

Body:
Javascript is working fine alongside my bootstrap cdn but my css file seems to be overridden by default bootstrap cdn, need help in adding the !important tag to my css file.

I have tried almost every possible event but none helping

My code snippet is as follows:

var nodes = document.querySelectorAll('li'),
  _nodes = [].slice.call(nodes, 0);

var getDirection = function(ev, obj) {
  var w = obj.offsetWidth,
    h = obj.offsetHeight,
    x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
    y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
    d = Math.round(Math.atan2(y, x) / 1.57079633 + 5) % 4;

  return d;
};

var addClass = function(ev, obj, state) {
  var direction = getDirection(ev, obj),
    class_suffix = "";

  obj.className = "";

  switch (direction) {
    case 0:
      class_suffix = '-top';
      break;
    case 1:
      class_suffix = '-right';
      break;
    case 2:
      class_suffix = '-bottom';
      break;
    case 3:
      class_suffix = '-left';
      break;
  }

  obj.classList.add(state + class_suffix);
};

_nodes.forEach(function(el) {
  el.addEventListener('mouseover', function(ev) {
    addClass(ev, this, 'in');
  }, false);

  el.addEventListener('mouseout', function(ev) {
    addClass(ev, this, 'out');
  }, false);
});

li {
  -webkit-perspective: 400px;
  perspective: 400px;
}

.info {
  -webkit-transform: rotate3d(1, 0, 0, 90deg);
  transform: rotate3d(1, 0, 0, 90deg);
  width: 100%;
  height: 100%;
  padding: 50px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border-radius: 4px;
  pointer-events: none;
  background-color: rgba(26, 188, 156, 0.9);
}

.in-top .info {
  -webkit-transform-origin: 50% 0%;
  transform-origin: 50% 0%;
  -webkit-animation: in-top 300ms ease 0ms 1 forwards;
  animation: in-top 300ms ease 0ms 1 forwards;
}

.out-top .info {
  -webkit-transform-origin: 50% 0%;
  transform-origin: 50% 0%;
  -webkit-animation: out-top 300ms ease 0ms 1 forwards;
  animation: out-top 300ms ease 0ms 1 forwards;
}

@-webkit-keyframes in-top {
  from {
    -webkit-transform: rotate3d(-1, 0, 0, 90deg);
    transform: rotate3d(-1, 0, 0, 90deg);
  }
  to {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
}

@keyframes in-top {
  from {
    -webkit-transform: rotate3d(-1, 0, 0, 90deg);
    transform: rotate3d(-1, 0, 0, 90deg);
  }
  to {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
}

@-webkit-keyframes out-top {
  from {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
  to {
    -webkit-transform: rotate3d(-1, 0, 0, 104deg);
    transform: rotate3d(-1, 0, 0, 104deg);
  }
}

@keyframes out-top {
  from {
    -webkit-transform: rotate3d(0, 0, 0, 0deg);
    transform: rotate3d(0, 0, 0, 0deg);
  }
  to {
    -webkit-transform: rotate3d(-1, 0, 0, 104deg);
    transform: rotate3d(-1, 0, 0, 104deg);
  }
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Direction-aware 3D hover effect (Concept)</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Direction-aware hover effect

CSS & bits of JS

          <svg viewBox='0 0 80 76' x='0px' y='0px'>
                   <g>
                      <path d='M 68.9708 24.8623 L 60.4554 2.3018 C 59.9641 0.7017 58.1628 -0.2583 56.5252 0.3817 L 1.9822 20.2222 C 0.3822 20.7022 -0.4179 22.6222 0.2222 24.2223 L 8.8624 47.7797 L 8.8624 35.1484 C 8.8624 29.5024 13.3425 24.8623 18.8857 24.8623 L 32.9442 24.8623 L 50.63 12.862 L 60.7829 24.8623 L 68.9708 24.8623 L 68.9708 24.8623 ZM 77.098 32.0625 L 18.8857 32.0625 C 17.2512 32.0625 16.0625 33.4511 16.0625 35.1484 L 16.0625 72.8491 C 16.0625 74.5477 17.2512 75.9375 18.8857 75.9375 L 77.098 75.9375 C 78.742 75.9375 79.9376 74.5477 79.9376 72.8491 L 79.9376 35.1484 C 79.9376 33.4511 78.742 32.0625 77.098 32.0625 L 77.098 32.0625 ZM 73.0626 68.0625 L 23.9375 68.0625 L 23.9375 61.0852 L 31.4704 43.7232 L 42.7696 57.6777 L 53.4138 46.8062 L 67.1695 41.9375 L 73.0626 55.0815 L 73.0626 68.0625 L 73.0626 68.0625 Z'></path>
                   </g>
                </svg>

Single-origin coffee whatever

Williamsburg tofu polaroid, 90's Bushwick irony locavore ethnic meh messenger bag Truffaut jean shorts.

My default stylesheet is overriden by BootStrap CSS. How to use !important exception

Body:
Load your custom css after the Bootstrap CSS, the order of the items you load in matters. In your current order, your CSS loads and then the Bootstrap does, overriding your styles.

To fix simply place your custom CSS after the Bootstrap load.

<head>
<meta charset="UTF-8">
<title>Direction-aware 3D hover effect (Concept)</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>


答:
You're essentially trying to create a parameterless function named endPosts for each row in posts. I don't even know what you're trying but this won't work. You can't declare a function twice.

And even if you could, endPosts doesn't do anything, so even if this would be valid code, it wouldn't output anything (except for the div).

Title: Include functions

Body:
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

<?php include 'includes/header.php'; ?>
<?php getPosts();?>

Some HTML Code

<?php endPosts(); ?>

Header.php

function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};

Any idea why this won't work? I'm getting a blank white screen right now.


问:
Mule; How can I make sure the flow completes without it being triggered again by the Quartz scheduer
I have a requirement in which the start of the flow is triggered to load customer data from a SQL database into a Mongo DB database. All the current trades need to be moved to the Mongo DB. Once the migration of current trades to MongoDB is complete, it is intended that new trades would start to be monitored and copied to MongoDB. The goal is to trigger the flow that monitors new customer trades to start after all the current customer trades has been moved to MongoDB. The problem is that moving the current customer trades is to be triggered from a property in a properties file.

```<code>   <flow name="migrateCurrentTrades">
     <quartz:inbound-endpoint responseTimeout="10000" doc:name="Task"
       cronExpression="0 */2 * * * ?" jobName="mailJob"
      repeatInterval="1000000"
                                         repeatCount="0">
            <quartz:event-generator-job/>
       </quartz:inbound-endpoint>
     <flow-ref name="readAndSave">
     <!-- This actually is a reference to a groovy script that starts the
             monitorCustomerActivity  flow below in the 'stopped'
            initialState
          -->

      <script-ref name="startMonitorCustomerActivityFlow"/>
   </flow>

     <!-- long running job----->
   <sub-flow name="readAndSave">
      <db:select  config-ref="mySQLConfig">
        <db:parameterized-query><![CDATA[
             SELECT * FROM CUSTOMER c WHERE status='ACTIVE'
            ]]>
      </db:parameterized-query>
    </db:select>
       <custom-transformer  class="com.gdc.CustomerTransformer" />
      <!-- Save to Mongo DB -- via queue -->
      <vm:outbound-endpoint path="mongodb-queue" exchange-pattern="one-way"/>
   </sub-flow>

  <flow name="monitorCustomerActivity" initialState="stopped">
     <quartz:inbound-endpoint responseTimeout="10000" doc:name="Task"
       cronExpression="0 */45 * * * ?" jobName="mailJob" repeatInterval="0"
                                         repeatCount="0">
            <quartz:event-generator-job/>
    </quartz:inbound-endpoint>
       <db:parameterized-query><![CDATA[
             SELECT * FROM CUSTOMER_TRADES c WHERE trade_status='NEW'
            ]]>
  </db:parameterized-query>
  </db:select>

    <custom-transformer class="com.gdc.TradesTransformer" />

   <!-- Save to Mongo DB -- via queue -->
      <vm:outbound-endpoint path="mongodb-queue" exchange-pattern="one-way"/>
   </flow>
</code>```

Unfortunately, the readAndSave flow keeps running repeatedly because it takes too long to complete. I have set the repeatInterval to a very high value and repeatCount to 0.  I want the readAndSave flow to only be triggered once and for it to complete. Although it starts the second flow, monitorCustomerActivity, it starts to interleave with it causing errors. How can I solve this problem, making sure the readAndSave flow be called only once and  complete saving the current customer trades before calling the second flow monitorCustomerActivity? I have battled with the problem for days

答:
Try out the below steps, Increased timeout, repeatCount = 0 + startdelay ( on  stop and start your anypoint/server it will wait for 20 secs and then the schedule starts).

Since it is Async, you can use flow instead of sub-flow.

```<code> <quartz:inbound-endpoint responseTimeout="60000" doc:name="Task"
    jobName="mailJob" repeatInterval="1000000"  repeatCount="0" startDelay="20000"> <quartz:event-generator-job/>
   </quartz:inbound-endpoint>
</code>```

         etc ....

```<code>      make readAndsave subflow to  `flow`

    <flow name="readAndSave">
  <db:select  config-ref="mySQLConfig" doc:name="Database">
    <db:parameterized-query><![CDATA[
         SELECT * FROM CUSTOMER c WHERE status='ACTIVE'
        ]]>
  </db:parameterized-query>
</db:select>
<logger message="readAndSave:Check how many times flow gets trigger by looking at this log entry" />
etc...
</code>```

Body:
I have a requirement in which the start of the flow is triggered to load customer data from a SQL database into a Mongo DB database. All the current trades need to be moved to the Mongo DB. Once the migration of current trades to MongoDB is complete, it is intended that new trades would start to be monitored and copied to MongoDB. The goal is to trigger the flow that monitors new customer trades to start after all the current customer trades has been moved to MongoDB. The problem is that moving the current customer trades is to be triggered from a property in a properties file.

   <flow name="migrateCurrentTrades">
     <quartz:inbound-endpoint responseTimeout="10000" doc:name="Task"
       cronExpression="0 */2 * * * ?" jobName="mailJob"
      repeatInterval="1000000"
                                         repeatCount="0">
            <quartz:event-generator-job/>
       </quartz:inbound-endpoint>
     <flow-ref name="readAndSave">

Body:
Try out the below steps, Increased timeout, repeatCount = 0 + startdelay ( on  stop and start your anypoint/server it will wait for 20 secs and then the schedule starts).

Since it is Async, you can use flow instead of sub-flow.

 <quartz:inbound-endpoint responseTimeout="60000" doc:name="Task"
    jobName="mailJob" repeatInterval="1000000"  repeatCount="0" startDelay="20000"> <quartz:event-generator-job/>
   </quartz:inbound-endpoint>

         etc ....

      make readAndsave subflow to  `flow`

    <flow name="readAndSave">
  <db:select  config-ref="mySQLConfig" doc:name="Database">
    <db:parameterized-query><![CDATA[
         SELECT * FROM CUSTOMER c WHERE status='ACTIVE'
        ]]>
  </db:parameterized-query>
</db:select>
<logger message="readAndSave:Check how many times flow gets trigger by looking at this log entry" />
etc...


问:
Padding issue on HTML email
I have an issue with excess padding appearing around either the table or image on mobile with a HTML email signature and I'm unable to find the solution.

I must of tried every single solution I have researched including:

Adding display:block to the image

Adding a line-height: 1px to the td

Adding font-size: 0; to the td

Making sure every section had padding: 0; and margin: 0;

Adding cellpadding="0" and cellspacing="0" to all tables, tr and td elements

Adding width and height to the table and td (which didn't have any effect)

Adding float: left and align="left"

Adding table-layout:fixed;

Adding border: 0; border-spacing: 0; and border-collapse; on elements

The issue seems to appear on Samsung and iPhone devices that I have tested.

Any new suggestions would be appreciated.

The image that specifically has extra spacing is here:

```<code><table align="left" cellpadding="0" cellspacing="0" style="border-collapse: collapse; border-spacing: 0; table-layout:fixed; mso-table-lspace:0pt;mso-table-rspace:0pt; padding:0; margin: 0; float:left; line-height: 1px; font-size: 0;" width="180">
    <tr style="padding: 0; margin: 0;">
        <td valign="bottom" style="padding:0 25px 0 0; margin:0; font-size: 0 !important;" cellpadding="0" cellspacing="0"><img src="logo.png" width="" alt="" style="display: block !important;"></td>
    </tr>
</table>
</code>```

How here is the entire code as I have two tables side by side which may be the cause of the issue:

```<code><!DOCTYPE html>
<html>
<head>
<style>
a {
    color: #00001b;
    text-decoration: underline;
}
table {
    padding: 0;
    margin: 0;
    display: block;
}

</style>
</head>
<body>
<table style="font-family: Helvetica, sans-serif; max-width: 367px;" width="100%" cellspacing="0" cellpadding="0">
<tr>
    <td>
        <table style="border-bottom: 3px solid #000; padding-bottom: 8px;" width="367" cellspacing="0">
            <tr style="padding: 0; margin: 0;">
                <td cellspacing="0" cellpadding="0" style="border-collapse: collapse; mso-table-lspace:0pt;mso-table-rspace:0pt; padding:0; margin: 0;" border="0" height="10">
                    <table align="left" cellpadding="0" cellspacing="0" style="border-collapse: collapse; border-spacing: 0; table-layout:fixed; mso-table-lspace:0pt;mso-table-rspace:0pt; padding:0; margin: 0; float:left; line-height: 1px; font-size: 0;" width="180">
                        <tr style="padding: 0; margin: 0;">
                            <td valign="bottom" style="padding:0 25px 0 0; margin:0; font-size: 0 !important;" cellpadding="0" cellspacing="0"><img src="logo.png" width="" alt="" style="display: block !important; padding: 0; margin: 0;"></td>
                        </tr>
                    </table>
                    <table align="left" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse; border-spacing: 0; mso-table-lspace:0pt;mso-table-rspace:0pt; margin: 0; padding: 0 0 7px 0; line-height:1px; font-size:0; float:left;">
                        <tr>
                            <td cellpadding="0" cellspacing="0" width="165" style="text-align: left;">
                                <strong style="font-size: 16px; font-family: Garamond;">First Name Last Name</strong><br />
                                <span style="font-size: 11px; line-height: 100%;"><em>Job Title / GIA GG, BA</em></span><br />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </td>
</tr>
<tr>
    <td colspan="2">
    <p style="font-size: 11px; line-height: 160%; margin: 10px 0;">
    <strong>T:</strong> <a href="tel:0000000">00000000</a> |
    <strong>W:</strong> <a href="http://www.website.com.au">www.website.com.au</a><br /> Street Address | City | State Postcode</p>
    <p style="margin:6px 0;"><a href="https://www.facebook.com/"><img src="facebook.png" alt="Facebook" width="28" height="28"></a> <a href="https://www.instagram.com"><img src="instagram.png" alt="Instagram" width="28" height="28"></a></p>
    </td>
</tr>
</table>
</body>
</html>
</code>```

答:
```<code><table style="font-family: Helvetica, sans-serif; max-width: 367px;" width="100%" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <table style="border-bottom: 3px solid #000; padding-bottom: 8px;" width="345" cellspacing="0" cellpadding="0" border="0">
                <tr>
                    <td valign="top">
                        <table align="left" cellpadding="0" cellspacing="0" border="0" width="180">
                            <tr>
                                <td valign="bottom" cellpadding="0" cellspacing="0"><img src="logo.png" width="180" height="100" alt="" style="display: block"></td>
                            </tr>
                        </table>
                    </td>
                    <td valign="top">
                        <table align="left" border="0" cellpadding="0" cellspacing="0" width="165">
                            <tr>
                                <td style="text-align: left;padding:0 0 0 25px;">
                                    <strong style="font-size: 16px; font-family: Garamond;">First Name Last Name</strong><br />
                                    <span style="font-size: 11px; line-height: 100%;"><em>Job Title / GIA GG, BA</em></span><br />
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td colspan="2">
        <p style="font-size: 11px; line-height: 160%; margin: 10px 0;">
        <strong>T:</strong> <a href="tel:0000000">00000000</a> |
        <strong>W:</strong> <a href="http://www.website.com.au">www.website.com.au</a><br /> Street Address | City | State Postcode</p>
        <p style="margin:6px 0;"><a href="https://www.facebook.com/"><img src="facebook.png" alt="Facebook" width="28" height="28"></a> <a href="https://www.instagram.com"><img src="instagram.png" alt="Instagram" width="28" height="28"></a></p>
        </td>
    </tr>
</table>
</code>```

You may want to add a 	 between your two tables. I've also moved the 25px padding to the left of the copy, rather than the image. (I've assumed the img dimensions here). This looked ok on my EoA previews, if it doesn't help could you post a screenshot of your issue?

Title: Padding issue on HTML email

Body:
I have an issue with excess padding appearing around either the table or image on mobile with a HTML email signature and I'm unable to find the solution.

I must of tried every single solution I have researched including:

Adding display:block to the image

Adding a line-height: 1px to the td

Adding font-size: 0; to the td

Making sure every section had padding: 0; and margin: 0;

Adding cellpadding="0" and cellspacing="0" to all tables, tr and td elements

Adding width and height to the table and td (which didn't have any effect)

Adding float: left and align="left"

Adding table-layout:fixed;

Adding border: 0; border-spacing: 0; and border-collapse; on elements

The issue seems to appear on Samsung and iPhone devices that I have tested.

Any new suggestions would be appreciated.

The image that specifically has extra spacing is here:

How here is the entire code as I have two tables side by side which may be the cause of the issue:

<!DOCTYPE html>

                                First Name Last Name

                                Job Title / GIA GG, BA

    T: 00000000 |
    W: www.website.com.au
 Street Address | City | State Postcode

Body:
<table style="font-family: Helvetica, sans-serif; max-width: 367px;" width="100%" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <table style="border-bottom: 3px solid #000; padding-bottom: 8px;" width="345" cellspacing="0" cellpadding="0" border="0">
                <tr>
                    <td valign="top">
                        <table align="left" cellpadding="0" cellspacing="0" border="0" width="180">
                            <tr>
                                <td valign="bottom" cellpadding="0" cellspacing="0"><img src="logo.png" width="180" height="100" alt="" style="display: block"></td>
                            </tr>
                        </table>
                    </td>
                    <td valign="top">
                        <table align="left" border="0" cellpadding="0" cellspacing="0" width="165">
                            <tr>
                                <td style="text-align: left;padding:0 0 0 25px;">
                                    <strong style="font-size: 16px; font-family: Garamond;">First Name Last Name</strong><br />
                                    <span style="font-size: 11px; line-height: 100%;"><em>Job Title / GIA GG, BA</em></span><br />
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td colspan="2">
        <p style="font-size: 11px; line-height: 160%; margin: 10px 0;">
        <strong>T:</strong> <a href="tel:0000000">00000000</a> |
        <strong>W:</strong> <a href="http://www.website.com.au">www.website.com.au</a><br /> Street Address | City | State Postcode</p>
        <p style="margin:6px 0;"><a href="https://www.facebook.com/"><img src="facebook.png" alt="Facebook" width="28" height="28"></a>&nbsp;<a href="https://www.instagram.com"><img src="instagram.png" alt="Instagram" width="28" height="28"></a></p>
        </td>
    </tr>
</table>

You may want to add a </td><td> between your two tables. I've also moved the 25px padding to the left of the copy, rather than the image. (I've assumed the img dimensions here). This looked ok on my EoA previews, if it doesn't help could you post a screenshot of your issue?


问:
Error after SDK update
I've just updated Android SDK and now my project gives this error.
How can I solve it?
Thanks in advance</p>

```<code>  Error:Could not find com.android.tools.build:gradle:3.0.0-alpha4.
  Searched in the following locations:
   file:/C:/Program Files/Android/Android Studio
  3/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-
  3.0.0-alpha4.pom
file:/C:/Program Files/Android/Android Studio
 3/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-
 3.0.0-alpha4.jar
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-
alpha4/gradle-3.0.0-alpha4.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-
alpha4/gradle-3.0.0-alpha4.jar
Required by:
project :
</code>```

答:
You should read migration guide

Change you build.gradle:

```<code>buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
    }
}
</code>```

Title: Error after SDK update

Body:
I've just updated Android SDK and now my project gives this error.
How can I solve it?
Thanks in advance

  Error:Could not find com.android.tools.build:gradle:3.0.0-alpha4.
  Searched in the following locations:
   file:/C:/Program Files/Android/Android Studio
  3/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-
  3.0.0-alpha4.pom
file:/C:/Program Files/Android/Android Studio
 3/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-
 3.0.0-alpha4.jar
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-
alpha4/gradle-3.0.0-alpha4.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-
alpha4/gradle-3.0.0-alpha4.jar
Required by:
project :

Body:
You should read migration guide

Change you build.gradle:

buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
    }
}


问:
target children and parent on click with document onclick not working
I've developed a script which acts as a modal trigger.

What it does is: whenever a user clicks on an element with the class "toggle-feature" it'll open activate a modal (from which the element has specified via data-toggle).

For example, if I click:

```<code><button class="toggle-feature" data-toggle="random-modal" data-class="custom-class">Test</button>
</code>```

It should add the class "custom-class" to this element:

```<code><div id="random-modal">Random Modal</div>
</code>```

So far, it works as semi-intended. However, if the element that is supposed to act as a "trigger" has children, and one of the children is clicked on, the modal won't activate.

I have tried so many approaches (which includes changing almost every line of code), along with e.stopPropagation() and the use of document.querySelectorAll(".toggle-feature, .toggle-feature *") - but none of them ever seemed to work.

This is my (simplified and prettied) JavaScript:

```<code>// globals
var regex;

// functionality
document.onclick = function(e){ // on document click
    var tf = document.getElementsByClassName("toggle-feature");
    e.stopPropagation(); // does not stop dom bubbling up

    for(var i = 0; i < tf.length; i++){ // iterate through each toggle button

        if(e.target == tf[i]){ // if the element clicked was one of the toggles

            if(tf[i].hasAttribute("data-toggle")){ // if the element has specified a modal to togal
                var modal = document.getElementById(tf[i].getAttribute("data-toggle")); // get the specified modal
                regex = new RegExp("(?:^|\\s)" + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active") + "(?!\\S)"); // some regex for targeting a specific class

                if(modal.className.match(regex)){ // if the modal has the "active" class

                    modal.className = modal.className.replace(regex, ""); // remove the class

                } else { // vice versa

                    modal.className = modal.className + " " + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active");

                }
            }
        }
    }
}
</code>```

Here is the JsFiddle for it (along with all the original JS, and an example): https://jsfiddle.net/n8t6u4s6/

答:
I managed to figure out a working solution, which utilizes the children and parentNode properties - whilst defining a separate function to handle activating the modal(s).

This is what I came up with (for anyone who might face a similar problem in the future).

```<code>function toggleModal(clicked, parent){
    var elem = (parent == undefined ? clicked : parent),
        regex = new RegExp("(?:^|\\s)" + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active") + "(?!\\S)"),
        modal;

    if(elem.hasAttribute("data-toggle")){
        modal = document.getElementById(elem.getAttribute("data-toggle"));
        modal.className = (modal.className.match(regex) ? modal.className.replace(regex, "") : modal.className + " " + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active"));
    } else if(elem.hasAttribute("data-open")){
        modal = document.getElementById(elem.getAttribute("data-open"));
        modal.className = (!modal.className.match(regex) ? modal.className + " " + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active") : modal.className);
    } else if(elem.hasAttribute("data-close")){
        modal = document.getElementById(elem.getAttribute("data-close"));
        modal.className = (modal.className.match(regex) ? modal.className.replace(regex, "") : modal.className);
    }
}

document.onclick = function(e){
    var tf = document.getElementsByClassName("toggle-feature");
    for(var i = 0; i < tf.length; i++){
        if(e.target == tf[i]){
            toggleModal(tf[i]);
        } else {
            for(var x = 0; x < tf[i].children.length; x++){
                if(e.target == tf[i].children[x]){
                    toggleModal(tf[i].children[x], tf[i]);
                }
            }
        }
    }
}
</code>```

Hopefully it helps someone out!

Fiddle: https://jsfiddle.net/n8t6u4s6/15/

Body:
I've developed a script which acts as a modal trigger.

What it does is: whenever a user clicks on an element with the class "toggle-feature" it'll open activate a modal (from which the element has specified via data-toggle).

For example, if I click:

<button class="toggle-feature" data-toggle="random-modal" data-class="custom-class">Test</button>

It should add the class "custom-class" to this element:

Random Modal

So far, it works as semi-intended. However, if the element that is supposed to act as a "trigger" has children, and one of the children is clicked on, the modal won't activate.

I have tried so many approaches (which includes changing almost every line of code), along with e.stopPropagation() and the use of document.querySelectorAll(".toggle-feature, .toggle-feature *") - but none of them ever seemed to work.

This is my (simplified and prettied) JavaScript:

// globals
var regex;

// functionality
document.onclick = function(e){ // on document click
    var tf = document.getElementsByClassName("toggle-feature");
    e.stopPropagation(); // does not stop dom bubbling up

    for(var i = 0; i < tf.length; i++){ // iterate through each toggle button

        if(e.target == tf[i]){ // if the element clicked was one of the toggles

            if(tf[i].hasAttribute("data-toggle")){ // if the element has specified a modal to togal
                var modal = document.getElementById(tf[i].getAttribute("data-toggle")); // get the specified modal
                regex = new RegExp("(?:^|\\s)" + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active") + "(?!\\S)"); // some regex for targeting a specific class

                if(modal.className.match(regex)){ // if the modal has the "active" class

                    modal.className = modal.className.replace(regex, ""); // remove the class

                } else { // vice versa

                    modal.className = modal.className + " " + (tf[i].hasAttribute("data-class") ? tf[i].getAttribute("data-class") : "active");

                }
            }
        }
    }
}

Here is the JsFiddle for it (along with all the original JS, and an example): https://jsfiddle.net/n8t6u4s6/

Body:
I managed to figure out a working solution, which utilizes the children and parentNode properties - whilst defining a separate function to handle activating the modal(s).

This is what I came up with (for anyone who might face a similar problem in the future).

function toggleModal(clicked, parent){
    var elem = (parent == undefined ? clicked : parent),
        regex = new RegExp("(?:^|\\s)" + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active") + "(?!\\S)"),
        modal;

    if(elem.hasAttribute("data-toggle")){
        modal = document.getElementById(elem.getAttribute("data-toggle"));
        modal.className = (modal.className.match(regex) ? modal.className.replace(regex, "") : modal.className + " " + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active"));
    } else if(elem.hasAttribute("data-open")){
        modal = document.getElementById(elem.getAttribute("data-open"));
        modal.className = (!modal.className.match(regex) ? modal.className + " " + (elem.hasAttribute("data-class") ? elem.getAttribute("data-class") : "active") : modal.className);
    } else if(elem.hasAttribute("data-close")){
        modal = document.getElementById(elem.getAttribute("data-close"));
        modal.className = (modal.className.match(regex) ? modal.className.replace(regex, "") : modal.className);
    }
}

document.onclick = function(e){
    var tf = document.getElementsByClassName("toggle-feature");
    for(var i = 0; i < tf.length; i++){
        if(e.target == tf[i]){
            toggleModal(tf[i]);
        } else {
            for(var x = 0; x < tf[i].children.length; x++){
                if(e.target == tf[i].children[x]){
                    toggleModal(tf[i].children[x], tf[i]);
                }
            }
        }
    }
}

Hopefully it helps someone out!

Fiddle: https://jsfiddle.net/n8t6u4s6/15/