问:
Enforce max characters on Swing JTextArea with a few curve balls
I'm trying to add functionality to a Swing JLabel and JTextArea such that:

The user is only allowed to enter 500 characters into the textarea (max)

The label contains a string message telling the user how many characters they have left (after every key stroke or backspace)

When the components initialize the label reads "500 characters maximum!"

For the first 500 characters typed, for every keystroke (a - z, A - Z, 0 - 9, and punctuation) typed, the label reads "x characters remaining", where x is the number of chars they have left before they reach the max of 500

When the 500th character is typed, the label reads "0 characters remaining", and no further characters can be typed into the text area

If the user types the backspace button (KeyEvent.VK_BACK_SPACE), they "free" up a character, and the count increments. Thus if they had 400 characters remaining, and they type backspace, the label now reads "401 characters remaining"

If the user highlights a set of characters and performs a bulk command on them (such as a backspace, or replacing the highlighted text with a single character), the correct # of chars remaining will be calculated correctly and the label will be updated. So if they have 50 chars remaining, and they highlight 5 letters and hit backspace, they now have "55 characters remaining"

I have 90% of this functionality working, but have a few bugs, and have no clue as to how to implement the last item above (bulk commands on highlighted text). Here's what I have:

```<code>boolean ignoreInput = false;
int charMax = 500;
JLabel charCntLabel = getLabel();
JTextArea myTextArea = getTextArea();

myTextArea.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
        return;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // If we should be ignoring input then set make sure we
        // enforce max character count and remove the newly typed key.
        if(ignoreInput)
            myTextArea.setText(myTextArea.getText().substring(0,
                myTextArea.getText().length()));
    }

    @Override
    public void keyPressed(KeyEvent e) {
        String charsRemaining = " characters remaining";
        int newLen = 0;

        // The key has just been pressed so Swing hasn't updated
        // the text area with the new KeyEvent.
        int currLen = myTextArea.getText().length();

        // Adjust newLen depending on whether the user just pressed
        // the backspace key or not.
        if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            newLen = currLen - 1;
            ignoreInput = false;
        }
        else
            newLen = currLen + 1;

        if(newLen < 0)
            newLen = 0;

        if(newLen == 0)
            charCntLabel.setText(charMax + " characters maximum!");
        else if(newLen >= 0 && newLen < charMax)
            charCntLabel.setText((charMax - newLen) + charsRemaining);
        else if(newLen >= charMax) {
            ignoreInput = true;
            charCntLabel.setText("0 " + charsRemaining);
        }
    }
});
</code>```

The above code works pretty well, but has a few bugs:

It doesn't prevent the user from typing in > 500 characters. When the user types in the 500th character, the label reads "0 characters remaining." But you can continue to type in characters after that, and the label stays the same.

If you have > 500 characters in the textarea, and you start backspacing, you'll see each character being removed from the textarea (the underlying model), but the label stays the same. But, once you backspace enough to get to the 500th character, and you backspace, the label will start changing properly, telling you that you have "1 characters remaining", "2 characters remaining", etc. So...

This code seems to work but just stops working > 500 characters. Once you get back inside that 500 char max, it begins working again.

The questions

Is there a simpler way to implement this desired functionality (and for a Swing JTextArea)? I feel like I'm reinventing the wheel here and that there might be a "cleaner" way of enforcing character maximums and updating their respective labels.

If not, can anybody spot my > 500 char bug? I've been looking at it all morning and am pulling my hair out.

Most importantly, how do I implement my requirement to handle bulk commands to highlighted text? How do I hand text selections inside the textarea, listen for changes to the highlighted text (e.g., deleting multiple highlighted characters with the backspace button, etc.), and correctly calculate the new value for chars remaining?

Thanks in advance.

答:
To add on to what Ray S. Kan said:

There is an easier way to limit the characters for a JTextArea without having to use a DocumentFilter as shown by Ray S. Kan, but the issue with his answer is that it does not prevent someone from pasting in a long text. The following will prevent a user from pasting in stuff to bypass the limit:

```<code>@Override
public void keyTyped(KeyEvent e) {
    int max = 25;
    if(text.getText().length() > max+1) {
        e.consume();
        String shortened = text.getText().substring(0, max);
        text.setText(shortened);
    }else if(text.getText().length() > max) {
        e.consume();
    }
}
</code>```

This will stop a key from being pressed if the length is not pass max, but if it passes max, it will simply replace the string in the text area with a shorter string. The text variable is the JTextArea swing object.

Body:
I'm trying to add functionality to a Swing JLabel and JTextArea such that:

The user is only allowed to enter 500 characters into the textarea (max)

The label contains a string message telling the user how many characters they have left (after every key stroke or backspace)

When the components initialize the label reads "500 characters maximum!"

For the first 500 characters typed, for every keystroke (a - z, A - Z, 0 - 9, and punctuation) typed, the label reads "x characters remaining", where x is the number of chars they have left before they reach the max of 500

When the 500th character is typed, the label reads "0 characters remaining", and no further characters can be typed into the text area

If the user types the backspace button (KeyEvent.VK_BACK_SPACE), they "free" up a character, and the count increments. Thus if they had 400 characters remaining, and they type backspace, the label now reads "401 characters remaining"

If the user highlights a set of characters and performs a bulk command on them (such as a backspace, or replacing the highlighted text with a single character), the correct # of chars remaining will be calculated correctly and the label will be updated. So if they have 50 chars remaining, and they highlight 5 letters and hit backspace, they now have "55 characters remaining"

I have 90% of this functionality working, but have a few bugs, and have no clue as to how to implement the last item above (bulk commands on highlighted text). Here's what I have:

boolean ignoreInput = false;
int charMax = 500;
JLabel charCntLabel = getLabel();
JTextArea myTextArea = getTextArea();

myTextArea.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
        return;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // If we should be ignoring input then set make sure we
        // enforce max character count and remove the newly typed key.
        if(ignoreInput)
            myTextArea.setText(myTextArea.getText().substring(0,
                myTextArea.getText().length()));
    }

    @Override
    public void keyPressed(KeyEvent e) {
        String charsRemaining = " characters remaining";
        int newLen = 0;

        // The key has just been pressed so Swing hasn't updated
        // the text area with the new KeyEvent.
        int currLen = myTextArea.getText().length();

        // Adjust newLen depending on whether the user just pressed
        // the backspace key or not.
        if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            newLen = currLen - 1;
            ignoreInput = false;
        }
        else
            newLen = currLen + 1;

        if(newLen < 0)
            newLen = 0;

        if(newLen == 0)
            charCntLabel.setText(charMax + " characters maximum!");
        else if(newLen >= 0 && newLen < charMax)
            charCntLabel.setText((charMax - newLen) + charsRemaining);
        else if(newLen >= charMax) {
            ignoreInput = true;
            charCntLabel.setText("0 " + charsRemaining);
        }
    }
});

The above code works pretty well, but has a few bugs:

It doesn't prevent the user from typing in > 500 characters. When the user types in the 500th character, the label reads "0 characters remaining." But you can continue to type in characters after that, and the label stays the same.

If you have > 500 characters in the textarea, and you start backspacing, you'll see each character being removed from the textarea (the underlying model), but the label stays the same. But, once you backspace enough to get to the 500th character, and you backspace, the label will start changing properly, telling you that you have "1 characters remaining", "2 characters remaining", etc. So...

This code seems to work but just stops working > 500 characters. Once you get back inside that 500 char max, it begins working again.

The questions

Is there a simpler way to implement this desired functionality (and for a Swing JTextArea)? I feel like I'm reinventing the wheel here and that there might be a "cleaner" way of enforcing character maximums and updating their respective labels.

If not, can anybody spot my > 500 char bug? I've been looking at it all morning and am pulling my hair out.

Most importantly, how do I implement my requirement to handle bulk commands to highlighted text? How do I hand text selections inside the textarea, listen for changes to the highlighted text (e.g., deleting multiple highlighted characters with the backspace button, etc.), and correctly calculate the new value for chars remaining?

Thanks in advance.

Body:
To add on to what Ray S. Kan said:

There is an easier way to limit the characters for a JTextArea without having to use a DocumentFilter as shown by Ray S. Kan, but the issue with his answer is that it does not prevent someone from pasting in a long text. The following will prevent a user from pasting in stuff to bypass the limit:

@Override
public void keyTyped(KeyEvent e) {
    int max = 25;
    if(text.getText().length() > max+1) {
        e.consume();
        String shortened = text.getText().substring(0, max);
        text.setText(shortened);
    }else if(text.getText().length() > max) {
        e.consume();
    }
}

This will stop a key from being pressed if the length is not pass max, but if it passes max, it will simply replace the string in the text area with a shorter string. The text variable is the JTextArea swing object.


来源: stackexchange

问:
MySQL workbench error 1064 when adding trigger
I am new to SQL and more specifically using MySQL Workbench.

I have created a database with two tables Grades and GPAList.

I want to take the average value of every entry in Grades (grouped by student id [sid is the name of the column]) once I have those averages, store them in the GPAList table with their corresponding students. This is intended to trigger every time a new entry is added to Grades.

This is the trigger that I have created:

```<code>CREATE DEFINER = CURRENT_USER TRIGGER `ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW
BEGIN
SELECT sid, SUM ( CASE grade
                    when 'A' then 4.0
                    when 'B' then 3.5
                    when 'C' then 3.0
                    when 'D' then 2.5
                    when 'F' then 1.0
                    else 0
                end
                ) / COUNT(*) Grades
INTO GPAList
FROM Grades
GROUP BY sid;
END
</code>```

The error that I am encountering is:

```<code>Error 1064: You have an error in your SQL syntax; check the manual that
 corresponds to your MySQL server version for the right syntax to use near '' at
line 1 SQL Statement:  CREATE DEFINER = CURRENT_USER TRIGGER
`ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW
FOLLOWS `Grades_AFTER_UPDATE`
</code>```

When I write this code in the workbench, no syntax errors are shown. When I try to apply this trigger, my code is converted to:

```<code>DROP TRIGGER IF EXISTS `ProjectName`.`Grades_AFTER_UPDATE_1`;

    DELIMITER $$
    USE `ProjectName`$$
    CREATE DEFINER = CURRENT_USER TRIGGER `ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW FOLLOWS `Grades_AFTER_UPDATE`
    $$
    DELIMITER ;
</code>```

Only after clicking apply once more do I see the 1064 error listed above. Is there some easy fix that I am missing?

There is a Grades_AFTER_UPDATE that Grades_AFTER_UPDATE_1 is following, so that shouldn't be the problem.

答:
I'm not sure why you would want to store all averages after a single insert, but the correct insert logic is something like this:

```<code>INSERT INTO GPALIST(sid, grades)
    SELECT sid,
           AVG (CASE grade
                    when 'A' then 4.0
                    when 'B' then 3.5
                    when 'C' then 3.0
                    when 'D' then 2.5
                    when 'F' then 1.0
                    else 0
                 end) as Grades
   FROM Grades
   GROUP BY sid;
</code>```

I suspect the trigger would want to access new. somewhere along the way.

ContentLicense: CC BY-SA 3.0

Body:
I am new to SQL and more specifically using MySQL Workbench.

I have created a database with two tables Grades and GPAList.

I want to take the average value of every entry in Grades (grouped by student id [sid is the name of the column]) once I have those averages, store them in the GPAList table with their corresponding students. This is intended to trigger every time a new entry is added to Grades.

This is the trigger that I have created:

CREATE DEFINER = CURRENT_USER TRIGGER `ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW
BEGIN
SELECT sid, SUM ( CASE grade
                    when 'A' then 4.0
                    when 'B' then 3.5
                    when 'C' then 3.0
                    when 'D' then 2.5
                    when 'F' then 1.0
                    else 0
                end
                ) / COUNT(*) Grades
INTO GPAList
FROM Grades
GROUP BY sid;
END

The error that I am encountering is:

Error 1064: You have an error in your SQL syntax; check the manual that
 corresponds to your MySQL server version for the right syntax to use near '' at
line 1 SQL Statement:  CREATE DEFINER = CURRENT_USER TRIGGER
`ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW
FOLLOWS `Grades_AFTER_UPDATE`

When I write this code in the workbench, no syntax errors are shown. When I try to apply this trigger, my code is converted to:

DROP TRIGGER IF EXISTS `ProjectName`.`Grades_AFTER_UPDATE_1`;

    DELIMITER $$
    USE `ProjectName`$$
    CREATE DEFINER = CURRENT_USER TRIGGER `ProjectName`.`Grades_AFTER_UPDATE_1` AFTER UPDATE ON `Grades` FOR EACH ROW FOLLOWS `Grades_AFTER_UPDATE`
    $$
    DELIMITER ;

Only after clicking apply once more do I see the 1064 error listed above. Is there some easy fix that I am missing?

There is a Grades_AFTER_UPDATE that Grades_AFTER_UPDATE_1 is following, so that shouldn't be the problem.

Body:
I'm not sure why you would want to store all averages after a single insert, but the correct insert logic is something like this:

INSERT INTO GPALIST(sid, grades)
    SELECT sid,
           AVG (CASE grade
                    when 'A' then 4.0
                    when 'B' then 3.5
                    when 'C' then 3.0
                    when 'D' then 2.5
                    when 'F' then 1.0
                    else 0
                 end) as Grades
   FROM Grades
   GROUP BY sid;

I suspect the trigger would want to access new. somewhere along the way.


问:
htaccess redirect issue
The redirect only works on mac..?

```<code>AddHandler php5-script .php

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</code>```

Test at tipfortip.com

答: It is not clear from your question what problem you are trying to solve. When I click on your test link, I get redirected to https://www.tipfortip.com and I am not on a mac. (In fact, the OS of the client machine accessing the site is irrelevant.) Are you saying that this rewrite works on a non-Mac server, but not on a mac server? Also, you do not need to repeat the RewriteEngine On--you only need that once.</p>

ContentLicense: CC BY-SA 2.5

Title: htaccess redirect issue

Body:
The redirect only works on mac..?

AddHandler php5-script .php

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Test at tipfortip.com


问:
DB2 LUW 10.5 - How to force DB2 Stored procedures to use latest stats for most optimized plan
We see an issue occasionally. Stored procedure running a SQL runs very slow.  Same SQL when run from command line runs very fast.  It seems stored procedure uses a different path.  The workaround for us is to drop and recreate the procedure, after which it picks up the right plan.

Is there a way to execute a stored procedure with an instruction to regenerate execution plan at run time, so as to get the best plan every time.

答:
You probably don't want to recompile plans every time you call your procedure, as you lose the performance benefit of having the procedure in the first place.

When you do need to recompile it, which shouldn't happen too frequently in a stable environment, you can use the REBIND_ROUTINE_PACKAGE system stored procedure:

```<code>call SYSPROC.REBIND_ROUTINE_PACKAGE('P', 'YOUR_SP', '')
</code>```

If you do decide that you want the plan to be recreated each time the procedure is called, you can set the REOPT ALWAYS bind option when you create the procedure, using the many ways described in the manual, for example by executing  call SYSPROC.SET_ROUTINE_OPTS('REOPT ALWAYS) before creating the procedure

Body:
You probably don't want to recompile plans every time you call your procedure, as you lose the performance benefit of having the procedure in the first place.

When you do need to recompile it, which shouldn't happen too frequently in a stable environment, you can use the REBIND_ROUTINE_PACKAGE system stored procedure:

call SYSPROC.REBIND_ROUTINE_PACKAGE('P', 'YOUR_SP', '')

If you do decide that you want the plan to be recreated each time the procedure is called, you can set the REOPT ALWAYS bind option when you create the procedure, using the many ways described in the manual, for example by executing  call SYSPROC.SET_ROUTINE_OPTS('REOPT ALWAYS) before creating the procedure


问:
How to get the last item of specific type from a list / collection?
Currently I'm working with Outlook and I'm iterating through a list of items.

Problem here:
I want to ask in the foreach-loop if the current item is the last one - but I can't accomplish this kind of problem.

This is my code:

```<code>lastAppointmentItem = myAppointmentItems.GetLast();
foreach (Outlook.AppointmentItem myItem in myAppointmentItems)
{
    // Types
    // myAppointmentItems = Outlook.Items
    // myItem = Outlook.AppointmentItem
    if(myItem.Equals(lastAppointmentItem)) { do_something(); }
}
</code>```

When I run the program I get a

```<code>System.Runtime.InteropServices.COMException:
// The last element of the list cannot be called
</code>```

So how can I solve my problem - do you guys know?

Thanks in advance!

Greetings.

答: Don't use "foreach" loop using a "for" loop from 1 to myAppointmentItems. Don't forget to sort it (myAppointmentItems.Sort(...)) to have a meaningful order.

Body:
Currently I'm working with Outlook and I'm iterating through a list of items.

Problem here:
I want to ask in the foreach-loop if the current item is the last one - but I can't accomplish this kind of problem.

This is my code:

lastAppointmentItem = myAppointmentItems.GetLast();
foreach (Outlook.AppointmentItem myItem in myAppointmentItems)
{
    // Types
    // myAppointmentItems = Outlook.Items
    // myItem = Outlook.AppointmentItem
    if(myItem.Equals(lastAppointmentItem)) { do_something(); }
}

When I run the program I get a

System.Runtime.InteropServices.COMException:
// The last element of the list cannot be called

So how can I solve my problem - do you guys know?

Thanks in advance!

Greetings.


问:
Row number custom coded in sql
I am using bigquery #standardsql to work on a table. The table will note a conversion (1) for user who purchase something in month 9 and month 10. And for user who did not purchase at month 10, will only have 0 in their row

So far , this is the query for custom_coded

```<code>(case when row_number()
  over (partition by customer_id order by purchase_date asc) =
                  count(*) over (partition by customer_id)
             then 1 else 0 END) AS custom_coded
</code>```

and this is the result so far

What i expect is that customer_id = 288 only have 0 in custom_coded since he did not purchase in next month, or month 10. And customer_id = 879 expected to have 1 in his latest purchase_date since he have a purchase record at month 10

This is the expected result

I previously asked in this thread (Decode maximum number in rows for sql), however the dataset didn't satisfy the idea for the analysis that i'm going to executed

答:
Below is for BigQuery Standard SQL

#standardSQL
SELECT customer_id, item_purchased, purchase_date,
  (CASE WHEN
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date ASC) =
        COUNT(*) OVER (PARTITION BY customer_id)
    AND SUM(DISTINCT (CASE FORMAT_DATE('%Y%m', purchase_date)
        WHEN '201709' THEN 1 WHEN '201710' THEN 2 ELSE 0 END))
        OVER(PARTITION BY customer_id) = 3
    THEN 1 ELSE 0
  END) AS custom_coded
FROM `project.dataset.table`
```

