问:
Limit the date to today and block the previous dates
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html></code>```

Thank you very much for your help and your time.

答:
Three things:

You need to get your Current Date and set time to start of day.

You need to get your Selected Date and set time to start of day

Compare whether Selected Date is Greater or Equal to the Current Date.

Note that when you compare dates, you need to also consider the time.
Most calendar tools, include the time as a response to the selected date. You need to be aware of that.

This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)

```<code>const isValidDate = (selectedDate) => {
    const currentDate = new Date();

    // reset to start of day
    currentDate.setHours(0);
    currentDate.setMinutes(0);
    currentDate.setSeconds(0);
    currentDate.setMilliseconds(0);

    const newDate = new Date(selectedDate);
    newDate.setHours(0);
    newDate.setMinutes(0);
    newDate.setSeconds(0);
    newDate.setMilliseconds(0);

    return newDate.getTime() >= currentDate.getTime();
}
</code>```

To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.

```<code>isValidDate(selectedDateFromDatePicker);
</code>```

Body:
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">

<form action="#" onsubmit="return validation()" >

Date start :

<input type="date" name="date_start" id="date_start">

<input type="submit" value="ok">
</form>

Thank you very much for your help and your time.

Body:
Three things:

You need to get your Current Date and set time to start of day.

You need to get your Selected Date and set time to start of day

Compare whether Selected Date is Greater or Equal to the Current Date.

Note that when you compare dates, you need to also consider the time.
Most calendar tools, include the time as a response to the selected date. You need to be aware of that.

This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)

const isValidDate = (selectedDate) => {
    const currentDate = new Date();

    // reset to start of day
    currentDate.setHours(0);
    currentDate.setMinutes(0);
    currentDate.setSeconds(0);
    currentDate.setMilliseconds(0);

    const newDate = new Date(selectedDate);
    newDate.setHours(0);
    newDate.setMinutes(0);
    newDate.setSeconds(0);
    newDate.setMilliseconds(0);

    return newDate.getTime() >= currentDate.getTime();
}

To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.

isValidDate(selectedDateFromDatePicker);


来源: stackexchange

问:
Detect a selection change in Excel VBA ListBox
I need to detect when a selection change is made in a listbox so I can write the value to a sheet, the moment an item is selected or deselected.

There doesn't seem to be an event to capture this.  OnChange doesnt get triggered, or OnClick.  I tried to use an OnMouseUp event, and this does get fired at the right time, but seems to then disable the selection - so the event fires, but the listbox doesnt register a change in the status of the row being selected.

答:
You can use this to trigger the event.

```<code>Private Sub ListBox1_Change()
    MsgBox "Something changed"
End Sub
</code>```

Put this in the forms code.

ContentLicense: CC BY-SA 4.0

Body:
You can use this to trigger the event.

Private Sub ListBox1_Change()
    MsgBox "Something changed"
End Sub

Put this in the forms code.


问:
Creating files using Linux
I am trying to create multiple files using Linux command on my terminal, but it keeps saying -bash: marcel: No such file or directory. Is there a problem with the formatting of my code?

Here is my code:

```<code>$ touch hello.txt index.html question1.txt question2.txt question3.md <marcel>.info remove-me-1.txt remove-me-2.txt
</code>```

答:
< and > are special characters used to redirect streams: you must quote that filename:

touch hello.txt index.html question1.txt question2.txt question3.md "<marcel>.info" remove-me-1.txt remove-me-2.txt
```

Title: Creating files using Linux

Body:
I am trying to create multiple files using Linux command on my terminal, but it keeps saying -bash: marcel: No such file or directory. Is there a problem with the formatting of my code?

Here is my code:

$ touch hello.txt index.html question1.txt question2.txt question3.md <marcel>.info remove-me-1.txt remove-me-2.txt


问:
Live on heap or stack when use new operator within a function block?
For instance:

```<code>void Func()
{
    int* i = new int; // the simplest case

    vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here
    vector<int*>* vPointer = new vector<int*>;
}

void main()
{
    Func();
}

</code>```

So, if I allocate dynamic memory(by using new operator) for local variables in functions,

Do they live on heap or stack?

when the program exits the function, are they still dangling around on heap or destroyed as function variables?

Can I use new operator on non-pointer types? How to delete (or return back the allocated heap memory) it later?

Thank you!

答:
```<code>int i = 3;
</code>```

