问:
How to properly format working javascript for Code by Zapier
I'm trying to recreate a simple javascript for loop to run in Zapier.

My Javascript skills would likely place me as "experienced but still newbish", so converting this to function correctly in Zapier has proven rather difficult. My code operates as expected until I attempt to rewrite it using Zapier's requirements.

For the example below, I have substituted the inputData with dummy text in "input".

Here's an example of my working model in JS:

```<code>const input = "Company Name: Shire Homes, Inc. | First Name: Frodo
| Last Name: Baggins |"
const fout = input.match(/\: (.*?) \|/g)

for (let i = 0; i < fout.length; i++) {
  console.log(fout[i].slice(2, -2))
}
</code>```

Which logs:

Shire Homes, Inc.
Frodo
Baggins

Since Zapier requires the data to be returned, instead of iterating over each string against the regex, I only get the first string and then it stops. How would one rewrite this to function correctly in Zapier?

I need to return each iteration as a string value since I'm going to be inserting the data elsewhere.

Thanks in advance!

答:
Great question!

Instead of just iterating over the matches, you want to do something with each of them and get the result. The best way to do this is the .map function (docs).

And like you mentioned, you need to return something from the whole function. There are a few options and which you want depends on what the eventual Zap will do.

If you want the output to be a single string (such as "Shire Homes, Inc.,Frodo,Baggins") to use it all at once, then you'll want to join it.