<p>You can test / play with above using dummy data from your question   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 288 customer_id, 'Rice' item_purchased, DATE '2017-09-02' purchase_date UNION ALL
  SELECT 288, 'Rice', DATE '2017-09-02' UNION ALL
  SELECT 288, 'Rice', DATE '2017-09-06' UNION ALL
  SELECT 879, 'Plate', DATE '2017-09-01' UNION ALL
  SELECT 879, 'Plate', DATE '2017-09-25' UNION ALL
  SELECT 879, 'Plate', DATE '2017-10-25' UNION ALL
  SELECT 879, 'Plate', DATE '2017-10-27'
)
SELECT customer_id, item_purchased, purchase_date,
  (CASE WHEN
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date ASC) =
        COUNT(*) OVER (PARTITION BY customer_id)
    AND SUM(DISTINCT (CASE FORMAT_DATE('%Y%m', purchase_date)
        WHEN '201709' THEN 1 WHEN '201710' THEN 2 ELSE 0 END))
        OVER(PARTITION BY customer_id) = 3
    THEN 1 ELSE 0
  END) AS custom_coded
FROM `project.dataset.table`
ORDER BY customer_id, purchase_date
</code>```

result is

customer_id item_purchased  purchase_date   custom_coded
288         Rice            2017-09-02      0
288         Rice            2017-09-02      0
288         Rice            2017-09-06      0
879         Plate           2017-09-01      0
879         Plate           2017-09-25      0
879         Plate           2017-10-25      0
879         Plate           2017-10-27      1
```

Title: Row number custom coded in sql

Body:
I am using bigquery #standardsql to work on a table. The table will note a conversion (1) for user who purchase something in month 9 and month 10. And for user who did not purchase at month 10, will only have 0 in their row

So far , this is the query for custom_coded

(case when row_number()
  over (partition by customer_id order by purchase_date asc) =
                  count(*) over (partition by customer_id)
             then 1 else 0 END) AS custom_coded

and this is the result so far

What i expect is that customer_id = 288 only have 0 in custom_coded since he did not purchase in next month, or month 10. And customer_id = 879 expected to have 1 in his latest purchase_date since he have a purchase record at month 10

This is the expected result

I previously asked in this thread (Decode maximum number in rows for sql), however the dataset didn't satisfy the idea for the analysis that i'm going to executed

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT customer_id, item_purchased, purchase_date,
  (CASE WHEN
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date ASC) =
        COUNT(*) OVER (PARTITION BY customer_id)
    AND SUM(DISTINCT (CASE FORMAT_DATE('%Y%m', purchase_date)
        WHEN '201709' THEN 1 WHEN '201710' THEN 2 ELSE 0 END))
        OVER(PARTITION BY customer_id) = 3
    THEN 1 ELSE 0
  END) AS custom_coded
FROM `project.dataset.table`

You can test / play with above using dummy data from your question

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 288 customer_id, 'Rice' item_purchased, DATE '2017-09-02' purchase_date UNION ALL
  SELECT 288, 'Rice', DATE '2017-09-02' UNION ALL
  SELECT 288, 'Rice', DATE '2017-09-06' UNION ALL
  SELECT 879, 'Plate', DATE '2017-09-01' UNION ALL
  SELECT 879, 'Plate', DATE '2017-09-25' UNION ALL
  SELECT 879, 'Plate', DATE '2017-10-25' UNION ALL
  SELECT 879, 'Plate', DATE '2017-10-27'
)
SELECT customer_id, item_purchased, purchase_date,
  (CASE WHEN
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date ASC) =
        COUNT(*) OVER (PARTITION BY customer_id)
    AND SUM(DISTINCT (CASE FORMAT_DATE('%Y%m', purchase_date)
        WHEN '201709' THEN 1 WHEN '201710' THEN 2 ELSE 0 END))
        OVER(PARTITION BY customer_id) = 3
    THEN 1 ELSE 0
  END) AS custom_coded
FROM `project.dataset.table`
ORDER BY customer_id, purchase_date

result is

customer_id item_purchased  purchase_date   custom_coded
288         Rice            2017-09-02      0
288         Rice            2017-09-02      0
288         Rice            2017-09-06      0
879         Plate           2017-09-01      0
879         Plate           2017-09-25      0
879         Plate           2017-10-25      0
879         Plate           2017-10-27      1


问:
Keep timer code working after form is closed
i'm currently making a program with expire date and i want my timer to work even when program is closed, this is my code:

```<code>    private int counter = 30;
    private void Form2_Load(object sender, EventArgs e)
    {
        timer1.Interval = 1000; // 1 day
        timer1.Tick += timer1_Tick;
        timer1.Start();
    }

    private void timer1_Tick_1(object sender, EventArgs e)
    {

            counter--;
            if (counter == 0)
                timer1.Stop();
            label3.Text = counter.ToString();

    }

   private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {

    }
</code>```

i will be happy to know how to do it if its possible to do it

答:
If the timer shall keep on counting, even if your program is shut down, you can't use a timer. Use the DateTime class instead.

Save the value of DateTime.Now to disk (e.g. with an application setting), then, in order to check for expiry, load that value again, and compare it to the current time:

Assuming startOfPeriod is the start of your expiry period:

```<code>if( startOfPeriod.AddDays( 30 ) < DateTime.Now )
{
// Time has expired
}
</code>```

Note: Be aware, that in this approach, your software can expire in the midth of the day. If you don't want that to happen, replace the above if expression with:

```<code>if( startOfPeriod.Date.AddDays( 30 ) < DateTime.Now.Date )
</code>```

Body:
i'm currently making a program with expire date and i want my timer to work even when program is closed, this is my code:

    private int counter = 30;
    private void Form2_Load(object sender, EventArgs e)
    {
        timer1.Interval = 1000; // 1 day
        timer1.Tick += timer1_Tick;
        timer1.Start();
    }

    private void timer1_Tick_1(object sender, EventArgs e)
    {

            counter--;
            if (counter == 0)
                timer1.Stop();
            label3.Text = counter.ToString();

    }

   private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {

    }

i will be happy to know how to do it if its possible to do it

Body:
If the timer shall keep on counting, even if your program is shut down, you can't use a timer. Use the DateTime class instead.

Save the value of DateTime.Now to disk (e.g. with an application setting), then, in order to check for expiry, load that value again, and compare it to the current time:

Assuming startOfPeriod is the start of your expiry period:

if( startOfPeriod.AddDays( 30 ) < DateTime.Now )
{
// Time has expired
}

Note: Be aware, that in this approach, your software can expire in the midth of the day. If you don't want that to happen, replace the above if expression with:

if( startOfPeriod.Date.AddDays( 30 ) < DateTime.Now.Date )


问:
how to change the result to 0 when the result is NULL in sql statement
I have a select statement, sth like..

```<code>select col1, col2, col3 from tbl1 where (conditions)
</code>```

If there is no row,

All I see is..

```<code>NULL,NULL,NULL
</code>```

What I want to get is

```<code>0,0,0
</code>```

I know there is sth like..

```<code>select when (condition) then RESULT else 0 end as 'Col1',..... from tbl1
</code>```

But if i Do that, I have to check condition everyline..

Any better idea??

答:
For this type of queries u can use nvl function of sql. Syntax given below..                                        </p>

```<code>Nvl( null value colum,0)
</code>```

<p>example-- like if one employe dont get the comisition then query wl be..                            </p>

```<code>Select  nvl( cmsn_pct,0) from employee;
</code>```

Body:
I have a select statement, sth like..

select col1, col2, col3 from tbl1 where (conditions)

If there is no row,

All I see is..

NULL,NULL,NULL

What I want to get is

0,0,0

I know there is sth like..

select when (condition) then RESULT else 0 end as 'Col1',..... from tbl1

But if i Do that, I have to check condition everyline..

Any better idea??

Body:
For this type of queries u can use nvl function of sql. Syntax given below..

Nvl( null value colum,0)

example-- like if one employe dont get the comisition then query wl be..

Select  nvl( cmsn_pct,0) from employee;


问:
How to determine when NSURLSessionTask's request begins?
I use NSURLSessionTasks and I'm trying to monitor how long some of my HTTP Requests take, what delegate method (or something else) can I monitor for when the NSURLSessionTask actually makes the initial request?  If this were a NSURLConnection inside an NSOperation I'd just start a timer when I start the request but I don't have control over when tasks start.

答:
I know this is an old question but for those searching the delegate method
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
on URLSessionTaskDelegate should be able to provide plenty of info about the request including how long it took.</p>


问:
R: find largest interval in dates with condition
I have a data frame with date and price. For some dates, price is NA. I'm trying to find the largest interval in dates between "last" (in a continuous sequence) NA price and last non-NA price. I'm completely lost - I suspect difftime needs to be used but I cannot come up with a condition for this.

E.g.:

```<code> DF = structure(list(rollup_date = c("2017-05-01 00:00:00", "2017-05-02 00:00:00",
"2017-05-03 00:00:00", "2017-05-04 00:00:00", "2017-05-05 00:00:00",
"2017-05-06 00:00:00", "2017-05-07 00:00:00", "2017-05-08 00:00:00",
"2017-05-09 00:00:00", "2017-05-10 00:00:00", "2017-05-11 00:00:00",
"2017-05-12 00:00:00", "2017-05-13 00:00:00", "2017-05-14 00:00:00",
"2017-05-15 00:00:00"), RegularPrice = c(6.47, 6.47, 6.47, 6.47,
NA, NA, NA, NA, NA, NA, NA, 6.47, NA, 6.47, 6.47)), .Names = c("rollup_date",
"RegularPrice"), row.names = 145624:145638, class = "data.frame")
</code>```

So, outputs here are 7 days (5/11 - 5/04) and 1 day (5/13 - 5/12). All solutions can be stored and then I just pick largest.

答:
```<code>DF$rollup_date = as.POSIXct(DF$rollup_date)
with(rle(is.na(DF$RegularPrice)),
     sapply(which(values == TRUE),
            function(i) difftime(time1 = DF$rollup_date[cumsum(lengths)[i]],
                                 time2 = DF$rollup_date[cumsum(lengths)[i-1]],
                                 units = "days")))
#[1] 7 1
</code>```

Body:
I have a data frame with date and price. For some dates, price is NA. I'm trying to find the largest interval in dates between "last" (in a continuous sequence) NA price and last non-NA price. I'm completely lost - I suspect difftime needs to be used but I cannot come up with a condition for this.

E.g.:

 DF = structure(list(rollup_date = c("2017-05-01 00:00:00", "2017-05-02 00:00:00",
"2017-05-03 00:00:00", "2017-05-04 00:00:00", "2017-05-05 00:00:00",
"2017-05-06 00:00:00", "2017-05-07 00:00:00", "2017-05-08 00:00:00",
"2017-05-09 00:00:00", "2017-05-10 00:00:00", "2017-05-11 00:00:00",
"2017-05-12 00:00:00", "2017-05-13 00:00:00", "2017-05-14 00:00:00",
"2017-05-15 00:00:00"), RegularPrice = c(6.47, 6.47, 6.47, 6.47,
NA, NA, NA, NA, NA, NA, NA, 6.47, NA, 6.47, 6.47)), .Names = c("rollup_date",
"RegularPrice"), row.names = 145624:145638, class = "data.frame")

So, outputs here are 7 days (5/11 - 5/04) and 1 day (5/13 - 5/12). All solutions can be stored and then I just pick largest.


问:
Exception handling: Differentiating between instances of the same error in Python
What is the recommended way of separately handling exceptions of the same type based on differences in what caused the exception?

Let's say one desire to handle the following two instances of AttributeError differently:

'str' object has no attribute 'append'

'float' object has no attribute 'append'

At the same time, we don't want to handle other attribute errors.

Are there any generalizable answers that work for all exception types? Can I interrogate the exception object for details using some method or function on the exception object?

```<code>Try:
    blah
Except AttributeError as exc:
    if exc.baz('foo') is bar:
         handle 'str' object has no attribute 'append'
    elif plugh(exc):
         handle 'float' object has no attribute 'append'
    else:
         raise exc
</code>```

I assume that the obvious answer is to refactor. My question specifically regards the cases where that would be inefficient or simply not possible (if there are any such cases at all).

答:
You can see what methods and attributes an object has by using dir.

In Python 3.6, from:

```<code>a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    print(dir(e))
</code>```

You get:

```<code>['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
</code>```

That narrows down the things we can test since we don't want a dunder, leaving only args and with_traceback. It seems then that the best you could get is to use args which returns the string in a tuple:

```<code>a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    if 'str' in e.args[0]:
        print('Need to handle string')
    elif 'float' in e.args[0]:
        print('Need to handle float')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is the recommended way of separately handling exceptions of the same type based on differences in what caused the exception?

Let's say one desire to handle the following two instances of AttributeError differently:

'str' object has no attribute 'append'

'float' object has no attribute 'append'

At the same time, we don't want to handle other attribute errors.

Are there any generalizable answers that work for all exception types? Can I interrogate the exception object for details using some method or function on the exception object?

Try:
    blah
Except AttributeError as exc:
    if exc.baz('foo') is bar:
         handle 'str' object has no attribute 'append'
    elif plugh(exc):
         handle 'float' object has no attribute 'append'
    else:
         raise exc

I assume that the obvious answer is to refactor. My question specifically regards the cases where that would be inefficient or simply not possible (if there are any such cases at all).

Body:
You can see what methods and attributes an object has by using dir.

In Python 3.6, from:

a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    print(dir(e))

You get:

['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']

That narrows down the things we can test since we don't want a dunder, leaving only args and with_traceback. It seems then that the best you could get is to use args which returns the string in a tuple:

a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    if 'str' in e.args[0]:
        print('Need to handle string')
    elif 'float' in e.args[0]:
        print('Need to handle float')


问:
How to dock the Firefox Browser Console
How do I dock the Browser Console window in Firefox?

The Browser Console currently opens in a separate window. I'd prefer for it to be docked to the bottom of the main window.

There's a similar question for Firebug.

答: The best I could do was manually to dock Browser Console window and Firefox window in my desktop environment (Gnome on Fedora) so that they are both visible when debugging.</p>

Title: How to dock the Firefox Browser Console


问:
Are there any GUI/WYSIWYG CMS editor based on Jekyll?
I find Jekyll to be very easy and useful to maintain static html sites and blogs, especially along with GitHub pages. Wanted to know if there are any Static site generators or CMS which helps in maintaining Jekyll sites with live preview, inline editing, layout management, file management etc.</p>

答:
I'm searching for the same, as all Static site generators I found require Markdown knowledge which isn't suitable at all for my clients.
I found this great CMS (Kinda!) https://sitecake.com/

Still don't know how to manage collections with it, say listing of few products with lightbox details, but I believe it is possible.


问:
Find how many minutes old a file is
First of all, I know I am not supposed to as "code sample" here. Sadly, I am not a programmer and I have a situation where I need to update a line in a report to present to the customer, but I do not know how to do it.

I have access to PHP file report.php. In the same server and folder as report.php there is a file called report.csv. When report.php is loaded in browser, I want to show one line which will say:

Report.cvs is X minutes old that is all.

If the report is 10 days old, then also I can show the age in minutes. I dont need any complicated X days, Y hours, Z mins etc.

I am worried i might break something in server if I try to add myself since I am not programmer. Is there anyone who can show me what I need to add to report.php to make this work?

答:
Looking through the documentation http://php.net/manual/en/function.fstat.php you might find that filectime ( string $filename ) may be useful.

Now if the file is consistently updated by users you may find that storing the creation/upload time in a Database like SQL/sqlite may be useful.

Title: Find how many minutes old a file is


问:
How to make a button show a table onclick
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Button1" onclick='myfunction();'>
<div id="displaytable" style="visibility: hidden">
  <table id="displaytable" style="display: none; width: 100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div></code>```

答:
To add to the list of answers , you can always use classList web API to solve this problem.

You just have to write a class , say

```<code>hide{
display:none;
}
</code>```

and toggle it with the toggle method of element.classList like

```<code>  tableelement.classList.toggle('hidden')
</code>```

a fiddle can be seen here

var click = document.getElementById('clickme');
click.addEventListener('click', myfunction);

function myfunction() {
  var tablewrap = document.getElementById('displaytable');
  tablewrap.classList.toggle('hidden')
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}

.placeholder {
  font-size: 12px;
}</code>```

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

  <input type="button" id="clickme" value="Show/Hide" />

```

Further reading here classList web API

Body:
I am trying to embed a table inside a button to no avail, such that when the button is clicked the table shows and when it is clicked again, the table disappears. Here is a copy of my code:

function myfunction(){
  document.getElementById("displaytable").style.display = "none";
}

<input type="button" value="Button1" onclick='myfunction();'>

      column1
      column2
      column3

      1
      2
      33

      4
      5
      6

Body:
To add to the list of answers , you can always use classList web API to solve this problem.

You just have to write a class , say

hide{
display:none;
}

and toggle it with the toggle method of element.classList like

  tableelement.classList.toggle('hidden')

a fiddle can be seen here

var click = document.getElementById('clickme');
click.addEventListener('click', myfunction);

function myfunction() {
  var tablewrap = document.getElementById('displaytable');
  tablewrap.classList.toggle('hidden')
};

.hidden {
  display: none;
}

.placeholder {
  font-size: 12px;
}

<div id="displaytable" class="placeholder">
  <table id="displaytable2" width="100%" cellpadding="1" cellspacing="0" border="3">
    <tr align="center">
      <td class="lbl">column1</td>
      <td class="lbl">column2</td>
      <td class="lbl">column3</td>
    </tr>
    <tr>
      <td align="center">1</td>
      <td align="center">2</td>
      <td align="center">33</td>
    </tr>
    <tr>
      <td align="center">4</td>
      <td align="center">5</td>
      <td align="center">6</td>
    </tr>
  </table>
</div>
<div>
  <input type="button" id="clickme" value="Show/Hide" />