this creates an object of type int on the stack. (The C++ standard uses the term "automatic storage", and I'm usually a stickler for proper use of formal terms, but "stack" and "heap" are deeply embedded in programming vocabulary, so "stack" and "heap" are just fine as technical terms).

```<code>int *ip = 0;
</code>```

this creates an object of type int* on the stack. ip holds a null pointer.

```<code>int *ip = new int;
</code>```

this creates an object of type int* on the stack, just like the previous one. It holds a pointer to memory on the heap (see earlier parenthetical; the formal term is "free store"). You know that the memory is on the heap because that's what operator new does.

When you're finished with the heap memory you have to release it:

```<code>delete ip;
</code>```

if you don't delete it and the function that created it returns, the local variable (ip) that held the pointer is gone. The memory has been allocated and it hasn't been freed, so unless you copied the pointer to some place else, you have no way to get at the memory you allocated. That's called a "memory leak".

Body:
For instance:

void Func()
{
    int* i = new int; // the simplest case

    vector<int*> v = new vector<int*>; // another case, not sure if **new** is using correctly here
    vector<int*>* vPointer = new vector<int*>;
}

void main()
{
    Func();
}

So, if I allocate dynamic memory(by using new operator) for local variables in functions,

Do they live on heap or stack?

when the program exits the function, are they still dangling around on heap or destroyed as function variables?

Can I use new operator on non-pointer types? How to delete (or return back the allocated heap memory) it later?

Thank you!

Body:
int i = 3;

this creates an object of type int on the stack. (The C++ standard uses the term "automatic storage", and I'm usually a stickler for proper use of formal terms, but "stack" and "heap" are deeply embedded in programming vocabulary, so "stack" and "heap" are just fine as technical terms).

int *ip = 0;

this creates an object of type int* on the stack. ip holds a null pointer.

int *ip = new int;

this creates an object of type int* on the stack, just like the previous one. It holds a pointer to memory on the heap (see earlier parenthetical; the formal term is "free store"). You know that the memory is on the heap because that's what operator new does.

When you're finished with the heap memory you have to release it:

delete ip;

if you don't delete it and the function that created it returns, the local variable (ip) that held the pointer is gone. The memory has been allocated and it hasn't been freed, so unless you copied the pointer to some place else, you have no way to get at the memory you allocated. That's called a "memory leak".


问:
Variable binwith in geom_histogram()
I like to set up different binwidths in ggplot2.

As an example I use the dataset

```<code>library(Stat2Data)
data("YouthRisk2007")
</code>```

```<code>head(YouthRisk2007)
  ride.alc.driver female grade age4 smoke DriverLicense
1               1      1    10   15     1             0
2               1      1    10   18     1             1
3               1     NA    NA   NA    NA            NA
4               0      0    11   17     0             1
5               0      0    11   17     0             1
6               0      0    11   17     1             1
</code>```

With

```<code>library(dplyr)
library(ggplot2)

YouthRisk2007 %>%
    ggplot(aes(age4)) +
      geom_histogram(binwidth = 1)
</code>```

you generate a histogram for every year.

Now I like to set up different binwidth (14-15 year, 16-17 year, 18 years [width of the classes]) so that the area is proportional to the frequency (not just the hight of the bin).
The binwidth should vary visually, not just for counting the frequency.

My first idea was to set up the binwidth as a vector binwidth = c(2,3) but this is not allowed.

Is there a way to do this?

答:
If you know your desired breakpoints beforehand, you can use the scale_x_binned(). It requires ggplot v3.3.0+.

library(ggplot2)

ggplot(mtcars) +
  geom_bar(aes(mpg)) +
  scale_x_binned(breaks = c(10, 13, 15, 16, 25, 30))
```

Created on 2020-05-28 by the reprex package (v0.3.0)

Title: Variable binwith in geom_histogram()

Body:
I like to set up different binwidths in ggplot2.

As an example I use the dataset

library(Stat2Data)
data("YouthRisk2007")

head(YouthRisk2007)
  ride.alc.driver female grade age4 smoke DriverLicense
1               1      1    10   15     1             0
2               1      1    10   18     1             1
3               1     NA    NA   NA    NA            NA
4               0      0    11   17     0             1
5               0      0    11   17     0             1
6               0      0    11   17     1             1

With

library(dplyr)
library(ggplot2)

YouthRisk2007 %>%
    ggplot(aes(age4)) +
      geom_histogram(binwidth = 1)

you generate a histogram for every year.

Now I like to set up different binwidth (14-15 year, 16-17 year, 18 years [width of the classes]) so that the area is proportional to the frequency (not just the hight of the bin).
The binwidth should vary visually, not just for counting the frequency.

My first idea was to set up the binwidth as a vector binwidth = c(2,3) but this is not allowed.

Is there a way to do this?

Body:
If you know your desired breakpoints beforehand, you can use the scale_x_binned(). It requires ggplot v3.3.0+.

library(ggplot2)

ggplot(mtcars) +
  geom_bar(aes(mpg)) +
  scale_x_binned(breaks = c(10, 13, 15, 16, 25, 30))

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
How to rollback whole Transaction for Splitter incase any submessage fails
Current Use Case:
With below configuration, we are trying to split Parent message using Custom Iterator processor and assign different endpoints to different submessages inside the test processor, based on its content.

```<code>from("endpoint")
    .split().method(iteratorProcessor, "execute")
    .shareUnitOfWork()
    .stopOnException()
    .bean(testProcessor, "process")
    .receipientList(header("destination"));
</code>```

With the above, success case is working as expected.

Issue:
In case after the split, first message posting is successful and second message posting fails, we are observing that second sub message alone is directed to the error handler.

Requirement:
If any failure occurs in the entire process, we want to redirect the IN message to error handler(complete rollback) and don't post any other submessages.

答:
Welcome to Stack overflow!

In case of an error, due to the statement stopOnException(), the Splitter aborts processing.

That means for your goal to do a complete rollback

You are fine for all not yet processed records.

Your problem are the already successfully processed records

For these you have to run a compensation logic as part of your rollback. For example if already processed records are written to a database, you could delete them later when a failure in the Splitter occurs.

Added due to comments

According to the Splitter docs, since you use shareUnitOfWork() you should receive just one error message when the Splitter is done and at least 1 error occured (instead of one error message per failed submessage). So if you also use useOriginalMessage() in your error handler, you should then receive the original IN message.

If this does not work, it could collide with stopOnException() (never tried this). It would be a try to remove stopOnException() and check if it works like this.

You cannot directly compensate an already delivered JMS message, but you can build a compensation that you can trigger afterwards. For example send the failed messages from the error handler to another queue whose consumer rolls back whatever the first message did.

Body:
Current Use Case:
With below configuration, we are trying to split Parent message using Custom Iterator processor and assign different endpoints to different submessages inside the test processor, based on its content.

from("endpoint")
    .split().method(iteratorProcessor, "execute")
    .shareUnitOfWork()
    .stopOnException()
    .bean(testProcessor, "process")
    .receipientList(header("destination"));

With the above, success case is working as expected.

Issue:
In case after the split, first message posting is successful and second message posting fails, we are observing that second sub message alone is directed to the error handler.

Requirement:
If any failure occurs in the entire process, we want to redirect the IN message to error handler(complete rollback) and don't post any other submessages.


问:
Why are these elements appearing behind each other/mixing
I was creating a web portfolio, I created the welcome section then I created the projects section, but the projects section appears behind the welcome section. Why is this happening? I tried making some elements as block but it won’t work.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    background-color: black;
}
a{
    text-decoration: none;
}
header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1% 0.8%;
    box-shadow: 0px 2px 10px #888888;
}
.logo{
    cursor: pointer;
    color: white;
    font-family: 'Staatliches';
    letter-spacing: 5px;
    font-size: larger;
}
.nav-area{
    list-style: none;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 25px;
}
.nav-area li{
    display: inline-block;
    padding: 0 15px;
    text-transform: uppercase;
}
.nav-area li a{
    transition: all .3s ease 0s;
    color: white;
}
.nav-area li a:hover{
    color: rgb(0, 204, 255);
}

.text-container{
    color: white;
    position: absolute;
    left: 13%;
    top: 42%;
    transform:translate(-13%, -42%);
}
.text-container p:nth-child(1){
    font-family: monospace;
    font-weight: bold;
    font-size: 35px;
}
.text-container p:nth-child(2){
    font-family: monospace;
    font-weight: bold;
    font-size: 70px;
}
.text-container p:nth-child(3){
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    line-height: 30px;
    font-size: 35px;
    margin-top: 10px;
}
.model {
    height: 650px;
    position: absolute;
    top: 13%;
    left: 70%;
    transform: translateX(-70%);
}
.text-container button{
    width: 130px;
    height: 42px;
    border-radius: 10px;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    font-weight: bold;
    font-size: 14px;
    outline: none;
    margin: 20px 10px;
}
.hire-btn{
    border: 2px solid grey;
}
.hire-btn{
    border: 2px solid grey;
}
button:hover{
    transform: scale(1.1);
}
.welcome-section{
    display: block;
}
.projects-section{
    text-align: center;
    padding: 10rem 10rem;
    background-color: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rajdeep Thakare</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Staatliches&display=swap" rel="stylesheet"> </head>
<body>
    <header>
        <div class="logo"><h1>Rajdeep Thakare</h1></div>
        <nav>
<ul class="nav-area">
<li>home</li>
<li>About</li>
<li>portfolio</li>
<li>services</li>
<li>contact</li>
</ul>
</nav>
</header>
    <section class="welcome-section">
<div class="text-container">
    <p>Hello,</p>
    <p>I am Rajdeep</p>
    <p>Maker and Hobbyist!!</p>
    <button class="hire-btn">Hire Me</button>
    <button class="down-btn">Download CV</button>
</div>
    <img class="model" src="https://drive.google.com/file/d/12vEKYhBZvpfRXV0aJ1wXmXk59lwplRe0/view?usp=sharing" alt="my photo">
</section>

<section class="projects-section">
    <div>
        <h1>MY PROJECTS</h1>
    </div>
</section>
</body>
</html></code>```

Code link - https://codepen.io/Rajdeep100/pen/WNQqoGQ?editors=1100

答:
You only need to give some height to your welcome-section. Like an example give it 400px to the welcome-section class. Check the image given here
Portfolio Page

Body:
I was creating a web portfolio, I created the welcome section then I created the projects section, but the projects section appears behind the welcome section. Why is this happening? I tried making some elements as block but it won’t work.

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    background-color: black;
}
a{
    text-decoration: none;
}
header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1% 0.8%;
    box-shadow: 0px 2px 10px #888888;
}
.logo{
    cursor: pointer;
    color: white;
    font-family: 'Staatliches';
    letter-spacing: 5px;
    font-size: larger;
}
.nav-area{
    list-style: none;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 25px;
}
.nav-area li{
    display: inline-block;
    padding: 0 15px;
    text-transform: uppercase;
}
.nav-area li a{
    transition: all .3s ease 0s;
    color: white;
}
.nav-area li a:hover{
    color: rgb(0, 204, 255);
}