If you want to use each item separately (such as one step writes "shire" while another writes ("frodo"), you'll return them as an array and the result will fan out. It's unlikely you want this.

If you want to use each separately in subsequent zaps (the most likely option), then you'll want to put it in an object.

So let's look at the code!

// this is handled by Zapier already, but we need the variable to test it
const inputData = {text: "Company Name: Shire Homes, Inc. | First Name: Frodo | Last Name: Baggins |"}
const rawSegments = inputData.text.match(/\: (.*?) \|/g)

const segments = rawSegments.map(s => s.slice(2, -2))

// probably want to return an object

// option 1
// return {result: segments.join('')}

// option 2; probably don't want this
// return segments

// option 3; probably the best, but depends on the data being in the same order every time
return {
  company: segments[0],
  fname: segments[1],
  lname: segments[2]
}
```

There's some JS shorthand in there, but hopefully it's clear what's going on.

Body:
I'm trying to recreate a simple javascript for loop to run in Zapier.

My Javascript skills would likely place me as "experienced but still newbish", so converting this to function correctly in Zapier has proven rather difficult. My code operates as expected until I attempt to rewrite it using Zapier's requirements.

For the example below, I have substituted the inputData with dummy text in "input".

Here's an example of my working model in JS:

const input = "Company Name: Shire Homes, Inc. | First Name: Frodo
| Last Name: Baggins |"
const fout = input.match(/\: (.*?) \|/g)

for (let i = 0; i < fout.length; i++) {
  console.log(fout[i].slice(2, -2))
}

Which logs:

Shire Homes, Inc.
Frodo
Baggins

Since Zapier requires the data to be returned, instead of iterating over each string against the regex, I only get the first string and then it stops. How would one rewrite this to function correctly in Zapier?

I need to return each iteration as a string value since I'm going to be inserting the data elsewhere.

Thanks in advance!

Body:
Great question!

Instead of just iterating over the matches, you want to do something with each of them and get the result. The best way to do this is the .map function (docs).

And like you mentioned, you need to return something from the whole function. There are a few options and which you want depends on what the eventual Zap will do.

If you want the output to be a single string (such as "Shire Homes, Inc.,Frodo,Baggins") to use it all at once, then you'll want to join it.

If you want to use each item separately (such as one step writes "shire" while another writes ("frodo"), you'll return them as an array and the result will fan out. It's unlikely you want this.

If you want to use each separately in subsequent zaps (the most likely option), then you'll want to put it in an object.

So let's look at the code!

// this is handled by Zapier already, but we need the variable to test it
const inputData = {text: "Company Name: Shire Homes, Inc. | First Name: Frodo | Last Name: Baggins |"}
const rawSegments = inputData.text.match(/\: (.*?) \|/g)

const segments = rawSegments.map(s => s.slice(2, -2))

// probably want to return an object

// option 1
// return {result: segments.join('')}

// option 2; probably don't want this
// return segments

// option 3; probably the best, but depends on the data being in the same order every time
return {
  company: segments[0],
  fname: segments[1],
  lname: segments[2]
}

There's some JS shorthand in there, but hopefully it's clear what's going on.


来源: stackexchange

问:
wsHttpBinding not supported by silverlight
How do people typically do session with WCF if this binding isn't supported in silverlight?</p>

答: Silverlight supports BasicHttpBinding and PollingDuplexHttpBinding (if you need duplex). Check out this MSDN post.</p>

ContentLicense: CC BY-SA 3.0


问:
Adding dynamically third party javascript widgets to the web app
I am working on a React js project where I should dynamically add third party scripts (widgets) to the web app.

Widgets include any kind of third party platforms: Twitter, Instagram, Youplay, Youtube etc.

The current code that I have looks like this:

```<code>    appendThirdPartyScript(externalScript) {
    // Create an element outside the document to parse the string with
    const head = document.createElement("head");

    // Parse the string
    head.innerHTML = externalScript;

    // Copy those nodes to the real `head`, duplicating script elements so
    // they get processed
    let node = head.firstChild;
    while (node) {
        const next = node.nextSibling;
        if (node.tagName === "SCRIPT") {
            // Just appending this element wouldn't run it, we have to make a fresh copy
            const newNode = document.createElement("script");
            if (node.src) {
                newNode.src = node.src;
            }
            while (node.firstChild) {
                // Note we have to clone these nodes
                newNode.appendChild(node.firstChild.cloneNode(true));
                node.removeChild(node.firstChild);
            }
            node = newNode;
        }
        document.head.appendChild(node);
        node = next;
    }
}
</code>```

So basically the scripts urls comes from the backend/api and that is a list of scripts smth like ['http://twitter-widget.js', 'http://instagram-widget.js']

So since I have an array of scripts as string I use a for loop to go thru each of element and call appendThirdPartyScript('somescript')

```<code>data.externalScripts.map(script => {
      this.appendThirdPartyScript("" + script);
});
</code>```

This solution worked for almost all cases until I came to this case:
['http://embed.tt.se/v10/tt-widget.js', 'new tt.TTWidget({WhereToAddWidget: 'tt-quiz-XMuxmuWHc',type: 'quiz',ID: 'xxx',clientID: 'xxx',});']

So basically the error I get is:

tt is not a function

I am assuming that the first script hasn't completed loading (in this case http://embed.tt.se/v10/tt-widget.js) and the next one is trying to call something that does not exists.

When I try to hard code http://embed.tt.se/v10/tt-widget.js within head tag in index.html directly than it works!

So this approach of dynamically adding third party widgets is not reliable. Anyone can let me know if my current code needs to be changed or any suggestion would be pretty much appreciated!

答:
This seems to work but probably not best solution:</p>

```<code> const delayTime = 500;
    externalScriptArray.forEach((script, index) => {
        setTimeout(() => {
            this.appendNewTagElementToDom(script);
        }, delayTime*index);
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a React js project where I should dynamically add third party scripts (widgets) to the web app.

Widgets include any kind of third party platforms: Twitter, Instagram, Youplay, Youtube etc.

The current code that I have looks like this:

    appendThirdPartyScript(externalScript) {
    // Create an element outside the document to parse the string with
    const head = document.createElement("head");

    // Parse the string
    head.innerHTML = externalScript;

    // Copy those nodes to the real `head`, duplicating script elements so
    // they get processed
    let node = head.firstChild;
    while (node) {
        const next = node.nextSibling;
        if (node.tagName === "SCRIPT") {
            // Just appending this element wouldn't run it, we have to make a fresh copy
            const newNode = document.createElement("script");
            if (node.src) {
                newNode.src = node.src;
            }
            while (node.firstChild) {
                // Note we have to clone these nodes
                newNode.appendChild(node.firstChild.cloneNode(true));
                node.removeChild(node.firstChild);
            }
            node = newNode;
        }
        document.head.appendChild(node);
        node = next;
    }
}

So basically the scripts urls comes from the backend/api and that is a list of scripts smth like ['http://twitter-widget.js', 'http://instagram-widget.js']

So since I have an array of scripts as string I use a for loop to go thru each of element and call appendThirdPartyScript('somescript')

data.externalScripts.map(script => {
      this.appendThirdPartyScript("" + script);
});

This solution worked for almost all cases until I came to this case:
['http://embed.tt.se/v10/tt-widget.js', 'new tt.TTWidget({WhereToAddWidget: 'tt-quiz-XMuxmuWHc',type: 'quiz',ID: 'xxx',clientID: 'xxx',});']

So basically the error I get is:

tt is not a function

I am assuming that the first script hasn't completed loading (in this case http://embed.tt.se/v10/tt-widget.js) and the next one is trying to call something that does not exists.

When I try to hard code http://embed.tt.se/v10/tt-widget.js within head tag in index.html directly than it works!

So this approach of dynamically adding third party widgets is not reliable. Anyone can let me know if my current code needs to be changed or any suggestion would be pretty much appreciated!

Body:
This seems to work but probably not best solution:

 const delayTime = 500;
    externalScriptArray.forEach((script, index) => {
        setTimeout(() => {
            this.appendNewTagElementToDom(script);
        }, delayTime*index);
    });


问:
Module six not found, although module six is installed
I cannot run jupyter lab as it complains about module six. Module six is already installed with conda. I even tried to install with pip too, but it says it is already installed and doesn't do anything. So, what to do here?

```<code>jupyter lab
Traceback (most recent call last):
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\ilyas\Anaconda3\Scripts\jupyter-lab.EXE\__main__.py", line 5, in <module>
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyterlab\labapp.py", line 11, in <module>
    from jupyter_core.application import JupyterApp, base_aliases
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyter_core\application.py", line 30, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\__init__.py", line 1, in <module>
    from .traitlets import *
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\traitlets.py", line 57, in <module>
    import six
ModuleNotFoundError: No module named 'six'
</code>```

I tried to remove with conda, and then re-install but that also did not work:

```<code>conda remove six
RemoveError: This operation will remove conda without replacing it with
another version of conda.
</code>```

Install with pip:

```<code>pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

python -m pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)
</code>```

Environment:

Windows 10

python 3.7

jupyter-lab 1.0.0a3

six 1.12.0

答:
Tried the following but still NOT solved:

I had to do this in the following error:

```<code>pip uninstall six

pip install six
</code>```

Then I get the the ModuleNotFoundError: No module named 'jupyter_server' error.

So I install jupyter_server with conda, and now the jupyter lab is working.

```<code>conda install -c conda-forge jupyter_server
</code>```

Even though the notebook is opening, I could not import packages. Checking the command prompt was showing the jupyterlab-manager was outdated. So, did the following:

```<code>jupyter labextension install @jupyter-widgets/jupyterlab-manager
</code>```

Still, the notebook opens but cannot do anything with it.

Body:
I cannot run jupyter lab as it complains about module six. Module six is already installed with conda. I even tried to install with pip too, but it says it is already installed and doesn't do anything. So, what to do here?

jupyter lab
Traceback (most recent call last):
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\ilyas\Anaconda3\Scripts\jupyter-lab.EXE\__main__.py", line 5, in <module>
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyterlab\labapp.py", line 11, in <module>
    from jupyter_core.application import JupyterApp, base_aliases
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyter_core\application.py", line 30, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\__init__.py", line 1, in <module>
    from .traitlets import *
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\traitlets.py", line 57, in <module>
    import six
ModuleNotFoundError: No module named 'six'

I tried to remove with conda, and then re-install but that also did not work:

conda remove six
RemoveError: This operation will remove conda without replacing it with
another version of conda.

Install with pip:

pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

python -m pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

Environment:

Windows 10

python 3.7

jupyter-lab 1.0.0a3

six 1.12.0

Body:
Tried the following but still NOT solved:

I had to do this in the following error:

pip uninstall six

pip install six

Then I get the the ModuleNotFoundError: No module named 'jupyter_server' error.

So I install jupyter_server with conda, and now the jupyter lab is working.

conda install -c conda-forge jupyter_server

Even though the notebook is opening, I could not import packages. Checking the command prompt was showing the jupyterlab-manager was outdated. So, did the following:

jupyter labextension install @jupyter-widgets/jupyterlab-manager

Still, the notebook opens but cannot do anything with it.


问:
Looking for Woocommerce bulk pricing quantity ranges database table
I'm importing a Wordpress database into my own database and I need to match wordpress tables and columns to my database tables and columns. I need to find the woocommerce bulk pricing quantity ranges and prices.

I've checked all Woocommerce tables starting with wp_woocommerce… and the wp_posts table and a bunch of others but I can't find them. The normal prices are in wp_postmeta where meta_key like "%price%" but the quantity ranges don't seem to be in this table.

On WooCommerce > status under "active plugins" it says WooCommerce Dynamic Pricing & Discounts -> RightPress

At Woocommerce > Pricing and Discounts i see this:

which is the info i'm trying to find

And you can see the result here.

答: it's here: select * from wp_options where option_name like "%rp_wcdpd_settings%"


问:
How do I obtain an element from a dataframe only if there's a corresponding element in another dataframe?
```<code>first_df['Abbrev'] = ['HW', 'GB', 'TT']
first_df['Val'] = ['Hello World', 'Good Bye', '']

second_df['Value'] = ['Hello World', 'Good Bye', 'Good Bye']
</code>```

and my expected output is:

```<code>output_df['result'] = ['HW', 'GB', 'GB']
</code>```

I've tried using:

```<code>output_df['result'] = first_df[first_df.Val.isin(second_df.Value)]
if first_df['Abbrev']:
    return output_df['result']
</code>```

which doesn't produce desirable results.

答:
Using map

```<code>second_df['Value'].map(dict(zip(first_df['Val'],first_df['Abbrev'])))
</code>```

Body:
first_df['Abbrev'] = ['HW', 'GB', 'TT']
first_df['Val'] = ['Hello World', 'Good Bye', '']

second_df['Value'] = ['Hello World', 'Good Bye', 'Good Bye']

and my expected output is:

output_df['result'] = ['HW', 'GB', 'GB']

I've tried using:

output_df['result'] = first_df[first_df.Val.isin(second_df.Value)]
if first_df['Abbrev']:
    return output_df['result']

which doesn't produce desirable results.

Body:
Using map

second_df['Value'].map(dict(zip(first_df['Val'],first_df['Abbrev'])))


问:
Why the folder has been created everytime I save an image in Laravel?
After going through a lot of documentation I am able to save an image in Laravel.

But now I am getting an error that every time I save the image it got saved in a separate folder created for that image.

So if I save an image it got saved like

http://localhost/storage/uploads/phpAC6E.tmp.jpg/gedmQBjYgGecrqiuJol6wQs0BKkkMuCko91opWvi.jpeg

Notice the folder phpAC6E.tmp.jpg got created automatically.

The question here is not what I am looking for.

I don't know where I am going wrong I had tried many things but it doesn't work. Below are my code snippets :

filesystem.php configuration-

```<code>'local' => [
            'driver' => 'local',
            'root' => storage_path('app/public/uploads'),
            'url' => env('APP_URL').'/storage/uploads',
            'visibility' => 'private',
        ],
</code>```

My controller function-

```<code>public function save(Request $request){

        $file = $request->file('image');

        $ext = $file->getClientOriginalExtension();
        $path = Storage::disk('local')->put($file->getFilename().'.'. $ext,  $request->file('image'));

        return Storage::url($path);

    }
</code>```

The folders have been created like this.

答:
why not try this code. its working properly. it saves in the public folder by creating first attachment folder outside the root of the domain and saving the file inside. if you would want to save inthe public folder then change to: </p>

```<code>$file->move(public_path('attachments'), $name);

if($request->hasfile('filename'))
{
   $file=$request->file('filename');

   $name=$file->getClientOriginalName();
   $file->move(public_path().'/attachments', $name);
   DB::table('tblname')->insert([
   'filename' => $name,
 ]);

}
</code>```

Body:
After going through a lot of documentation I am able to save an image in Laravel.

But now I am getting an error that every time I save the image it got saved in a separate folder created for that image.

So if I save an image it got saved like

http://localhost/storage/uploads/phpAC6E.tmp.jpg/gedmQBjYgGecrqiuJol6wQs0BKkkMuCko91opWvi.jpeg

Notice the folder phpAC6E.tmp.jpg got created automatically.

The question here is not what I am looking for.

I don't know where I am going wrong I had tried many things but it doesn't work. Below are my code snippets :

filesystem.php configuration-

'local' => [
            'driver' => 'local',
            'root' => storage_path('app/public/uploads'),
            'url' => env('APP_URL').'/storage/uploads',
            'visibility' => 'private',
        ],

My controller function-

public function save(Request $request){

        $file = $request->file('image');

        $ext = $file->getClientOriginalExtension();
        $path = Storage::disk('local')->put($file->getFilename().'.'. $ext,  $request->file('image'));

        return Storage::url($path);

    }

The folders have been created like this.

Body:
why not try this code. its working properly. it saves in the public folder by creating first attachment folder outside the root of the domain and saving the file inside. if you would want to save inthe public folder then change to:

$file->move(public_path('attachments'), $name);

if($request->hasfile('filename'))
{
   $file=$request->file('filename');

   $name=$file->getClientOriginalName();
   $file->move(public_path().'/attachments', $name);
   DB::table('tblname')->insert([
   'filename' => $name,
 ]);

}


问:
jquery scroll to div and focus a textbox
I am trying to achieve two things with a single onclick of anchor tag. First, when I click on search, I am scrolling to a particular div, and then trying to focus on the textbox within that div. Below is the link to the sample code. I am able to scroll to the div, but somehow the textbox is losing focus. What is wrong with the code?

http://jsfiddle.net/e9tJ5/1/

答:
You need to prevetDefault.

```<code>$("#searchlink").click(function(e){
 e.preventDefault();
 $("#searchtext").focus();
});
</code>```

Return false also does the same.

Check working example at http://jsfiddle.net/e9tJ5/5/

Body:
You need to prevetDefault.

$("#searchlink").click(function(e){
 e.preventDefault();
 $("#searchtext").focus();
});

Return false also does the same.

Check working example at http://jsfiddle.net/e9tJ5/5/


问:
How to send a number over serial to an arduino?
I'm trying to send a number value over serial to an Arduino to control an Individually Addressable LEDstrip. Using the Arduino IDE "Serial Monitor" I'm able to send a number to the light strip with no issue. However when i try to do it externally by reading from a text file in processing it doesn't go through.

After some debugging I can see that Processing has the number right and its stored in the variable. However the lightstip will only ever light up on led, instead of the number given.

Processing Code:

import processing.serial.*;
import java.io.*;

Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}
void draw()
{
  while(true) {
  // Read data from the file
  {
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println(number);
    myPort.write(number);
    delay(5000);
  }
  }
}
```

<p>Arduino Code:</p>

<pre class="lang-c prettyprint-override"><code>if ( Serial.available()) // Check to see if at least one character is available
  {
    char ch = Serial.read();
      if(index <  3 && ch >= '0' && ch <= '9'){
      strValue[index++] = ch;
      }
      else
      {
        Lnum = atoi(strValue);
        Serial.println(Lnum);
        for(i = 0; i < 144; i++)
        {
          leds[i] = CRGB::Black;
          FastLED.show();
          delay(1);

        }
        re = 1;
        index = 0;
        strValue[index] = 0;
        strValue[index+1] = 0;
        strValue[index+2] = 0;
    }
  }
</code>```

What I want the program to do is read a number from a text file and light up that number of LEDs on the 144led lightstrip.

答:
Here are a couple of comments on your code that should help make improvements in the future. It's important to form good coding habits early on: it will make your life so much easier (I'm speaking a mostly self taught programmer that started with flash so I know what messy and hacky is ;) )

