问:
how to getting numbers from calculator text area(without operators)?
in my previous question, i got no useful answer, i hope i get something :)

here's my code:

```<code>import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Calculator extends JFrame
{
  public Calculator()
{
    JFrame jf = new JFrame("Calculator");
    jf.setLocation(500,200);
    jf.setSize(600,400);
    jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

    /*=======================Add panel==============================
    ================================================================*/
    JPanel jp = new JPanel();
    jp.setLayout(null);
    jp.setBackground(Color.cyan);
    jf.add(jp);

    /*========================Add Textarea========================
    ================================================================*/

    JTextArea jta = new JTextArea("");
    jta.setBounds(100,25,290,50);
    jp.add(jta);

    /*========================Creating Font========================
    ===============================================================*/

    Font labels = new Font("Lucida Console",Font.PLAIN, 20);
    Font nums = new Font("Lucida Console",Font.PLAIN, 9);

    /*========================Add Labels============================
    ================================================================*/

    /*  for H align: ,SwingConstants.CENTER */
    JLabel jlbl = new JLabel("=");
    jlbl.setFont(labels);   //  MAKING FONT BIGGER
    jlbl.setBounds(400,30,50,40);
    jp.add(jlbl);

    JLabel jlbl_result = new JLabel();
    String temp = jta.getText();
    jlbl_result.setText(temp);

    /*=========================Adding button============================
    ====================================================================*/

    JButton jbtn1 = new JButton("1");
    jbtn1.setBounds(120,100,50,40);
    jbtn1.setBackground(Color.green);
    jp.add(jbtn1);

    JButton jbtn2 = new JButton("2");
    jbtn2.setBounds(180,100,50,40);
    jbtn2.setBackground(Color.green);
    jp.add(jbtn2);

    JButton jbtn3 = new JButton("3");
    jbtn3.setBounds(240,100,50,40);
    jbtn3.setBackground(Color.green);
    jp.add(jbtn3);

    JButton jbtn4 = new JButton("4");
    jbtn4.setBounds(120,155,50,40);
    jbtn4.setBackground(Color.green);
    jp.add(jbtn4);

    JButton jbtn5 = new JButton("5");
    jbtn5.setBounds(180,155,50,40);
    jbtn5.setBackground(Color.green);
    jp.add(jbtn5);

    JButton jbtn6 = new JButton("6");
    jbtn6.setBounds(240,155,50,40);
    jbtn6.setBackground(Color.green);
    jp.add(jbtn6);

    JButton jbtn7 = new JButton("7");
    jbtn7.setBounds(120,210,50,40);
    jbtn7.setBackground(Color.green);
    jp.add(jbtn7);

    JButton jbtn8 = new JButton("8");
    jbtn8.setBounds(180,210,50,40);
    jbtn8.setBackground(Color.green);
    jp.add(jbtn8);

    JButton jbtn9 = new JButton("9");
    jbtn9.setBounds(240,210,50,40);
    jbtn9.setBackground(Color.green);
    jp.add(jbtn9);

    JButton jbtn0 = new JButton("0");
    jbtn0.setBounds(180,265,50,40);
    jbtn0.setBackground(Color.green);
    jp.add(jbtn0);

    JButton jbtn_sum = new JButton("+");
    jbtn_sum.setBounds(380,100,40,40);
    jbtn_sum.setFont(nums);
    jbtn_sum.setBackground(Color.gray);
    jp.add(jbtn_sum);

    JButton jbtn_sub = new JButton("-");
    jbtn_sub.setBounds(380,100,40,40);
    jbtn_sub.setFont(nums);
    jbtn_sub.setBackground(Color.gray);
    jp.add(jbtn_sub);

    JButton jbtn_equal = new JButton("-");
    jbtn_equal.setBounds(380,155,40,40);
    jbtn_equal.setFont(nums);
    jp.add(jbtn_equal);

    jf.setVisible(true);

            jbtn1.addActionListener(e->jta.append("1"));
            jbtn2.addActionListener(e->jta.append("2"));
            jbtn3.addActionListener(e->jta.append("3"));
            jbtn4.addActionListener(e->jta.append("4"));
            jbtn5.addActionListener(e->jta.append("5"));
            jbtn6.addActionListener(e->jta.append("6"));
            jbtn7.addActionListener(e->jta.append("7"));
            jbtn8.addActionListener(e->jta.append("8"));
            jbtn9.addActionListener(e->jta.append("9"));
            jbtn0.addActionListener(e->jta.append("0"));
            jbtn_equal.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt2)
                {

                }
            });
            //jbtn_sub.addActionListener(e->jta.append("-"));
            jbtn_sum.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {

                }
            });
}
public static void main(String...ser)
{
    new Calculator();
}
}
</code>```

i know! there is a lot of code, i want to put number that i entered to JTextArea inside variable, how to get numbers(just numbers without operators )
and assign it to variable?

and... how many variable is required to do it?(in case if i have more than 5 variable)

and a lot of questions..., i cant write it down here

thank you for help(forgive me of my bad grammar)

答:
Get the text from the JTextArea and then split it by non-number characters into an array of Strings, like this:

```<code>String[] numbers = jta.getText().split("\\D+");
</code>```

For example, if you used this regex to split the string "1+23-5" you would get this array: {"1","23","5"}.

If you want to store the numbers as ints, use a for-each loop to copy the String array into an int array:

```<code>int[] ints = new int[numbers.length]
for( int i = 0; i < numbers.length; i++){
    ints[i] = Integer.parseInt(numbers[i]);
}
</code>```

Then, instead of putting each number in a separate variable, just keep them in the array and access them by index when needed.

Body:
in my previous question, i got no useful answer, i hope i get something :)

here's my code:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Calculator extends JFrame
{
  public Calculator()
{
    JFrame jf = new JFrame("Calculator");
    jf.setLocation(500,200);
    jf.setSize(600,400);
    jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

    /*=======================Add panel==============================
    ================================================================*/
    JPanel jp = new JPanel();
    jp.setLayout(null);
    jp.setBackground(Color.cyan);
    jf.add(jp);

    /*========================Add Textarea========================
    ================================================================*/

    JTextArea jta = new JTextArea("");
    jta.setBounds(100,25,290,50);
    jp.add(jta);

    /*========================Creating Font========================
    ===============================================================*/

    Font labels = new Font("Lucida Console",Font.PLAIN, 20);
    Font nums = new Font("Lucida Console",Font.PLAIN, 9);

    /*========================Add Labels============================
    ================================================================*/

    /*  for H align: ,SwingConstants.CENTER */
    JLabel jlbl = new JLabel("=");
    jlbl.setFont(labels);   //  MAKING FONT BIGGER
    jlbl.setBounds(400,30,50,40);
    jp.add(jlbl);

    JLabel jlbl_result = new JLabel();
    String temp = jta.getText();
    jlbl_result.setText(temp);

    /*=========================Adding button============================
    ====================================================================*/

    JButton jbtn1 = new JButton("1");
    jbtn1.setBounds(120,100,50,40);
    jbtn1.setBackground(Color.green);
    jp.add(jbtn1);

    JButton jbtn2 = new JButton("2");
    jbtn2.setBounds(180,100,50,40);
    jbtn2.setBackground(Color.green);
    jp.add(jbtn2);

    JButton jbtn3 = new JButton("3");
    jbtn3.setBounds(240,100,50,40);
    jbtn3.setBackground(Color.green);
    jp.add(jbtn3);

    JButton jbtn4 = new JButton("4");
    jbtn4.setBounds(120,155,50,40);
    jbtn4.setBackground(Color.green);
    jp.add(jbtn4);

    JButton jbtn5 = new JButton("5");
    jbtn5.setBounds(180,155,50,40);
    jbtn5.setBackground(Color.green);
    jp.add(jbtn5);

    JButton jbtn6 = new JButton("6");
    jbtn6.setBounds(240,155,50,40);
    jbtn6.setBackground(Color.green);
    jp.add(jbtn6);

    JButton jbtn7 = new JButton("7");
    jbtn7.setBounds(120,210,50,40);
    jbtn7.setBackground(Color.green);
    jp.add(jbtn7);

    JButton jbtn8 = new JButton("8");
    jbtn8.setBounds(180,210,50,40);
    jbtn8.setBackground(Color.green);
    jp.add(jbtn8);

    JButton jbtn9 = new JButton("9");
    jbtn9.setBounds(240,210,50,40);
    jbtn9.setBackground(Color.green);
    jp.add(jbtn9);

    JButton jbtn0 = new JButton("0");
    jbtn0.setBounds(180,265,50,40);
    jbtn0.setBackground(Color.green);
    jp.add(jbtn0);

    JButton jbtn_sum = new JButton("+");
    jbtn_sum.setBounds(380,100,40,40);
    jbtn_sum.setFont(nums);
    jbtn_sum.setBackground(Color.gray);
    jp.add(jbtn_sum);

    JButton jbtn_sub = new JButton("-");
    jbtn_sub.setBounds(380,100,40,40);
    jbtn_sub.setFont(nums);
    jbtn_sub.setBackground(Color.gray);
    jp.add(jbtn_sub);

    JButton jbtn_equal = new JButton("-");
    jbtn_equal.setBounds(380,155,40,40);
    jbtn_equal.setFont(nums);
    jp.add(jbtn_equal);

    jf.setVisible(true);

            jbtn1.addActionListener(e->jta.append("1"));
            jbtn2.addActionListener(e->jta.append("2"));
            jbtn3.addActionListener(e->jta.append("3"));
            jbtn4.addActionListener(e->jta.append("4"));
            jbtn5.addActionListener(e->jta.append("5"));
            jbtn6.addActionListener(e->jta.append("6"));
            jbtn7.addActionListener(e->jta.append("7"));
            jbtn8.addActionListener(e->jta.append("8"));
            jbtn9.addActionListener(e->jta.append("9"));
            jbtn0.addActionListener(e->jta.append("0"));
            jbtn_equal.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt2)
                {

                }
            });
            //jbtn_sub.addActionListener(e->jta.append("-"));
            jbtn_sum.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {

                }
            });
}
public static void main(String...ser)
{
    new Calculator();
}
}