.text-container{
    color: white;
    position: absolute;
    left: 13%;
    top: 42%;
    transform:translate(-13%, -42%);
}
.text-container p:nth-child(1){
    font-family: monospace;
    font-weight: bold;
    font-size: 35px;
}
.text-container p:nth-child(2){
    font-family: monospace;
    font-weight: bold;
    font-size: 70px;
}
.text-container p:nth-child(3){
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    line-height: 30px;
    font-size: 35px;
    margin-top: 10px;
}
.model {
    height: 650px;
    position: absolute;
    top: 13%;
    left: 70%;
    transform: translateX(-70%);
}
.text-container button{
    width: 130px;
    height: 42px;
    border-radius: 10px;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    font-weight: bold;
    font-size: 14px;
    outline: none;
    margin: 20px 10px;
}
.hire-btn{
    border: 2px solid grey;
}
.hire-btn{
    border: 2px solid grey;
}
button:hover{
    transform: scale(1.1);
}
.welcome-section{
    display: block;
}
.projects-section{
    text-align: center;
    padding: 10rem 10rem;
    background-color: grey;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rajdeep Thakare</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Staatliches&display=swap" rel="stylesheet">

Rajdeep Thakare

home

About

portfolio

services

contact

Hello,

I am Rajdeep

Maker and Hobbyist!!

    <button class="hire-btn">Hire Me</button>
    <button class="down-btn">Download CV</button>

MY PROJECTS

Code link - https://codepen.io/Rajdeep100/pen/WNQqoGQ?editors=1100


问:
Unable to start the graphical user interface of RapidMiner in Mac OS
I was not able to start rapidminer by double clicking on lib/rapidminer.jar. I also tried java -jar lib/rapidminer.jar that also doesn't work.

I tried ./scripts/rapidminer and rapid miner started

```<code>RAPIDMINER_HOME is not set. Trying the directory '.'...
No maximum Java memory defined, using 1024 Mb...
Java version: 16
grep: /proc/cpuinfo: No such file or directory
Number of cores: 4
Number of GC Threads: 3
Starting RapidMiner from '.', using classes from './lib/rapidminer.jar'...
Java version: 16
Starting with CMS garbage collector
Starting in multi-core mode
RapidMiner version 5.3.008, Copyright (C) 2001-2012
RapidMiner comes with ABSOLUTELY NO WARRANTY; This is free software,
and you are welcome to redistribute it under certain conditions;
see license information in the file named LICENSE.
Usage: com.rapidminer.RapidMinerCommandLine [-f] PROCESS [-Mname=value]
  PROCESS       a repository location containing a process
  -f            interpret PROCESS as a file rather than a repository location (deprecated)
  -Mname=value  sets the macro 'name' with the value 'value'
</code>```

I want to launch the GUI also
I tried : ./scripts/RapidMinerGUI

```<code>RAPIDMINER_HOME is not set. Trying the directory '.'...
grep: /proc/cpuinfo: No such file or directory
Number of cores: 4
Number of GC Threads: 3
No maximum Java memory defined, using 1024 Mb...
Starting RapidMiner from '.', using classes from './lib/rapidminer.jar'...
Java version: 16
Starting with CMS garbage collector
Starting in multi-core mode
May 7, 2013 2:38:31 PM com.rapid_i.Launcher ensureRapidMinerHomeSet
INFO: rapidminer.home is '.'.
May 7, 2013 2:38:31 PM com.rapid_i.Launcher main
INFO: Launching RapidMiner, platform ANY
May 7, 2013 2:38:32 PM com.rapidminer.tools.FileSystemService getUserRapidMinerDir
WARNING: Unable to create user home rapidminer directory /Users/.RapidMiner5
May 7, 2013 2:38:32 PM com.rapidminer.tools.ParameterService init
INFO: Reading configuration resource com/rapidminer/resources/rapidminerrc.
May 7, 2013 2:38:32 PM com.rapidminer.tools.FileSystemService getUserRapidMinerDir
WARNING: Unable to create user home rapidminer directory /Users/.RapidMiner5
May 7, 2013 2:38:32 PM com.rapidminer.tools.I18N <clinit>
</code>```

Please help me run the rapidminer gui in Mac.

答:
You can set the RAPIDMINER_HOME variable with the location of RapidMiner folder:

```<code>export RAPIDMINER_HOME=/home/user/development/rapidminer-5
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was not able to start rapidminer by double clicking on lib/rapidminer.jar. I also tried java -jar lib/rapidminer.jar that also doesn't work.

I tried ./scripts/rapidminer and rapid miner started

RAPIDMINER_HOME is not set. Trying the directory '.'...
No maximum Java memory defined, using 1024 Mb...
Java version: 16
grep: /proc/cpuinfo: No such file or directory
Number of cores: 4
Number of GC Threads: 3
Starting RapidMiner from '.', using classes from './lib/rapidminer.jar'...
Java version: 16
Starting with CMS garbage collector
Starting in multi-core mode
RapidMiner version 5.3.008, Copyright (C) 2001-2012
RapidMiner comes with ABSOLUTELY NO WARRANTY; This is free software,
and you are welcome to redistribute it under certain conditions;
see license information in the file named LICENSE.
Usage: com.rapidminer.RapidMinerCommandLine [-f] PROCESS [-Mname=value]
  PROCESS       a repository location containing a process
  -f            interpret PROCESS as a file rather than a repository location (deprecated)
  -Mname=value  sets the macro 'name' with the value 'value'

I want to launch the GUI also
I tried : ./scripts/RapidMinerGUI

RAPIDMINER_HOME is not set. Trying the directory '.'...
grep: /proc/cpuinfo: No such file or directory
Number of cores: 4
Number of GC Threads: 3
No maximum Java memory defined, using 1024 Mb...
Starting RapidMiner from '.', using classes from './lib/rapidminer.jar'...
Java version: 16
Starting with CMS garbage collector
Starting in multi-core mode
May 7, 2013 2:38:31 PM com.rapid_i.Launcher ensureRapidMinerHomeSet
INFO: rapidminer.home is '.'.
May 7, 2013 2:38:31 PM com.rapid_i.Launcher main
INFO: Launching RapidMiner, platform ANY
May 7, 2013 2:38:32 PM com.rapidminer.tools.FileSystemService getUserRapidMinerDir
WARNING: Unable to create user home rapidminer directory /Users/.RapidMiner5
May 7, 2013 2:38:32 PM com.rapidminer.tools.ParameterService init
INFO: Reading configuration resource com/rapidminer/resources/rapidminerrc.
May 7, 2013 2:38:32 PM com.rapidminer.tools.FileSystemService getUserRapidMinerDir
WARNING: Unable to create user home rapidminer directory /Users/.RapidMiner5
May 7, 2013 2:38:32 PM com.rapidminer.tools.I18N <clinit>

Please help me run the rapidminer gui in Mac.

Body:
You can set the RAPIDMINER_HOME variable with the location of RapidMiner folder:

export RAPIDMINER_HOME=/home/user/development/rapidminer-5


问:
Regex to replace %variables%
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

```<code>{'search': 'replace',
 'foo':    'bar'}
</code>```

And a string like this:

```<code>Foo bar %foo% % search %.
</code>```

I'd like to replace each variable with it's equivalent text from the dictionary:

```<code>Foo bar bar replace.
</code>```

My current regex fails, so here it is (key and value are from dictionary.items()):

```<code> re.sub(r'%\d+' + key + '[^%]\d+%', value, text)
</code>```

Any help would be appreciated, as this regex stuff is driving me nuts...

答:
If you're flexible with your syntax in your string, Python has a built in mechanism for that:

```<code>>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}
Hello, Blender, my name is Ken
</code>```

Alternatively, if you want that syntax, I'd avoid regular expressions and just do this:

```<code>>>> vars = {'search': 'replace',
...  'foo':    'bar'}
>>> mystring = "Foo bar %foo% % search %."
>>> for k, v in vars.items():
...     mystring = mystring.replace('%%%s%%' % k, v)
...
>>> print mystring
Foo bar bar % search %.
</code>```

Title: Regex to replace %variables%

Body:
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

{'search': 'replace',
 'foo':    'bar'}

And a string like this:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:

Foo bar bar replace.

My current regex fails, so here it is (key and value are from dictionary.items()):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...

Body:
If you're flexible with your syntax in your string, Python has a built in mechanism for that:

>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}
Hello, Blender, my name is Ken

Alternatively, if you want that syntax, I'd avoid regular expressions and just do this:

>>> vars = {'search': 'replace',
...  'foo':    'bar'}
>>> mystring = "Foo bar %foo% % search %."
>>> for k, v in vars.items():
...     mystring = mystring.replace('%%%s%%' % k, v)
...
>>> print mystring
Foo bar bar % search %.


问:
How can i force playsinline for all <video> content
I have researched several fixes for this issue but not seem to have solved the problem.

I will outline below the steps I've taken to allow video from a < video > tag element to play in line. I need a solution that will work across different websites and not something that will only work for youtube etc.

Reference I'm using the WKWebView as the containing browser for the web content. I have set allowsInlineMediaPlayback = true (WKWebViewConfiguration). I have also implemented the following piece of JavaScript that i call on a webpage and successfully amends the attributes of the video tag to include "playsinline" "autoplay". thinking being no matter what guff the website developer has , or hasnt got in there i can be sure the attributes i need are added to the video tag. (as a side note i think youtube and others are also making it difficult for devleopers to affect how there website behaves (however much better the UX would be if they did))

Anyway to the code >>

```<code>WKWebViewConfiguration *dx = [[WKWebViewConfiguration alloc] init];
    dx.allowsInlineMediaPlayback = TRUE;
    WKWebView * webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0,  cell.wv.bounds.size.width, cell.wv.bounds.size.height) configuration:dx];

    [cell addSubview:webview];

    webview.navigationDelegate = self;
    webview.UIDelegate = self;

    webview.frame = CGRectMake(0, 0,  cell.wv.bounds.size.width, cell.wv.bounds.size.height);

    [[webview scrollView] setBounces:NO];
    webview.scrollView.scrollEnabled = NO;

    NSURL *nsurl=[NSURL URLWithString:urlws[indexPath.row]];
    NSURLRequest *request = [NSURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 60.0];
    [webview loadRequest:request];

 NSString *jsCallBack = @"var b = document.querySelector(\"video\"); b.setAttribute(\"webkit-playsinline\",\"\"); b.setAttribute(\"autoplay\",\"\"); b.setAttribute(\"muted\",\"\");";