```<code>import processing.serial.*;
//import java.io.*; // don't include unused imports

Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
}
void draw()
{
  // don't use blocking while, draw() already gets called continuously
  //while(true) {
  // Read data from the file
  //{
    // don't load the file over and over again
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);// int(lines[0]) works in Processing, but the Java approach is ok too
    println("parsed number: " + number);
    if(myPort != null){
      myPort.write(number);
    }
    // don't use blocking delays, ideally not even in Arduino
    //delay(5000);
  //}
  //}
}
</code>```

Here's a version of the Processing code that loads the text file, parses the integer then sends it to serial only once (if everything is ok, otherwise basic error checking should reveal debug friendly information):

```<code>import processing.serial.*;
Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
  // Read data from the file
  try{
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println("parsed number: " + number);
    // validate the data, just in case something went wrong
    if(number < 0 && number > 255){
      println("invalid number: " + number + ", expecting 0-255 byte sized values only");
      return;
    }
    if(myPort != null){
      myPort.write(number);
    }
  }catch(Exception e){
    println("Error loading text file");
    e.printStackTrace();
  }
}
void draw()
{
  // display the latest value if you want
}

// add a keyboard shortcut to reload if you need to
</code>```

Your strip has 144 leds (less than 255) which fits nicely in a single byte which is what the Processing sketch sends

On the Arduino side there's nothing too crazy going on, so as long as you validate the data coming in should be fine:

```<code>#include "FastLED.h"

#define NUM_LEDS 64
#define DATA_PIN 7
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

int numLEDsLit = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("resetting");
  LEDS.addLeds<WS2812,DATA_PIN,RGB>(leds,NUM_LEDS);
  LEDS.setBrightness(84);
}

void loop() {
  updateSerial();
  updateLEDs();
}

void updateSerial(){
  // if there's at least one byte to read
  if( Serial.available() > 0 )
  {
    // read it and assign it to the number of LEDs to light up
    numLEDsLit = Serial.read();
    // constrain to a valid range (just in case something goes funny and we get a -1, etc.)
    numLEDsLit = constrain(numLEDsLit,0,NUM_LEDS);
  }
}

// uses blacking delay
void updateLEDs(){
  // for each LED
  for(int i = 0; i < 144; i++)
  {
    // light up only the number of LEDs received via Serial, turn the LEDs off otherwise
    if(i < numLEDsLit){
      leds[i] = CRGB::White;
    }else{
      leds[i] = CRGB::Black;
    }
    FastLED.show();
    delay(1);
  }
}
</code>```

Adjust the pins/LED chipsets/etc. based on your actual physical setup.

Body:
I'm trying to send a number value over serial to an Arduino to control an Individually Addressable LEDstrip. Using the Arduino IDE "Serial Monitor" I'm able to send a number to the light strip with no issue. However when i try to do it externally by reading from a text file in processing it doesn't go through.

After some debugging I can see that Processing has the number right and its stored in the variable. However the lightstip will only ever light up on led, instead of the number given.

Processing Code:

import processing.serial.*;
import java.io.*;

Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}
void draw()
{
  while(true) {
  // Read data from the file
  {
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println(number);
    myPort.write(number);
    delay(5000);
  }
  }
}

Arduino Code:

if ( Serial.available()) // Check to see if at least one character is available
  {
    char ch = Serial.read();
      if(index <  3 && ch >= '0' && ch <= '9'){
      strValue[index++] = ch;
      }
      else
      {
        Lnum = atoi(strValue);
        Serial.println(Lnum);
        for(i = 0; i < 144; i++)
        {
          leds[i] = CRGB::Black;
          FastLED.show();
          delay(1);

        }
        re = 1;
        index = 0;
        strValue[index] = 0;
        strValue[index+1] = 0;
        strValue[index+2] = 0;
    }
  }

What I want the program to do is read a number from a text file and light up that number of LEDs on the 144led lightstrip.

Body:
Here are a couple of comments on your code that should help make improvements in the future. It's important to form good coding habits early on: it will make your life so much easier (I'm speaking a mostly self taught programmer that started with flash so I know what messy and hacky is ;) )

import processing.serial.*;
//import java.io.*; // don't include unused imports

Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
}
void draw()
{
  // don't use blocking while, draw() already gets called continuously
  //while(true) {
  // Read data from the file
  //{
    // don't load the file over and over again
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);// int(lines[0]) works in Processing, but the Java approach is ok too
    println("parsed number: " + number);
    if(myPort != null){
      myPort.write(number);
    }
    // don't use blocking delays, ideally not even in Arduino
    //delay(5000);
  //}
  //}
}

Here's a version of the Processing code that loads the text file, parses the integer then sends it to serial only once (if everything is ok, otherwise basic error checking should reveal debug friendly information):

import processing.serial.*;
Serial myPort;  // Create object from Serial class

void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
  // Read data from the file
  try{
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println("parsed number: " + number);
    // validate the data, just in case something went wrong
    if(number < 0 && number > 255){
      println("invalid number: " + number + ", expecting 0-255 byte sized values only");
      return;
    }
    if(myPort != null){
      myPort.write(number);
    }
  }catch(Exception e){
    println("Error loading text file");
    e.printStackTrace();
  }
}
void draw()
{
  // display the latest value if you want
}

// add a keyboard shortcut to reload if you need to

Your strip has 144 leds (less than 255) which fits nicely in a single byte which is what the Processing sketch sends

On the Arduino side there's nothing too crazy going on, so as long as you validate the data coming in should be fine:

#include "FastLED.h"

#define NUM_LEDS 64
#define DATA_PIN 7
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

int numLEDsLit = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("resetting");
  LEDS.addLeds<WS2812,DATA_PIN,RGB>(leds,NUM_LEDS);
  LEDS.setBrightness(84);
}

void loop() {
  updateSerial();
  updateLEDs();
}

void updateSerial(){
  // if there's at least one byte to read
  if( Serial.available() > 0 )
  {
    // read it and assign it to the number of LEDs to light up
    numLEDsLit = Serial.read();
    // constrain to a valid range (just in case something goes funny and we get a -1, etc.)
    numLEDsLit = constrain(numLEDsLit,0,NUM_LEDS);
  }
}

// uses blacking delay
void updateLEDs(){
  // for each LED
  for(int i = 0; i < 144; i++)
  {
    // light up only the number of LEDs received via Serial, turn the LEDs off otherwise
    if(i < numLEDsLit){
      leds[i] = CRGB::White;
    }else{
      leds[i] = CRGB::Black;
    }
    FastLED.show();
    delay(1);
  }
}

Adjust the pins/LED chipsets/etc. based on your actual physical setup.


问:
Unexpected behavior with ViewScoped beans when using Spring-Session clustering with Hazelcast
I am working on introducing clustering to a JSF based Spring-Boot web application and as soon as we enabled session-replication with Hazelcast, we started noticing that several of our JSF pages that utilize ViewScoped beans were no longer functioning correctly.  If we disable session replication and Hazelcast the odd behavior no longer occurs.

I first noticed the problem in one of our pages that utilizes a PrimeFaces Wizard component.  Values entered on the first page of the wizard are lost when the second page is "submitted".

Then on a different page I noticed that a command button was no longer calling the actionListener method on the managed bean.  I set a breakpoint in the method and the breakpoint is never hit, but the page "blinks" and refreshes back to its initial state.  I did note that the PostConstruct method on the managed bean is NOT called again, so it is not generating a new instance of the ViewScoped bean.

None of these problems occur when I disable session replication and Hazelcast though.  As far as I can tell, inspecting the session and its contents, it does look like sessions are being created and properly stored, as far as I can tell anyway.

The app is a Spring-Boot web application using the joinfaces starters to bring in JSF 2.3.7 (Mojarra), PrimeFaces 6.2, and Omnifaces 1.14.1.  We initially developed the app without any session-replication in place and we had no problems with our ViewScoped beans.

The ViewScoped beans are using org.springframework.stereotype.Component annotation, just like you see in the joinfaces examples, and javax.faces.view.ViewScoped as the scope annotation.  I have also tried bringing in Weld and using the @Named annotation as well as falling back on the old deprecated JSF @ManagedBean and @ViewScoped annotations, but the same behavior persists in all cases.

I have gone through and ensured that our ManagedBeans are all fully serializable as well as any attributes on the beans themselves.

To demonstrate what I am seeing I picked two very simple examples from a couple places on the web and created a simple Spring-Boot project that you can clone and run yourself.

https://github.com/illingtonFlex/ViewScopeDemo

This demo app contains two managed beans and two xhtml files.

The first example is one that a copied from an example on BalusC's website:
http://balusc.omnifaces.org/2010/06/benefits-and-pitfalls-of-viewscoped.html

The xhtml file looks like this:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<h:head>
    <title>Really simple CRUD</title>
</h:head>
<h:body>
    <h3>List items</h3>
    <h:form rendered="#{not empty viewScopedController.list}">
        <h:dataTable value="#{viewScopedController.list}" var="item">
            <h:column><f:facet name="header">ID</f:facet>#{item.id}</h:column>
            <h:column><f:facet name="header">Value</f:facet>#{item.value}</h:column>
            <h:column><h:commandButton value="edit" action="#{viewScopedController.doEdit(item)}" /></h:column>
            <h:column><h:commandButton value="delete" action="#{viewScopedController.delete(item)}" /></h:column>
        </h:dataTable>
    </h:form>
    <h:panelGroup rendered="#{empty viewScopedController.list}">
        <p>Table is empty! Please add new items.</p>
    </h:panelGroup>
    <h:panelGroup rendered="#{!viewScopedController.edit}">
        <h3>Add item</h3>
        <h:form>
            <p>Value: <h:inputText value="#{viewScopedController.item.value}" /></p>
            <p><h:commandButton value="add" action="#{viewScopedController.add}" /></p>
        </h:form>
    </h:panelGroup>
    <h:panelGroup rendered="#{viewScopedController.edit}">
        <h3>Edit item #{viewScopedController.item.id}</h3>
        <h:form>
            <p>Value: <h:inputText value="#{viewScopedController.item.value}" /></p>
            <p><h:commandButton value="save" action="#{viewScopedController.save}" /></p>
        </h:form>
    </h:panelGroup>