</div>

Further reading here classList web API


问:
selenium throwing element not visible exception error when element is actually visible in the page
I am trying to login in the sandbox Paypal application using the given url but,It throws element not visible exception error when trying to find the email id and password field in the page using the below code.

Code to reproduce an issue

```<code>driver.get("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-7NA824468C3295748#/checkout/login");
Thread.sleep(20000);
driver.findElement(By.cssSelector("input[id='email']")).sendKeys("shariftest@gmail.com");
driver.findElement(By.cssSelector("input[id='password']")).sendKeys("test@1234");
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(6000);
</code>```

Its very strange that these element locators are absolutely correct and its visible in the page, but still throw an error when trying to find the element using selenium.

Please try the above code to reproduce the issue.

答:
I looked at the source html, both input fields have display: none as style. That's why you can't sendKeys to them.

```<code><input id="email" name="login_email" type="email" value="" autocomplete="off" placeholder="Email" style="display:none">
</code>```

You can use JavaScript to set the value, example for the email field:

```<code>driver.executeScript("arguments[0].value = 'you@yourprovider.nl'", driver.findElement(By.id("email")));
</code>```

Body:
I am trying to login in the sandbox Paypal application using the given url but,It throws element not visible exception error when trying to find the email id and password field in the page using the below code.

Code to reproduce an issue

driver.get("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-7NA824468C3295748#/checkout/login");
Thread.sleep(20000);
driver.findElement(By.cssSelector("input[id='email']")).sendKeys("shariftest@gmail.com");
driver.findElement(By.cssSelector("input[id='password']")).sendKeys("test@1234");
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(6000);

Its very strange that these element locators are absolutely correct and its visible in the page, but still throw an error when trying to find the element using selenium.

Please try the above code to reproduce the issue.

Body:
I looked at the source html, both input fields have display: none as style. That's why you can't sendKeys to them.

<input id="email" name="login_email" type="email" value="" autocomplete="off" placeholder="Email" style="display:none">

You can use JavaScript to set the value, example for the email field:

driver.executeScript("arguments[0].value = 'you@yourprovider.nl'", driver.findElement(By.id("email")));


问:
VS2010 C++ variadic template example
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

```<code>template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};
</code>```

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!

答:
Variadic templates are a patch upon a kludge upon a hack -- you're not going to enjoy this. The way to do this (off the top of my head) is to use template specialization together with inheritance. Something along these lines:

```<code>template<typename Classname, typename... Args>
class CFunctorStartExT;

template<typename Classname, typename Arg0, typename... Args>
class CFunctorStartExT : private CFunctorStartExT<Classname, Args...> {
protected:
  Arg0 m_arg;
};

template<typename Classname>
class CFunctorStartExT {
protected:
  Classname &m_Functor;
};
</code>```

I've never done this before, and haven't tested it, but this is the general idea. You could have a look at a std::tuple implementation for something that actually works.

Title: VS2010 C++ variadic template example

Body:
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!

Body:
Variadic templates are a patch upon a kludge upon a hack -- you're not going to enjoy this. The way to do this (off the top of my head) is to use template specialization together with inheritance. Something along these lines:

template<typename Classname, typename... Args>
class CFunctorStartExT;

template<typename Classname, typename Arg0, typename... Args>
class CFunctorStartExT : private CFunctorStartExT<Classname, Args...> {
protected:
  Arg0 m_arg;
};

template<typename Classname>
class CFunctorStartExT {
protected:
  Classname &m_Functor;
};

I've never done this before, and haven't tested it, but this is the general idea. You could have a look at a std::tuple implementation for something that actually works.


问:
gRPC: How to configure SSL in client?
Its new topic for me. I'm able to connect as plaintext.

```<code>public ManagedChannel getChannel(String serviceName){
    TSServiceClientManager scm = TSServiceManagementFactory.getInstance().getServiceClientManager();
    TSServiceConnectionInfo connInfo = scm.getServiceConnectionInfo(serviceName);
    if(channel == null){
        channel = ManagedChannelBuilder.forAddress(connInfo.getHost(), connInfo.getPort())
                .usePlaintext(true) //need help here for SSL code
                .build();
    }

    return channel;
}
</code>```

I was told to enable client-side SSL. I know how to generate, keystore, truststore, pem, CA etc.
I need help in :

How to enable SSL instead of .usePlaintext(true) as shown in above code?

(Kindly rewrite the code considering the cert file, keystore, truststore and .pem file exist)

And

I want to know is there anything to do with server to make SSL connection work?

答:
Since grpc-java 1.37.0 it is possible for most users to configure TLS without using transport-specific APIs. This leverages the ChannelCredentials concept introduced in 1.34.0.

```<code>ChannelCredentials creds = TlsChannelCredentials.newBuilder()
    // if server's cert doesn't chain to a standard root
    .trustManager(caFile)
    .keyManager(clientCertFile, keyFile) // client cert
    .build();
channel = Grpc.newChannelBuilderForAddress(serverHost, serverPort, creds)
    .build();
</code>```

TlsServerCredentials and Grpc.newServerBuilderForPort() would be used on server-side.

Advanced use cases may need to use transport-specific APIs like GrpcSslContexts and NettyChannelBuilder.sslContext().

Original answer: You need to use a transport-specific API. You're likely using Netty today. For Netty, you need to configure Netty's SslContext and pass it to gRPC. Your usage may look something like this:

```<code>SslContext sslcontext = GrpcSslContexts.forClient()
    // if server's cert doesn't chain to a standard root
    .trustManager(caFile)
    .keyManager(clientCertFile, keyFile) // client cert
    .build();
channel = NettyChannelBuilder.forAddress(serverHost, serverPort)
    .sslContext(sslContext)
    .build();
</code>```

If you need server-side configuration, it would use the similar NettyServerBuilder.sslContext(). But the context itself would be different.

Title: gRPC: How to configure SSL in client?

Body:
Its new topic for me. I'm able to connect as plaintext.

public ManagedChannel getChannel(String serviceName){
    TSServiceClientManager scm = TSServiceManagementFactory.getInstance().getServiceClientManager();
    TSServiceConnectionInfo connInfo = scm.getServiceConnectionInfo(serviceName);
    if(channel == null){
        channel = ManagedChannelBuilder.forAddress(connInfo.getHost(), connInfo.getPort())
                .usePlaintext(true) //need help here for SSL code
                .build();
    }

    return channel;
}

I was told to enable client-side SSL. I know how to generate, keystore, truststore, pem, CA etc.
I need help in :

How to enable SSL instead of .usePlaintext(true) as shown in above code?

(Kindly rewrite the code considering the cert file, keystore, truststore and .pem file exist)

And

I want to know is there anything to do with server to make SSL connection work?

Body:
Since grpc-java 1.37.0 it is possible for most users to configure TLS without using transport-specific APIs. This leverages the ChannelCredentials concept introduced in 1.34.0.

ChannelCredentials creds = TlsChannelCredentials.newBuilder()
    // if server's cert doesn't chain to a standard root
    .trustManager(caFile)
    .keyManager(clientCertFile, keyFile) // client cert
    .build();
channel = Grpc.newChannelBuilderForAddress(serverHost, serverPort, creds)
    .build();

TlsServerCredentials and Grpc.newServerBuilderForPort() would be used on server-side.

Advanced use cases may need to use transport-specific APIs like GrpcSslContexts and NettyChannelBuilder.sslContext().

Original answer: You need to use a transport-specific API. You're likely using Netty today. For Netty, you need to configure Netty's SslContext and pass it to gRPC. Your usage may look something like this:

SslContext sslcontext = GrpcSslContexts.forClient()
    // if server's cert doesn't chain to a standard root
    .trustManager(caFile)
    .keyManager(clientCertFile, keyFile) // client cert
    .build();
channel = NettyChannelBuilder.forAddress(serverHost, serverPort)
    .sslContext(sslContext)
    .build();

If you need server-side configuration, it would use the similar NettyServerBuilder.sslContext(). But the context itself would be different.


问:
PostgreSQL - join tables using pattern matching
I have two tables and need to join them using two columns that are similar.

The first table is called articles has a column called 'slug' with slug lines for articles, ex: 'trump-fails-yet-again.'

The second table is called log and has a column called path with the url path for the articles, ex: '/articles/trump-fails-yet-again/'

Here is my search query:

```<code>"SELECT articles.title, count(*) as num FROM articles, log WHERE articles.slug LIKE CONCAT('%',log.path) GROUP BY articles.title;"
</code>```

This returns nothing but brackets, []

I have also tried:

```<code>"SELECT articles.title, count(*) as num FROM articles JOIN log ON articles.slug SIMILAR TO CONCAT('%',log.path) GROUP BY articles.title;"
</code>```

That returns a DataError: invalid regular expression: quantifier operand invalid

Any help is greatly appreciated!

答:
try this:</p>

```<code>` select articles.title, count(*) as views from articles
  join log on articles.slug ~~ ('%' || articles.slug || '%')
  group by articles.title;`
</code>```

Body:
I have two tables and need to join them using two columns that are similar.

The first table is called articles has a column called 'slug' with slug lines for articles, ex: 'trump-fails-yet-again.'

The second table is called log and has a column called path with the url path for the articles, ex: '/articles/trump-fails-yet-again/'