[webView  evaluateJavaScript:jsCallBack completionHandler:^(NSString *result, NSError *error)
 {
     NSLog(@"Error %@",error);
     NSLog(@"Result %@",result);
</code>```

I then kick off the playback by calling this js code from ios

```<code>NSString *jsCallBack = @"var element = document.querySelector('[aria-label=\"Play\"]'); element.click();";

         [webView  evaluateJavaScript:jsCallBack completionHandler:^(NSString *result, NSError *error)
          {
</code>```

Results :

The play function is called and video plays but the user is taken into full screen playback which is not what should happen. @IOS WebKit is good, but  needs more work and we need some more intelligent apis for this i think as its now seldom that any user wants to see a video in full screen. Its natural if the devise it turned on its side for full screen but otherwise it really smacks of a bad user experience.

If anyone has any ideas please let me know. Many thanks

答:
I had the same issue, I solved adding these to config.xml:

```<code><preference name="AllowInlineMediaPlayback" value="true" />
</code>```

This allows media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.

For more details read:

https://cordova.apache.org/docs/en/5.1.1/guide/platforms/ios/config.html

Playing video inline in Ionic/Phonegap (webkit-playsinline not working)

Body:
I have researched several fixes for this issue but not seem to have solved the problem.

I will outline below the steps I've taken to allow video from a < video > tag element to play in line. I need a solution that will work across different websites and not something that will only work for youtube etc.

Reference I'm using the WKWebView as the containing browser for the web content. I have set allowsInlineMediaPlayback = true (WKWebViewConfiguration). I have also implemented the following piece of JavaScript that i call on a webpage and successfully amends the attributes of the video tag to include "playsinline" "autoplay". thinking being no matter what guff the website developer has , or hasnt got in there i can be sure the attributes i need are added to the video tag. (as a side note i think youtube and others are also making it difficult for devleopers to affect how there website behaves (however much better the UX would be if they did))

Anyway to the code >>

WKWebViewConfiguration *dx = [[WKWebViewConfiguration alloc] init];
    dx.allowsInlineMediaPlayback = TRUE;
    WKWebView * webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0,  cell.wv.bounds.size.width, cell.wv.bounds.size.height) configuration:dx];

    [cell addSubview:webview];

    webview.navigationDelegate = self;
    webview.UIDelegate = self;

    webview.frame = CGRectMake(0, 0,  cell.wv.bounds.size.width, cell.wv.bounds.size.height);

    [[webview scrollView] setBounces:NO];
    webview.scrollView.scrollEnabled = NO;

    NSURL *nsurl=[NSURL URLWithString:urlws[indexPath.row]];
    NSURLRequest *request = [NSURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 60.0];
    [webview loadRequest:request];

 NSString *jsCallBack = @"var b = document.querySelector(\"video\"); b.setAttribute(\"webkit-playsinline\",\"\"); b.setAttribute(\"autoplay\",\"\"); b.setAttribute(\"muted\",\"\");";

[webView  evaluateJavaScript:jsCallBack completionHandler:^(NSString *result, NSError *error)
 {
     NSLog(@"Error %@",error);
     NSLog(@"Result %@",result);

I then kick off the playback by calling this js code from ios

NSString *jsCallBack = @"var element = document.querySelector('[aria-label=\"Play\"]'); element.click();";

         [webView  evaluateJavaScript:jsCallBack completionHandler:^(NSString *result, NSError *error)
          {

Results :

The play function is called and video plays but the user is taken into full screen playback which is not what should happen. @IOS WebKit is good, but  needs more work and we need some more intelligent apis for this i think as its now seldom that any user wants to see a video in full screen. Its natural if the devise it turned on its side for full screen but otherwise it really smacks of a bad user experience.

If anyone has any ideas please let me know. Many thanks

Body:
I had the same issue, I solved adding these to config.xml:

<preference name="AllowInlineMediaPlayback" value="true" />

This allows media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.

For more details read:

https://cordova.apache.org/docs/en/5.1.1/guide/platforms/ios/config.html

Playing video inline in Ionic/Phonegap (webkit-playsinline not working)


问:
Mean of the selected row in grouped dataframe
can you please help me with the following situation? I want to groupby my df based on team and season and then I want to get mean of the goals scored till the date of the match. I thought about using rolling, but I cant figure it out how, since for each row it will different.

DF:

```<code>Date      Home   Away    Season  Home_goals  Away_goals
1.1.2019  Team 1 Team 2  2019    1           1
2.1.2019  Team 3 Team 4  2019    2           3
3.1.2019  Team 1 Team 3  2019    2           1
2.1.2020  Team 1 Team 4  2020    3           4
4.1.2019  Team 1 Team 5  2019    1           3
</code>```

Expected output:

```<code>Date      Home   Away    Season  Home_goals  Away_goals  Mean_home_goals
1.1.2019  Team 1 Team 2  2019    1           1           1
2.1.2019  Team 3 Team 4  2019    2           3           2
3.1.2019  Team 1 Team 3  2019    2           1           1.5((1+3)/2)
2.1.2020  Team 1 Team 4  2020    3           4           3 (its new season)
4.1.2019  Team 1 Team 5  2019    1           3           1.33 ((1+3+1)/3)
</code>```

Thanks

答:
You can do:

```<code>groups = df.groupby(['Home','Season'])['Home_goals']
df['Mean_home_goalds'] = groups.cumsum()/groups.cumcount().add(1)
</code>```

Output:

```<code>       Date    Home    Away  Season  Home_goals  Away_goals  Mean_home_goalds
0  1.1.2019  Team 1  Team 2    2019           1           1          1.000000
1  2.1.2019  Team 3  Team 4    2019           2           3          2.000000
2  3.1.2019  Team 1  Team 3    2019           2           1          1.500000
3  2.1.2020  Team 1  Team 4    2020           3           4          3.000000
4  4.1.2019  Team 1  Team 5    2019           1           3          1.333333
</code>```

Body:
can you please help me with the following situation? I want to groupby my df based on team and season and then I want to get mean of the goals scored till the date of the match. I thought about using rolling, but I cant figure it out how, since for each row it will different.

DF:

Date      Home   Away    Season  Home_goals  Away_goals
1.1.2019  Team 1 Team 2  2019    1           1
2.1.2019  Team 3 Team 4  2019    2           3
3.1.2019  Team 1 Team 3  2019    2           1
2.1.2020  Team 1 Team 4  2020    3           4
4.1.2019  Team 1 Team 5  2019    1           3

Expected output:

Date      Home   Away    Season  Home_goals  Away_goals  Mean_home_goals
1.1.2019  Team 1 Team 2  2019    1           1           1
2.1.2019  Team 3 Team 4  2019    2           3           2
3.1.2019  Team 1 Team 3  2019    2           1           1.5((1+3)/2)
2.1.2020  Team 1 Team 4  2020    3           4           3 (its new season)
4.1.2019  Team 1 Team 5  2019    1           3           1.33 ((1+3+1)/3)

Thanks

Body:
You can do:

groups = df.groupby(['Home','Season'])['Home_goals']
df['Mean_home_goalds'] = groups.cumsum()/groups.cumcount().add(1)

Output:

       Date    Home    Away  Season  Home_goals  Away_goals  Mean_home_goalds
0  1.1.2019  Team 1  Team 2    2019           1           1          1.000000
1  2.1.2019  Team 3  Team 4    2019           2           3          2.000000
2  3.1.2019  Team 1  Team 3    2019           2           1          1.500000
3  2.1.2020  Team 1  Team 4    2020           3           4          3.000000
4  4.1.2019  Team 1  Team 5    2019           1           3          1.333333


问:
Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)
```<code><form class="modal-content" id="bookingForm">
    <div class="formContainer">
      <h1>Booking Form</h1>
      <p>Please fill in this form to Book The Trip.</p>
      <hr>
      <label for="email"><b>Email</b></label>
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      <label><b>Package</b></label>

      <input type="text" id="packageFields" name="teste2">

      <label for="psw"><b>Name</b></label>
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      <label for="psw-repeat"><b>Phone No.</b></label>
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      <label for="psw-repeat"><b>Date Of Journey</b></label>
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

      <p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p>

      <div class="clearfix">
        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>
      </div>
    </div>
  </form>
</div>
    </section>
    <!-- animation -->
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
    AOS.init();

    var modal = document.getElementById('bookingForm');
// Script To Copy Package Name To The Form Automatically
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

function setPackage(packageName) {
  document.querySelector('#packageFields').value = packageName;
}
    </script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>

    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

 <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
 <script src="/__/firebase/7.14.5/firebase-app.js"></script>

 <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
 <script src="/__/firebase/7.14.5/firebase-analytics.js"></script>

 <!-- Add Firebase products that you want to use -->
 <script src="/__/firebase/7.14.5/firebase-auth.js"></script>
 <script src="/__/firebase/7.14.5/firebase-firestore.js"></script>
 <script src="/__/firebase/init.js"></script>
 <script src="bookingSubmit.js">    </script>
</code>```

This Is The Html And The JavaSript Is Given Below:

```<code>var firebaseConfig = {
   apiKey: "AIzaSyDT80mEpNS4CpdByl2ugrSTGzgQpkbzzeI",
   authDomain: "himwhitecab.firebaseapp.com",
   databaseURL: "https://himwhitecab.firebaseio.com",
   projectId: "himwhitecab",
   storageBucket: "himwhitecab.appspot.com",
   messagingSenderId: "505950138314",
   appId: "1:505950138314:web:c37c1b2c593f30e911e933",
   measurementId: "G-ECR97G3YY0"
 };

//reference messages collection

firebase.initializeApp(firebaseConfig);
var firestore =  firebase.firestore();

const submitBtn = document.querySelector("#signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection(BookingData);

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});
</code>```

I am using this to store the data of my contact forms in my Firebase.

But It Gives The Error:

Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
      at initializeApp (http://localhost:5000//firebase/7.14.5/firebase-app.js:1:15287)
      at Object.ee.initializeApp (http://localhost:5000//firebase/7.14.5/firebase-app.js:1:19566)
      at http://localhost:5000/bookingSubmit.js:15:10

How To Solve This Problem....??

Thanks For Help In Advance.

PS: I am Also using one more html file called index.html

答:
You will get that error message if you try to execute initializeApp() more than once on the same page.

Your first execution is here:

```<code>firebase.initializeApp(firebaseConfig);
</code>```

Your second execution is actually inside this script include:

```<code><script src="/__/firebase/init.js"></script>
</code>```

If you want to use that script to automatically initialize Firebase, then you don't need to call initializeApp manually.  Just make sure your Firebase code runs after that script executes.

Body:
<form class="modal-content" id="bookingForm">

Booking Form

Please fill in this form to Book The Trip.

      Email
      <input type="text" placeholder="Enter Email" name="email" required id="email">

      Package

      <input type="text" id="packageFields" name="teste2">

      Name
      <input type="text" placeholder="Enter Name" name="name" required id="name">

      Phone No.
      <input type="tel" placeholder="Enter Phone No." name="psw-repeat" required id="phone">

      Date Of Journey
      <input type="date" placeholder="Enter Phone No." name="psw-repeat" required id="date">

By creating an account you agree to our Terms & Privacy.

        <button type="submit" class="signupbtn">Confirm Booking</button>
        <button type="button" onclick="document.getElementById('bookingForm').style.display='none'" class="cancelbtn">Cancel</button>

  </form>

This Is The Html And The JavaSript Is Given Below:

var firebaseConfig = {
   apiKey: "AIzaSyDT80mEpNS4CpdByl2ugrSTGzgQpkbzzeI",
   authDomain: "himwhitecab.firebaseapp.com",
   databaseURL: "https://himwhitecab.firebaseio.com",
   projectId: "himwhitecab",
   storageBucket: "himwhitecab.appspot.com",
   messagingSenderId: "505950138314",
   appId: "1:505950138314:web:c37c1b2c593f30e911e933",
   measurementId: "G-ECR97G3YY0"
 };

//reference messages collection

firebase.initializeApp(firebaseConfig);
var firestore =  firebase.firestore();

const submitBtn = document.querySelector("#signupbtn");

let email = document.querySelector('#email');
let packageFields = document.querySelector('#packageFields');
let name = document.querySelector('#name');
let phone = document.querySelector('#phone');
let date = document.querySelector('#date');

const db = firestore.collection(BookingData);

submitBtn.addEventListner('click', function(){
  let userEmailInput = email.value;
  let userPackageInput = packageFields.value;
  let userNameInput = name.value;
  let userPhoneInput = phone.value;
  let userDateInput = date.value;

  db.doc()
  .set({
    email:userEmailInput,
    package:userPackageInput,
    name:userNameInput,
    phone:userPhoneInput,
    date:userDateInput
  })
  .then(function(){
    console.log("Data Saved");
  })
  .catch(function(error){
    console.log(error);
  });
});

I am using this to store the data of my contact forms in my Firebase.

But It Gives The Error:

Uncaught FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
      at initializeApp (http://localhost:5000//firebase/7.14.5/firebase-app.js:1:15287)
      at Object.ee.initializeApp (http://localhost:5000//firebase/7.14.5/firebase-app.js:1:19566)
      at http://localhost:5000/bookingSubmit.js:15:10

How To Solve This Problem....??

Thanks For Help In Advance.

PS: I am Also using one more html file called index.html

Body:
You will get that error message if you try to execute initializeApp() more than once on the same page.

Your first execution is here:

firebase.initializeApp(firebaseConfig);

Your second execution is actually inside this script include:

<script src="/__/firebase/init.js"></script>

If you want to use that script to automatically initialize Firebase, then you don't need to call initializeApp manually.  Just make sure your Firebase code runs after that script executes.


问:
Missing return statement, how can I fix?
Goal: I have a class called "InvokeChromeTest" I'm extending to another class called "Base" to access chromedriver and data.properties. When running my code, I get the error:

Error:(22, 3) java: missing return statement

I am unsure how to fix this. Here is my sample code as follows. Please let me know what I can do to fix.

src/test/java/loginPage/InvokeChromeTest

```<code>package loginPage;

import credentials.ProfileCredentials;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import resources.Base;

public class InvokeChromeTest extends Base {

  @Test

  public WebDriver initializeDriver() {
    driver = initializeDriver();
    driver.get(dataProperties.getProperty("url"));
    ProfileCredentials p = new ProfileCredentials(driver);
    p.getAuthorize().click();
    p.getApiKey().sendKeys("testKey");
    p.getAuthCred().click();
    p.getCloseAuth().click();

  }

  @AfterTest
  public void teardown() {
    driver.close();
  }

}
</code>```

src/main/java/resources/Base

```<code>package resources;

import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Base {

  public WebDriver driver;
  protected Properties dataProperties;

  public WebDriver initializeDriver() {
    // Create global property file
    dataProperties = new Properties();
    InputStream dataPropertiesInputStream = null;
    try{
      dataPropertiesInputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
      dataProperties.load(dataPropertiesInputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    String browserName = dataProperties.getProperty("browser");
    System.out.println(browserName);

    if (browserName.equals("chrome")) {
      WebDriverManager.chromedriver().setup();
      driver = new ChromeDriver();
    } else if (browserName.equals("firefox")) {
      WebDriverManager.firefoxdriver().setup();
      driver = new FirefoxDriver();
    }
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    return driver;
  }

}
</code>```

src/main/java/credentials/ProfileCredentials

```<code>package credentials;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class ProfileCredentials {

  WebDriver driver;

  public ProfileCredentials(WebDriver driver) {
    this.driver = driver;
  }

  private By authorize = By.xpath("//button[@class='btn authorize unlocked']");
  private By apikey = By.xpath("//div[@class='wrapper']//section//input");
  private By authorizecred = By.xpath("//button[@class='btn modal-btn auth authorize button']");
  private By closeauth = By.xpath("//button[@class='btn modal-btn auth btn-done button']");

  public WebElement getAuthorize() {
    return driver.findElement(authorize);
  }

  public WebElement getApiKey() {
    return driver.findElement(apikey);
  }

  public WebElement getAuthCred() {
    return driver.findElement(authorizecred);
  }

  public WebElement getCloseAuth() {
    return driver.findElement(closeauth);
  }
}
</code>```

答: I figured out the problem. "Base" and "InvokeChromeTest" had the same method name. This is why it was recursive.</p>

Body:
Goal: I have a class called "InvokeChromeTest" I'm extending to another class called "Base" to access chromedriver and data.properties. When running my code, I get the error:

Error:(22, 3) java: missing return statement

I am unsure how to fix this. Here is my sample code as follows. Please let me know what I can do to fix.

src/test/java/loginPage/InvokeChromeTest

package loginPage;

import credentials.ProfileCredentials;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import resources.Base;

public class InvokeChromeTest extends Base {

  @Test

  public WebDriver initializeDriver() {
    driver = initializeDriver();
    driver.get(dataProperties.getProperty("url"));
    ProfileCredentials p = new ProfileCredentials(driver);
    p.getAuthorize().click();
    p.getApiKey().sendKeys("testKey");
    p.getAuthCred().click();
    p.getCloseAuth().click();

  }

  @AfterTest
  public void teardown() {
    driver.close();
  }

}

src/main/java/resources/Base

package resources;

import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Base {

  public WebDriver driver;
  protected Properties dataProperties;

  public WebDriver initializeDriver() {
    // Create global property file
    dataProperties = new Properties();
    InputStream dataPropertiesInputStream = null;
    try{
      dataPropertiesInputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
      dataProperties.load(dataPropertiesInputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    String browserName = dataProperties.getProperty("browser");
    System.out.println(browserName);

    if (browserName.equals("chrome")) {
      WebDriverManager.chromedriver().setup();
      driver = new ChromeDriver();
    } else if (browserName.equals("firefox")) {
      WebDriverManager.firefoxdriver().setup();
      driver = new FirefoxDriver();
    }
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    return driver;
  }

}

src/main/java/credentials/ProfileCredentials

package credentials;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class ProfileCredentials {

  WebDriver driver;

  public ProfileCredentials(WebDriver driver) {
    this.driver = driver;
  }

  private By authorize = By.xpath("//button[@class='btn authorize unlocked']");
  private By apikey = By.xpath("//div[@class='wrapper']//section//input");
  private By authorizecred = By.xpath("//button[@class='btn modal-btn auth authorize button']");
  private By closeauth = By.xpath("//button[@class='btn modal-btn auth btn-done button']");

  public WebElement getAuthorize() {
    return driver.findElement(authorize);
  }

  public WebElement getApiKey() {
    return driver.findElement(apikey);
  }

  public WebElement getAuthCred() {
    return driver.findElement(authorizecred);
  }

  public WebElement getCloseAuth() {
    return driver.findElement(closeauth);
  }
}


问:
Can't add vertex with python in neptune workbench
I'm trying to put together a demo of Neptune using Neptune workbench, but something's not working right.  I've got this block set up:

from __future__  import print_function  # Python 2/3 compatibility

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

graph = Graph()

cluster_url = #my cluster

remoteConn = DriverRemoteConnection( f'wss://{cluster_url}:8182/gremlin','g')

g = graph.traversal().withRemote(remoteConn)

import uuid

tmp = uuid.uuid4()
tmp_id=str(id)

def get_id(name):
    uid = uuid.uuid5(uuid.NAMESPACE_DNS, f"{name}.licensing.company.com")
    return str(uid)

def add_sku(name):
    tmp_id = get_id(name)
    g.addV('SKU').property('id', tmp_id, 'name', name)
    return name

def get_values():
    return g.V().properties().toList()

```

The problem is that calling add_sku doesn't result in a vertex being added to the graph.  Doing the same operation in a cell with gremlin magic works, and I can retrieve values through python, but I can't add vertices.  Does anyone see what I'm missing here?

答:
The Python code is not working because it is missing a terminal step (next() or iterate()) on the end of it which forces it to evaluate.  If you add the terminal step it should work:</p>

```<code>g.addV('SKU').property('id', tmp_id, 'name', name).next()
</code>```

Body:
I'm trying to put together a demo of Neptune using Neptune workbench, but something's not working right.  I've got this block set up:

from __future__  import print_function  # Python 2/3 compatibility

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

graph = Graph()

cluster_url = #my cluster

remoteConn = DriverRemoteConnection( f'wss://{cluster_url}:8182/gremlin','g')

g = graph.traversal().withRemote(remoteConn)

import uuid

tmp = uuid.uuid4()
tmp_id=str(id)

def get_id(name):
    uid = uuid.uuid5(uuid.NAMESPACE_DNS, f"{name}.licensing.company.com")
    return str(uid)

def add_sku(name):
    tmp_id = get_id(name)
    g.addV('SKU').property('id', tmp_id, 'name', name)
    return name

def get_values():
    return g.V().properties().toList()

The problem is that calling add_sku doesn't result in a vertex being added to the graph.  Doing the same operation in a cell with gremlin magic works, and I can retrieve values through python, but I can't add vertices.  Does anyone see what I'm missing here?

Body:
The Python code is not working because it is missing a terminal step (next() or iterate()) on the end of it which forces it to evaluate.  If you add the terminal step it should work:

g.addV('SKU').property('id', tmp_id, 'name', name).next()


问:
NULL values are not inserted into sql table
I have a CSV file with three columns of "movieId", "imdbId", "tmdbId". The column "tmdbId" contains multiple empty rows.(movieId is a froeign key referring to a primary key in another table)

When I read this data frame into R, the empty rows are treated as NA values. If I import this CSV file into mysql DB using the following command, the rows with NA values don’t get inserted in the table, even though I allow NULL values. I should also mention that, I do not get any errors.

Beside the following command, I also tried importing the dataset using MySQL workbench, but it did not work.

any suggestion?

```<code>LOAD DATA LOCAL INFILE 'links.csv' INTO TABLE links
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(movieId, imdbId, tmdbId);
</code>```

I know NULL and NA values are not the same, but I do not understand why R treats empty rows as NA. I tried to replace NA with NULL, but R does not support this operation.

The TABLE

```<code>CREATE TABLE links (
    movieId int NOT NULL,
    imdbId int DEFAULT NULL,
    tmdbId int DEFAULT NULL,
    KEY movieId (movieId),
    CONSTRAINT links_ibfk_1 FOREIGN KEY (movieId) REFERENCES movieId_title (movieId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

The CSV file looks like this:
enter image description here

Here is an example of an empty row for the third column:
enter image description here

答:
As @Alec suggested, you can do set foreign_key_checks = 0. Then, you can replace zeros with NULL using the following command:

```<code>UPDATE table_name
SET col_name= NULL
WHERE  col_name  = 0;
</code>```

Body:
I have a CSV file with three columns of "movieId", "imdbId", "tmdbId". The column "tmdbId" contains multiple empty rows.(movieId is a froeign key referring to a primary key in another table)

When I read this data frame into R, the empty rows are treated as NA values. If I import this CSV file into mysql DB using the following command, the rows with NA values don’t get inserted in the table, even though I allow NULL values. I should also mention that, I do not get any errors.

Beside the following command, I also tried importing the dataset using MySQL workbench, but it did not work.

any suggestion?

LOAD DATA LOCAL INFILE 'links.csv' INTO TABLE links
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(movieId, imdbId, tmdbId);

I know NULL and NA values are not the same, but I do not understand why R treats empty rows as NA. I tried to replace NA with NULL, but R does not support this operation.

The TABLE

CREATE TABLE links (
    movieId int NOT NULL,
    imdbId int DEFAULT NULL,
    tmdbId int DEFAULT NULL,
    KEY movieId (movieId),
    CONSTRAINT links_ibfk_1 FOREIGN KEY (movieId) REFERENCES movieId_title (movieId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

The CSV file looks like this:
enter image description here

Here is an example of an empty row for the third column:
enter image description here

Body:
As @Alec suggested, you can do set foreign_key_checks = 0. Then, you can replace zeros with NULL using the following command:

UPDATE table_name
SET col_name= NULL
WHERE  col_name  = 0;


问:
unable to install the python library "requests" on windows 7
Encountering error while running the command

```<code>pip install requests
</code>```

or

```<code>pip3 install requests
</code>```

same error while installing any other python package on this system. Do I need to get any port opened on this system?

```<code>Collecting requests
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  Could not fetch URL https://pypi.org/simple/requests/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerific
ationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self
signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
  ERROR: Could not find a version that satisfies the requirement requests (from
versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming
 the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retrie
s exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1
, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certi
ficate in certificate chain (_ssl.c:1108)'))) - skipping
</code>```

答:
i think your problem is related with a proxy, not a firewall.
anyway maybe you can ask pip to ignore the certificate issue, take a read at this post </p>

Body:
Encountering error while running the command

pip install requests

or

pip3 install requests

same error while installing any other python package on this system. Do I need to get any port opened on this system?

Collecting requests
  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, stat
us=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL
: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate
in certificate chain (_ssl.c:1108)'))': /simple/requests/
  Could not fetch URL https://pypi.org/simple/requests/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerific
ationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self
signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
  ERROR: Could not find a version that satisfies the requirement requests (from
versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming
 the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retrie
s exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1
, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certi
ficate in certificate chain (_ssl.c:1108)'))) - skipping


问:
Inspecting HTTP POST headers in Python without downloading body
A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded?

```<code>opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProcessor, HTTPRefreshProcessor)
r = make_post_request() # makes Request object to send
res = opener.open(r)
info = response.info()
content_disp = info.getheader('content-disposition')
filename = content_disp.split('=')[1]
content = res.read() # or skip based on filename
</code>```

I was under the impression that the body won't download until read(), which would be useful for skipping certain download (such as files already downloaded) but I am not seeing great deal of performance improvement.

答: HTTP is a connection-less protocol, meaning that there is no channel established, in which a server could write data in several steps. So If a POST or a GET request is send to a sever, it MUST responds with a complete response, as it can't know, if itwas the 1st or 2nd request. Cookies, AJAX, Comet helps to emulate something like a channel, but there isn't one. Thats why there is the HEAD request: With this the browser can determine, if a resource must be loaded or not.</p>

Body:
A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded?

opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProcessor, HTTPRefreshProcessor)
r = make_post_request() # makes Request object to send
res = opener.open(r)
info = response.info()
content_disp = info.getheader('content-disposition')
filename = content_disp.split('=')[1]
content = res.read() # or skip based on filename

I was under the impression that the body won't download until read(), which would be useful for skipping certain download (such as files already downloaded) but I am not seeing great deal of performance improvement.


问:
Hide/show options of optgroup (angular material) with a click
I have a list of interventions, interv1, interv2, interv3 ...
for each of these interventions, i have a list of elements, it gives this following :

```<code><mat-optgroup *ngFor="let interv of listIntervDiag" [label]="interv.name" [disabled]="interv.disabled">
         <mat-option *ngFor="let element of interv.listElement" [value]="option">
                      {{ element }}
         </mat-option>
</mat-optgroup>
</code>```

I would like to do a tree (like here https://material.angular.io/components/tree/overview) but in the select element.

At the beginning I show only my OptGroup, when click on one of these group options, I want to show the list of elements related to (the options)

Is it possible to do that ?

maybe not ... I guess the solution could be to do 2 select, and according to the selection of the first select it shows differents element in the second one (which is disable if nothing is selected in the first one).

Thanks for your help

答:
Adding to the hide show response to stop the list from scrolling when you select items.  Add cdk virtual scrolling </p>

```<code>  <mat-select [value]="selections | async" multiple >
    <cdk-virtual-scroll-viewport [itemSize]="10">
      <mat-optgroup *cdkVirtualFor="let interv of listIntervDiag"; let i = index;">
        <mat-label (click)="activeToggler(i)">{{interv.name}}</mat-label>
        <mat-option [class.active]="i === activeClassIndex"
        *ngFor="let childOption of interv.children" [value]="childOption">
          {{childOption.name}}
        </mat-option>
      </mat-optgroup>
    </cdk-virtual-scroll-viewport>
  </mat-select>
</code>```

<p>& css</p>

```<code>cdk-virtual-scroll-viewport {
  height: 256px;
}
</code>```

Body:
I have a list of interventions, interv1, interv2, interv3 ...
for each of these interventions, i have a list of elements, it gives this following :

<mat-optgroup *ngFor="let interv of listIntervDiag" [label]="interv.name" [disabled]="interv.disabled">
         <mat-option *ngFor="let element of interv.listElement" [value]="option">
                      {{ element }}
         </mat-option>
</mat-optgroup>

I would like to do a tree (like here https://material.angular.io/components/tree/overview) but in the select element.

At the beginning I show only my OptGroup, when click on one of these group options, I want to show the list of elements related to (the options)

Is it possible to do that ?

maybe not ... I guess the solution could be to do 2 select, and according to the selection of the first select it shows differents element in the second one (which is disable if nothing is selected in the first one).

Thanks for your help

Body:
Adding to the hide show response to stop the list from scrolling when you select items.  Add cdk virtual scrolling

  <mat-select [value]="selections | async" multiple >
    <cdk-virtual-scroll-viewport [itemSize]="10">
      <mat-optgroup *cdkVirtualFor="let interv of listIntervDiag"; let i = index;">
        <mat-label (click)="activeToggler(i)">{{interv.name}}</mat-label>
        <mat-option [class.active]="i === activeClassIndex"
        *ngFor="let childOption of interv.children" [value]="childOption">
          {{childOption.name}}
        </mat-option>
      </mat-optgroup>
    </cdk-virtual-scroll-viewport>
  </mat-select>

& css

cdk-virtual-scroll-viewport {
  height: 256px;
}


问:
Laravel Relationship between two tables error after submitting the first post
Post Model:

```<code>class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class, 'id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class, 'id');
    }

    public function size()
    {
        return $this->hasOne(Size::class, 'id');
    }
}
</code>```

index.blade.php:

```<code>@foreach ($posts as $post)
    <td><img src="{{ url('storage/'. $post->image) }}" width="100" height="50"></td>
    <td>{{ $post->name }}</td>
    <td>{{ $post->size->name }}</td>
    <td>{{ $post->category->name }}</td>
    <td>{{ $post->gender->name }}</td>
    <td>{{ $post->price }} $</td>
    <td></td>
    </tbody>
@endforeach
</code>```

Posts table:

```<code>public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('genders_id');
        $table->string('sizes_id');
        $table->string('categories_id');
        $table->integer('price');
        $table->string('image');
        $table->timestamps();
    });
}
</code>```

PostsController:

```<code>public function store(PostValidation $request)
{
    $image = $request->file('image')->store('image');

    Post::create([
        'name' => $request->name,
        'image' => $image,
        'genders_id' => $request->gender,
        'categories_id' => $request->categories,
        'sizes_id' => $request->size,
        'price' => $request->price
    ]);

    return redirect(route('post.index'));
}
</code>```

The issue is {{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }} works after my first post, whenever I add a second post it gives me the following error:

Trying to get property 'name' of non-object (View:
  C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php)
  {{ $post->size->name }}

答:
Try to update your model like following, you mixed up the order of parameters in hasOne() :

```<code>class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class,'categories_id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class,'genders_id');
    }

    public function size()
    {
        return $this->hasOne(Size::class,'sizes_id');
    }
}
</code>```

The standard naming scheme for 1 to many relation is singular column names:

```<code>        'genders_id' => 'gender_id'
        'categories_id' => 'category_id'
        'sizes_id' => 'size_id'