i know! there is a lot of code, i want to put number that i entered to JTextArea inside variable, how to get numbers(just numbers without operators )
and assign it to variable?

and... how many variable is required to do it?(in case if i have more than 5 variable)

and a lot of questions..., i cant write it down here

thank you for help(forgive me of my bad grammar)

Body:
Get the text from the JTextArea and then split it by non-number characters into an array of Strings, like this:

String[] numbers = jta.getText().split("\\D+");

For example, if you used this regex to split the string "1+23-5" you would get this array: {"1","23","5"}.

If you want to store the numbers as ints, use a for-each loop to copy the String array into an int array:

int[] ints = new int[numbers.length]
for( int i = 0; i < numbers.length; i++){
    ints[i] = Integer.parseInt(numbers[i]);
}

Then, instead of putting each number in a separate variable, just keep them in the array and access them by index when needed.


来源: stackexchange

问:
Windows batch file with loop through subfolders
I didnt succeed writing an approriate batch file and would appreciate some help.

Let's say I have an exe in D:\Test\ called script.exe.
To execute this script.exe it requires an additional argument of a .bin files (e.g. bin01.bin, bin02.bin).

Therefore it would be like: script.exe -i bin01.bin, script.exe -i bin01

I want the script to execute with all .bin files from all subfolders

D:\Test\script.exe

D:\Test\Folder01\bin01.bin

D:\Test\Folder01\bin02.bin

D:\Test\Folder02\bin01.bin

D:\Test\Folder03\bin01.bin

anyone could help me here?
Thanks a lot in advance.

答:
For direct execution from within a command prompt window:

```<code>for /R "D:\Test" %I in (*.bin) do @D:\Test\script.exe -i "%I"
</code>```

And the same command line for usage in a batch file:

```<code>@for /R "D:\Test" %%I in (*.bin) do @D:\Test\script.exe -i "%%I"
</code>```

The command FOR searches recursive in directory D:\Test and all subdirectories for files matching the wildcard pattern *.bin.

The name of each found file is assigned with full path to case-sensitive loop variable I.

FOR executes for each file the executable D:\Test\script.exe with first argument -i and second argument being the name of found file with full path enclosed in double quotes to work for any *.bin file name even those containing a space or one of these characters: &()[]{}^=;!'+,`~.

@ at beginning of entire FOR command line just tells Windows command interpreter cmd.exe not to echo the command line after preprocessing before execution to console window as by default.

@ at beginning of D:\Test\script.exe avoids the output of this command to console executed on each iteration of the loop.

Most often the echo of a command line before execution is turned off at beginning of the batch file with @echo off as it can be seen below.

```<code>@echo off
for /R "D:\Test" %%I in (*.bin) do D:\Test\script.exe -i "%%I"
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

ContentLicense: CC BY-SA 3.0

Body:
For direct execution from within a command prompt window:

for /R "D:\Test" %I in (*.bin) do @D:\Test\script.exe -i "%I"

And the same command line for usage in a batch file:

@for /R "D:\Test" %%I in (*.bin) do @D:\Test\script.exe -i "%%I"

The command FOR searches recursive in directory D:\Test and all subdirectories for files matching the wildcard pattern *.bin.

The name of each found file is assigned with full path to case-sensitive loop variable I.

FOR executes for each file the executable D:\Test\script.exe with first argument -i and second argument being the name of found file with full path enclosed in double quotes to work for any *.bin file name even those containing a space or one of these characters: &()[]{}^=;!'+,`~.

@ at beginning of entire FOR command line just tells Windows command interpreter cmd.exe not to echo the command line after preprocessing before execution to console window as by default.

@ at beginning of D:\Test\script.exe avoids the output of this command to console executed on each iteration of the loop.

Most often the echo of a command line before execution is turned off at beginning of the batch file with @echo off as it can be seen below.

@echo off
for /R "D:\Test" %%I in (*.bin) do D:\Test\script.exe -i "%%I"

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?


问:
Asp.Net core (Full .Net framework) vs Asp.Net core (.Net Core) Performance
I find that one of the key benefit of Asp.Net core is multi fold performance improvement (requests per second) compared to traditional Asp.Net.  I find many bench mark sites talks about Asp.Net core performance, but I'm not sure if the performance is based on Asp.Net core with .Net core framework or the same performance benefit applies to asp.net core (full .Net framework).

Any idea/articles that explains/compares performance between asp.net core (.Net core) vs asp.net (full framework)?

Thanks

答:
I recently develop using ASP.NET Core 2.0, and I have the same question regarding performance improvement beside its excellent cross platform support. There are many comparison from google search result, and the briefing idea is:

ASP.NET Core  2.0 is about 6x-23x faster than ASP.NET 4.6

Here are two resources for your reference

https://www.ageofascent.com/2016/02/18/asp-net-core-exeeds-1-15-million-requests-12-6-gbps/
https://github.com/aspnet/benchmarks

ContentLicense: CC BY-SA 4.0


问:
Position image on page with title using ImageMagick or similar command line tool
I have a landscape image foo.png which I'd like to lay out on a page like this:

```<code>+--------------+
|              |
|  title text  |
|              |
|  +--------+  |
|  |foo.png |  |
|  |        |  |
|  +--------+  |
|              |
|              |
+--------------+
</code>```

I've got the image positioned properly on the page with:

convert -background white -page letter+20+300 -resize 572x572 foo.png -layers flatten laid-out.png

However, I can't find the right use of -annotate, -draw text or label: to get that title text to show up in the right place.

The eventual goal is to script this for about a hundred images, so I need a command-line solution.

答:
Here is an alternate way to do it in ImageMagick using montage.

logo.jpg

```<code>montage -title "Testing" logo.jpg -geometry 160x120+25+25 -tile 1x1 -frame 0 -background white logo_title.jpg
</code>```

The geometry argument 160x120 resizes to that dimension and the +25+25 adds a border of that size. Note that this gives somewhat less flexibility in positioning the title than GeeMack's solution.

Body:
I have a landscape image foo.png which I'd like to lay out on a page like this:

+--------------+
|              |
|  title text  |
|              |
|  +--------+  |
|  |foo.png |  |
|  |        |  |
|  +--------+  |
|              |
|              |
+--------------+

I've got the image positioned properly on the page with:

convert -background white -page letter+20+300 -resize 572x572 foo.png -layers flatten laid-out.png

However, I can't find the right use of -annotate, -draw text or label: to get that title text to show up in the right place.

The eventual goal is to script this for about a hundred images, so I need a command-line solution.

Body:
Here is an alternate way to do it in ImageMagick using montage.

logo.jpg

montage -title "Testing" logo.jpg -geometry 160x120+25+25 -tile 1x1 -frame 0 -background white logo_title.jpg

The geometry argument 160x120 resizes to that dimension and the +25+25 adds a border of that size. Note that this gives somewhat less flexibility in positioning the title than GeeMack's solution.


问:
Can I use grep to extract a single column of a CSV file?
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
```

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

答:
As the other answers have said, using grep is a bad/unfortunate idea.

The only way I can think of using grep is to pull out a specific row where the 3rd column == some value. E.g.,

```<code>grep '^\([^;]*;\)\{2\}Bell;' test.txt
1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
</code>```

Or if the first column is the index (not counting it as a column):

```<code>grep '^\([^;]*;\)\{3\}39;' test.txt
1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
</code>```

Even using grep in this case leads to a pretty ugly solution.

Edit: Didn't see Charles Duffy's answer... that's pretty clever.

Body:
I'm trying to solve o problem I have to do as soon as possible.
I have a csv file, fields separated by ;.
I'm asked to make a shell command using grep to list only the third column, using regex. I can't use cut. It is an exercise.

My file is like this:

1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008
2;Wayne;Watkins;22;Lanme Place;Cotoiwi;NC;86578
3;Danny;Vega;25;Fofci Center;Momahbih;MS;21027
4;Larry;Robinson;23;Bammek Boulevard;Gaizatoh;NE;27517
5;Myrtie;Black;20;Savon Square;Gokubpat;PA;92219
6;Nellie;Greene;23;Utebu Plaza;Rotvezri;VA;17526
7;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
8;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
9;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
10;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
11;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302
12;Stanley;Tucker;54;Cure View;Woocabu;OH;45475
13;Lina;Holloway;41;Sajric River;Furutwe;ME;62184
14;Hettie;Carlson;57;Zuheho Pike;Gokrobo;PA;89098
15;Maud;Phelps;57;Lafni Drive;Gokemu;MD;87066
16;Della;Roberson;53;Zafe Glen;Celoshuv;WV;56749
17;Cory;Roberson;56;Riltav Manor;Uwsupep;LA;07983
18;Stella;Hayes;30;Omki Square;Figjitu;GA;35813
19;Robert;Griffin;22;Kiroc Road;Wiregu;OH;39594
20;Clyde;Reynolds;19;Lupow Ridge;Kedkuha;WI;29749
21;Calvin;Reyes;47;Paad Loop;Beejdij;KS;29247
22;Douglas;Graves;43;Gouk Square;Sekolim;NY;13226
23;Josephine;Estrada;48;Ocgig Pike;Beheho;WI;87305
24;Eugene;Matthews;26;Daew Drive;Riftemij;ME;93302

I think I should use something like: cat < test.csv | grep 'regex'.

Thanks.

Body:
As the other answers have said, using grep is a bad/unfortunate idea.

The only way I can think of using grep is to pull out a specific row where the 3rd column == some value. E.g.,

grep '^\([^;]*;\)\{2\}Bell;' test.txt
1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008

Or if the first column is the index (not counting it as a column):

grep '^\([^;]*;\)\{3\}39;' test.txt
1;Evan;Bell;39;Obigod Manor;Ekjipih;TN;25008

Even using grep in this case leads to a pretty ugly solution.

Edit: Didn't see Charles Duffy's answer... that's pretty clever.


问:
Display Custom Total Saving in generated invoice in WooCommerce 3
In WooCommerce I am using WooCommerce Print Invoices & Packing lists plugin…

How can I display the total savings of any order in the invoices generated by this plugin ?

1 year ago I have been using this code based on [this answer] and that was working before I updated WooCommerce :

```<code><?php

    $discount_total = 0;
    $_order = wc_get_order( $order_id );
    foreach ($_order->get_items() as $order_item) {
        if ($order_item['variation_id'] > 0) {
            $line_item = wc_get_product( $order_item['variation_id'] );
        } else {
            $line_item = wc_get_product( $order_item['product_id'] );
        }
        $sale_price = $line_item->sale_price;
        $regular_price = $line_item->regular_price;

        if ( !empty($sale_price) ) {
            $discount = ($regular_price - $sale_price) * $order_item['item_meta']['_qty'][0];
            $discount_total += $discount;
        }
    }
    $discount_saving = round ( $discount_total + $_order->get_total_discount() );
    if ( $discount_total > 0 ) {

    <tr>
        <td class="order_saving" colspan="5"><strong><?php _e( 'Total Savings:  ', 'woocommerce' ); ?></strong></td>
        <td class="value" colspan="2" ><span class="woocommerce-Price-saving saving"><?php echo $discount_saving ; ?></span></td>
    </tr>
<?php } ?>
</code>```

So now it doesn't works anymore. I have tried to make changes without success.

So what is the right solution?

答:
Here is the updated code that will work for WooCommerce version 3+:

```<code><?php
///////////// HERE BEGINS CUSTOMIZATION /////////////

$discount_total = 0;
$_order = wc_get_order( $order_id );
foreach ($_order->get_items() as $line_item) {
    // The WC_product object
    $_product = $line_item->get_product();

    // The product prices
    $sale_price = $_product->get_sale_price();
    $regular_price = $_product->get_regular_price();

    if ( !empty($sale_price) ) {
        $discount = ($regular_price - $sale_price) * $line_item->get_quantity();
        $discount_total += $discount;
    }
}

$discount_saving = round ( $discount_total + $_order->get_total_discount() );

if ( $discount_total > 0 ) {
    ?>

    <tr>
    <td class="order_saving" colspan="5"><strong><?php _e( 'Total Savings: ', 'woocommerce' ); ?></strong></td>
    <td class="value" colspan="2" ><span class="woocommerce-Price-saving saving"><?php echo $discount_saving ; ?></span></td>
    </tr>

    <?php
}
///////////// END OF CUSTOMIZATION /////////////
?>
</code>```

This should works for you now

Related threads:

How to get WooCommerce order details

Get Order items and WC_Order_Item_Product in Woocommerce 3

Body:
In WooCommerce I am using WooCommerce Print Invoices & Packing lists plugin…

How can I display the total savings of any order in the invoices generated by this plugin ?

1 year ago I have been using this code based on [this answer] and that was working before I updated WooCommerce :

<?php

    $discount_total = 0;
    $_order = wc_get_order( $order_id );
    foreach ($_order->get_items() as $order_item) {
        if ($order_item['variation_id'] > 0) {
            $line_item = wc_get_product( $order_item['variation_id'] );
        } else {
            $line_item = wc_get_product( $order_item['product_id'] );
        }
        $sale_price = $line_item->sale_price;
        $regular_price = $line_item->regular_price;

        if ( !empty($sale_price) ) {
            $discount = ($regular_price - $sale_price) * $order_item['item_meta']['_qty'][0];
            $discount_total += $discount;
        }
    }
    $discount_saving = round ( $discount_total + $_order->get_total_discount() );
    if ( $discount_total > 0 ) {

        <?php _e( 'Total Savings:  ', 'woocommerce' ); ?>
        <?php echo $discount_saving ; ?>

<?php } ?>

So now it doesn't works anymore. I have tried to make changes without success.

So what is the right solution?

Body:
Here is the updated code that will work for WooCommerce version 3+:

<?php
///////////// HERE BEGINS CUSTOMIZATION /////////////

$discount_total = 0;
$_order = wc_get_order( $order_id );
foreach ($_order->get_items() as $line_item) {
    // The WC_product object
    $_product = $line_item->get_product();

    // The product prices
    $sale_price = $_product->get_sale_price();
    $regular_price = $_product->get_regular_price();

    if ( !empty($sale_price) ) {
        $discount = ($regular_price - $sale_price) * $line_item->get_quantity();
        $discount_total += $discount;
    }
}

$discount_saving = round ( $discount_total + $_order->get_total_discount() );

if ( $discount_total > 0 ) {
    ?>

    <tr>
    <td class="order_saving" colspan="5"><strong><?php _e( 'Total Savings: ', 'woocommerce' ); ?></strong></td>
    <td class="value" colspan="2" ><span class="woocommerce-Price-saving saving"><?php echo $discount_saving ; ?></span></td>
    </tr>

    <?php
}
///////////// END OF CUSTOMIZATION /////////////
?>

This should works for you now

Related threads:

How to get WooCommerce order details

Get Order items and WC_Order_Item_Product in Woocommerce 3


问:
How I can improve execution time of recursive promise on Edge? On chrome it is almost instantenous for 100000 records
In code snippet below the promise is recursively called after completion of itself. I ran the following code snippet on Edge and on Chrome and am seeing a marked difference in execution time. Is there something wrong that I am doing? How I can improve the execution time on Edge?

Please ignore the promise 'anti-pattern'. It is just to simulate an asynchronous method.

Chrome result -
Count - 99999
Start 1512416096194
last update 1512416096509
End 1512416096577
recursiveFnReturnsPromise finished

execution time - 397ms

Edge result -
Count - 99999
Start 1512415183349
last update 1512415508413
End 1512415907219
recursiveFnReturnsPromise finished

execution time between the start and the end- 723870ms

execution time between last the DOM update and the end- 398806ms

//large array
let aValues = Array(100000);

//utility function
function writeln(text) {
  let p = document.createElement('div');
  p.innerText = text;
  document.getElementById('v1').appendChild(p);
}

writeln('Start ' +Date.now()); //note start recursion time

recursiveFnReturnsPromiseV1(aValues, 1).then(function() {
  writeln('End ' +Date.now());//note end recursion time
  writeln('recursiveFnReturnsPromise finished');
}, function() {
  writeln('End' +Date.now());
  writeln('recursiveFnReturnsPromise failed');
})

//the recursive functions which returns a promise
function recursiveFnReturnsPromiseV1(pValues, ix) {
  if (pValues.length <= ix)
    return Promise.resolve();

  return new Promise(function(c, e) {
    document.getElementById('output').innerText = ix;
    if(ix==99999) writeln('last update ' +Date.now());
    c();
  }).then(function() {
    return recursiveFnReturnsPromiseV1(pValues, ++ix);
  })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Count - <span id='output'></span>
<div id='v1'></div></code>```

Note - for anyone interested in trying to do promise recursion right please see related post - What is the difference in following pattern to call recursive JavaScript function which returns a promise?

答:
Even without interacting with the DOM, Promises are dramatically slower in Firefox.

```<code>(async()=>{
  let start = Date.now();
  for (let i = 0; i < 1e6; i++) await Promise.resolve();
  let end = Date.now();
  console.log(end-start, 'ms');
})();
</code>```

On my machine, this completes in 0.25 seconds in Node.js, 6 seconds in Chrome, and 16 seconds in Firefox. (I don't have Edge).

I would avoid iterating over an excessive number of Promises. It should be doable — in any realistic code the majority of wall clock time will be spent rendering updates in the browser or waiting for asynchronous calls to complete, and only a small fraction will be in actually executing the asynchronous calls themselves. Perform more work synchronously if that's the case.

This is slightly faster for some reason:

```<code>(async()=>{
  let start = Date.now();
  await Promise.all(Array(1e6).fill(Promise.resolve()));
  let end = Date.now();
  console.log(end-start, 'ms');
})();
</code>```

1 second in Node.js, 2.5 seconds in Chrome, 4 seconds in Firefox. (And in fact, the bulk of the work is in actually building the array, I get <1 second if I move that outside the timed section.)

Using Promise.all might be faster because the script produces the work all at once, but waiting for it to complete does not enter the interpreter (to a very rough approximation). That might be a good workaround if Promises are not as fast as they are in V8.

Body:
In code snippet below the promise is recursively called after completion of itself. I ran the following code snippet on Edge and on Chrome and am seeing a marked difference in execution time. Is there something wrong that I am doing? How I can improve the execution time on Edge?

Please ignore the promise 'anti-pattern'. It is just to simulate an asynchronous method.

Chrome result -
Count - 99999
Start 1512416096194
last update 1512416096509
End 1512416096577
recursiveFnReturnsPromise finished

execution time - 397ms

Edge result -
Count - 99999
Start 1512415183349
last update 1512415508413
End 1512415907219
recursiveFnReturnsPromise finished

execution time between the start and the end- 723870ms

execution time between last the DOM update and the end- 398806ms

//large array
let aValues = Array(100000);

//utility function
function writeln(text) {
  let p = document.createElement('div');
  p.innerText = text;
  document.getElementById('v1').appendChild(p);
}

writeln('Start ' +Date.now()); //note start recursion time

recursiveFnReturnsPromiseV1(aValues, 1).then(function() {
  writeln('End ' +Date.now());//note end recursion time
  writeln('recursiveFnReturnsPromise finished');
}, function() {
  writeln('End' +Date.now());
  writeln('recursiveFnReturnsPromise failed');
})

//the recursive functions which returns a promise
function recursiveFnReturnsPromiseV1(pValues, ix) {
  if (pValues.length <= ix)
    return Promise.resolve();

  return new Promise(function(c, e) {
    document.getElementById('output').innerText = ix;
    if(ix==99999) writeln('last update ' +Date.now());
    c();
  }).then(function() {
    return recursiveFnReturnsPromiseV1(pValues, ++ix);
  })
}

Count -

Note - for anyone interested in trying to do promise recursion right please see related post - What is the difference in following pattern to call recursive JavaScript function which returns a promise?

Body:
Even without interacting with the DOM, Promises are dramatically slower in Firefox.

(async()=>{
  let start = Date.now();
  for (let i = 0; i < 1e6; i++) await Promise.resolve();
  let end = Date.now();
  console.log(end-start, 'ms');
})();

On my machine, this completes in 0.25 seconds in Node.js, 6 seconds in Chrome, and 16 seconds in Firefox. (I don't have Edge).

I would avoid iterating over an excessive number of Promises. It should be doable — in any realistic code the majority of wall clock time will be spent rendering updates in the browser or waiting for asynchronous calls to complete, and only a small fraction will be in actually executing the asynchronous calls themselves. Perform more work synchronously if that's the case.

This is slightly faster for some reason:

(async()=>{
  let start = Date.now();
  await Promise.all(Array(1e6).fill(Promise.resolve()));
  let end = Date.now();
  console.log(end-start, 'ms');
})();

1 second in Node.js, 2.5 seconds in Chrome, 4 seconds in Firefox. (And in fact, the bulk of the work is in actually building the array, I get <1 second if I move that outside the timed section.)

Using Promise.all might be faster because the script produces the work all at once, but waiting for it to complete does not enter the interpreter (to a very rough approximation). That might be a good workaround if Promises are not as fast as they are in V8.


问:
What is value of 'if not' in the code?
I'm learning Python and a bit confused what if not doing in the below code? I presume if not is like else statement. But it turns out I'm wrong.  What is the value of if not exists in this code? Also another naive question, the variable exists is defined within a for loop, why is it available globally?

```<code>import scrabble
import string

for letter in string.ascii_lowercase:
    for word in scrabble.wordlist:
        exists = False
        if letter * 2 in word:
            exists = True
            break
    if not exists:
        print(letter)

print(exists) # Globally exists = True
</code>```

答:
Here are some explanations:

```<code>import string

# let's create our own wordlist
wordlist = ["cat","moose"]

# Loop all letters from a-z
for letter in string.ascii_lowercase:
    # Inner-loop all words in wordlist
    for word in wordlist:
        # Start with exists = False
        exists = False
        # If letter is repeated break the inner loop and set exists = True
        if letter * 2 in word:
            exists = True
            break
    # Check if exists is False (which it is if double letter didn't exist in any word)
    if not exists:
        print(letter)

# This will print the last exists value (True if 'z' is doubled in any word else false)
print(exists)
</code>```

Since the only letter that is repeated in any of the words in wordlist is 'o': All letters except 'o' is printed out followed by a False

```<code>a
b
c
d
...
False
</code>```

BTW, you can get the same result with this code snippet:

```<code>import string

doubleletters = []
wordlist = ["cat","moose"]

# Loop through wordlist and extend the doubleletters list
for word in wordlist:
    doubleletters.extend(i[0] for i in zip(word,word[1:]) if len(set(i)) == 1)

print('\n'.join(i for i in string.ascii_lowercase if i not in doubleletters))
</code>```

Title: What is value of 'if not' in the code?

Body:
I'm learning Python and a bit confused what if not doing in the below code? I presume if not is like else statement. But it turns out I'm wrong.  What is the value of if not exists in this code? Also another naive question, the variable exists is defined within a for loop, why is it available globally?

import scrabble
import string

for letter in string.ascii_lowercase:
    for word in scrabble.wordlist:
        exists = False
        if letter * 2 in word:
            exists = True
            break
    if not exists:
        print(letter)

print(exists) # Globally exists = True

Body:
Here are some explanations:

import string

# let's create our own wordlist
wordlist = ["cat","moose"]

# Loop all letters from a-z
for letter in string.ascii_lowercase:
    # Inner-loop all words in wordlist
    for word in wordlist:
        # Start with exists = False
        exists = False
        # If letter is repeated break the inner loop and set exists = True
        if letter * 2 in word:
            exists = True
            break
    # Check if exists is False (which it is if double letter didn't exist in any word)
    if not exists:
        print(letter)

# This will print the last exists value (True if 'z' is doubled in any word else false)
print(exists)

Since the only letter that is repeated in any of the words in wordlist is 'o': All letters except 'o' is printed out followed by a False

a
b
c
d
...
False

BTW, you can get the same result with this code snippet:

import string

doubleletters = []
wordlist = ["cat","moose"]

# Loop through wordlist and extend the doubleletters list
for word in wordlist:
    doubleletters.extend(i[0] for i in zip(word,word[1:]) if len(set(i)) == 1)

print('\n'.join(i for i in string.ascii_lowercase if i not in doubleletters))


问:
Python CSV files: Printing all a user's details
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

```<code>     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")
</code>```

This is my result:

```<code>Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!
</code>```

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

答:
Your print statements aren't inside the for-loop, but after it. So they only get run once. And your checking found to decide whether to print doesn't make sense: this prints based on whether any row matches, not whether the current one does. Also, there's no need to do else: pass. You should change your code to the following:

```<code>def Report1():
    found=False
    UserFind=input("Please enter a username")
    with open("Report.csv","r") as c:
        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
                found= True
        if not found:
            print("User doesn't exist or wrong details...")
</code>```

Body:
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")

This is my result:

Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

Body:
Your print statements aren't inside the for-loop, but after it. So they only get run once. And your checking found to decide whether to print doesn't make sense: this prints based on whether any row matches, not whether the current one does. Also, there's no need to do else: pass. You should change your code to the following:

def Report1():
    found=False
    UserFind=input("Please enter a username")
    with open("Report.csv","r") as c:
        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
                found= True
        if not found:
            print("User doesn't exist or wrong details...")


问:
Java Is there a feature for replacing placeholders inside a String with a String variable
I have a requirement to move all the hard-coded error logs to DB. Some of the error logs comes in the format

```<code>"xxxxx" + variable + "xxxxxx";
</code>```

It is  not possible to change the structure of the table. Neither can I do some String insert based on the position since the values in the DB can always change.

Is there a feature in any Java libraries or third party ones where you can have placeholders in the String value and they get replaced by variables.
To quote an example, we could think of the good old

```<code>printf("bla %s %d bla,", var, var2);
</code>```

or the SQL PreparedStatement class

```<code>stmt("select * from blah where a = ?");
</code>```

And the '?' gets replaced by a variable content.

Any suggestions would be of great help.

答: JDK 7+ has String.format() which I what I think you're looking for

Body:
I have a requirement to move all the hard-coded error logs to DB. Some of the error logs comes in the format

"xxxxx" + variable + "xxxxxx";

It is  not possible to change the structure of the table. Neither can I do some String insert based on the position since the values in the DB can always change.

Is there a feature in any Java libraries or third party ones where you can have placeholders in the String value and they get replaced by variables.
To quote an example, we could think of the good old

printf("bla %s %d bla,", var, var2);

or the SQL PreparedStatement class

stmt("select * from blah where a = ?");

And the '?' gets replaced by a variable content.

Any suggestions would be of great help.


问:
How to get the sum of a column up to a certain value?
I have a google sheet that I am using to try and calculate leveling and experience points. Column A has the level and Column B has the exp needed to reach the next level. i.e. To get to Level 3 you need 600 exp.

A   B

1   200

2   400

3   600

...

99   19800

In column I2 I have an integer for an amount of exp (e.g. 2000), in column J2 I want to figure out what level someone would be at if they started from 0.

答:
Using a helper column (for example Z): put =sum(B$1:B1) in cell Z1 and drag down. This will compute the sums required for each level. In J2, use the formula

```<code>=vlookup(I2, {B:B, Z:Z}, 2) + 1
</code>```

which looks up I2 in column B, and returns the nearest match that is less than or equal to the search key. It adds 1 to find the level that would be reached, because your table has this kind of an offset to you: the entry against level N is about achieving level N+1.

You may want to put 0 0 on top of the table, to correctly handle the amounts under 200. Or treat them with a separate if condition.

Using algebra

In your specific scenario, the point amount required for level N can be computed as

```<code>200*(1+2+3+...+N-1) = 200*(N-1)*N/2 = 100*(N-1/2)^2 - 25
</code>```

So, given x amount of points, we can find N directly with algebra:

```<code>N = floor(sqrt((x+25)/100)+1/2)
</code>```

which means that the formula

```<code>=floor(sqrt((I2 + 25) / 100) + 1/2)
</code>```

will have the desired effect in cell J2, without the need for an extra column and vlookup.

However, the second approach only works for this specific point values.

Body:
Using a helper column (for example Z): put =sum(B$1:B1) in cell Z1 and drag down. This will compute the sums required for each level. In J2, use the formula

=vlookup(I2, {B:B, Z:Z}, 2) + 1

which looks up I2 in column B, and returns the nearest match that is less than or equal to the search key. It adds 1 to find the level that would be reached, because your table has this kind of an offset to you: the entry against level N is about achieving level N+1.

You may want to put 0 0 on top of the table, to correctly handle the amounts under 200. Or treat them with a separate if condition.

Using algebra

In your specific scenario, the point amount required for level N can be computed as

200*(1+2+3+...+N-1) = 200*(N-1)*N/2 = 100*(N-1/2)^2 - 25

So, given x amount of points, we can find N directly with algebra:

N = floor(sqrt((x+25)/100)+1/2)

which means that the formula

=floor(sqrt((I2 + 25) / 100) + 1/2)

will have the desired effect in cell J2, without the need for an extra column and vlookup.

However, the second approach only works for this specific point values.


问:
Oracle 12c Forms & Reports setup_fmw_12.2.1.3.0_fr_win64.exe installation error: self-extraction to C:\...... .tmp failed
While installing Oracle 12c Forms & Reports: setup_fmw_12.2.1.3.0_fr_win64.exe file, got installation error: self-extraction to C:...... .tmp failed

How can I successfully install the Oracle Forms Reports?
I already have installed the weblogic infrastructure.

答:
What does the log file say the reason was? First two reasons that come to mind are Disk Space or File Write Permissions.

Open this file in a text editor and let us know what it says:
C:\Users\User\AppData\Local\Temp\OraInstall2017-11-30_05-11-55PM\launcher2017-11-30_05-11-55PM.log


问:
intellij - setting to replace the caret at the beginning of each line with correct indent
I am looking for the setting that forces the caret to placed at the beginning of each line. Currently if I click anywhere, the caret gets positioned there. It is not the behavior I like, I would like it to be replaced, in order to prevent me to do it incorrectly. I think it is an option commonly used, and was standard in the intellij I became in some other company but I am bad at describing it.
Sorry for my approximative vocabulary and thanks for any hint.</p>

答:
Go to File → Settings

On the left pane, expand Editor, then select General.

Find the Virtual Space section, and uncheck "Allow placement of caret after end of line".


问:
FBConnect : Facebook authent screen not redirecting to my app
I downloaded the sample app from the latest facebook ios SDK. I set my appId in the facebook init, set the appId in the URL scheme.

When i run the app, it opens the facebook app, with a message saying "you already authorized this app, click ok".

When i click ok, it just stays in the facebook app, redirection is not working...

Do you have any idea what i'm missing ?

Thanks, Vincent.

答:
Did you make the change to the .plist file properly?
You say you set your appID in URL scheme but actually it is fb[appId]. So if your appId is 123456, the URL Scheme in .plist should be "fb123456".

ContentLicense: CC BY-SA 2.5


问:
Matlab opening same file from different folders and not overwriting each other
I'm pretty new to Matlab, and I'm looking for possibly a way to open a file call data.txt from several subfolders of 2414A,2443A,6732A,4577A... and so on, without overwriting on top of each other. All of them are in one giant folder, just within different subfolders.

My question is, instead of changing the folder name every time I open the data.txtand setting a variable for each of the txt file, is there a quicker way to do so? Because my end goal is to concatenate all of the data.txt matrcies for computation.

I currently just have:

```<code>cd C:\User\Aisk_000\Desktop\A\NC\Subjects\2414A\
NC1 = dlmread('data.txt');
cd ../2443A\
NC2 = dlmread('data.xt');
cd ../6732A\
</code>```

...etc. It definitely serves the job, though.

答:
As simple as this:

```<code>files = dir('C:\User\Aisk_000\Desktop\A\NC\Subjects\*\data.txt');
files_num = numel(files);
files_data = cell(files_num,1);

for i = 1:files_num
    file = files(i);
    file_path = fullfile(file.folder,file.name);

    files_data{i} = dlmread(file_path);
end
</code>```

If you want to build up a simple indexing system, use this code instead:

```<code>files = dir('C:\Users\Zarathos\Desktop\*\data.txt');
files_num = numel(files);
files_data = cell(files_num,2);

for i = 1:files_num
    file = files(i);

    file_folder_idx = strsplit(file.folder,'\');
    file_folder_idx = file_folder_idx{end};

    file_path = fullfile(file.folder,file.name);

    files_data{i,1} = file_folder_idx;
    files_data{i,2} = dlmread(file_path);
end
</code>```

So if you have to save your files back to disk after they have been modified, you will be able to rebuild the structure of your C:\User\Aisk_000\Desktop\A\NC\Subjects\ folder and know in which path you have to save the file data currently being processed.

Body:
I'm pretty new to Matlab, and I'm looking for possibly a way to open a file call data.txt from several subfolders of 2414A,2443A,6732A,4577A... and so on, without overwriting on top of each other. All of them are in one giant folder, just within different subfolders.

My question is, instead of changing the folder name every time I open the data.txtand setting a variable for each of the txt file, is there a quicker way to do so? Because my end goal is to concatenate all of the data.txt matrcies for computation.

I currently just have:

cd C:\User\Aisk_000\Desktop\A\NC\Subjects\2414A\
NC1 = dlmread('data.txt');
cd ../2443A\
NC2 = dlmread('data.xt');
cd ../6732A\

...etc. It definitely serves the job, though.

Body:
As simple as this:

files = dir('C:\User\Aisk_000\Desktop\A\NC\Subjects\*\data.txt');
files_num = numel(files);
files_data = cell(files_num,1);

for i = 1:files_num
    file = files(i);
    file_path = fullfile(file.folder,file.name);

    files_data{i} = dlmread(file_path);
end

If you want to build up a simple indexing system, use this code instead:

files = dir('C:\Users\Zarathos\Desktop\*\data.txt');
files_num = numel(files);
files_data = cell(files_num,2);

for i = 1:files_num
    file = files(i);

    file_folder_idx = strsplit(file.folder,'\');
    file_folder_idx = file_folder_idx{end};

    file_path = fullfile(file.folder,file.name);

    files_data{i,1} = file_folder_idx;
    files_data{i,2} = dlmread(file_path);
end

So if you have to save your files back to disk after they have been modified, you will be able to rebuild the structure of your C:\User\Aisk_000\Desktop\A\NC\Subjects\ folder and know in which path you have to save the file data currently being processed.


问:
VBA Word The remote server machine does not exist or is unavailable
This is a problem similar to several already posted. I need specific help though since I don't know how to apply the answers to other questions.

Basically, I'm writing code in Access that references MSWord, and if I run the code multiple times, it starts failing with the message

The remote server machine does not exist or is unavailable

Here's the code:

```<code>Private Sub CreateWordMergeDoc_Click()

On Error GoTo Err_CreateWordMergeDoc_Click

Dim strSQL, strChurch, strDistLang, strFind, strReplace As String
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim wrdMergeDoc As Word.Document
Dim strFilepath As String

strFilepath = "O:\Church Phone List"

'Require choice for church and district
If IsNull(Me![ChurchCombo]) = True Then
    MsgBox "Select church", , "Church Phone List"
    Me.ChurchCombo.SetFocus
    GoTo CloseSub
End If

strChurch = Me![ChurchCombo]
strDistLang = Me![DistrictChoiceCombo]

If strDistLang = "" Then
    MsgBox "Select District", , "Church Phone List"
    Me.DistrictChoiceCombo.SetFocus
    GoTo CloseSub
Else
    strDistLang = IIf(Me![DistrictChoiceCombo] = "", "Church", Me![DistrictChoiceCombo])
End If

'Create SQL string from present church/district information
strSQL = "SELECT Churches.* " & vbCrLf & _
"FROM Churches " & vbCrLf & _
"WHERE (((Churches.Church)='" & strChurch & "') AND ((Churches.[District/Language])Like'" & strDistLang & "')) " & vbCrLf & _
"ORDER BY Churches.NAME;"

Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True

Set wrdDoc = wrdApp.Documents.Open(strFilepath & "\Phone Merge Document.docx")

With wrdDoc

    With .ActiveWindow
        'Open the header/footer and add the church (and district if appropriate)
        .ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader
        .Selection.EndKey Unit:=wdLine
        .Selection.TypeText Text:=strChurch & IIf(strDistLang <> "Church", " (" & strDistLang & ")", "")
        'Close header/footer
        .ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument
    End With

    With .MailMerge
        .MainDocumentType = wdCatalog
        .OpenDataSource NAME:= _
            GetNamePath _
            , ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
            AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
            WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
            Format:=wdOpenFormatAuto, Connection:= _
            "DSN=MS Access Database;DBQ=" & strFilepath & "2017\Phone List 2017.mdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;" _
            , SQLStatement:=strSQL, SubType:= _
           wdMergeSubTypeOther

        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    .Close SaveChanges:=wdDoNotSaveChanges

End With

    With wrdApp
        .Selection.WholeStory
        With .Selection.ParagraphFormat
            .SpaceBeforeAuto = False
            .SpaceAfterAuto = False
        End With
        .Selection.ParagraphFormat.TabStops.ClearAll
        .ActiveDocument.DefaultTabStop = InchesToPoints(0.5)
        'Add a tab stop
        .Selection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.1), _
            Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces

        'Replace (C) and (¢) with [C] and [c] since auto replace for (c) may be enabled
        .Selection.Find.Replacement.ClearFormatting
        With .Selection.Find
            .Text = "(C)"
            .Replacement.Text = "[C]"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        .Selection.Find.Execute Replace:=wdReplaceAll
        With .Selection.Find
            .Text = "(¢)"
            .Replacement.Text = "[c]"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        .Selection.Find.Execute Replace:=wdReplaceAll

        'Lock document so track changes stays on
        .ActiveDocument.Protect Password:="onebody1", NoReset:=False, Type:= _
             wdAllowOnlyRevisions, UseIRM:=False, EnforceStyleLock:=False
        .ChangeFileOpenDirectory _
         strFilepath & "\Track-Change Documents\"
    End With

    strFind = "/"
    strReplace = " "

    strDistLang = Replace(strDistLang, strFind, strReplace)

     wrdApp.ActiveDocument.SaveAs2 FileName:=strChurch & IIf(strDistLang <> "Church", " - " & strDistLang, ""), FileFormat _
        :=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=14

    wrdApp.ActiveDocument.Activate

'quit the word application:

wrdApp.Quit

MsgBox "Completed", , "Church Phone List"

CloseSub:

'Clear the object variables:

Set wrdDoc = Nothing
Set wrdApp = Nothing

Exit_CreateWordMergeDoc_Click:
Set wrdDoc = Nothing
Set wrdApp = Nothing
    Exit Sub

Err_CreateWordMergeDoc_Click:
MsgBox Err.Description
    Resume Exit_CreateWordMergeDoc_Click

End Sub
</code>```

I'd be quite thankful if someone could help clean up the code with regard to the error message.

答:
It appears that your problem is likely due to the calls to the unqualified InchesToPoints methods.

It doesn't appear (from what I can see on MSDN) that Access' Application object includes that method, and therefore it is defaulting to using the method which is part of the Word.Application object.  This will create an instance of that object that isn't being released at the end of your program.

The easiest fix is to simply qualify the call by specifying that you want to use the late-bound Word.Application object you create, i.e. use wrdApp.InchesToPoints.

Body:
This is a problem similar to several already posted. I need specific help though since I don't know how to apply the answers to other questions.

Basically, I'm writing code in Access that references MSWord, and if I run the code multiple times, it starts failing with the message

The remote server machine does not exist or is unavailable

Here's the code:

Private Sub CreateWordMergeDoc_Click()

On Error GoTo Err_CreateWordMergeDoc_Click

Dim strSQL, strChurch, strDistLang, strFind, strReplace As String
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim wrdMergeDoc As Word.Document
Dim strFilepath As String

strFilepath = "O:\Church Phone List"

'Require choice for church and district
If IsNull(Me![ChurchCombo]) = True Then
    MsgBox "Select church", , "Church Phone List"
    Me.ChurchCombo.SetFocus
    GoTo CloseSub
End If

strChurch = Me![ChurchCombo]
strDistLang = Me![DistrictChoiceCombo]

If strDistLang = "" Then
    MsgBox "Select District", , "Church Phone List"
    Me.DistrictChoiceCombo.SetFocus
    GoTo CloseSub
Else
    strDistLang = IIf(Me![DistrictChoiceCombo] = "", "Church", Me![DistrictChoiceCombo])
End If

'Create SQL string from present church/district information
strSQL = "SELECT Churches.* " & vbCrLf & _
"FROM Churches " & vbCrLf & _
"WHERE (((Churches.Church)='" & strChurch & "') AND ((Churches.[District/Language])Like'" & strDistLang & "')) " & vbCrLf & _
"ORDER BY Churches.NAME;"

Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True

Set wrdDoc = wrdApp.Documents.Open(strFilepath & "\Phone Merge Document.docx")

With wrdDoc

    With .ActiveWindow
        'Open the header/footer and add the church (and district if appropriate)
        .ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader
        .Selection.EndKey Unit:=wdLine
        .Selection.TypeText Text:=strChurch & IIf(strDistLang <> "Church", " (" & strDistLang & ")", "")
        'Close header/footer
        .ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument
    End With

    With .MailMerge
        .MainDocumentType = wdCatalog
        .OpenDataSource NAME:= _
            GetNamePath _
            , ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
            AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
            WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
            Format:=wdOpenFormatAuto, Connection:= _
            "DSN=MS Access Database;DBQ=" & strFilepath & "2017\Phone List 2017.mdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;" _
            , SQLStatement:=strSQL, SubType:= _
           wdMergeSubTypeOther

        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    .Close SaveChanges:=wdDoNotSaveChanges

End With

    With wrdApp
        .Selection.WholeStory
        With .Selection.ParagraphFormat
            .SpaceBeforeAuto = False
            .SpaceAfterAuto = False
        End With
        .Selection.ParagraphFormat.TabStops.ClearAll
        .ActiveDocument.DefaultTabStop = InchesToPoints(0.5)
        'Add a tab stop
        .Selection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.1), _
            Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces

        'Replace (C) and (¢) with [C] and [c] since auto replace for (c) may be enabled
        .Selection.Find.Replacement.ClearFormatting
        With .Selection.Find
            .Text = "(C)"
            .Replacement.Text = "[C]"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        .Selection.Find.Execute Replace:=wdReplaceAll
        With .Selection.Find
            .Text = "(¢)"
            .Replacement.Text = "[c]"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = True
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        .Selection.Find.Execute Replace:=wdReplaceAll

        'Lock document so track changes stays on
        .ActiveDocument.Protect Password:="onebody1", NoReset:=False, Type:= _
             wdAllowOnlyRevisions, UseIRM:=False, EnforceStyleLock:=False
        .ChangeFileOpenDirectory _
         strFilepath & "\Track-Change Documents\"
    End With

    strFind = "/"
    strReplace = " "

    strDistLang = Replace(strDistLang, strFind, strReplace)

     wrdApp.ActiveDocument.SaveAs2 FileName:=strChurch & IIf(strDistLang <> "Church", " - " & strDistLang, ""), FileFormat _
        :=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=14

    wrdApp.ActiveDocument.Activate

'quit the word application:

wrdApp.Quit

MsgBox "Completed", , "Church Phone List"

CloseSub:

'Clear the object variables:

Set wrdDoc = Nothing
Set wrdApp = Nothing

Exit_CreateWordMergeDoc_Click:
Set wrdDoc = Nothing
Set wrdApp = Nothing
    Exit Sub

Err_CreateWordMergeDoc_Click:
MsgBox Err.Description
    Resume Exit_CreateWordMergeDoc_Click

End Sub

I'd be quite thankful if someone could help clean up the code with regard to the error message.


问:
Arduino game "Stop It"
so I am making this game "stop it" which is a game that (in my case) are 6 led's next to eachother, glowing + making a sound 1 by 1 and every time you press button 1 (knop1), when led 1 burns, the leds start blinking faster.

I have that figured out
But I need a 2nd button (knop2) which you need to be able to press at any time to fully stop the game, but I keep failing on this.
I have tried many things but every one of them failed
Also sorry for a somewhat complex code...

This is the code:

```<code>    #define NOTE_E4  330          //Declareren van de noten
    #define NOTE_G4  392
    #define NOTE_A4  440
    #define NOTE_0   000
    //----------------------------------------------------------------------------------------------------------------------------------------
    int noten[] = {               //De noten
    NOTE_E4, NOTE_G4, NOTE_A4, NOTE_E4, NOTE_A4
    };
    //----------------------------------------------------------------------------------------------------------------------------------------
    int duur[] = {                //de duur van elke noot
    225, 225, 950, 225, 925
    };
    //----------------------------------------------------------------------------------------------------------------------------------------
    const int buzzer = 9;         //Hier staat de pin van de buzzer voor het lied
    const int snelheid = 1.5; //Snelheid, een hoger getal laat alles trager gaan, een lager getal laat het sneller gaan

    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;
    int gluid = 9;
    int run = 0;
    int knop = 12;
    int knop2 = 11;
    int n = 220;

    //----------------------------------------------------------------------------------------------------------------------------------------

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(knop, INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("We shall begin. \n   ");
      delay(500);
      for (int i=0;i<5;i++){                //5 staat voor het max aantal noten
      int wacht = duur[i] * (snelheid * 0.9);
      tone(buzzer,noten[i],wacht);          //tone(pin,frequentie,duur)
      delay(wacht);}                        //delay zorgt er hier voor dat de vorige noot niet word afgespeeld tijdens de vorige noot
      delay(100);
      Serial.println("Press the red button to start.");
      Serial.println("You can press the black button any time to stop.");
    }

    //----------------------------------------------------------------------------------------------------------------------------------------

    void loop(){
        if (n <= 10)
        {
          n = 60;
        }

else if (n == 20) {
Serial.begin(9600);
Serial.println("You won! Congratz!");
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, HIGH);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, HIGH);
delay(150);
digitalWrite(led6, LOW);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
digitalWrite(buzzer, LOW);
n = 10;
digitalWrite(led6, LOW);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
digitalWrite(buzzer, LOW);
digitalWrite(gluid, LOW);
n = 220;
delay(500);
}
else
  if(digitalRead(knop) == LOW)
  {

     if(run == 0){
      run = 255;
      Serial.println("Next stage.");
      n = n - 20; }

     else{
      run = 0;
         }
       }
  if(run > 0)

  {
     {
      digitalWrite(led6, HIGH);
      delay(n);
      digitalWrite(led6, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led5, HIGH);
      delay(n);
      digitalWrite(led5, LOW);
      delay(n);
      tone(gluid, 900);
    }
    {
      digitalWrite(led4, HIGH);
      delay(n);
      digitalWrite(led4, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led3, HIGH);
      delay(n);
      digitalWrite(led3, LOW);
      delay(n);
      tone(gluid, 900);
    }
    {
      digitalWrite(led2, HIGH);
      delay(n);
      digitalWrite(led2, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led1, HIGH);
      delay(n);
      digitalWrite(led1, LOW);
      delay(n);
      tone(gluid, 600);
    }
  }
}
</code>```

答:
The key is to re-organize your code into a state machine.  Remember that loop() is going to be called over and over.  Each time it's called, you should check what the current state of the game is and, depending on the inputs, change to the next state and return.

To illustrate, I'll use a much simpler game.  Press the start button to make one LED blink until the stop button is pressed.

```<code>// The WRONG WAY
void loop() {
    while (digitalRead(knop1) == HIGH) {}  // wait for start button
    while (digitalRead(knop2) == HIGH) {
        digitalWrite(led1, HIGH);
        delay(250);
        digitalWrite(led1, LOW);
        delay(250);
    }
}
</code>```

The code above is like your code in that you try to do (almost) everything on each call to loop().  This makes it hard to watch for inputs.  For example, notice how we check the stop button only after each complete blink cycle.  This means the response time might not be very good (and, in fact, if the user presses and releases the button very quickly, we might miss it altogether).

A state machine approach uses a global variable or two to keep track of what the game should be doing right now.  At each point, we check the state and the inputs to determine if we need to change our state.

```<code>// The BETTER WAY
enum { stopped, blink_on, blink_off } state = stopped;
unsigned long target = 0;

void loop() {
    switch (state) {
        case stopped:
            if (digitalRead(knop1) == LOW) {
                digitalWrite(led1, HIGH);
                state = blink_on;
                target = millis() + 250;
            }
            break;
        case blink_on:
            if (digitalRead(knop2) == LOW) {
                digitalWrite(led1, LOW);
                state = stopped;
            } else if (millis() >= target) {
                digitalWrite(led1, LOW);
                state = blink_off;
                target = millis() + 250;
            }
            break;
        case blink_off:
            if (digitalRead(knop2) == LOW) {
                state = stopped;
            } else if (millis() >= target) {
                digitalWrite(led1, HIGH);
                state = blink_on;
                target = millis() + 250;
            }
            break;
    }
}
</code>```

There are other ways to organize state machine code, but they're basically equivalent.  For example, you might decide to check the inputs before checking the state.  You might also want to factor out the transitions to eliminate the duplicate code.  I haven't done those things in this sample, because I want to make it clear how a state machine works in general.

Once you have your code organized as a state machine, it's relatively easy to respond to any input at any time.

Title: Arduino game "Stop It"

Body:
so I am making this game "stop it" which is a game that (in my case) are 6 led's next to eachother, glowing + making a sound 1 by 1 and every time you press button 1 (knop1), when led 1 burns, the leds start blinking faster.

I have that figured out
But I need a 2nd button (knop2) which you need to be able to press at any time to fully stop the game, but I keep failing on this.
I have tried many things but every one of them failed
Also sorry for a somewhat complex code...

This is the code:

    #define NOTE_E4  330          //Declareren van de noten
    #define NOTE_G4  392
    #define NOTE_A4  440
    #define NOTE_0   000
    //----------------------------------------------------------------------------------------------------------------------------------------
    int noten[] = {               //De noten
    NOTE_E4, NOTE_G4, NOTE_A4, NOTE_E4, NOTE_A4
    };
    //----------------------------------------------------------------------------------------------------------------------------------------
    int duur[] = {                //de duur van elke noot
    225, 225, 950, 225, 925
    };
    //----------------------------------------------------------------------------------------------------------------------------------------
    const int buzzer = 9;         //Hier staat de pin van de buzzer voor het lied
    const int snelheid = 1.5; //Snelheid, een hoger getal laat alles trager gaan, een lager getal laat het sneller gaan

    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;
    int gluid = 9;
    int run = 0;
    int knop = 12;
    int knop2 = 11;
    int n = 220;

    //----------------------------------------------------------------------------------------------------------------------------------------

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(knop, INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("We shall begin. \n   ");
      delay(500);
      for (int i=0;i<5;i++){                //5 staat voor het max aantal noten
      int wacht = duur[i] * (snelheid * 0.9);
      tone(buzzer,noten[i],wacht);          //tone(pin,frequentie,duur)
      delay(wacht);}                        //delay zorgt er hier voor dat de vorige noot niet word afgespeeld tijdens de vorige noot
      delay(100);
      Serial.println("Press the red button to start.");
      Serial.println("You can press the black button any time to stop.");
    }

    //----------------------------------------------------------------------------------------------------------------------------------------

    void loop(){
        if (n <= 10)
        {
          n = 60;
        }

else if (n == 20) {
Serial.begin(9600);
Serial.println("You won! Congratz!");
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, HIGH);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, LOW);
delay(150);
digitalWrite(led6, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led1, HIGH);
delay(150);
digitalWrite(led6, LOW);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
digitalWrite(buzzer, LOW);
n = 10;
digitalWrite(led6, LOW);
digitalWrite(led5, LOW);
digitalWrite(led4, LOW);
digitalWrite(led3, LOW);
digitalWrite(led2, LOW);
digitalWrite(led1, LOW);
digitalWrite(buzzer, LOW);
digitalWrite(gluid, LOW);
n = 220;
delay(500);
}
else
  if(digitalRead(knop) == LOW)
  {

     if(run == 0){
      run = 255;
      Serial.println("Next stage.");
      n = n - 20; }

     else{
      run = 0;
         }
       }
  if(run > 0)

  {
     {
      digitalWrite(led6, HIGH);
      delay(n);
      digitalWrite(led6, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led5, HIGH);
      delay(n);
      digitalWrite(led5, LOW);
      delay(n);
      tone(gluid, 900);
    }
    {
      digitalWrite(led4, HIGH);
      delay(n);
      digitalWrite(led4, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led3, HIGH);
      delay(n);
      digitalWrite(led3, LOW);
      delay(n);
      tone(gluid, 900);
    }
    {
      digitalWrite(led2, HIGH);
      delay(n);
      digitalWrite(led2, LOW);
      delay(n);
      tone(gluid, 700);
    }
    {
      digitalWrite(led1, HIGH);
      delay(n);
      digitalWrite(led1, LOW);
      delay(n);
      tone(gluid, 600);
    }
  }
}

Body:
The key is to re-organize your code into a state machine.  Remember that loop() is going to be called over and over.  Each time it's called, you should check what the current state of the game is and, depending on the inputs, change to the next state and return.

To illustrate, I'll use a much simpler game.  Press the start button to make one LED blink until the stop button is pressed.

// The WRONG WAY
void loop() {
    while (digitalRead(knop1) == HIGH) {}  // wait for start button
    while (digitalRead(knop2) == HIGH) {
        digitalWrite(led1, HIGH);
        delay(250);
        digitalWrite(led1, LOW);
        delay(250);
    }
}

The code above is like your code in that you try to do (almost) everything on each call to loop().  This makes it hard to watch for inputs.  For example, notice how we check the stop button only after each complete blink cycle.  This means the response time might not be very good (and, in fact, if the user presses and releases the button very quickly, we might miss it altogether).

A state machine approach uses a global variable or two to keep track of what the game should be doing right now.  At each point, we check the state and the inputs to determine if we need to change our state.

// The BETTER WAY
enum { stopped, blink_on, blink_off } state = stopped;
unsigned long target = 0;

void loop() {
    switch (state) {
        case stopped:
            if (digitalRead(knop1) == LOW) {
                digitalWrite(led1, HIGH);
                state = blink_on;
                target = millis() + 250;
            }
            break;
        case blink_on:
            if (digitalRead(knop2) == LOW) {
                digitalWrite(led1, LOW);
                state = stopped;
            } else if (millis() >= target) {
                digitalWrite(led1, LOW);
                state = blink_off;
                target = millis() + 250;
            }
            break;
        case blink_off:
            if (digitalRead(knop2) == LOW) {
                state = stopped;
            } else if (millis() >= target) {
                digitalWrite(led1, HIGH);
                state = blink_on;
                target = millis() + 250;
            }
            break;
    }
}

There are other ways to organize state machine code, but they're basically equivalent.  For example, you might decide to check the inputs before checking the state.  You might also want to factor out the transitions to eliminate the duplicate code.  I haven't done those things in this sample, because I want to make it clear how a state machine works in general.

Once you have your code organized as a state machine, it's relatively easy to respond to any input at any time.


问:
How can a looping pygame.mixer playlist be set playing in the background?
I've got a playlist of .ogg music files and I wanna set them playing in the game background on a big playlist loop. So, once all of the music files have been played by pygame.mixer, it loops back to the beginning to start again.

However, when I load the first track, set it playing and then add the other tracks to the queue, only the first track plays. I'm not sure how to get the queue to loop. What am I doing wrong?

```<code>playlist = ["2.ogg", "3.ogg", "1.ogg"]
pygame.mixer.init(frequency = 48000)
pygame.mixer.music.load("1.ogg")
pygame.mixer.music.play()
for track in playlist:
    pygame.mixer.music.queue(track)
</code>```

答:
I try to use queue() but it doesn't work for me.

Maybe it needs for event loop to work but it doesn't work for me too.

In documentation below queue() I found this comment:

This method only queues one music file.

  If you call it and there already is a queued file, it will be overrided.

so queue is not so usefull.

I use pygame.mixer.music.set_endevent() with for event loop to start next track

```<code>import pygame

# define own event type
NEXT = pygame.USEREVENT + 1

playlist = [
    'track_one.ogg',
    'track_two.ogg',
    'track_three.ogg',
    'track_four.ogg',
]

tracks_number = len(playlist)
current_track = 0

pygame.init() # need it for event loop
#screen = pygame.display.set_mode((800,600)) # it can be useful to stop program

pygame.mixer.init(frequency = 48000)

# start first track
pygame.mixer.music.load(playlist[current_track])
pygame.mixer.music.play()

# send event NEXT every time tracks ends
pygame.mixer.music.set_endevent(NEXT)

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == NEXT:

            # get next track (modulo number of tracks)
            current_track = (current_track + 1) % tracks_number

            print("Play:", playlist[current_track])

            pygame.mixer.music.load(playlist[current_track])
            pygame.mixer.music.play()

pygame.quit()
</code>```

Body:
I've got a playlist of .ogg music files and I wanna set them playing in the game background on a big playlist loop. So, once all of the music files have been played by pygame.mixer, it loops back to the beginning to start again.

However, when I load the first track, set it playing and then add the other tracks to the queue, only the first track plays. I'm not sure how to get the queue to loop. What am I doing wrong?

playlist = ["2.ogg", "3.ogg", "1.ogg"]
pygame.mixer.init(frequency = 48000)
pygame.mixer.music.load("1.ogg")
pygame.mixer.music.play()
for track in playlist:
    pygame.mixer.music.queue(track)

Body:
I try to use queue() but it doesn't work for me.

Maybe it needs for event loop to work but it doesn't work for me too.

In documentation below queue() I found this comment:

This method only queues one music file.

  If you call it and there already is a queued file, it will be overrided.

so queue is not so usefull.

I use pygame.mixer.music.set_endevent() with for event loop to start next track

import pygame

# define own event type
NEXT = pygame.USEREVENT + 1

playlist = [
    'track_one.ogg',
    'track_two.ogg',
    'track_three.ogg',
    'track_four.ogg',
]

tracks_number = len(playlist)
current_track = 0

pygame.init() # need it for event loop
#screen = pygame.display.set_mode((800,600)) # it can be useful to stop program

pygame.mixer.init(frequency = 48000)

# start first track
pygame.mixer.music.load(playlist[current_track])
pygame.mixer.music.play()