Here is my search query:

"SELECT articles.title, count(*) as num FROM articles, log WHERE articles.slug LIKE CONCAT('%',log.path) GROUP BY articles.title;"

This returns nothing but brackets, []

I have also tried:

"SELECT articles.title, count(*) as num FROM articles JOIN log ON articles.slug SIMILAR TO CONCAT('%',log.path) GROUP BY articles.title;"

That returns a DataError: invalid regular expression: quantifier operand invalid

Any help is greatly appreciated!

Body:
try this:

` select articles.title, count(*) as views from articles
  join log on articles.slug ~~ ('%' || articles.slug || '%')
  group by articles.title;`


问:
How to embed a Facebook Analytics report?
Is it possible to embed a Facebook Analytics report on a website?

答: No, Facebook Analytics does not support this.</p>


问:
While trying to deploy application in Weblogic 12c. i got exception
while deploy application in weblogic12c. i got following exception. i'm newbie to weblogic12c. any suggestion??

weblogic.application.ModuleException: java.lang.NoSuchMethodException: org.eclipse.persistence.jaxb.JAXBContext.getBeanInfo(java.lang.Class)
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:73)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:24)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:48)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused By: java.lang.NoSuchMethodException: org.eclipse.persistence.jaxb.JAXBContext.getBeanInfo(java.lang.Class)
    at java.lang.Class.getMethod(Class.java:1786)
    at org.apache.cxf.common.util.ReflectionInvokationHandler.invoke(ReflectionInvokationHandler.java:52)
    at com.sun.proxy.$Proxy107.getBeanInfo(Unknown Source)
    at org.apache.cxf.common.jaxb.JAXBUtils.getBeanInfo(JAXBUtils.java:1155)
    at org.apache.cxf.jaxb.JAXBSchemaInitializer.getBeanInfo(JAXBSchemaInitializer.java:140)
    at org.apache.cxf.jaxb.JAXBDataBinding.checkForJAXBAnnotations(JAXBDataBinding.java:436)
    at org.apache.cxf.jaxb.JAXBDataBinding.justCheckForJAXBAnnotations(JAXBDataBinding.java:424)
    at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:349)
    at org.apache.cxf.service.factory.AbstractServiceFactoryBean.initializeDataBindings(AbstractServiceFactoryBean.java:86)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.buildServiceFromWSDL(ReflectionServiceFactoryBean.java:446)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.initializeServiceModel(ReflectionServiceFactoryBean.java:548)
    at org.apache.cxf.service.factory.ReflectionServiceFactoryBean.create(ReflectionServiceFactoryBean.java:265)
    at org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean.create(JaxWsServiceFactoryBean.java:205)
    at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpoint(AbstractWSDLBasedEndpointFactory.java:101)
    at org.apache.cxf.frontend.ServerFactoryBean.create(ServerFactoryBean.java:159)
    at org.apache.cxf.jaxws.JaxWsServerFactoryBean.create(JaxWsServerFactoryBean.java:211)
    at org.apache.cxf.jaxws.EndpointImpl.getServer(EndpointImpl.java:453)
    at org.apache.cxf.jaxws.EndpointImpl.doPublish(EndpointImpl.java:333)
    at org.apache.cxf.jaxws.EndpointImpl.publish(EndpointImpl.java:250)
    at org.apache.cxf.jaxws.EndpointImpl.publish(EndpointImpl.java:536)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1681)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:678)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
    at weblogic.servlet.internal.EventsManager.executeContextListener(EventsManager.java:243)
    at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:200)
    at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:185)
    at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1838)
    at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2876)
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1661)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:823)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:73)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:24)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.SingleModuleDeployment.activate(SingleModuleDeployment.java:48)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

答: I replaced all jars with Java 8 specific. now it's working fine. Thanks for your support guys. </p>


问:
'App not Installed' Error on Android
I have a program working in the Android Emulator. Every now and again I have been creating a signed .apk and exporting it to my HTC Desire to test. It has all been fine.

On my latest exported .apk I get the error message 'App not installed' when I try to install the .apk. It runs fine on the emulators.

As I have mainly been testing on the emulators and only every now and again exporting to a real phone I am not sure when this happened. What is the likely cause of it not installing on a physical phone but running fine in the emulators?

I have tried rebooting the phone & removing the existing .apk, does not fix the fault.

答:
In my case, it's because Android Studio 3.0 sets android:testOnly="true" on APKs that build from the release Build Variant.

https://commonsware.com/blog/2017/10/31/android-studio-3p0-flag-test-only.html

So run ./gradlew assembleRelease solve my issue

Title: 'App not Installed' Error on Android


问:
Produce balanced mini batch with Dataset API
I've a question about the new dataset API (tensorflow 1.4rc1).
I've a unbalanced dataset wrt to labels 0 and 1. My goal is to create balanced mini batches during the preprocessing.

Assume I've two filtered datasets:

```<code>ds_pos = dataset.filter(lambda l, x, y, z: tf.reshape(tf.equal(l, 1), []))
ds_neg = dataset.filter(lambda l, x, y, z: tf.reshape(tf.equal(l, 0), [])).repeat()
</code>```

Is there a way to combine these two datasets such that the resulting dataset looks like ds = [0, 1, 0, 1, 0, 1]:

Something like this:

```<code>dataset = tf.data.Dataset.zip((ds_pos, ds_neg))
dataset = dataset.apply(...)
# dataset looks like [0, 1, 0, 1, 0, 1, ...]
dataset = dataset.batch(20)
</code>```

My current approach is:

```<code>def _concat(x, y):
   return tf.cond(tf.random_uniform(()) > 0.5, lambda: x, lambda: y)
dataset = tf.data.Dataset.zip((ds_pos, ds_neg))
dataset = dataset.map(_concat)
</code>```

But I've the feeling there is a more elegant way.

Thanks in advance!

答:
You are on the right track. The following example uses Dataset.flat_map() to turn each pair of a positive example and a negative example into two consecutive examples in the result:

```<code>dataset = tf.data.Dataset.zip((ds_pos, ds_neg))

# Each input element will be converted into a two-element `Dataset` using
# `Dataset.from_tensors()` and `Dataset.concatenate()`, then `Dataset.flat_map()`
# will flatten the resulting `Dataset`s into a single `Dataset`.
dataset = dataset.flat_map(
    lambda ex_pos, ex_neg: tf.data.Dataset.from_tensors(ex_pos).concatenate(
        tf.data.Dataset.from_tensors(ex_neg)))

dataset = dataset.batch(20)
</code>```

Body:
I've a question about the new dataset API (tensorflow 1.4rc1).
I've a unbalanced dataset wrt to labels 0 and 1. My goal is to create balanced mini batches during the preprocessing.

Assume I've two filtered datasets:

ds_pos = dataset.filter(lambda l, x, y, z: tf.reshape(tf.equal(l, 1), []))
ds_neg = dataset.filter(lambda l, x, y, z: tf.reshape(tf.equal(l, 0), [])).repeat()

Is there a way to combine these two datasets such that the resulting dataset looks like ds = [0, 1, 0, 1, 0, 1]:

Something like this:

dataset = tf.data.Dataset.zip((ds_pos, ds_neg))
dataset = dataset.apply(...)
# dataset looks like [0, 1, 0, 1, 0, 1, ...]
dataset = dataset.batch(20)

My current approach is:

def _concat(x, y):
   return tf.cond(tf.random_uniform(()) > 0.5, lambda: x, lambda: y)
dataset = tf.data.Dataset.zip((ds_pos, ds_neg))
dataset = dataset.map(_concat)

But I've the feeling there is a more elegant way.

Thanks in advance!

Body:
You are on the right track. The following example uses Dataset.flat_map() to turn each pair of a positive example and a negative example into two consecutive examples in the result:

dataset = tf.data.Dataset.zip((ds_pos, ds_neg))

# Each input element will be converted into a two-element `Dataset` using
# `Dataset.from_tensors()` and `Dataset.concatenate()`, then `Dataset.flat_map()`
# will flatten the resulting `Dataset`s into a single `Dataset`.
dataset = dataset.flat_map(
    lambda ex_pos, ex_neg: tf.data.Dataset.from_tensors(ex_pos).concatenate(
        tf.data.Dataset.from_tensors(ex_neg)))

dataset = dataset.batch(20)