</code>```

Body:
Post Model:

class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class, 'id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class, 'id');
    }

    public function size()
    {
        return $this->hasOne(Size::class, 'id');
    }
}

index.blade.php:

@foreach ($posts as $post)
    image) }}" width="100" height="50">
    {{ $post->name }}
    {{ $post->size->name }}
    {{ $post->category->name }}
    {{ $post->gender->name }}
    {{ $post->price }} $

@endforeach

Posts table:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('genders_id');
        $table->string('sizes_id');
        $table->string('categories_id');
        $table->integer('price');
        $table->string('image');
        $table->timestamps();
    });
}

PostsController:

public function store(PostValidation $request)
{
    $image = $request->file('image')->store('image');

    Post::create([
        'name' => $request->name,
        'image' => $image,
        'genders_id' => $request->gender,
        'categories_id' => $request->categories,
        'sizes_id' => $request->size,
        'price' => $request->price
    ]);

    return redirect(route('post.index'));
}

The issue is {{ $post->size->name }} {{ $post->gender->name }} {{ $post->category->name }} works after my first post, whenever I add a second post it gives me the following error:

Trying to get property 'name' of non-object (View:
  C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php)
  {{ $post->size->name }}

Body:
Try to update your model like following, you mixed up the order of parameters in hasOne() :

class Post extends Model
{
    protected $fillable = [
        'name',
        'image',
        'genders_id',
        'categories_id',
        'sizes_id',
        'price'
    ];

    public function category()
    {
        return $this->hasOne(Category::class,'categories_id');
    }

    public function gender()
    {
        return $this->hasOne(Gender::class,'genders_id');
    }

    public function size()
    {
        return $this->hasOne(Size::class,'sizes_id');
    }
}

The standard naming scheme for 1 to many relation is singular column names:

        'genders_id' => 'gender_id'
        'categories_id' => 'category_id'
        'sizes_id' => 'size_id'


问:
Functions In CoffeeScript
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

```<code>function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}
</code>```

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

```<code><script type="text/javascript" src="../coffee/convert.js"></script>

<script type="text/javascript">
    convert(6, 3, 10);
</script>
</code>```

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

答:
```<code>convert = (num1, num2, num3) -> num1 + num2 * num3
</code>```

Title: Functions In CoffeeScript

Body:
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?


问:
CSS selector. Select one of two classes with the similar name
I try to parse web-site using AngleSharpe and I have the following case:

```<code><div class="list another">
  <div class="item1"></div>
  <div class="item2"></div>
</div>

...

<div class="list">
  <div class="item1"></div>
  <div class="item2"></div>
</div>
</code>```

I need to get class "list", but I'm getting the first "list another" by order.

```<code>var selector = @"div[class$='list']";
var cell = document.QuerySelectorAll(selector);
</code>```

I tried to use the following various:

```<code>"div[class$=list]"
"div.list"
</code>```

When I'm using selector with parent class of "list", which differ from parent class of "list another" like "parent class > list", I don't get nothing.

Please give me advice how will be right or where necessary see to solve this issue

答: Thanks a lot everyone! It didn't work because I didn't notice that this class is changing by script in browser. And because of this class unavailable in AngleSharp. I found "nonscript" section.</p>

Body:
I try to parse web-site using AngleSharpe and I have the following case:

...

I need to get class "list", but I'm getting the first "list another" by order.

var selector = @"div[class$='list']";
var cell = document.QuerySelectorAll(selector);

I tried to use the following various:

"div[class$=list]"
"div.list"

When I'm using selector with parent class of "list", which differ from parent class of "list another" like "parent class > list", I don't get nothing.

Please give me advice how will be right or where necessary see to solve this issue


问:
Cannot find a module json
I need to import this json file that it is in the assets filder.

```<code>{
    "HOME": "home"
}
</code>```

So I do in my component:

```<code>  import config from "../../../assets/file/config.json";
</code>```

But I obtain this error:

```<code>Cannot find module '../../..//config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
</code>```

So I modified my tsconfig.json in this way:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "resolveJsonModule": true,
    "esModuleInterop": true
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
</code>```

But the error it doesn't disappear, it is throwed the same. Anyone can help me?

folder structure is

```<code>assets/ file/ and in the /file there is the config.jo;
</code>```

答:
Try importing it directly from the asset as :

```<code> import config from "assets/file/config.json";
</code>```

And further, if it doesn't work, you may need to set "resolveJsonModule": true in ts.config

Title: Cannot find a module json

Body:
I need to import this json file that it is in the assets filder.

{
    "HOME": "home"
}

So I do in my component:

  import config from "../../../assets/file/config.json";

But I obtain this error:

Cannot find module '../../..//config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

So I modified my tsconfig.json in this way:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "resolveJsonModule": true,
    "esModuleInterop": true
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

But the error it doesn't disappear, it is throwed the same. Anyone can help me?

folder structure is

assets/ file/ and in the /file there is the config.jo;

Body:
Try importing it directly from the asset as :

 import config from "assets/file/config.json";

And further, if it doesn't work, you may need to set "resolveJsonModule": true in ts.config


问:
Active checkbox changes table background color except for a cell
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html></code>```

Thanks already for the help.

答:
If your table is always the same HTML structure, you can select via :nth-child() any element inside the HTML tree.

for instance :  #checkbox_id:checked + table  tbody tr:nth-child(1) td:nth-child(2)

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }
    #checkbox_id:checked + table  tbody tr:nth-child(1) td:nth-child(2) {
      background-color: red;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html></code>```

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.

other option, select cells with a class and overwrite bg color

```<code> #checkbox_id:checked + table  td {
      background-color: red;
    }
    #checkbox_id:checked + table  [class]{
      background-color: yellow;
    }
</code>```

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table  td {
      background-color: red;
    }
    #checkbox_id:checked + table  [class]{
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html></code>```

Body:
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Check6</title>

    CLICCA
    <input type="checkbox" id="checkbox_id">

Thanks already for the help.

Body:
If your table is always the same HTML structure, you can select via :nth-child() any element inside the HTML tree.

for instance :  #checkbox_id:checked + table  tbody tr:nth-child(1) td:nth-child(2)

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }
    #checkbox_id:checked + table  tbody tr:nth-child(1) td:nth-child(2) {
      background-color: red;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html>

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.

other option, select cells with a class and overwrite bg color

 #checkbox_id:checked + table  td {
      background-color: red;
    }
    #checkbox_id:checked + table  [class]{
      background-color: yellow;
    }

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table  td {
      background-color: red;
    }
    #checkbox_id:checked + table  [class]{
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html>


问:
Restore DB using a bak file. The backup set holds a backup of a database other than the existing database
I am attempting to restore a DB for example versionB using a .bak file of version A.

It seems like that is not the right thing to do because I am getting an error:

TITLE: Microsoft SQL Server Management Studio

Restore of database 'B' failed.

  (Microsoft.SqlServer.Management.RelationalEngineTasks)

ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing 'B' database. (Microsoft.SqlServer.SmoExtended)

答:
To overwrite a database with a backup taken from a different database you must specify the WITH REPLACE option in the RESTORE command.

REPLACE should be used rarely and only after careful consideration.
  Restore normally prevents accidentally overwriting a database with a
  different database. If the database specified in a RESTORE statement
  already exists on the current server and the specified database family
  GUID differs from the database family GUID recorded in the backup set,
  the database is not restored. This is an important safeguard.