# send event NEXT every time tracks ends
pygame.mixer.music.set_endevent(NEXT)

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == NEXT:

            # get next track (modulo number of tracks)
            current_track = (current_track + 1) % tracks_number

            print("Play:", playlist[current_track])

            pygame.mixer.music.load(playlist[current_track])
            pygame.mixer.music.play()

pygame.quit()


问:
WPF - Clipping ContentControl inside Canvas
I have a ContentControl and its content is a custom FrameworkElement. FrameworkElement has only one child and it is a DrawingVisual. Basicly the ContentControl is a container for the DrawingVisual(which contains shapes) and ContentControl has the thumbs that the user use to drag, resize, rotate the control. ContentControl is added to a Canvas to display. I want to set clipping region of the ContentControl to a specific region in the Canvas. However when I set the Clip property of ContentControl to this region(RectangleGeometry specified in Canvas coordinate system) the DrawingVisual inside the ContentControl is clipped as if the given region is in the coordinate system of the ContentControl.

I can constrain the user to drag only inside this region but i don't want to do that. I want the user to be able drag outside and when a part of ContentControl is outside I don't want that part to be rendered. How can I do this?

答: create an intermediate contentcontrol in the canvas, position this to be where you want things to clip, set cliptobounds=true on it, put your existing contentcontrol inside of it.</p>


问:
Writing a custom loss function without y_true in Keras
I'm implementing a triplet loss function in Keras. In general, loss functions take predicted values with ground truth as arguments. But triplet loss doesn't use labels, just the output. I tried to write the function with just one parameter:

```<code>def triplet_loss(y_pred):
    margin = 1
    return K.mean(K.square(y_pred[0]) - K.square(y_pred[1]) + margin)
</code>```

It failed saying triplet_loss() takes 1 argument but two arguments were given (in score_array = fn(y_true, y_pred). When I write the function with two arguments y_true, y_pred, the program runs without error. Why is that? Should I just implement this function with these two arguments although y_true won't be used? Is this correct or is there another way of doing it?

答:
Well.... simply don't use the ground truth:

```<code>def triplet_loss(y_true,y_pred):
    #all your code as it is.
</code>```

It's not very usual to have networks trained without ground truth. When we expect it to learn something, there is very very often a ground truth. If you don't, simply ignore it.

Also, if y_true is ignored, what are you passing to the fit method? Just a dummy array?

Body:
I'm implementing a triplet loss function in Keras. In general, loss functions take predicted values with ground truth as arguments. But triplet loss doesn't use labels, just the output. I tried to write the function with just one parameter:

def triplet_loss(y_pred):
    margin = 1
    return K.mean(K.square(y_pred[0]) - K.square(y_pred[1]) + margin)

It failed saying triplet_loss() takes 1 argument but two arguments were given (in score_array = fn(y_true, y_pred). When I write the function with two arguments y_true, y_pred, the program runs without error. Why is that? Should I just implement this function with these two arguments although y_true won't be used? Is this correct or is there another way of doing it?

Body:
Well.... simply don't use the ground truth:

def triplet_loss(y_true,y_pred):
    #all your code as it is.

It's not very usual to have networks trained without ground truth. When we expect it to learn something, there is very very often a ground truth. If you don't, simply ignore it.

Also, if y_true is ignored, what are you passing to the fit method? Just a dummy array?


问:
what is "PGC-I-0222-Redundant definition for symbol"
how to solve pgcc&openacc linker error "__pgi_uacc_multicorestart", "__pgi_uacc_multicoreend"

This is a follow up question after the one above.

In "compile lbe.c to lbe.o message:", I always see the "PGC-I-0222-Redundant definition" message. Is it a warning or error? Why would it happen? How do I fix it?

```<code>PGC-I-0222-Redundant definition for symbol __THROW (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 74)
PGC-I-0222-Redundant definition for symbol __extension__ (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 358)
</code>```

答: There are just information messages indicating that the symbols are getting defined twice.  Since it's the same definition for both, it's fine and no need to fix.</p>

Body:
how to solve pgcc&openacc linker error "__pgi_uacc_multicorestart", "__pgi_uacc_multicoreend"

This is a follow up question after the one above.

In "compile lbe.c to lbe.o message:", I always see the "PGC-I-0222-Redundant definition" message. Is it a warning or error? Why would it happen? How do I fix it?

PGC-I-0222-Redundant definition for symbol __THROW (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 74)
PGC-I-0222-Redundant definition for symbol __extension__ (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 358)


问:
Mapping SQL query behind a button click(oracle apex)
I am trying to build a GUI for my data base . I have uploaded my data on apex.oracle , i can apply queries and get the data i want .What i want next is to create GUI with buttons and a display form so that when user  clicks the button a sql query executes in the back end and result is showed in the display form.Is there any tutorial online for that?

Any help would be appreciated

Update
I read the manual . I have watched many youtube tutorials but my GUI is different .I thing i need to change my view to "Component view".But i cant find the icon
here is sreen shot from manual
enter image description here

and below is my GUI

enter image description here

Basically when i create a new form on the same page .But when i click on "+"(in region tab) my page automatically adds it as a "static content".
As in the video below
https://www.youtube.com/watch?v=Nm5sVJpeZ8c
i want  a new window to pop when creating button ,text field,form on the same page.But my app automatically adds it and i have to change attributes after the addition.
I just want a simple search form as shown in the video

答:
Maybe an Apex manual?

This one is "Application Express Application Builder User's Guide"

https://docs.oracle.com/database/122/HTMDB/toc.htm

Bobby


问:
Is horizontal size class still compact for iPhone 7 Plus on landscape?
As per references like this or this, I take that iPhone 7 Plus on landscape should have regular size class.

This is the code in the current view controller, as per this reference:

```<code>- (void) traitCollectionDidChange: (UITraitCollection *) previousTraitCollection {
    [super traitCollectionDidChange: previousTraitCollection];
    NSLog(@"current trait collection: %@",self.traitCollection);
    NSLog(@"previous trait collection: %@", previousTraitCollection);
}
</code>```

And this is the output on the console when going from portrait to landscape on iPhone 7 Plus:

```<code>current trait collection: <UITraitCollection: 0x1c44efd00; _UITraitNameUserInterfaceIdiom = Phone, _UITraitNameDisplayScale = 3.000000, _UITraitNameDisplayGamut = P3, _UITraitNameHorizontalSizeClass = Compact, _UITraitNameVerticalSizeClass = Compact, _UITraitNameTouchLevel = 0, _UITraitNameInteractionModel = 1, _UITraitNameUserInterfaceStyle = 1, _UITraitNameUserInterfaceLayoutDirection = 0, _UITraitNameForceTouchCapability = 2, _UITraitNamePreferredContentSizeCategory = UICTContentSizeCategoryL, _UITraitNameDisplayCornerRadius = 0.000000>
previous trait collection: <UITraitCollection: 0x1c02fa900; _UITraitNameUserInterfaceIdiom = Phone, _UITraitNameDisplayScale = 3.000000, _UITraitNameDisplayGamut = P3, _UITraitNameHorizontalSizeClass = Compact, _UITraitNameVerticalSizeClass = Regular, _UITraitNameTouchLevel = 0, _UITraitNameInteractionModel = 1, _UITraitNameUserInterfaceStyle = 1, _UITraitNameUserInterfaceLayoutDirection = 0, _UITraitNameForceTouchCapability = 2, _UITraitNamePreferredContentSizeCategory = UICTContentSizeCategoryL, _UITraitNameDisplayCornerRadius = 0.000000>
</code>```

The horizontal size class remains compact and I expected change from compact to regular.

Using iOS 11.1.2 and Xcode 9.1

答:
Do you have display zoom turned on for the device?

https://help.apple.com/iphone/11/#/iphd6804774e

In "Standard" mode, the horizontal size class in landscape will be Regular.  In "Zoomed" mode, it will be Compact.

Body:
As per references like this or this, I take that iPhone 7 Plus on landscape should have regular size class.

This is the code in the current view controller, as per this reference:

- (void) traitCollectionDidChange: (UITraitCollection *) previousTraitCollection {
    [super traitCollectionDidChange: previousTraitCollection];
    NSLog(@"current trait collection: %@",self.traitCollection);
    NSLog(@"previous trait collection: %@", previousTraitCollection);
}

And this is the output on the console when going from portrait to landscape on iPhone 7 Plus:

current trait collection: <UITraitCollection: 0x1c44efd00; _UITraitNameUserInterfaceIdiom = Phone, _UITraitNameDisplayScale = 3.000000, _UITraitNameDisplayGamut = P3, _UITraitNameHorizontalSizeClass = Compact, _UITraitNameVerticalSizeClass = Compact, _UITraitNameTouchLevel = 0, _UITraitNameInteractionModel = 1, _UITraitNameUserInterfaceStyle = 1, _UITraitNameUserInterfaceLayoutDirection = 0, _UITraitNameForceTouchCapability = 2, _UITraitNamePreferredContentSizeCategory = UICTContentSizeCategoryL, _UITraitNameDisplayCornerRadius = 0.000000>
previous trait collection: <UITraitCollection: 0x1c02fa900; _UITraitNameUserInterfaceIdiom = Phone, _UITraitNameDisplayScale = 3.000000, _UITraitNameDisplayGamut = P3, _UITraitNameHorizontalSizeClass = Compact, _UITraitNameVerticalSizeClass = Regular, _UITraitNameTouchLevel = 0, _UITraitNameInteractionModel = 1, _UITraitNameUserInterfaceStyle = 1, _UITraitNameUserInterfaceLayoutDirection = 0, _UITraitNameForceTouchCapability = 2, _UITraitNamePreferredContentSizeCategory = UICTContentSizeCategoryL, _UITraitNameDisplayCornerRadius = 0.000000>

The horizontal size class remains compact and I expected change from compact to regular.

Using iOS 11.1.2 and Xcode 9.1