问:
Java UTF-8 to ASCII conversion with supplements
we are accepting all sorts of national characters in UTF-8 string on the input, and we need to convert them to ASCII string on the output for some legacy use. (we don't accept Chinese and Japanese chars, only European languages)

We have a small utility to get rid of all the diacritics:

```<code>public static final String toBaseCharacters(final String sText) {
    if (sText == null || sText.length() == 0)
        return sText;

    final char[] chars = sText.toCharArray();
    final int iSize = chars.length;
    final StringBuilder sb = new StringBuilder(iSize);

    for (int i = 0; i < iSize; i++) {
        String sLetter = new String(new char[] { chars[i] });
        sLetter = Normalizer.normalize(sLetter, Normalizer.Form.NFC);

        try {
            byte[] bLetter = sLetter.getBytes("UTF-8");
            sb.append((char) bLetter[0]);
        } catch (UnsupportedEncodingException e) {
        }
    }
    return sb.toString();
}
</code>```

The question is how to replace all the german sharp s (ß, Đ, đ) and other characters that get through the above normalization method, with their supplements (in case of ß, supplement would probably be "ss" and in case od Đ supplement would be either "D" or "Dj").

Is there some simple way to do it, without million of .replaceAll() calls?

So for example: Đonardan = Djonardan, Blaß = Blass  and so on.

We can replace all "problematic" chars with empty space, but would like to avoid this to make the output as similar to the input as possible.

Thank you for your answers,

Bozo

答:
Here's my converter which uses lucene...</p>

```<code>private final KeywordTokenizer keywordTokenizer = new KeywordTokenizer(new StringReader(""));
private final ASCIIFoldingFilter asciiFoldingFilter = new ASCIIFoldingFilter(keywordTokenizer);
private final TermAttribute termAttribute = (TermAttribute) asciiFoldingFilter.getAttribute(TermAttribute.class);

public String process(String line)
{
    if (line != null)
    {
        try
        {
            keywordTokenizer.reset(new StringReader(line));
            if (asciiFoldingFilter.incrementToken())
            {
                return termAttribute.term();
            }
        }
        catch (IOException e)
        {
            logger.warn("Failed to parse: " + line, e);
        }
    }
    return null;
}
</code>```

Body:
we are accepting all sorts of national characters in UTF-8 string on the input, and we need to convert them to ASCII string on the output for some legacy use. (we don't accept Chinese and Japanese chars, only European languages)

We have a small utility to get rid of all the diacritics:

public static final String toBaseCharacters(final String sText) {
    if (sText == null || sText.length() == 0)
        return sText;

    final char[] chars = sText.toCharArray();
    final int iSize = chars.length;
    final StringBuilder sb = new StringBuilder(iSize);

    for (int i = 0; i < iSize; i++) {
        String sLetter = new String(new char[] { chars[i] });
        sLetter = Normalizer.normalize(sLetter, Normalizer.Form.NFC);

        try {
            byte[] bLetter = sLetter.getBytes("UTF-8");
            sb.append((char) bLetter[0]);
        } catch (UnsupportedEncodingException e) {
        }
    }
    return sb.toString();
}

The question is how to replace all the german sharp s (ß, Đ, đ) and other characters that get through the above normalization method, with their supplements (in case of ß, supplement would probably be "ss" and in case od Đ supplement would be either "D" or "Dj").

Is there some simple way to do it, without million of .replaceAll() calls?

So for example: Đonardan = Djonardan, Blaß = Blass  and so on.

We can replace all "problematic" chars with empty space, but would like to avoid this to make the output as similar to the input as possible.

Thank you for your answers,

Bozo

Body:
Here's my converter which uses lucene...

private final KeywordTokenizer keywordTokenizer = new KeywordTokenizer(new StringReader(""));
private final ASCIIFoldingFilter asciiFoldingFilter = new ASCIIFoldingFilter(keywordTokenizer);
private final TermAttribute termAttribute = (TermAttribute) asciiFoldingFilter.getAttribute(TermAttribute.class);

public String process(String line)
{
    if (line != null)
    {
        try
        {
            keywordTokenizer.reset(new StringReader(line));
            if (asciiFoldingFilter.incrementToken())
            {
                return termAttribute.term();
            }
        }
        catch (IOException e)
        {
            logger.warn("Failed to parse: " + line, e);
        }
    }
    return null;
}


问:
Reset the filter if match not found in select box
I am trying to create a filter which will show the results in the table based on the selection in the select box.

Also, by default the 'City' select box will be set user location which I'm grabbing and setting ng-init="my.city='${city}'". So, the default results would be filtered based on user location.

The only problem I've is, when the user location doesn't match any of the values in my 'City' select box, it should be reset. i.e. 'Select a city' option should be selected, and all the results would be shown without any filter being applied.

In my code, if I select any of the city and then try to select 'Select a city' the filter is not getting reset'.

How do I fix this?

Here's the complete code:

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter) {
 $scope.loc = {
  Sydney: 4,
  Toronto: 7,
  London: 3,
  Berlin: 7
 };
 $scope.country = ['Australia', 'India', 'Germany', 'China', 'Canada', 'United Kingdom'];
 $scope.fullData = [{
  name: 'ABC',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'DEF',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'ABC',
  countryName: 'United Kingdom',
  city: 'London'
 }, {
  name: 'ABC',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'DEF',
  countryName: 'Canada',
  city: 'Toronto'
 }, {
  name: 'DEF',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'BCD',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Canada',
  city: 'Toronto'
 }];
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div class="container">
  <div ng-app="myApp" ng-controller="myCtrl">
    <div class="row">
      <div class="col-md-3">
        <label>Search Keyword:</label>
        <input type="text" class="form-control" ng-model="my.$"/>
      </div>
      <div class="col-md-3">
        <label>Country:</label>
        <select class="form-control" ng-model="my.countryName" ng-options="countryName as countryName for countryName in country">
          <option value="" selected>Select a country</option>
        </select>
      </div>
      <div class="col-md-3">
        <label>City</label>
        <select class="form-control" ng-model="my.city" ng-init="my.city='${city}'" ng-options="key as key for (key, value) in loc">
          <option value="" selected>Select a city</option>
        </select>
      </div>
    </div>
    <hr />
    <div class="row">
      <table class="table table-bordered">
        <tr>
          <th>Name</th>
          <th>Country</th>
          <th>City</th>
        </tr>
        <tr ng-repeat="item in fullData | filter: my">
          <td>{{item.name}}</td>
          <td>{{item.countryName}}</td>
          <td>{{item.city}}</td>
        </tr>
      </table>
    </div>
  </div>
</div></code>```

答:
in this case filter aplied in empty object that was a property named city but your all property of object that filter applied on it should have an empty value in first .

you must initial your object  in your controller

```<code> $scope.my={$:'',countryName:'',city:''};
</code>```

and delete ng-init city property

try folowing

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.my={$:'',countryName:'',city:''};
 $scope.loc = {
  Sydney: 4,
  Toronto: 7,
  London: 3,
  Berlin: 7
 };
 $scope.country = ['Australia', 'India', 'Germany', 'China', 'Canada', 'United Kingdom'];
 $scope.fullData = [{
  name: 'ABC',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'DEF',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'ABC',
  countryName: 'United Kingdom',
  city: 'London'
 }, {
  name: 'ABC',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'DEF',
  countryName: 'Canada',
  city: 'Toronto'
 }, {
  name: 'DEF',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'BCD',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Canada',
  city: 'Toronto'
 }];
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div class="container">
  <div ng-app="myApp" ng-controller="myCtrl">
    <div class="row">
      <div class="col-md-3">
        <label>Search Keyword:</label>
        <input type="text" class="form-control" ng-model="my.$"/>
      </div>
      <div class="col-md-3">
        <label>Country:</label>
        <select class="form-control" ng-model="my.countryName" ng-options="countryName as countryName for countryName in country">
          <option value="" selected>Select a country</option>
        </select>
      </div>
      <div class="col-md-3">
        <label>City</label>
        <select class="form-control" ng-model="my.city"  ng-options="key as key for (key, value) in loc">
          <option value="" selected>Select a city</option>
        </select>
      </div>
    </div>
    <hr />
    <div class="row">
      <table class="table table-bordered">
        <tr>
          <th>Name</th>
          <th>Country</th>
          <th>City</th>
        </tr>
        <tr ng-repeat="item in fullData | filter: my">
          <td>{{item.name}}</td>
          <td>{{item.countryName}}</td>
          <td>{{item.city}}</td>
        </tr>
      </table>
    </div>
  </div>
</div></code>```

Body:
I am trying to create a filter which will show the results in the table based on the selection in the select box.

Also, by default the 'City' select box will be set user location which I'm grabbing and setting ng-init="my.city='${city}'". So, the default results would be filtered based on user location.

The only problem I've is, when the user location doesn't match any of the values in my 'City' select box, it should be reset. i.e. 'Select a city' option should be selected, and all the results would be shown without any filter being applied.

In my code, if I select any of the city and then try to select 'Select a city' the filter is not getting reset'.

How do I fix this?

Here's the complete code:

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter) {
 $scope.loc = {
  Sydney: 4,
  Toronto: 7,
  London: 3,
  Berlin: 7
 };
 $scope.country = ['Australia', 'India', 'Germany', 'China', 'Canada', 'United Kingdom'];
 $scope.fullData = [{
  name: 'ABC',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'DEF',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'ABC',
  countryName: 'United Kingdom',
  city: 'London'
 }, {
  name: 'ABC',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'DEF',
  countryName: 'Canada',
  city: 'Toronto'
 }, {
  name: 'DEF',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'BCD',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Canada',
  city: 'Toronto'
 }];
}]);

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Search Keyword:
        <input type="text" class="form-control" ng-model="my.$"/>

        Country:
        <select class="form-control" ng-model="my.countryName" ng-options="countryName as countryName for countryName in country">
          <option value="" selected>Select a country</option>
        </select>

        City
        <select class="form-control" ng-model="my.city" ng-init="my.city='${city}'" ng-options="key as key for (key, value) in loc">
          <option value="" selected>Select a city</option>
        </select>

          Name
          Country
          City

          {{item.name}}
          {{item.countryName}}
          {{item.city}}