</h:body>
</html>
</code>```

and the ViewScoped bean backing this page looks like this:

```<code>package help.me.understand.jsf.ViewScopeDemo.controller;

import help.me.understand.jsf.ViewScopeDemo.model.Item;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Component
@ViewScoped
@Data
@EqualsAndHashCode(callSuper=false)
@ToString
public class ViewScopedController implements Serializable {
    private static final Logger log = LoggerFactory.getLogger(ViewScopedController.class);
    private List<Item> list;
    private Item item = new Item();
    private boolean edit;

    @PostConstruct
    public void init() {
        // list = dao.list();
        // Actually, you should retrieve the list from DAO. This is just for demo.
        list = new ArrayList<Item>();
        list.add(new Item(1L, "item1"));
        list.add(new Item(2L, "item2"));
        list.add(new Item(3L, "item3"));
    }

    public void add() {
        // dao.create(item);
        // Actually, the DAO should already have set the ID from DB. This is just for demo.
        item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
        list.add(item);
        item = new Item(); // Reset placeholder.
    }

    public void doEdit(Item item) {
        this.item = item;
        edit = true;
    }

    public void save() {
        // dao.update(item);
        item = new Item(); // Reset placeholder.
        edit = false;
    }

    public void delete(Item item) {
        // dao.delete(item);
        list.remove(item);
    }

    public List<Item> getList() {
        return list;
    }

    public Item getItem() {
        return item;
    }

    public boolean isEdit() {
        return edit;
    }

    // Other getters/setters are actually unnecessary. Feel free to add them though.
}
</code>```

If you start the application and navigate to localhost:8080/index.xhtml, click edit on one of the entries.  Then enter a new name in the text field and click save.  The save method on the managed bean is never called, and the page "resets" to its initial state.  If you disable Hazelcast and session-replication by commenting out the @EnableHazelcastHttpSession annotation along with the hazelcastInstance @Bean defined in ViewScopeDemoApplication, the above example steps work.  The save method is called, and the name of the edited item is changed.

To demonstrate another example of odd ViewScoped behavior I copied the Wizard example code verbatim from the PrimeFaces showcase:
https://www.primefaces.org/showcase/ui/panel/wizard.xhtml

With the app started, you can access this example via
localhost:8080/wizard.xhtml

With Hazelcast and session-replication enabled, you can set a break point in the onFlowProcess method, which fires when navigating from one page of the wizard to the next.  You can see that values entered on the first step of the wizard are lost (they become null) on subsequent wizard page changes.  Disable Hazelcast and the values persist across the entire span of Wizard tabs.

I am not seeing any errors or exceptions of any kind in the logs when the problems occur.  Nor do I see any problems in the browser debug console for that matter.  However, its clear from these two examples that the ViewScoped beans are behaving differently depending on whether or not Hazelcast session-replication is enabled.

Thank you in advance for your help and consideration!

答:
I seem to have stumbled onto a solution for my ViewScoped problems.  I will admit that I do not fully understand exactly how this made a difference yet, but I thought I would post a solution for others who might come across this post in the future.  Hopefully someone more wise than I can come along and help me understand why this worked, and possibly point out why its not a good idea if a better solution is available.

The thing that did the trick was adding the following property to my application.properties file:

```<code>spring.session.servlet.filter-dispatcher-types=async, error, forward, include
</code>```

The thing is though, setting ANY dispatcher type other than "request" seems to cause my ViewScoped beans to behave as I expect them to.  If "request" is one of the dispatcher types that you specify, the odd ViewScope behavior seems to manifest.

I will update the Github project mentioned in the original post so that others can play with it and see the difference.

Hopefully this will at least serve as a clue for someone else having a similar problem!

Body:
I am working on introducing clustering to a JSF based Spring-Boot web application and as soon as we enabled session-replication with Hazelcast, we started noticing that several of our JSF pages that utilize ViewScoped beans were no longer functioning correctly.  If we disable session replication and Hazelcast the odd behavior no longer occurs.

I first noticed the problem in one of our pages that utilizes a PrimeFaces Wizard component.  Values entered on the first page of the wizard are lost when the second page is "submitted".

Then on a different page I noticed that a command button was no longer calling the actionListener method on the managed bean.  I set a breakpoint in the method and the breakpoint is never hit, but the page "blinks" and refreshes back to its initial state.  I did note that the PostConstruct method on the managed bean is NOT called again, so it is not generating a new instance of the ViewScoped bean.

None of these problems occur when I disable session replication and Hazelcast though.  As far as I can tell, inspecting the session and its contents, it does look like sessions are being created and properly stored, as far as I can tell anyway.

The app is a Spring-Boot web application using the joinfaces starters to bring in JSF 2.3.7 (Mojarra), PrimeFaces 6.2, and Omnifaces 1.14.1.  We initially developed the app without any session-replication in place and we had no problems with our ViewScoped beans.

The ViewScoped beans are using org.springframework.stereotype.Component annotation, just like you see in the joinfaces examples, and javax.faces.view.ViewScoped as the scope annotation.  I have also tried bringing in Weld and using the @Named annotation as well as falling back on the old deprecated JSF @ManagedBean and @ViewScoped annotations, but the same behavior persists in all cases.

I have gone through and ensured that our ManagedBeans are all fully serializable as well as any attributes on the beans themselves.

To demonstrate what I am seeing I picked two very simple examples from a couple places on the web and created a simple Spring-Boot project that you can clone and run yourself.

https://github.com/illingtonFlex/ViewScopeDemo

This demo app contains two managed beans and two xhtml files.

The first example is one that a copied from an example on BalusC's website:
http://balusc.omnifaces.org/2010/06/benefits-and-pitfalls-of-viewscoped.html

The xhtml file looks like this:

<!DOCTYPE html>

<h:head>
    <title>Really simple CRUD</title>
</h:head>
<h:body>

List items

    <h:form rendered="#{not empty viewScopedController.list}">
        <h:dataTable value="#{viewScopedController.list}" var="item">
            <h:column><f:facet name="header">ID</f:facet>#{item.id}</h:column>
            <h:column><f:facet name="header">Value</f:facet>#{item.value}</h:column>
            <h:column><h:commandButton value="edit" action="#{viewScopedController.doEdit(item)}" /></h:column>
            <h:column><h:commandButton value="delete" action="#{viewScopedController.delete(item)}" /></h:column>
        </h:dataTable>
    </h:form>
    <h:panelGroup rendered="#{empty viewScopedController.list}">

Table is empty! Please add new items.

    </h:panelGroup>
    <h:panelGroup rendered="#{!viewScopedController.edit}">

Add item

        <h:form>

Value: <h:inputText value="#{viewScopedController.item.value}" />

<h:commandButton value="add" action="#{viewScopedController.add}" />

        </h:form>
    </h:panelGroup>
    <h:panelGroup rendered="#{viewScopedController.edit}">

Edit item #{viewScopedController.item.id}

        <h:form>

Value: <h:inputText value="#{viewScopedController.item.value}" />

<h:commandButton value="save" action="#{viewScopedController.save}" />

        </h:form>
    </h:panelGroup>
</h:body>

and the ViewScoped bean backing this page looks like this:

package help.me.understand.jsf.ViewScopeDemo.controller;

import help.me.understand.jsf.ViewScopeDemo.model.Item;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Component
@ViewScoped
@Data
@EqualsAndHashCode(callSuper=false)
@ToString
public class ViewScopedController implements Serializable {
    private static final Logger log = LoggerFactory.getLogger(ViewScopedController.class);
    private List<Item> list;
    private Item item = new Item();
    private boolean edit;

    @PostConstruct
    public void init() {
        // list = dao.list();
        // Actually, you should retrieve the list from DAO. This is just for demo.
        list = new ArrayList<Item>();
        list.add(new Item(1L, "item1"));
        list.add(new Item(2L, "item2"));
        list.add(new Item(3L, "item3"));
    }

    public void add() {
        // dao.create(item);
        // Actually, the DAO should already have set the ID from DB. This is just for demo.
        item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
        list.add(item);
        item = new Item(); // Reset placeholder.
    }

    public void doEdit(Item item) {
        this.item = item;
        edit = true;
    }

    public void save() {
        // dao.update(item);
        item = new Item(); // Reset placeholder.
        edit = false;
    }

    public void delete(Item item) {
        // dao.delete(item);
        list.remove(item);
    }

    public List<Item> getList() {
        return list;
    }

    public Item getItem() {
        return item;
    }

    public boolean isEdit() {
        return edit;
    }

    // Other getters/setters are actually unnecessary. Feel free to add them though.
}

If you start the application and navigate to localhost:8080/index.xhtml, click edit on one of the entries.  Then enter a new name in the text field and click save.  The save method on the managed bean is never called, and the page "resets" to its initial state.  If you disable Hazelcast and session-replication by commenting out the @EnableHazelcastHttpSession annotation along with the hazelcastInstance @Bean defined in ViewScopeDemoApplication, the above example steps work.  The save method is called, and the name of the edited item is changed.

To demonstrate another example of odd ViewScoped behavior I copied the Wizard example code verbatim from the PrimeFaces showcase:
https://www.primefaces.org/showcase/ui/panel/wizard.xhtml

With the app started, you can access this example via
localhost:8080/wizard.xhtml

With Hazelcast and session-replication enabled, you can set a break point in the onFlowProcess method, which fires when navigating from one page of the wizard to the next.  You can see that values entered on the first step of the wizard are lost (they become null) on subsequent wizard page changes.  Disable Hazelcast and the values persist across the entire span of Wizard tabs.

I am not seeing any errors or exceptions of any kind in the logs when the problems occur.  Nor do I see any problems in the browser debug console for that matter.  However, its clear from these two examples that the ViewScoped beans are behaving differently depending on whether or not Hazelcast session-replication is enabled.

Thank you in advance for your help and consideration!

Body:
I seem to have stumbled onto a solution for my ViewScoped problems.  I will admit that I do not fully understand exactly how this made a difference yet, but I thought I would post a solution for others who might come across this post in the future.  Hopefully someone more wise than I can come along and help me understand why this worked, and possibly point out why its not a good idea if a better solution is available.

The thing that did the trick was adding the following property to my application.properties file:

spring.session.servlet.filter-dispatcher-types=async, error, forward, include

The thing is though, setting ANY dispatcher type other than "request" seems to cause my ViewScoped beans to behave as I expect them to.  If "request" is one of the dispatcher types that you specify, the odd ViewScope behavior seems to manifest.

I will update the Github project mentioned in the original post so that others can play with it and see the difference.

Hopefully this will at least serve as a clue for someone else having a similar problem!


问:
Anyway to avoid floating point operation for Max Points on Line problem
I'm trying to solve "Max Points on Line" problem on Leet code. I inevitably need to do floating point operation to calculation Y-Intercept and slope of each line. Due to my past bad experience, I'm trying to avoid floating point operations as much as I can. Do you have any suggestion how I can do that here?

I am using LeetCode framework for development and pretty much just have access to standard C++ library.
Tried using double or long double but one of the test cases already pushes the numbers to the limits of the accuracy of these data types.

```<code>//P1[0] is X coordinate for point P1 and P1[1] is Y coordinate

long double slopeCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ( (long double)p2[1] - (long double)p1[1] ) / ((long double)p2[0] - (long double)p1[0]);
}

long double yIntersectionCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ((long double)p1[1]*(long double)p2[0] - (long double)p2[1]*(long double)p1[0]) / (long double)(p2[0] - p1[0]);
}
</code>```

If the two points are (0, 0) and (94911150, 94911151) the slope is calculated as 1 which is inaccurate. I'm trying to avoid the floating point division if possible.

NOTE: Max Points on a Line problem is to be given points in 2D space (in this case integer coordinates) and find the maximum number of points that are on one line. E.g if the points are (0,0), (2,2), (4,3), (1,1) the answer is 3 which are points (0,0), (1,1), and (2,2)

答:
If you want to avoid using floating point, what you can do to determine if a point z is collinear with two other points x and y is to compute the determinant of the matrix

```<code>{{1,z1,z2},{1,x1,x2},{1,y1,y2}}
</code>```

If the determinant is 0, then they are collinear. Since computing the determinant using the permutation definition involves only multiplication and addition/subtraction, all your computations will remain as integers. The reason it will be 0 is that the determinant is twice the area of the triangle with x,y,z as vertices,which is zero if and only if the triangle is degenerate.

Another approach would be to use Fraction objects, in particular the slope and the intercept  of the lines defined by two integers are identified as Fractions ("rational numbers"), and a reduced fraction is identified by its numerator and denominator, so you can use the pair of fractions (slope,intercept) as identifiers and since you never use floating point arithmetic you won't need to deal with roundoff error. See https://martin-thoma.com/fractions-in-cpp/ for a sample implementation of Fractions, the important part is that you can use the arithmetic operators, and normalization.

EDIT: boost has a rational number library, if you want to use it https://www.boost.org/doc/libs/1_68_0/libs/rational/

Body:
I'm trying to solve "Max Points on Line" problem on Leet code. I inevitably need to do floating point operation to calculation Y-Intercept and slope of each line. Due to my past bad experience, I'm trying to avoid floating point operations as much as I can. Do you have any suggestion how I can do that here?

I am using LeetCode framework for development and pretty much just have access to standard C++ library.
Tried using double or long double but one of the test cases already pushes the numbers to the limits of the accuracy of these data types.

//P1[0] is X coordinate for point P1 and P1[1] is Y coordinate

long double slopeCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ( (long double)p2[1] - (long double)p1[1] ) / ((long double)p2[0] - (long double)p1[0]);
}

long double yIntersectionCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ((long double)p1[1]*(long double)p2[0] - (long double)p2[1]*(long double)p1[0]) / (long double)(p2[0] - p1[0]);
}

If the two points are (0, 0) and (94911150, 94911151) the slope is calculated as 1 which is inaccurate. I'm trying to avoid the floating point division if possible.

NOTE: Max Points on a Line problem is to be given points in 2D space (in this case integer coordinates) and find the maximum number of points that are on one line. E.g if the points are (0,0), (2,2), (4,3), (1,1) the answer is 3 which are points (0,0), (1,1), and (2,2)

Body:
If you want to avoid using floating point, what you can do to determine if a point z is collinear with two other points x and y is to compute the determinant of the matrix

{{1,z1,z2},{1,x1,x2},{1,y1,y2}}

If the determinant is 0, then they are collinear. Since computing the determinant using the permutation definition involves only multiplication and addition/subtraction, all your computations will remain as integers. The reason it will be 0 is that the determinant is twice the area of the triangle with x,y,z as vertices,which is zero if and only if the triangle is degenerate.

Another approach would be to use Fraction objects, in particular the slope and the intercept  of the lines defined by two integers are identified as Fractions ("rational numbers"), and a reduced fraction is identified by its numerator and denominator, so you can use the pair of fractions (slope,intercept) as identifiers and since you never use floating point arithmetic you won't need to deal with roundoff error. See https://martin-thoma.com/fractions-in-cpp/ for a sample implementation of Fractions, the important part is that you can use the arithmetic operators, and normalization.

EDIT: boost has a rational number library, if you want to use it https://www.boost.org/doc/libs/1_68_0/libs/rational/


问:
Divide screen experiment in upper/lower part
I am new with Matlab and Psychtoolbox, and I have three codes :

One code that creates circles with a certain pattern of movement that we can call pattern 1

Another code that creates circles with a different pattern of movement (pattern 2)

A code that plays pattern 1 OR pattern 2 (like we would play a video) on a full screen.

I would like to divide the screen in two where pattern 1 will be played in the upper part, and pattern 2 played in the lower part in 50 % of the trials, and the inverse (pattern 1 in lower part/ pattern 2 in the upper part) in the rest of the trials. Both patterns have to be played at the same time. Is there a function or a set of functions that would allow me to do that?

Thank you very much for your help!

答:
I think without the code it is very difficult to answer. In general, you can choose where to present stimuli by determining the rect.

For instance, if you screen is 1280 x 1024 your rect is

```<code>rect = [0 0 1280 1024];
</code>```

The you can create the upper and lower rect by

```<code>upperRect = [0 0 rect(3) rect(4)/2];
lowerRect = [0 rect(4)/2+1 rect(3) rect(4)];
</code>```

You can now use these to display things only in one half of the screen. The exact implementation depends on your code though.

Body:
I think without the code it is very difficult to answer. In general, you can choose where to present stimuli by determining the rect.

For instance, if you screen is 1280 x 1024 your rect is

rect = [0 0 1280 1024];

The you can create the upper and lower rect by

upperRect = [0 0 rect(3) rect(4)/2];
lowerRect = [0 rect(4)/2+1 rect(3) rect(4)];

You can now use these to display things only in one half of the screen. The exact implementation depends on your code though.


问:
Routing - WebAPI and MVC in one project
I have 2 controllers. Both dealing with Bar (a child of Foo).

One of them is for MVC which returns views.

```<code>[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    public IActionResult Index()
    {
        // ...
    }

    public IActionResult SomeAction()
    {
        // ...
    }
}
</code>```

One of them is for the API, which exists under a folder of "api".

```<code>[Route("api/Foo/Bar")]
[ApiController]
public class FooBarAPIController : ControllerBase
{
    //
}
</code>```

Without adding the following line to the FooBarController class, I can access the API controller (for example: /api/foo/bar/{id}), and the MVC controller (for example: /FooBar/SomeAction)

[Route("Foo/Bar")]

But when I do, routing is messed up and I get the following error trying to access /Foo/Bar/SomeAction

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Controllers.MVC.FooBarController.Index

Controllers.MVC.FooBarController.SomeAction

答:
When you don't have the attribute applied, FooBarController uses conventional routing, which you probably have already by default. It normally has Index as the default action, and allow you to also specify the action name, thus everything works.

When you apply the attribute, all actions in this controller now use attribute routing. These two routing types aren't combined, you can only use one or the other. Note that

"With attribute routing the controller name and action names play no
  role in which action is selected."

(docs source). So these two actions become the same, their names ignored, and it is impossible to figure out which one to use. So you need to help it:

```<code>[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    [Route("")]      // To make it default for "Foo/Bar"
    [Route("Index")] // Combines to define the route template "Foo/Bar/Index"
    public IActionResult Index()
    {
        // ...
    }

    [Route("SomeAction")] // Combines to define the route template "Foo/Bar/SomeAction"
    public IActionResult SomeAction()
    {
        // ...
    }
}
</code>```

Yes, it is more verbose. From the same source:

Attribute routing requires more input to specify a route; the
  conventional default route handles routes more succinctly. However,
  attribute routing allows (and requires) precise control of which route
  templates apply to each action.

Title: Routing - WebAPI and MVC in one project

Body:
I have 2 controllers. Both dealing with Bar (a child of Foo).

One of them is for MVC which returns views.

[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    public IActionResult Index()
    {
        // ...
    }

    public IActionResult SomeAction()
    {
        // ...
    }
}

One of them is for the API, which exists under a folder of "api".

[Route("api/Foo/Bar")]
[ApiController]
public class FooBarAPIController : ControllerBase
{
    //
}

Without adding the following line to the FooBarController class, I can access the API controller (for example: /api/foo/bar/{id}), and the MVC controller (for example: /FooBar/SomeAction)

[Route("Foo/Bar")]

But when I do, routing is messed up and I get the following error trying to access /Foo/Bar/SomeAction

AmbiguousMatchException: The request matched multiple endpoints. Matches:

Controllers.MVC.FooBarController.Index

Controllers.MVC.FooBarController.SomeAction

Body:
When you don't have the attribute applied, FooBarController uses conventional routing, which you probably have already by default. It normally has Index as the default action, and allow you to also specify the action name, thus everything works.

When you apply the attribute, all actions in this controller now use attribute routing. These two routing types aren't combined, you can only use one or the other. Note that

"With attribute routing the controller name and action names play no
  role in which action is selected."

(docs source). So these two actions become the same, their names ignored, and it is impossible to figure out which one to use. So you need to help it:

[Route("Foo/Bar")]
public class FooBarController : ControllerBase
{
    [Route("")]      // To make it default for "Foo/Bar"
    [Route("Index")] // Combines to define the route template "Foo/Bar/Index"
    public IActionResult Index()
    {
        // ...
    }

    [Route("SomeAction")] // Combines to define the route template "Foo/Bar/SomeAction"
    public IActionResult SomeAction()
    {
        // ...
    }
}

Yes, it is more verbose. From the same source:

Attribute routing requires more input to specify a route; the
  conventional default route handles routes more succinctly. However,
  attribute routing allows (and requires) precise control of which route
  templates apply to each action.


问:
Multiline search and replace using C#/class Regex
I've some stored procedures that contain stuff like this:

```<code>SELECT columnA, columnB, COUNT(*) AS "COUNT" INTO temporaryTable
FROM tableA
WHERE columnA = "A"
  AND ISNULL(columnB, "B") = "B"
GROUP BY columnA, columnB
HAVING columnA = "A"
  AND ISNULL(columnB, "B") = "B"
SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.
</code>```

As said, there are procedures, so many instructions are in the same script.

I load each of theses procedures in a StringBuilder (that contains the same script that shown above).

I want to remove the HAVING part if (and only IF!). It is exactly the same as in the WHERE part (as above).

So I immediatly thought at the regular expressions.

I've something like this:

```<code>    static string RemoveHaving(Match m)
    {
        if (m.Groups[3].Value == m.Groups[7].Value)
        { /* WHERE == HAVING */
            Console.WriteLine("Same");
            return string.Concat(m.Groups[1].Value, m.Groups[9].Value);
        }

        Console.WriteLine("Not Same");
        return m.Groups[0].Value;
    }

    static void Main(string[] args)
    {
        // For the example:
        StringBuilder procedure = new StringBuilder();
        procedure.Append(@"
            SELECT columnA, columnB, COUNT(*) AS "COUNT" INTO temporaryTable
            FROM tableA
            WHERE columnA = "A"
              AND ISNULL(columnB, "B") = "B"
            GROUP BY columnA, columnB
            HAVING columnA = "A"
              AND ISNULL(columnB, "B") = "B"
            SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.");

        Regex reg = new Regex(@"((.*)where(.*)([\s^]+)group\s*by(.*)([\s^]+))having(.*)([\s^]+(SELECT|INSERT|UPDATE|DELETE))",
            RegexOptions.Compiled |
            RegexOptions.IgnoreCase |
            RegexOptions.Multiline);

        string newProcedure = reg.Replace(procedure, (MatchEvaluator)RemoveHaving);
        Console.WriteLine("---");
        Console.WriteLine(newProcedure);
        Console.WriteLine("---");
    }
</code>```

It works, but it does not seem to be the best way...

How do I detect safely the end of the HAVING?

How would you manage this work?

答:
First thought is this:

```<code>string pattern = @"WHERE\s+([\s\S]*?)\s+HAVING\s+\1\s+(SELECT|$)";
string output = Regex.Replace(input, pattern, @"WHERE $1 SELECT");
</code>```

However, this will only work if the statement is immediately followed by the SELECT keyword or an end-of-line. Different use of whitespace in the conditionals will also throw it off, as will reordering of subclauses. If you want something that's going to do this in a robust way, it's going to be VERY complicated without some kind of specialized SQL parser/optimizer.

Body:
I've some stored procedures that contain stuff like this:

SELECT columnA, columnB, COUNT(*) AS "COUNT" INTO temporaryTable
FROM tableA
WHERE columnA = "A"
  AND ISNULL(columnB, "B") = "B"
GROUP BY columnA, columnB
HAVING columnA = "A"
  AND ISNULL(columnB, "B") = "B"
SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.

As said, there are procedures, so many instructions are in the same script.

I load each of theses procedures in a StringBuilder (that contains the same script that shown above).

I want to remove the HAVING part if (and only IF!). It is exactly the same as in the WHERE part (as above).

So I immediatly thought at the regular expressions.

I've something like this:

    static string RemoveHaving(Match m)
    {
        if (m.Groups[3].Value == m.Groups[7].Value)
        { /* WHERE == HAVING */
            Console.WriteLine("Same");
            return string.Concat(m.Groups[1].Value, m.Groups[9].Value);
        }

        Console.WriteLine("Not Same");
        return m.Groups[0].Value;
    }

    static void Main(string[] args)
    {
        // For the example:
        StringBuilder procedure = new StringBuilder();
        procedure.Append(@"
            SELECT columnA, columnB, COUNT(*) AS "COUNT" INTO temporaryTable
            FROM tableA
            WHERE columnA = "A"
              AND ISNULL(columnB, "B") = "B"
            GROUP BY columnA, columnB
            HAVING columnA = "A"
              AND ISNULL(columnB, "B") = "B"
            SELECT * FROM temporaryTable -- There is not necessary to have an empty line between two instructions.");

        Regex reg = new Regex(@"((.*)where(.*)([\s^]+)group\s*by(.*)([\s^]+))having(.*)([\s^]+(SELECT|INSERT|UPDATE|DELETE))",
            RegexOptions.Compiled |
            RegexOptions.IgnoreCase |
            RegexOptions.Multiline);

        string newProcedure = reg.Replace(procedure, (MatchEvaluator)RemoveHaving);
        Console.WriteLine("---");
        Console.WriteLine(newProcedure);
        Console.WriteLine("---");
    }

It works, but it does not seem to be the best way...

How do I detect safely the end of the HAVING?

How would you manage this work?

Body:
First thought is this:

string pattern = @"WHERE\s+([\s\S]*?)\s+HAVING\s+\1\s+(SELECT|$)";
string output = Regex.Replace(input, pattern, @"WHERE $1 SELECT");

However, this will only work if the statement is immediately followed by the SELECT keyword or an end-of-line. Different use of whitespace in the conditionals will also throw it off, as will reordering of subclauses. If you want something that's going to do this in a robust way, it's going to be VERY complicated without some kind of specialized SQL parser/optimizer.


问:
How to close a python script that opened from a .bat file?
I have a .bat file that runs my python script looped forever:

```<code>:loop
start python test.py
timeout /t 120 /nobreak
goto :loop
</code>```

The only problem is, the python.exe window that opens to execute the script, doesn't close on its own. I've tried adding some exit commands in the script file, but they don't seem to work:

I.e: exit(), os._exit(0), quit(), sys.exit(1). None of those seem to work

Any idea how to close this window?

EDIT-

Should probably mention inside the python script are multiple Selenium Chrome Webdrivers being opened and used, not sure if this has an effect on it.

As an example, to replicate my issue:

```<code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.co.uk')
driver.close()
print("Test complete")
</code>```

Try running that python script with the .bat file I mentioned above to replicate my issue.

答:
Got this to work by adding

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

in my script, and running the script in the .bat file with:

```<code>start pythonw test.py
</code>```

Desired outcome achieved

Body:
I have a .bat file that runs my python script looped forever:

:loop
start python test.py
timeout /t 120 /nobreak
goto :loop

The only problem is, the python.exe window that opens to execute the script, doesn't close on its own. I've tried adding some exit commands in the script file, but they don't seem to work:

I.e: exit(), os._exit(0), quit(), sys.exit(1). None of those seem to work

Any idea how to close this window?

EDIT-

Should probably mention inside the python script are multiple Selenium Chrome Webdrivers being opened and used, not sure if this has an effect on it.

As an example, to replicate my issue:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.co.uk')
driver.close()
print("Test complete")

Try running that python script with the .bat file I mentioned above to replicate my issue.

Body:
Got this to work by adding

driver.quit()

in my script, and running the script in the .bat file with:

start pythonw test.py

Desired outcome achieved


问:
Compare values from two queries and return matching values in Ruby
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

```<code>class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases
</code>```

```<code>selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?
</code>```

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

答:
It is probably better left to SQL you handle the whole situation where you want to find the purchased and not purchased items e.g.

```<code>  purchase_table = Purchase.arel_table
  selected_items_table = SelectedItems.arel_table
  SelectedItems.joins(:sub_categories).joins(
      purchase_table.join(selected_items_table,Arel::Nodes::OuterJoin).on(
          selected_items_table[:id].eq(purchase_table[:selected_item_id]).and(
            purchase_table[:customer_id].eq(customer.id))
      ).join_sources)
  .where(sub_categories: {category_id: @category.id}).select(
      "selected_items.*,
       Case
         WHEN purchases.id IS NULL Then 'Not Purchased'
         ELSE 'Purchased'
       END AS purchasing_status"
   )
</code>```

This should result in the following:

```<code>  SELECT
    selected_items.*,
    Case
      WHEN purchases.id IS NULL Then 'Not Purchased'
      ELSE 'Purchased'
    END AS purchasing_status
  FROM
    selected_items
    INNER JOIN sub_categories ON sub_categories.selected_item_id = selected_items.id
    LEFT OUTER JOIN purchases ON purchases.selected_item_id = selected_items.id
       AND purchases.customer_id = [YOU CUSTOMER ID]
  WHERE
     sub_categories.category_id = [YOUR CATEGORY ID]
</code>```

However this is an extremely strange schema since I would have assumed that a Customer would make selections that could ultimately be purchased and that those selections would belong to a sub_category. e.g.

```<code>class Customer
  has_many :selected_items
  has_many :purchases, through: :selected_items

class Purchase
  belongs_to :selected_item

class SelectedItem
  belongs_to :customer
  belongs_to :sub_category
  has_one :purchase

class SubCategory
  belongs_to :category
  has_many :selected_items

class Category
  has_many :sub_categories
  has_many :selected_items, through: :sub_categories
</code>```

In this schema it would be far easier to determine if a SelectedItem for a Customer was Purchased or not

Body:
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases

selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

Body:
It is probably better left to SQL you handle the whole situation where you want to find the purchased and not purchased items e.g.

  purchase_table = Purchase.arel_table
  selected_items_table = SelectedItems.arel_table
  SelectedItems.joins(:sub_categories).joins(
      purchase_table.join(selected_items_table,Arel::Nodes::OuterJoin).on(
          selected_items_table[:id].eq(purchase_table[:selected_item_id]).and(
            purchase_table[:customer_id].eq(customer.id))
      ).join_sources)
  .where(sub_categories: {category_id: @category.id}).select(
      "selected_items.*,
       Case
         WHEN purchases.id IS NULL Then 'Not Purchased'
         ELSE 'Purchased'
       END AS purchasing_status"
   )

This should result in the following:

  SELECT
    selected_items.*,
    Case
      WHEN purchases.id IS NULL Then 'Not Purchased'
      ELSE 'Purchased'
    END AS purchasing_status
  FROM
    selected_items
    INNER JOIN sub_categories ON sub_categories.selected_item_id = selected_items.id
    LEFT OUTER JOIN purchases ON purchases.selected_item_id = selected_items.id
       AND purchases.customer_id = [YOU CUSTOMER ID]
  WHERE
     sub_categories.category_id = [YOUR CATEGORY ID]

However this is an extremely strange schema since I would have assumed that a Customer would make selections that could ultimately be purchased and that those selections would belong to a sub_category. e.g.

class Customer
  has_many :selected_items
  has_many :purchases, through: :selected_items

class Purchase
  belongs_to :selected_item

class SelectedItem
  belongs_to :customer
  belongs_to :sub_category
  has_one :purchase

class SubCategory
  belongs_to :category
  has_many :selected_items

class Category
  has_many :sub_categories
  has_many :selected_items, through: :sub_categories

In this schema it would be far easier to determine if a SelectedItem for a Customer was Purchased or not


问:
Error message doesn't disappear when the field it's filled in
On my form I want to have an error message every time a field is not filled in, it actually works, but then when the field is filled in the message is still there.

I have a clue where the error may be, it must be right here, but I tried to change the names and hopefully make it right, but it didn't work and the form was sent anyway, like the JavaScript wasn't even there.

```<code>    nameError = "Please type your name";
    document.getElementById("nome_error").innerHTML = nameError;
</code>```

Code:

document.getElementById("contactos").onsubmit = function() {
  var nome = document.forms["contactos"]["NomeM"].value;
  var assunto = document.forms["contactos"]["Assunto"].value;
  var email = document.forms["contactos"]["EmailMen"].value;
  var mensagem = document.forms["contactos"]["Mensagem"].value;

  var submit = true;

  if (nome == null || nome == "") {
    nameError = "Please type your name";
    document.getElementById("nome_error").innerHTML = nameError;
    submit = false;
  }

  if (assunto == null || assunto == "") {
    emailError = "Please type the subject of your message";
    document.getElementById("assunto_error").innerHTML = emailError;
    submit = false;
  }

  if (email == null || email == "") {
    telephoneError = "Please type your email";
    document.getElementById("email_error").innerHTML = telephoneError;
    submit = false;
  }

  if (mensagem == null || mensagem == "") {
    telephoneError = "Please type your message";
    document.getElementById("mensagem_error").innerHTML = telephoneError;
    submit = false;
  }

  return submit;
}

function removeWarning() {
  document.getElementById(this.id + "_error").innerHTML = "";
}

document.getElementById("NomeM").onkeyup = removeWarning;
document.getElementById("Assunto").onkeyup = removeWarning;
document.getElementById("EmailMen").onkeyup = removeWarning;
document.getElementById("Mensagem").onkeyup = removeWarning;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="site-section bg-light" id="section-contact">
  <div class="container">
    <div class="row">

      <div class="col-md-12 text-center mb-5 site-animate">
        <h2 class="display-4">Contacte-nos</h2>
        <div class="row justify-content-center">
          <div class="col-md-7">
          </div>
        </div>
      </div>

      <div class="col-md-7 mb-5 site-animate">
        <form action="index.php?cmd=contform" method="post" name="contactos" id="contactos">
          <div class="form-group">
            <label for="NomeM" class="sr-only">Name</label>
            <input type="text" class="form-control" name="NomeM" id="NomeM" name="NomeM" placeholder="Nome">
            <span class="error"><p id="nome_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Assunto" class="sr-only">Assunto</label>
            <input type="text" class="form-control" name="Assunto" id="Assunto" name="Assunto" placeholder="Assunto">
            <span class="error"><p id="assunto_error"></p></span>
          </div>
          <div class="form-group">
            <label for="EmailMen" class="sr-only">Email</label>
            <input type="email" class="form-control" id="EmailMen" name="EmailMen" placeholder="Email">
            <span class="error"><p id="email_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Mensagem" class="sr-only">Messagem</label>
            <textarea name="Mensagem" id="Mensagem" name="Mensagem" cols="30" rows="10" class="form-control" placeholder="Escreva a sua mensagem"></textarea>
            <span class="error"><p id="mensagem_error"></p></span>
          </div>
          <div class="form-group">
            <input type="submit" name="submit" id="submit" class="btn btn-primary btn-lg" value="Enviar Mensagem">
          </div>
        </form>
      </div>
      <div class="col-md-1"></div>

      <?php
   $sql="select * from Contactos";
   $res=$lig->query($sql);
   while($lin=$res->fetch_array()) {
    echo "<div class='col-md-4 site-animate'><p><img src='images/chef.jpg' alt='' class='img-fluid'></p>";
          echo "<p class='text-black'>Morada: <br> ".$lin['Morada']." <br> ".$lin['CodPostal']." <br> <br> ";
          echo " Telefone: <br> ".$lin['TelefoneCont']." <br> <br> Email: <br> ".$lin['EmailCont']." <br> <br> Fax: <br> ".$lin['Fax']." ";
   }

?>
      </p>

    </div>

  </div>
  </div>
</section></code>```

答:
The removeWarning() function doesn't work. It expects the ID of the element with the error message to be the same as the ID of the input field, with _error appended. But the IDs don't match up like that. For the name field, the ID is NomeM, but the error field is nome_error, not NomeM_error.

Fix your IDs so that the they match properly and the code should work. Don't forget that IDs are case-significant.

BTW, there's no need to test whether the value is null. It's always a string.

document.getElementById("contactos").onsubmit = function() {
  var nome = document.forms["contactos"]["NomeM"].value;
  var assunto = document.forms["contactos"]["Assunto"].value;
  var email = document.forms["contactos"]["EmailMen"].value;
  var mensagem = document.forms["contactos"]["Mensagem"].value;

  var submit = true;

  if (nome == "") {
    nameError = "Please type your name";
    document.getElementById("NomeM_error").innerHTML = nameError;
    submit = false;
  }

  if (assunto == "") {
    emailError = "Please type the subject of your message";
    document.getElementById("Assunto_error").innerHTML = emailError;
    submit = false;
  }

  if (email == "") {
    telephoneError = "Please type your email";
    document.getElementById("EmailMen_error").innerHTML = telephoneError;
    submit = false;
  }

  if (mensagem == "") {
    telephoneError = "Please type your message";
    document.getElementById("Mensagem_error").innerHTML = telephoneError;
    submit = false;
  }

  return submit;
}

function removeWarning() {
  document.getElementById(this.id + "_error").innerHTML = "";
}

document.getElementById("NomeM").onkeyup = removeWarning;
document.getElementById("Assunto").onkeyup = removeWarning;
document.getElementById("EmailMen").onkeyup = removeWarning;
document.getElementById("Mensagem").onkeyup = removeWarning;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="site-section bg-light" id="section-contact">
  <div class="container">
    <div class="row">

      <div class="col-md-12 text-center mb-5 site-animate">
        <h2 class="display-4">Contacte-nos</h2>
        <div class="row justify-content-center">
          <div class="col-md-7">
          </div>
        </div>
      </div>

      <div class="col-md-7 mb-5 site-animate">
        <form action="index.php?cmd=contform" method="post" name="contactos" id="contactos">
          <div class="form-group">
            <label for="NomeM" class="sr-only">Name</label>
            <input type="text" class="form-control" name="NomeM" id="NomeM" name="NomeM" placeholder="Nome">
            <span class="error"><p id="NomeM_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Assunto" class="sr-only">Assunto</label>
            <input type="text" class="form-control" name="Assunto" id="Assunto" name="Assunto" placeholder="Assunto">
            <span class="error"><p id="Assunto_error"></p></span>
          </div>
          <div class="form-group">
            <label for="EmailMen" class="sr-only">Email</label>
            <input type="email" class="form-control" id="EmailMen" name="EmailMen" placeholder="Email">
            <span class="error"><p id="EmailMen_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Mensagem" class="sr-only">Messagem</label>
            <textarea name="Mensagem" id="Mensagem" name="Mensagem" cols="30" rows="10" class="form-control" placeholder="Escreva a sua mensagem"></textarea>
            <span class="error"><p id="Mensagem_error"></p></span>
          </div>
          <div class="form-group">
            <input type="submit" name="submit" id="submit" class="btn btn-primary btn-lg" value="Enviar Mensagem">
          </div>
        </form>
      </div>
      <div class="col-md-1"></div>
    </div>
  </div>
  </div>
</section></code>```

Body:
On my form I want to have an error message every time a field is not filled in, it actually works, but then when the field is filled in the message is still there.

I have a clue where the error may be, it must be right here, but I tried to change the names and hopefully make it right, but it didn't work and the form was sent anyway, like the JavaScript wasn't even there.

    nameError = "Please type your name";
    document.getElementById("nome_error").innerHTML = nameError;

Code:

document.getElementById("contactos").onsubmit = function() {
  var nome = document.forms["contactos"]["NomeM"].value;
  var assunto = document.forms["contactos"]["Assunto"].value;
  var email = document.forms["contactos"]["EmailMen"].value;
  var mensagem = document.forms["contactos"]["Mensagem"].value;

  var submit = true;

  if (nome == null || nome == "") {
    nameError = "Please type your name";
    document.getElementById("nome_error").innerHTML = nameError;
    submit = false;
  }

  if (assunto == null || assunto == "") {
    emailError = "Please type the subject of your message";
    document.getElementById("assunto_error").innerHTML = emailError;
    submit = false;
  }

  if (email == null || email == "") {
    telephoneError = "Please type your email";
    document.getElementById("email_error").innerHTML = telephoneError;
    submit = false;
  }

  if (mensagem == null || mensagem == "") {
    telephoneError = "Please type your message";
    document.getElementById("mensagem_error").innerHTML = telephoneError;
    submit = false;
  }

  return submit;
}

function removeWarning() {
  document.getElementById(this.id + "_error").innerHTML = "";
}

document.getElementById("NomeM").onkeyup = removeWarning;
document.getElementById("Assunto").onkeyup = removeWarning;
document.getElementById("EmailMen").onkeyup = removeWarning;
document.getElementById("Mensagem").onkeyup = removeWarning;

Contacte-nos

        <form action="index.php?cmd=contform" method="post" name="contactos" id="contactos">

            Name
            <input type="text" class="form-control" name="NomeM" id="NomeM" name="NomeM" placeholder="Nome">

            Assunto
            <input type="text" class="form-control" name="Assunto" id="Assunto" name="Assunto" placeholder="Assunto">

            Email
            <input type="email" class="form-control" id="EmailMen" name="EmailMen" placeholder="Email">

            Messagem
            <textarea name="Mensagem" id="Mensagem" name="Mensagem" cols="30" rows="10" class="form-control" placeholder="Escreva a sua mensagem"></textarea>

            <input type="submit" name="submit" id="submit" class="btn btn-primary btn-lg" value="Enviar Mensagem">

        </form>

      <?php
   $sql="select * from Contactos";
   $res=$lig->query($sql);
   while($lin=$res->fetch_array()) {
    echo "

";
          echo "
Morada:
 ".$lin['Morada']."
 ".$lin['CodPostal']."

 ";
          echo " Telefone:
 ".$lin['TelefoneCont']."

 Email:
 ".$lin['EmailCont']."

 Fax:
 ".$lin['Fax']." ";
   }

?>

Body:
The removeWarning() function doesn't work. It expects the ID of the element with the error message to be the same as the ID of the input field, with _error appended. But the IDs don't match up like that. For the name field, the ID is NomeM, but the error field is nome_error, not NomeM_error.

Fix your IDs so that the they match properly and the code should work. Don't forget that IDs are case-significant.

BTW, there's no need to test whether the value is null. It's always a string.

document.getElementById("contactos").onsubmit = function() {
  var nome = document.forms["contactos"]["NomeM"].value;
  var assunto = document.forms["contactos"]["Assunto"].value;
  var email = document.forms["contactos"]["EmailMen"].value;
  var mensagem = document.forms["contactos"]["Mensagem"].value;

  var submit = true;

  if (nome == "") {
    nameError = "Please type your name";
    document.getElementById("NomeM_error").innerHTML = nameError;
    submit = false;
  }

  if (assunto == "") {
    emailError = "Please type the subject of your message";
    document.getElementById("Assunto_error").innerHTML = emailError;
    submit = false;
  }

  if (email == "") {
    telephoneError = "Please type your email";
    document.getElementById("EmailMen_error").innerHTML = telephoneError;
    submit = false;
  }

  if (mensagem == "") {
    telephoneError = "Please type your message";
    document.getElementById("Mensagem_error").innerHTML = telephoneError;
    submit = false;
  }

  return submit;
}

function removeWarning() {
  document.getElementById(this.id + "_error").innerHTML = "";
}

document.getElementById("NomeM").onkeyup = removeWarning;
document.getElementById("Assunto").onkeyup = removeWarning;
document.getElementById("EmailMen").onkeyup = removeWarning;
document.getElementById("Mensagem").onkeyup = removeWarning;

<section class="site-section bg-light" id="section-contact">
  <div class="container">
    <div class="row">

      <div class="col-md-12 text-center mb-5 site-animate">
        <h2 class="display-4">Contacte-nos</h2>
        <div class="row justify-content-center">
          <div class="col-md-7">
          </div>
        </div>
      </div>

      <div class="col-md-7 mb-5 site-animate">
        <form action="index.php?cmd=contform" method="post" name="contactos" id="contactos">
          <div class="form-group">
            <label for="NomeM" class="sr-only">Name</label>
            <input type="text" class="form-control" name="NomeM" id="NomeM" name="NomeM" placeholder="Nome">
            <span class="error"><p id="NomeM_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Assunto" class="sr-only">Assunto</label>
            <input type="text" class="form-control" name="Assunto" id="Assunto" name="Assunto" placeholder="Assunto">
            <span class="error"><p id="Assunto_error"></p></span>
          </div>
          <div class="form-group">
            <label for="EmailMen" class="sr-only">Email</label>
            <input type="email" class="form-control" id="EmailMen" name="EmailMen" placeholder="Email">
            <span class="error"><p id="EmailMen_error"></p></span>
          </div>
          <div class="form-group">
            <label for="Mensagem" class="sr-only">Messagem</label>
            <textarea name="Mensagem" id="Mensagem" name="Mensagem" cols="30" rows="10" class="form-control" placeholder="Escreva a sua mensagem"></textarea>
            <span class="error"><p id="Mensagem_error"></p></span>
          </div>
          <div class="form-group">
            <input type="submit" name="submit" id="submit" class="btn btn-primary btn-lg" value="Enviar Mensagem">
          </div>
        </form>
      </div>
      <div class="col-md-1"></div>
    </div>
  </div>
  </div>
</section>


问:
Only Last item in list shows in DataTemplate
I have 5 contents which I want to display in wrapPanels when the application starts but unfortunately, it's not working as I want. When I run the application.

```<code>public class Company
{
    public String EventName { get; set; }
    public String Attendees { get; set; }
    public String Date { get; set; }
}
</code>```

}

I expect all the contents to show up, but only Hiking shows

答:
The reason you're getting this problem is because you are overwriting the variable called "com" with each new value.

```<code>com = new Company { EventName = "Code Talks" ,Attendees ="50" , Date = "25/oct./2019" };
com = new Company { EventName = "Tic Tac", Attendees = "70", Date = "55/oct./2019" };
com = new Company { EventName = "Loney Talks", Attendees = "30", Date = "5/oct./2019" };
com = new Company { EventName = "Cofee Talks", Attendees = "50", Date = "25/oct./2019" };
com = new Company { EventName = "Hiking ", Attendees = "40", Date = "75/oct./2019" };
</code>```

Which is equivalent to trying to store several integers like this:

```<code>x=5;
x=4;
x=1;
</code>```

You will want to use some kind of array and add each item to it. If you are only ever going to use those 5 items, then a fixed length array will work fine:

```<code>Company[] coms = new Company[5];
coms[0] = new Company { EventName = "Code Talks" ,Attendees ="50" , Date = "25/oct./2019" };
coms[1] = new Company { EventName = "Tic Tac", Attendees = "70", Date = "55/oct./2019" };
coms[2] = new Company { EventName = "Loney Talks", Attendees = "30", Date = "5/oct./2019" };
coms[3] = new Company { EventName = "Cofee Talks", Attendees = "50", Date = "25/oct./2019" };
coms[4] = new Company { EventName = "Hiking ", Attendees = "40", Date = "75/oct./2019" };
</code>```

Body:
I have 5 contents which I want to display in wrapPanels when the application starts but unfortunately, it's not working as I want. When I run the application.

public class Company
{
    public String EventName { get; set; }
    public String Attendees { get; set; }
    public String Date { get; set; }
}

}

I expect all the contents to show up, but only Hiking shows

Body:
The reason you're getting this problem is because you are overwriting the variable called "com" with each new value.

com = new Company { EventName = "Code Talks" ,Attendees ="50" , Date = "25/oct./2019" };
com = new Company { EventName = "Tic Tac", Attendees = "70", Date = "55/oct./2019" };
com = new Company { EventName = "Loney Talks", Attendees = "30", Date = "5/oct./2019" };
com = new Company { EventName = "Cofee Talks", Attendees = "50", Date = "25/oct./2019" };
com = new Company { EventName = "Hiking ", Attendees = "40", Date = "75/oct./2019" };

Which is equivalent to trying to store several integers like this:

x=5;
x=4;
x=1;

You will want to use some kind of array and add each item to it. If you are only ever going to use those 5 items, then a fixed length array will work fine:

Company[] coms = new Company[5];
coms[0] = new Company { EventName = "Code Talks" ,Attendees ="50" , Date = "25/oct./2019" };
coms[1] = new Company { EventName = "Tic Tac", Attendees = "70", Date = "55/oct./2019" };
coms[2] = new Company { EventName = "Loney Talks", Attendees = "30", Date = "5/oct./2019" };
coms[3] = new Company { EventName = "Cofee Talks", Attendees = "50", Date = "25/oct./2019" };
coms[4] = new Company { EventName = "Hiking ", Attendees = "40", Date = "75/oct./2019" };