Body:
in this case filter aplied in empty object that was a property named city but your all property of object that filter applied on it should have an empty value in first .

you must initial your object  in your controller

 $scope.my={$:'',countryName:'',city:''};

and delete ng-init city property

try folowing

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$filter', function($scope, $filter) {
$scope.my={$:'',countryName:'',city:''};
 $scope.loc = {
  Sydney: 4,
  Toronto: 7,
  London: 3,
  Berlin: 7
 };
 $scope.country = ['Australia', 'India', 'Germany', 'China', 'Canada', 'United Kingdom'];
 $scope.fullData = [{
  name: 'ABC',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'DEF',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'CDE',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'BCD',
  countryName: 'Australia',
  city: 'Sydney'
 }, {
  name: 'ABC',
  countryName: 'United Kingdom',
  city: 'London'
 }, {
  name: 'ABC',
  countryName: 'China',
  city: 'Shanghai'
 }, {
  name: 'DEF',
  countryName: 'Canada',
  city: 'Toronto'
 }, {
  name: 'DEF',
  countryName: 'India',
  city: 'Bangalore'
 }, {
  name: 'BCD',
  countryName: 'Germany',
  city: 'Berlin'
 }, {
  name: 'ABC',
  countryName: 'Canada',
  city: 'Toronto'
 }];
}]);

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div class="container">
  <div ng-app="myApp" ng-controller="myCtrl">
    <div class="row">
      <div class="col-md-3">
        <label>Search Keyword:</label>
        <input type="text" class="form-control" ng-model="my.$"/>
      </div>
      <div class="col-md-3">
        <label>Country:</label>
        <select class="form-control" ng-model="my.countryName" ng-options="countryName as countryName for countryName in country">
          <option value="" selected>Select a country</option>
        </select>
      </div>
      <div class="col-md-3">
        <label>City</label>
        <select class="form-control" ng-model="my.city"  ng-options="key as key for (key, value) in loc">
          <option value="" selected>Select a city</option>
        </select>
      </div>
    </div>
    <hr />
    <div class="row">
      <table class="table table-bordered">
        <tr>
          <th>Name</th>
          <th>Country</th>
          <th>City</th>
        </tr>
        <tr ng-repeat="item in fullData | filter: my">
          <td>{{item.name}}</td>
          <td>{{item.countryName}}</td>
          <td>{{item.city}}</td>
        </tr>
      </table>
    </div>
  </div>
</div>


问:
Vuejs splice duplicate
I am building a editor where you have a duplicate function to duplicate your elements. The duplicate function works the following

```<code>let newDataB = JSON.parse(JSON.stringify(state.data.content[headerId].content[columnId].content[blockId]));
//Generate a new id
newDataB.id = shortid.generate();

//Generate new id's if the block has childs
if(typeof newDataB.data.data !== 'undefined') {
  if(typeof newDataB.data.data[0] !== 'undefined') {
    newDataB.data.data.forEach((value, key) => {
      newDataB.data.data[key].id = shortid.generate();
    });
  }
}

//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId + 1,0,newDataB);
</code>```

This code is located in my store this updates the store and sends it back to my vue application

Now the following things happens

One

https://www.dropbox.com/s/4nrc9dx0kk2lx02/2017-12-04%2015.55.06.gif?dl=0

this line of code changed in the video version

```<code>//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId - 1,0,newDataB);
</code>```

as you can see blockId + 1 is in changed to blockId - 1

Two

https://www.dropbox.com/s/0ees7f7s9plxb3y/2017-12-04%2015.55.53.gif?dl=0

now the code is the following

```<code>//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId,0,newDataB);
</code>```

as you can see blockId + 1 is in changed to blockId

Three

https://www.dropbox.com/s/k316sw85ewkgfhc/2017-12-04%2015.56.47.gif?dl=0

What wired is in this example is that the problem is happening after 2 times duplication

the code is the following

```<code>//blockId is a var which holds the current index of the block in the array
</code>```

state.data.content[headerId].content[columnId].content.splice(blockId + 1,0,newDataB);

as you can see blockId + 1 is now blockId + 1

Some last notes

The problem is solved when I save my state and then refresh my page. I do not know why this is happening (I want it to work without refreshing the page). What I want to make is that the user can duplicate content but still is able to edit the duplicated content this is now not possible.

Thank you very much for reading this and I hope you can help me :)

How the resizer works

The resizer is a component which edit's its data with the tooltip component that looks the following

The image Element requests a tooltip (done with commit in vuex)

The tooltip shows on top of the image element and renders the resizer bar

On change the tooltip commits the new data to vuex so vuex can pass it back to vue for rendering the changes

Code of the on change resizer

```<code>            this.$store.commit(types.CHANGE_BLOCK, {
                headerId: this.headerid,
                columnId: this.columnid,
                blockId: this.blockid,
                blockChildId: 0,
                properties: {
                    height: (this.value < 10 ? this.value + 10 : this.value)
                }
            });
</code>```

Code of the function in vuex

```<code>                        //ADJUSTMENTS BLOCK
                        _.each(data[Object.keys(data)[4]], function(value, key) {
                            state.data[domain][headerId].content[columnId].content[blockId].data[Object.keys(data)[4]][key] = value;
                        });
</code>```

答:
When you generate newDataB, you give it a new id, but your size-committing code doesn't use that; it seems to use headerId, columnId, and blockId to figure out which block(s) get updated. Since those are cloned values, the original and the new will be updated.

Maybe that id is supposed to be blockId?

Title: Vuejs splice duplicate

Body:
I am building a editor where you have a duplicate function to duplicate your elements. The duplicate function works the following

let newDataB = JSON.parse(JSON.stringify(state.data.content[headerId].content[columnId].content[blockId]));
//Generate a new id
newDataB.id = shortid.generate();

//Generate new id's if the block has childs
if(typeof newDataB.data.data !== 'undefined') {
  if(typeof newDataB.data.data[0] !== 'undefined') {
    newDataB.data.data.forEach((value, key) => {
      newDataB.data.data[key].id = shortid.generate();
    });
  }
}

//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId + 1,0,newDataB);

This code is located in my store this updates the store and sends it back to my vue application

Now the following things happens

One

https://www.dropbox.com/s/4nrc9dx0kk2lx02/2017-12-04%2015.55.06.gif?dl=0

this line of code changed in the video version

//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId - 1,0,newDataB);

as you can see blockId + 1 is in changed to blockId - 1

Two

https://www.dropbox.com/s/0ees7f7s9plxb3y/2017-12-04%2015.55.53.gif?dl=0

now the code is the following

//blockId is a var which holds the current index of the block in the array
state.data.content[headerId].content[columnId].content.splice(blockId,0,newDataB);

as you can see blockId + 1 is in changed to blockId

Three

https://www.dropbox.com/s/k316sw85ewkgfhc/2017-12-04%2015.56.47.gif?dl=0

What wired is in this example is that the problem is happening after 2 times duplication

the code is the following

//blockId is a var which holds the current index of the block in the array

state.data.content[headerId].content[columnId].content.splice(blockId + 1,0,newDataB);

as you can see blockId + 1 is now blockId + 1

Some last notes

The problem is solved when I save my state and then refresh my page. I do not know why this is happening (I want it to work without refreshing the page). What I want to make is that the user can duplicate content but still is able to edit the duplicated content this is now not possible.

Thank you very much for reading this and I hope you can help me :)

How the resizer works

The resizer is a component which edit's its data with the tooltip component that looks the following

The image Element requests a tooltip (done with commit in vuex)

The tooltip shows on top of the image element and renders the resizer bar

On change the tooltip commits the new data to vuex so vuex can pass it back to vue for rendering the changes

Code of the on change resizer

            this.$store.commit(types.CHANGE_BLOCK, {
                headerId: this.headerid,
                columnId: this.columnid,
                blockId: this.blockid,
                blockChildId: 0,
                properties: {
                    height: (this.value < 10 ? this.value + 10 : this.value)
                }
            });

Code of the function in vuex

                        //ADJUSTMENTS BLOCK
                        _.each(data[Object.keys(data)[4]], function(value, key) {
                            state.data[domain][headerId].content[columnId].content[blockId].data[Object.keys(data)[4]][key] = value;
                        });


问:
Add a vertical label to matplotlib colormap legend
This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

```<code>import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()
</code>```

It's anoying to not get an easy answer from google... can someone help me ?

答:
I believe your code is working. See this example:

```<code>import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris().data
X = iris[:,0]
Y = iris[:,1]
Z = iris[:,2]

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()
</code>```

Output:

Body:
This code enables me to plot a colormap of a "3d" array [X,Y,Z] (they are 3 simple np.array of elements). But I can't succeed in adding a vertical written label at the right of the colorbar legend.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)
import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()

It's anoying to not get an easy answer from google... can someone help me ?

Body:
I believe your code is working. See this example:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris().data
X = iris[:,0]
Y = iris[:,1]
Z = iris[:,2]

fig = plt.figure("Color MAP 2D+")

contour = plt.tricontourf(X, Y, Z, 100, cmap="bwr")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Color MAP 2D+")

#Legend
def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

import matplotlib.ticker as ticker
plt.colorbar(contour, format=ticker.FuncFormatter(fmt))

plt.show()

Output: