问:
pg_dump version mismatch
I have a remote postgres DB version 10.8 setup on a linux. I am trying to back it up on windows machine using postgres 9.6.12

pg_dump --host dahost --port 5432 --username "postgres" --no-password  --format tar --blobs --verbose --file "path\noury.backup" "highlands_wastewater"
```

<p>I get these errors</p>

```pg_dump: server version: 10.8 (Ubuntu 10.8-0ubuntu0.18.04.1); pg_dump version: 9.6.12
pg_dump: aborting because of server version mismatch
```

How can I backup this database remotely?

答:
As the error message says, you cannot use an older version of pg_dump with a newer PostgreSQL Version.

The reason behind that is that PostgreSQL 9.6 cannot know how to dump a v10 database properly — there may be new features in the newer version (for example, partitioned tables).

You'll have to install PostgreSQL v10 or later on your Windows machine (exactly v10 if you want to be able to restore the dump to the original database).

Don't use the tar format. The custom format offers more advantages.

Title: pg_dump version mismatch

Body:
I have a remote postgres DB version 10.8 setup on a linux. I am trying to back it up on windows machine using postgres 9.6.12

pg_dump --host dahost --port 5432 --username "postgres" --no-password  --format tar --blobs --verbose --file "path\noury.backup" "highlands_wastewater"

I get these errors

pg_dump: server version: 10.8 (Ubuntu 10.8-0ubuntu0.18.04.1); pg_dump version: 9.6.12
pg_dump: aborting because of server version mismatch

How can I backup this database remotely?


来源: stackexchange

问:
How to load external resources in Angular 7
In Angular 6, I was able to use external resources by adding below in angular.json

```<code>"assets": [
{"glob":"**/*", "input":"node_modules/xx", "output": "./yy"},
{"glob":"**/*", "input":"node_modules/mxgraph/javascript/src", "output": "./mxgraph"}
]
</code>```

In Angular 7 it does not work anymore. How do I achieve it in Angular 7?

答:
Try removing the period in the output path, and use a period for the input path. The output path is relative to the dist folder, and the input path is relative to the to where you run ng build.

```<code>"assets": [
   {"glob":"**/*", "input":"./node_modules/xx", "output": "/yy"},
   {"glob":"**/*", "input":"./node_modules/mxgraph/javascript/src", "output": "/mxgraph"}
]
</code>```

In Angular 7 it does not work anymore. How do I achieve it in Angular 7?

I don't think anything has changed between Angular 6 and 7 in regards to assert globs.

Please see the documentation:

https://github.com/angular/angular-cli/wiki/stories-asset-configuration

ContentLicense: CC BY-SA 4.0

Body:
In Angular 6, I was able to use external resources by adding below in angular.json

"assets": [
{"glob":"**/*", "input":"node_modules/xx", "output": "./yy"},
{"glob":"**/*", "input":"node_modules/mxgraph/javascript/src", "output": "./mxgraph"}
]

In Angular 7 it does not work anymore. How do I achieve it in Angular 7?

Body:
Try removing the period in the output path, and use a period for the input path. The output path is relative to the dist folder, and the input path is relative to the to where you run ng build.

"assets": [
   {"glob":"**/*", "input":"./node_modules/xx", "output": "/yy"},
   {"glob":"**/*", "input":"./node_modules/mxgraph/javascript/src", "output": "/mxgraph"}
]

In Angular 7 it does not work anymore. How do I achieve it in Angular 7?

I don't think anything has changed between Angular 6 and 7 in regards to assert globs.

Please see the documentation:

https://github.com/angular/angular-cli/wiki/stories-asset-configuration


问:
javax.inject.Provider vs String
I am trying to retrieve a set of JNDI keys in a webapp during the runtime.
The code looks like:

```<code>class Test{
    private final String someUrl;

    public Test(@Named("URL") String someUrl){
    // do something
    }

     public void dotEST( string someUrl){
      String x = someUrl;
      //some other logic
     }

}
</code>```

I want to understand the difference between using the above code and this:

```<code>class Test{
    private final Provider<String> someUrl;

    public Test(@Named("URL") Provider<String> someUrl){
    // do something
    }

     public void dotEST( Provider<String> someUrl){
      String x = someUrl.get();
      //some other logic
     }
}
</code>```

When and why should I use provider?

答:
```<code> public Test(@Named("URL") String someUrl){
</code>```

To call this method, someUrl must already be resolved and available (eg to the container)

```<code>public Test(@Named("URL") Provider<String> someUrl){
</code>```

here, retrieval can be postponed (or even not done) - its similar to lazy initialization. It dependes on implementation of Provider interface.

Title: javax.inject.Provider vs String

Body:
I am trying to retrieve a set of JNDI keys in a webapp during the runtime.
The code looks like:

class Test{
    private final String someUrl;

    public Test(@Named("URL") String someUrl){
    // do something
    }

     public void dotEST( string someUrl){
      String x = someUrl;
      //some other logic
     }

}

I want to understand the difference between using the above code and this:

class Test{
    private final Provider<String> someUrl;

    public Test(@Named("URL") Provider<String> someUrl){
    // do something
    }

     public void dotEST( Provider<String> someUrl){
      String x = someUrl.get();
      //some other logic
     }
}

When and why should I use provider?

Body:
 public Test(@Named("URL") String someUrl){

To call this method, someUrl must already be resolved and available (eg to the container)

public Test(@Named("URL") Provider<String> someUrl){

here, retrieval can be postponed (or even not done) - its similar to lazy initialization. It dependes on implementation of Provider interface.


问:
Why is there still a conflict between prototype and jquery?
I've already read about how to load prototype and jquery together but these techniques are not solving the problem.

I load jquery then this file (http://music.glumbo.com/izzyFeedback.js) and then prototype.

I've wrapped parts that use $ in izzyFeedback.js in

```<code>(function($) {

})(jQuery);
</code>```

but this does not work. If I comment out the prototype load then it works correctly.

答:
The JavaScript error console shows this:

```<code>Uncaught exception: TypeError: Cannot convert 'a' to object

Error thrown at line 1, column 62584 in initWidgetOnSuccess(a) in http://w.sharethis.com/share4x/js/st.8420922a8df40577276f021cf40c4bea.js:
    widget.metaInfo=a.data;
called from line 1, column 0 in http://wd.sharethis.com/api/getApi.php?return=json&url=http%3A%2F%2Fmusic.glumbo.com%2F&fpc=b3bd5f6-12f4973f8f5-23e02178-1&cb=initWidgetOnSuccess&service=initWidget:
    initWidgetOnSuccess();
</code>```

You attempt to retrieve the a.data property and a is not an object. The error appears to be that getApi.php does not return a valid JSON string.

ContentLicense: CC BY-SA 3.0

Body:
I've already read about how to load prototype and jquery together but these techniques are not solving the problem.

I load jquery then this file (http://music.glumbo.com/izzyFeedback.js) and then prototype.

I've wrapped parts that use $ in izzyFeedback.js in

(function($) {

})(jQuery);

but this does not work. If I comment out the prototype load then it works correctly.

Body:
The JavaScript error console shows this:

Uncaught exception: TypeError: Cannot convert 'a' to object

Error thrown at line 1, column 62584 in initWidgetOnSuccess(a) in http://w.sharethis.com/share4x/js/st.8420922a8df40577276f021cf40c4bea.js:
    widget.metaInfo=a.data;
called from line 1, column 0 in http://wd.sharethis.com/api/getApi.php?return=json&url=http%3A%2F%2Fmusic.glumbo.com%2F&fpc=b3bd5f6-12f4973f8f5-23e02178-1&cb=initWidgetOnSuccess&service=initWidget:
    initWidgetOnSuccess();

You attempt to retrieve the a.data property and a is not an object. The error appears to be that getApi.php does not return a valid JSON string.


问:
How to split a long number into pairs of digits
I have a string of a long number 12345678 and want to convert it to an array like this :

```<code>["12", "34", "56", "78"].
</code>```

I have tried array.split(//).map { |e| e.to_i  }  but it does

```<code>["1", "2", "3", "4", "5", "6", "7", "8"]
</code>```

答:
I think there is no need to use a regexp, I would do something like this:</p>

```<code>12345678.to_s.chars.each_slice(2).map(&:join)
#=> ["12","34","56","78"]
</code>```

Body:
I have a string of a long number 12345678 and want to convert it to an array like this :

["12", "34", "56", "78"].

I have tried array.split(//).map { |e| e.to_i  }  but it does

["1", "2", "3", "4", "5", "6", "7", "8"]

Body:
I think there is no need to use a regexp, I would do something like this:

12345678.to_s.chars.each_slice(2).map(&:join)
#=> ["12","34","56","78"]


问:
% change of 2 time period calculations in SQL (GBQ)
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019
```

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

答:
You can use conditional aggregation.  I'm not sure exactly what calculation you want, but something like this:</p>

```<code>SELECT (SUM(CASE WHEN YEAR = 2019 THEN A END) / SUM(CASE WHEN YEAR = 2018 THEN A) END) - 1 AS CALCULATION
FROM TABLE
WHERE YEAR IN (2018, 2019)
</code>```

Body:
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

Body:
You can use conditional aggregation.  I'm not sure exactly what calculation you want, but something like this:

SELECT (SUM(CASE WHEN YEAR = 2019 THEN A END) / SUM(CASE WHEN YEAR = 2018 THEN A) END) - 1 AS CALCULATION
FROM TABLE
WHERE YEAR IN (2018, 2019)


问:
How to stop Function reassigning Boolean value within loop
Im trying to learn Python via creating a basic language-learning app to test myself. In order to get it to test me with a different word each time I have tried to write a function that generates an intial key ONLY IF it is the first time it is run (after this i have another function which should generate a different key).

In order to do this I have tried to us a Boolean (isfirsttime) which I initially set to False within the main loop of the particular Tkinter window in which this part of the code runs (sorry if I'm not explaining this particulary well am admittedly a total begginer!).
 Within my function I then check if this value is False and then - it is - i generate a key and pass out this plus the value TRUE.
 Back in the main loop I then assign the value True to the variable isfirsttime.
 I think that the problem is that in the main loop the isfirsttime is FIRST assigned to False (to get the function checkfirst to work the first time) but this means that every time it is run it resets the Boolean to False.
 Could anybody explain to me how I can reassign the value of isfirst time to TRUE after the first time the code has run, in a way that will cause the checkfirst function to PASS everytime after that? (I know that my problem has something to do with scope but i cannot figure it out - and have tried functions within functions and endlessly reassigning variables so I'm obviously not getting something here!)
 Many thanks!

```<code>isfirsttime == False
             def checkfirst():
                 if isfirsttime==False:
                     for item in categories:
                             newkey=random.choice(list(tempdict))
                             print("key is" + newkey)
                     isfirsttime=not isfirsttime
                     print(str(isfirsttime) + "isfirsttime")
                     return newkey, True
                 else:
                     pass
genkey=checkfirst()[0]
isfirsttime=checkfirst()[1]
</code>```

答:
You can make the call like this:

```<code>genkey, isfirsttime = checkfirst()
</code>```

However, you still need to do something about the second time that checkfirst() is called.

Also, reading the comments under your question you need to sort out the assignment to isfirsttime:

```<code>isfirsttime = False         # assign isfirsttime to False
def checkfirst():
    # stuff omitted
</code>```

Body:
Im trying to learn Python via creating a basic language-learning app to test myself. In order to get it to test me with a different word each time I have tried to write a function that generates an intial key ONLY IF it is the first time it is run (after this i have another function which should generate a different key).

In order to do this I have tried to us a Boolean (isfirsttime) which I initially set to False within the main loop of the particular Tkinter window in which this part of the code runs (sorry if I'm not explaining this particulary well am admittedly a total begginer!).
 Within my function I then check if this value is False and then - it is - i generate a key and pass out this plus the value TRUE.
 Back in the main loop I then assign the value True to the variable isfirsttime.
 I think that the problem is that in the main loop the isfirsttime is FIRST assigned to False (to get the function checkfirst to work the first time) but this means that every time it is run it resets the Boolean to False.
 Could anybody explain to me how I can reassign the value of isfirst time to TRUE after the first time the code has run, in a way that will cause the checkfirst function to PASS everytime after that? (I know that my problem has something to do with scope but i cannot figure it out - and have tried functions within functions and endlessly reassigning variables so I'm obviously not getting something here!)
 Many thanks!

isfirsttime == False
             def checkfirst():
                 if isfirsttime==False:
                     for item in categories:
                             newkey=random.choice(list(tempdict))
                             print("key is" + newkey)
                     isfirsttime=not isfirsttime
                     print(str(isfirsttime) + "isfirsttime")
                     return newkey, True
                 else:
                     pass
genkey=checkfirst()[0]
isfirsttime=checkfirst()[1]

Body:
You can make the call like this:

genkey, isfirsttime = checkfirst()

However, you still need to do something about the second time that checkfirst() is called.

Also, reading the comments under your question you need to sort out the assignment to isfirsttime:

isfirsttime = False         # assign isfirsttime to False
def checkfirst():
    # stuff omitted


问:
Getting MonthAndYear name in sql?
I need a small script to get the current month name and current year. So as to create a unique batch to store statements. My preferred format is January2011 or Feb2011 whichever is easier to get. i.e. MonthYear</p>

答:
Try a query that looks like this:

```<code>SELECT DATENAME(month, GETDATE()), DATENAME(year, GETDATE());
</code>```

You can find some more information over here.

Title: Getting MonthAndYear name in sql?

Body:
Try a query that looks like this:

SELECT DATENAME(month, GETDATE()), DATENAME(year, GETDATE());

You can find some more information over here.


问:
na.locf - Negative length vectors are not allowed
I am trying carry forward non-na values until reaching the next non-na with the following code:

```<code>test3 <- data.table(final_data)

test3 <- test3[, na.locf(test3, na.rm = F, fromLast = F, maxgap = Inf), by = "gvkey"]
</code>```

It works when I don't include the ... by = gvkey] part.
However, I need the code to stop when reaching a new gvkey, bc otherwise it would carry forward wrong company data. I got it in long format (example below). As you can see, what happens if i don't use ...by = gvkey], it carries the value of gvkey1 over to gvkey2, which I want to avoid. But when doing so, I receive the following error message:

```<code>Error in `[.data.table`(test3, , na.locf(test3, na.rm = F, fromLast = F,  :
  negative length vectors are not allowed
</code>```

date	gvkey	dlcq	dlttq

date1	gvkey1	10	20

date2	gvkey1	NA	NA

date3	gvkey1	NA	10

.

.

.

date10	gvkey2	NA	NA

date11	gvkey2	10	NA

date12	gvkey2	NA	NA

```

Any suggestions/solutions very welcome!

答:
Using data.table::nafill() from the lastest development release (v1.12.3) form data.table

```<code>DT <- fread("date | gvkey | dlcq | dlttq
            date1 | gvkey1 | 10 | 20
            date2 | gvkey1 | NA | NA
            date3 | gvkey1 | NA | 10
            date10 | gvkey2 | NA | NA
            date11 | gvkey2 | 10 | NA
            date12 | gvkey2 | NA | NA")

cols = c("dlcq", "dlttq")
DT[, (cols) := lapply( .SD, nafill, type = "locf" ), by = gvkey, .SDcols = cols][]

#      date  gvkey dlcq dlttq
# 1:  date1 gvkey1   10    20
# 2:  date2 gvkey1   10    20
# 3:  date3 gvkey1   10    10
# 4: date10 gvkey2   NA    NA
# 5: date11 gvkey2   10    NA
# 6: date12 gvkey2   10    NA
</code>```

see: https://github.com/Rdatatable/data.table/wiki/Installation for instructions about loading the dev-version.

Body:
I am trying carry forward non-na values until reaching the next non-na with the following code:

test3 <- data.table(final_data)

test3 <- test3[, na.locf(test3, na.rm = F, fromLast = F, maxgap = Inf), by = "gvkey"]

It works when I don't include the ... by = gvkey] part.
However, I need the code to stop when reaching a new gvkey, bc otherwise it would carry forward wrong company data. I got it in long format (example below). As you can see, what happens if i don't use ...by = gvkey], it carries the value of gvkey1 over to gvkey2, which I want to avoid. But when doing so, I receive the following error message:

Error in `[.data.table`(test3, , na.locf(test3, na.rm = F, fromLast = F,  :
  negative length vectors are not allowed

date	gvkey	dlcq	dlttq

date1	gvkey1	10	20

date2	gvkey1	NA	NA

date3	gvkey1	NA	10

.

.

.

date10	gvkey2	NA	NA

date11	gvkey2	10	NA

date12	gvkey2	NA	NA

Any suggestions/solutions very welcome!

Body:
Using data.table::nafill() from the lastest development release (v1.12.3) form data.table

DT <- fread("date | gvkey | dlcq | dlttq
            date1 | gvkey1 | 10 | 20
            date2 | gvkey1 | NA | NA
            date3 | gvkey1 | NA | 10
            date10 | gvkey2 | NA | NA
            date11 | gvkey2 | 10 | NA
            date12 | gvkey2 | NA | NA")

cols = c("dlcq", "dlttq")
DT[, (cols) := lapply( .SD, nafill, type = "locf" ), by = gvkey, .SDcols = cols][]

#      date  gvkey dlcq dlttq
# 1:  date1 gvkey1   10    20
# 2:  date2 gvkey1   10    20
# 3:  date3 gvkey1   10    10
# 4: date10 gvkey2   NA    NA
# 5: date11 gvkey2   10    NA
# 6: date12 gvkey2   10    NA

see: https://github.com/Rdatatable/data.table/wiki/Installation for instructions about loading the dev-version.


问:
Google Sheets Conditional Formatting of another cell based on variable values
I have rows that include various totals of either 5, 10 or 12. I also have checkboxes that add up to a total of 12, and a cell value for each row that calculates the difference to reveal how many are left.

I'm wanting the last result cells to show colours from red to yellow to green that is independently reliant on the first cells value to show a specific shade of green/yellow/red. I'm only able to select a colour based on the single columns/cells value and not the value of another column/cell. Is this even possible?

I've run through a number of examples given on google and answers based on similar questions, but nothing seems to solve this specific situation.

This is what I'm expecting to happen: Green Yellow Red

For Green Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 10            | Green

Row 3:  5                 | 5             | Green

Row 4:  12                | 12            | Green
</code>```

For Variable Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 5             | Yellow

Row 3:  5                 | 4             | Green

Row 4:  12                | 3             | Red
</code>```

For Red Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 0             | Red

Row 3:  5                 | 1             | Red

Row 4:  12                | 2             | Red
</code>```

Basically: If we're looking at 3 cells next to each other in ABC, then if B is the variable, and A is the total value, then C should show the colour based on how equal B is to A for Green, or how much lower the value of B is to A for Yellow to Red.

答:
You can simply quote cells in conditional formatting formulae. For example, you could have cell C2 format based on the equation:

```<code>=A2>B2
</code>```

I think, based on what you've given, you want to scale it based on how much bigger the first is to the second. ie: if A is much bigger than B, turn C red but if A=B, turn C green. If that's the case then you can do colour scales with:

```<code>Minpoint: = 0    Red
Midpoint: = A2/2 Yellow
Maxpoint: = A2   Green
</code>```

And then put

```<code>=B2
</code>```

in C2.

Body:
I have rows that include various totals of either 5, 10 or 12. I also have checkboxes that add up to a total of 12, and a cell value for each row that calculates the difference to reveal how many are left.

I'm wanting the last result cells to show colours from red to yellow to green that is independently reliant on the first cells value to show a specific shade of green/yellow/red. I'm only able to select a colour based on the single columns/cells value and not the value of another column/cell. Is this even possible?

I've run through a number of examples given on google and answers based on similar questions, but nothing seems to solve this specific situation.

This is what I'm expecting to happen: Green Yellow Red

For Green Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 10            | Green

Row 3:  5                 | 5             | Green

Row 4:  12                | 12            | Green

For Variable Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 5             | Yellow

Row 3:  5                 | 4             | Green

Row 4:  12                | 3             | Red

For Red Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 0             | Red

Row 3:  5                 | 1             | Red

Row 4:  12                | 2             | Red

Basically: If we're looking at 3 cells next to each other in ABC, then if B is the variable, and A is the total value, then C should show the colour based on how equal B is to A for Green, or how much lower the value of B is to A for Yellow to Red.

Body:
You can simply quote cells in conditional formatting formulae. For example, you could have cell C2 format based on the equation:

=A2>B2

I think, based on what you've given, you want to scale it based on how much bigger the first is to the second. ie: if A is much bigger than B, turn C red but if A=B, turn C green. If that's the case then you can do colour scales with:

Minpoint: = 0    Red
Midpoint: = A2/2 Yellow
Maxpoint: = A2   Green

And then put

=B2

in C2.


问:
How to make a "Hello world" kernel
I followed this article on how to make a very simple kernel which prints "Hello, World". The files to my project are available on Github.

I built my cross compiler from this project. I use these command to cross compile, assemble, and build my ISO (CD-ROM image):

```<code>i686-elf-as boot.s -o boot.o
i686-elf-gcc -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra
i686-elf-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o kernel.o -lgcc
mkdir -p isodir/boot/grub
cp myos.bin isodir/boot/myos.bin
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o myos.iso isodir
</code>```

When I tried to execute it on VirtualBox, it gives the following message:

FATAL: No bootable medium found! System halted.

Why am I getting this error, and how can I fix it?

P.S. I use Ubuntu subsystem for Windows 10

答:
Likely there is a GRUB component missing or an incorrect version of Xorriso. In the Bare Bones article you linked to it says this:

You can easily create a bootable CD-ROM image containing the GRUB bootloader and your kernel using the program grub-mkrescue. You may need to install the GRUB utility programs and the program xorriso (version 0.5.6 or higher).

When using grub-mkrescue to make ISO images, more often than not unbootable ISOs is a result of Xorisso installation missing. If grub-mkrescue runs but doesn't produce ISOs at all then likely a GRUB component is missing. To ensure that you have all the GRUB and Xorriso components installed install the components on modern Ubuntu releases with:

```<code>sudo apt-get install grub2-common grub-pc xorriso
</code>```

Then attempt to rebuild and rerun your ISO image in VirtualBox.

Title: How to make a "Hello world" kernel

Body:
I followed this article on how to make a very simple kernel which prints "Hello, World". The files to my project are available on Github.

I built my cross compiler from this project. I use these command to cross compile, assemble, and build my ISO (CD-ROM image):

i686-elf-as boot.s -o boot.o
i686-elf-gcc -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra
i686-elf-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o kernel.o -lgcc
mkdir -p isodir/boot/grub
cp myos.bin isodir/boot/myos.bin
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o myos.iso isodir

When I tried to execute it on VirtualBox, it gives the following message:

FATAL: No bootable medium found! System halted.

Why am I getting this error, and how can I fix it?

P.S. I use Ubuntu subsystem for Windows 10

Body:
Likely there is a GRUB component missing or an incorrect version of Xorriso. In the Bare Bones article you linked to it says this:

You can easily create a bootable CD-ROM image containing the GRUB bootloader and your kernel using the program grub-mkrescue. You may need to install the GRUB utility programs and the program xorriso (version 0.5.6 or higher).

When using grub-mkrescue to make ISO images, more often than not unbootable ISOs is a result of Xorisso installation missing. If grub-mkrescue runs but doesn't produce ISOs at all then likely a GRUB component is missing. To ensure that you have all the GRUB and Xorriso components installed install the components on modern Ubuntu releases with:

sudo apt-get install grub2-common grub-pc xorriso

Then attempt to rebuild and rerun your ISO image in VirtualBox.


问:
Allow null - Javascript
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

```<code>validator="/([0-9])$/"
</code>```

I tried using the | but now it allows everything

```<code>validator="/([0-9]|)$/"
</code>```

Any ideas?

答:
\d+|(?:null)

A test set to work with:

Matches:

```<code>0
9
01
910
9019901990199019
null
</code>```

Does not match:

```<code>zero
one
</code>```

Title: Allow null - Javascript

Body:
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

validator="/([0-9])$/"

I tried using the | but now it allows everything

validator="/([0-9]|)$/"

Any ideas?

Body:
\d+|(?:null)

A test set to work with:

Matches:

0
9
01
910
9019901990199019
null

Does not match:

zero
one


问:
Question about javascript function structure
I have a codebase of javascript that I am working on, and have encountered a piece of structure that I am not familiar with. I would just like the name of it so I know what to look up and read about. Any additional information is appreciated.

This is in a Node.js/express environment.

What I'm specifically asking about is the fizz thing in file2.js, referenced in the line marked with a /*!!*/ in file1.js. It looks like some sort of wrapper around a series of functions. What is its proper name?

```<code>//file1.js

const file2 = require('filepath/file2')

foo.get('/bar', (req, res) => {
    file2.fizz.buzz(req.field.item, res)   /*!!*/
    localfunction(param1, param2)
})
</code>```

```<code>//file2.js
module.exports = {
  fizz: {
      buzz: (str, res) => {
          console.log("buzz")
      },
      bang: (param1, param2) => {
          console.log("bang!")
      }
  }
}
</code>```

Thanks!

答:
fizz is a property name (on the object referenced by the file2 variable).

Further Reading:

Object basics on MDN.

Body:
I have a codebase of javascript that I am working on, and have encountered a piece of structure that I am not familiar with. I would just like the name of it so I know what to look up and read about. Any additional information is appreciated.

This is in a Node.js/express environment.

What I'm specifically asking about is the fizz thing in file2.js, referenced in the line marked with a /*!!*/ in file1.js. It looks like some sort of wrapper around a series of functions. What is its proper name?

//file1.js

const file2 = require('filepath/file2')

foo.get('/bar', (req, res) => {
    file2.fizz.buzz(req.field.item, res)   /*!!*/
    localfunction(param1, param2)
})

//file2.js
module.exports = {
  fizz: {
      buzz: (str, res) => {
          console.log("buzz")
      },
      bang: (param1, param2) => {
          console.log("bang!")
      }
  }
}

Thanks!


问:
SVG rect animation direction bottom to top
I have the following SVG animation:

Demo: https://codepen.io/anon/pen/xNJYGe

HTML:

```<code><div class='batteryIcon'>
  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>
</div>
</code>```

CSS:

```<code>.batteryIcon {
  svg {
    width: 50px;
    display: block;
    .st0 {
      fill: none;
      stroke: #adadad;
      stroke-width: 20;
      stroke-miterlimit: 5;
    }
    .power {
      fill: #06B67A;
    }
  }
}
</code>```

My problem is that the animation goes from _top to bottom instead of bottom to top.
I tried to transform my rect by CSS and inline attribute, added rotate and direction attributes and also keyPoints. Nothing worked so far.

答:
Just animate the y value at the same time as the height. You want to finish the y at 150 and it needs to change by 880 so the starting value must be 880 + 150.

svg {
  width: 50px;
  display: block;
}
.st0 {
  fill: none;
  stroke: #adadad;
  stroke-width: 20;
  stroke-miterlimit: 5;
}
.power {
  fill: #06B67A;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='batteryIcon'>
  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="y" values="1030 ; 150" dur="2.5s" />
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>
</div></code>```

Body:
I have the following SVG animation:

Demo: https://codepen.io/anon/pen/xNJYGe

HTML:

  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>

CSS:

.batteryIcon {
  svg {
    width: 50px;
    display: block;
    .st0 {
      fill: none;
      stroke: #adadad;
      stroke-width: 20;
      stroke-miterlimit: 5;
    }
    .power {
      fill: #06B67A;
    }
  }
}

My problem is that the animation goes from _top to bottom instead of bottom to top.
I tried to transform my rect by CSS and inline attribute, added rotate and direction attributes and also keyPoints. Nothing worked so far.

Body:
Just animate the y value at the same time as the height. You want to finish the y at 150 and it needs to change by 880 so the starting value must be 880 + 150.

svg {
  width: 50px;
  display: block;
}
.st0 {
  fill: none;
  stroke: #adadad;
  stroke-width: 20;
  stroke-miterlimit: 5;
}
.power {
  fill: #06B67A;
}

<div class='batteryIcon'>
  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="y" values="1030 ; 150" dur="2.5s" />
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>
</div>


问:
How to search for specific words and values in a long string?
Ok my objective is:

1.Read in a text file. e.g containing text like this, teacher/student/1/sn/2/3/4/5/9/f/tn/02/

2.pass it to a string.

3.then beable to extract different parts of the string and place them in different arrays.

The bit I dont know how to do is the extracting specific parts of the string?
Is it possible to search for / and to treat what comes after it as a specific peice of information until the next / is read?

Or perhaps there is a more efficient approach?

Help and advice sought

Kindest regards
Adrian

答: Regular expressions will help you. Also see methods of String class.</p>


问:
Insert Statement into Derby Database
I am trying to insert a number of values into a table in my java derby database, I am getting the error java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.

```<code>    public boolean registerStudent(Student student)
    {
        try
        {
        Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/AceDrivingSchool", "ADC", "ADC");
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() + "', '" +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");
        conn.close();
        return true;
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
            return false;
        }
    }
</code>```

This should right the values to my table

答:
Answer given by @Basil is completely correct, you will have to read and understand it to get basic idea of How to build and execute query.

In your case though, I can see in comments that you're facing java.sql.SQLSyntaxErrorException: The number of values assigned is not the same as the number of specified or implied columns.
Reason behind this is your malformed SQL having additional ",".

Remove ",+, and other formatting in sql you will end up with this,

INSERT INTO adc.student
            (
                        emailaddress,
                        forename,
                        surname,
                        addressline1,
                        addressline2,
                        postcode,
                        telephoneno,
                        gender,
                        password,
                        isregistered,
                        isverified,
                        passedtheory,
                        passedpractical,
                        drivinglicenseno,
                        dob
            )
            VALUES
            (
                        student.Getemailaddress() ,
                        student.Getforename() ,
                        student.Getsurname() ,
                        student.Getaddressline1() ,
                        student.Getaddressline2() ,
                        student.Getpostcode() ,
                        student.Gettelephoneno() ,
                        student.Getgender() ,
                        student.Getpassword() ,
                        student.Isisregistered() ,
                        student.Isisverified() ,
                        student.Ispassedtheory() ,
                        ,
                        student.ispassedpractical() ,
                        student.getdrivinglicenseno() ,
                        NEW simpledateformat(yyyy-mm-dd).format(student.getdob())
            )
```

<p>SQL parsing fails at line 33. Remove additional <code>+ "', '"</code> after <code>student.isPassedTheory()</code> and you will be able to execute query.
You <em>should</em>  end up with following query format after fixing your code,</p>

<pre class="lang-sql prettyprint-override"><code>"INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");
</code>```

Title: Insert Statement into Derby Database

Body:
I am trying to insert a number of values into a table in my java derby database, I am getting the error java.sql.SQLSyntaxErrorException: VALUES clause must contain at least one element. Empty elements are not allowed.

    public boolean registerStudent(Student student)
    {
        try
        {
        Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/AceDrivingSchool", "ADC", "ADC");
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() + "', '" +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");
        conn.close();
        return true;
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

This should right the values to my table

Body:
Answer given by @Basil is completely correct, you will have to read and understand it to get basic idea of How to build and execute query.

In your case though, I can see in comments that you're facing java.sql.SQLSyntaxErrorException: The number of values assigned is not the same as the number of specified or implied columns.
Reason behind this is your malformed SQL having additional ",".

Remove ",+, and other formatting in sql you will end up with this,

INSERT INTO adc.student
            (
                        emailaddress,
                        forename,
                        surname,
                        addressline1,
                        addressline2,
                        postcode,
                        telephoneno,
                        gender,
                        password,
                        isregistered,
                        isverified,
                        passedtheory,
                        passedpractical,
                        drivinglicenseno,
                        dob
            )
            VALUES
            (
                        student.Getemailaddress() ,
                        student.Getforename() ,
                        student.Getsurname() ,
                        student.Getaddressline1() ,
                        student.Getaddressline2() ,
                        student.Getpostcode() ,
                        student.Gettelephoneno() ,
                        student.Getgender() ,
                        student.Getpassword() ,
                        student.Isisregistered() ,
                        student.Isisverified() ,
                        student.Ispassedtheory() ,
                        ,
                        student.ispassedpractical() ,
                        student.getdrivinglicenseno() ,
                        NEW simpledateformat(yyyy-mm-dd).format(student.getdob())
            )

SQL parsing fails at line 33. Remove additional + "', '" after student.isPassedTheory() and you will be able to execute query.
You should  end up with following query format after fixing your code,

"INSERT INTO ADC.STUDENT(EMAILADDRESS, FORENAME, SURNAME, ADDRESSLINE1, ADDRESSLINE2,"
                + " POSTCODE, TELEPHONENO, GENDER, PASSWORD, ISREGISTERED, ISVERIFIED, PASSEDTHEORY, PASSEDPRACTICAL, DRIVINGLICENSENO, DOB"
                + ") VALUES('" + student.getEmailAddress() +
                "', '" + student.getForename() + "', '" + student.getSurname() +
                "', '" + student.getAddressLine1() + "', '" + student.getAddressLine2() + "', '" + student.getPostcode() +
                "', '" + student.getTelephoneNo() + "', '" + student.getGender() + "', '" + student.getPassword() +
                "', '" + student.isIsRegistered() + "', '" + student.isIsVerified() + "', '" + student.isPassedTheory() +
                "', '" + student.isPassedPractical() + "', '" + student.getdrivingLicenseNo() + "', '" +
                new SimpleDateFormat("yyyy-MM-dd").format(student.getDob()) + "')");


问:
Mocha uncaught assertion error status response ECONNREFUSED 127.0.0.1:5000
Getting an error, when checking to see if index page renders hello world.

index page should render, hello world
         should render hello world 200:
       Uncaught AssertionError: expected [Error: connect ECONNREFUSED 127.0.0.1:5000] to have keys 'status', or 'statusCode'

router.spec.test

```<code>import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'chai'
import router from '../routes/';

chai.use(chaiHttp);

// simple test
describe('Array', () => {
      it('should return -1 when the value is not present', () => {
        assert.equal([1, 2, 3].indexOf(4), -1);
      });
});

describe('index page should render, hello world', () => {
it('should render hello world 200', (done) => {
    chai.request('http://localhost:5000/')
        .get('/').end((res)=>{

            expect(res).to.have.status(200);
            done();
        });
    })
})
</code>```

routes/index.js

```<code>import express from 'express';

const app = express();

app.get('/', (req, res) => {
    return res.status(200).json({
        message: "Hello World"
    })
})

export default app;
</code>```

答:
ECONNREFUSED is pretty clear, your server isn't running. That's because you've supplied the url as a string, not the express instance. You need to either fire it up manually (not ideal), or provide the router to the chai requester.

So

```<code>chai.request(router)
  .get('/') .....

</code>```

should work for you.

Body:
Getting an error, when checking to see if index page renders hello world.

index page should render, hello world
         should render hello world 200:
       Uncaught AssertionError: expected [Error: connect ECONNREFUSED 127.0.0.1:5000] to have keys 'status', or 'statusCode'

router.spec.test

import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'chai'
import router from '../routes/';

chai.use(chaiHttp);

// simple test
describe('Array', () => {
      it('should return -1 when the value is not present', () => {
        assert.equal([1, 2, 3].indexOf(4), -1);
      });
});

describe('index page should render, hello world', () => {
it('should render hello world 200', (done) => {
    chai.request('http://localhost:5000/')
        .get('/').end((res)=>{

            expect(res).to.have.status(200);
            done();
        });
    })
})

routes/index.js

import express from 'express';

const app = express();

app.get('/', (req, res) => {
    return res.status(200).json({
        message: "Hello World"
    })
})

export default app;

Body:
ECONNREFUSED is pretty clear, your server isn't running. That's because you've supplied the url as a string, not the express instance. You need to either fire it up manually (not ideal), or provide the router to the chai requester.

So

chai.request(router)
  .get('/') .....

should work for you.


问:
Stub function does not executed when executing test using sinon and mocha
I'm trying to mock a function in order to pass tests using sinon and mocha.

app.js:

```<code>const express = require('express');
const { isValid } = require('./utils/index');

const config = require('./config.json')[process.env.NODE_ENV || 'development']

const app = express();

app.get('/', (req, res)=> {

    const url = config.url;
   try {
    const validUrl = isValid(url)
    .then(() => {
        return res.redirect(`https://${url}`);
    })
    .catch(() => {
        return res.status(400).send('Unable to redirect to the given url');
    })
   } catch(error) {
      return res.send('Internal Server Error')
   }

})

const port = process.env.port || 3000;

const server = app.listen(port, ()=> {
    console.log('server listens on 127.0.0.1:3000');
})

module.exports = {server, app};
</code>```

config.json:

```<code>{
"development": {
    "url": "www.stackoverflow.com"
},
"test": {
    "url": "www.stackoverflow.com"
}

}
</code>```

utils/index.js:

```<code>const http = require('http');

module.exports.isValid = (url) => {
    const options = {
        method: 'HEAD',
        host: url
    }
const promise = new Promise((resolve, reject) => {
    const req = http.request(options, () => {
        return resolve(true)
    })
    req.on('error', () => {
        return reject(new Error('Not valid'))
    })

    req.end();
})

return promise;
}
</code>```

test/index.js:

```<code>const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const index = require('../utils/index')
const { expect } = chai;

const { server } = require('../app');
const {url} = require('../config.json')['test'];

describe('isValid Test', () => {

    it('Should redirects an error when the url is not valid', async() => {

        const stub = sinon.stub(index, 'isValid');
        stub.withArgs(url).returns(Promise.reject(new Error('Not Valid')));
        const { status } = await request(server).get('/');

        expect(status).to.equal(400);

    })
})
</code>```

When I execute the test I got this error:

```<code>    (node:23622) UnhandledPromiseRejectionWarning: Error: Not Valid
    at Context.it (/home/hs/perso/mockTests/chaiMock/test/index.js:17:52)
    at callFn (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:387:21)
    at Test.Runnable.run (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:379:7)
    at Runner.runTest (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:535:10)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:653:12
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:447:14)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:457:7
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:362:14)
    at Immediate.<anonymous> (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:425:5)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
(node:23622) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:23622) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
url:  www.stackoverflow.com
    1) Should redirects an error when the url is not valid

  0 passing (122ms)
  1 failing

  1) isValid Test
       Should redirects an error when the url is not valid:

      AssertionError: expected 302 to equal 400
      + expected - actual

      -302
      +400

      at Context.it (test/index.js:22:27)
      at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

答:
The problem here is that your app module is required and in turn pulls in the utils/index file before sinon stubs the function you're interested in, I believe the module loader then caches it so sinon trying to stub it has no effect.

To see your test pass successfully, you need to stub your isValid function before you require your app i.e.

```<code>const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const { expect } = chai;

const index = require('../utils/index');

/* Stub here before the server is required */
const stub = sinon.stub(index, 'isValid');

const { server } = require('../app');
const { url } = require('../config.json')['test'];

describe('isValid Test', () => {
  it('Should redirects an error when the url is not valid', async () => {
    stub.withArgs(url).rejects('Not Valid');

    const { status } = await request(server).get('/');

    expect(status).to.equal(400);
  });
});
</code>```

Also, to stop seeing the unhandled promise rejection when your tests run, you can use the .rejects() function rather than creating your own rejected promise.

Body:
I'm trying to mock a function in order to pass tests using sinon and mocha.

app.js:

const express = require('express');
const { isValid } = require('./utils/index');

const config = require('./config.json')[process.env.NODE_ENV || 'development']

const app = express();

app.get('/', (req, res)=> {

    const url = config.url;
   try {
    const validUrl = isValid(url)
    .then(() => {
        return res.redirect(`https://${url}`);
    })
    .catch(() => {
        return res.status(400).send('Unable to redirect to the given url');
    })
   } catch(error) {
      return res.send('Internal Server Error')
   }

})

const port = process.env.port || 3000;

const server = app.listen(port, ()=> {
    console.log('server listens on 127.0.0.1:3000');
})

module.exports = {server, app};

config.json:

{
"development": {
    "url": "www.stackoverflow.com"
},
"test": {
    "url": "www.stackoverflow.com"
}

}

utils/index.js:

const http = require('http');

module.exports.isValid = (url) => {
    const options = {
        method: 'HEAD',
        host: url
    }
const promise = new Promise((resolve, reject) => {
    const req = http.request(options, () => {
        return resolve(true)
    })
    req.on('error', () => {
        return reject(new Error('Not valid'))
    })

    req.end();
})

return promise;
}

test/index.js:

const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const index = require('../utils/index')
const { expect } = chai;

const { server } = require('../app');
const {url} = require('../config.json')['test'];

describe('isValid Test', () => {

    it('Should redirects an error when the url is not valid', async() => {

        const stub = sinon.stub(index, 'isValid');
        stub.withArgs(url).returns(Promise.reject(new Error('Not Valid')));
        const { status } = await request(server).get('/');

        expect(status).to.equal(400);

    })
})

When I execute the test I got this error:

    (node:23622) UnhandledPromiseRejectionWarning: Error: Not Valid
    at Context.it (/home/hs/perso/mockTests/chaiMock/test/index.js:17:52)
    at callFn (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:387:21)
    at Test.Runnable.run (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:379:7)
    at Runner.runTest (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:535:10)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:653:12
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:447:14)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:457:7
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:362:14)
    at Immediate.<anonymous> (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:425:5)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
(node:23622) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:23622) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
url:  www.stackoverflow.com
    1) Should redirects an error when the url is not valid

  0 passing (122ms)
  1 failing

  1) isValid Test
       Should redirects an error when the url is not valid:

      AssertionError: expected 302 to equal 400
      + expected - actual

      -302
      +400

      at Context.it (test/index.js:22:27)
      at process._tickCallback (internal/process/next_tick.js:68:7)

Body:
The problem here is that your app module is required and in turn pulls in the utils/index file before sinon stubs the function you're interested in, I believe the module loader then caches it so sinon trying to stub it has no effect.

To see your test pass successfully, you need to stub your isValid function before you require your app i.e.

const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const { expect } = chai;

const index = require('../utils/index');

/* Stub here before the server is required */
const stub = sinon.stub(index, 'isValid');

const { server } = require('../app');
const { url } = require('../config.json')['test'];

describe('isValid Test', () => {
  it('Should redirects an error when the url is not valid', async () => {
    stub.withArgs(url).rejects('Not Valid');

    const { status } = await request(server).get('/');

    expect(status).to.equal(400);
  });
});

Also, to stop seeing the unhandled promise rejection when your tests run, you can use the .rejects() function rather than creating your own rejected promise.


问:
VueJS block activity on not active browser tab
I have a web app written in Typescript and VueJS that execute a collection of tasks (ajax requests) and to track the whole process (and to execute one task after another) I use a Vue instance as bus to notify changes between components.
If the user open a new browser tab, the process stop. If the user come back, the process resumes.

The issue is present in Firefox and in Chrome.
I put in my code a simple window.setInterval to log every 2 seconds an 'Hello' and...surprise I have an 'Hello' every 2 seconds without any temporal 'hole'.
I see a very old issue in github for a similar situation: https://github.com/vuejs/Discussion/issues/76 but seems to be too old to be this.

I expect that the process doesn't stop but continues without interruptions..

答:
https://developers.google.com/web/updates/2017/03/background_tabs

Background tabs can have a dramatic negative effect on browser performance, especially on battery life. To mitigate this, Chrome has been placing various restrictions on background tabs for the last several years. Recently there’s been a number of efforts to make further improvements, and this document gives an overview of the Chrome policy. This document focuses on describing current policies in Chrome 57. Long-term strategy and further plans can be found in this document.

https://www.chromestatus.com/feature/6172836527865856

As an intervention we want to limit how much CPU a background page is allowed to use and to throttle timer queues when this limit is violated. Current target is that background page CPU load level should be under 1%.


问:
Current date into environment variable in React App
My task is to make a header with the current deploy date.
I couldn't get data from AWS, so I decided to set the build date in the environment variable during the build.

For this, I created a file .env and put some test variables. It works, but it is constant. How can I get the current date in the .env file?

```<code>REACT_APP_VAR1=123
REACT_APP_VAR2=dddd
REACT_APP_BUILD_TIME=(What should I write here?)
</code>```

答:
Use webpack DefinePlugin for this purpose.

In webpack config:

```<code>    plugins: [
        new webpack.DefinePlugin({
            BREACT_APP_BUILD_TIME: JSON.stringify(new Date().getTime()),
        })
    ]

</code>```

In your app:

```<code>const buildTime = new Date(+BREACT_APP_BUILD_TIME);
</code>```

Body:
My task is to make a header with the current deploy date.
I couldn't get data from AWS, so I decided to set the build date in the environment variable during the build.

For this, I created a file .env and put some test variables. It works, but it is constant. How can I get the current date in the .env file?

REACT_APP_VAR1=123
REACT_APP_VAR2=dddd
REACT_APP_BUILD_TIME=(What should I write here?)

Body:
Use webpack DefinePlugin for this purpose.

In webpack config:

    plugins: [
        new webpack.DefinePlugin({
            BREACT_APP_BUILD_TIME: JSON.stringify(new Date().getTime()),
        })
    ]

In your app:

const buildTime = new Date(+BREACT_APP_BUILD_TIME);


问:
I keep getting a syntax error when I try to check for int values in a substring?
For a homework assigntment I have to check for int values in a VARCHAR for example:
I have values that look like this:

```<code>cityCode
Cott1254
Stam2512
Berl0102
</code>```

I want to be able to check the sum of int values in these tables and make sure that they are even numbers > 0

I have tried the following but im getting a syntax error and this is only for checking if the whole number is greater than 0. The main problem is resolving the syntax error that I get.

```<code>CHECK SUBSTR(CAST(accommodatiecode, 5,4) AS INT)> 0;
</code>```

Any suggestions?

Thanks in advance.

答:
MySQL (historically) does not implement check constraints.  But the correct syntax is:

```<code>alter table t add constraint chk_t_col
    check (SUBSTR(accommodatiecode, 5, 4) + 0) > 0);
</code>```

This, of course, does not check for even or odd.  That would be more like:

```<code>accomodatiecode regexp '[0-9]{4}[02468]$'
</code>```

Body:
For a homework assigntment I have to check for int values in a VARCHAR for example:
I have values that look like this:

cityCode
Cott1254
Stam2512
Berl0102

I want to be able to check the sum of int values in these tables and make sure that they are even numbers > 0

I have tried the following but im getting a syntax error and this is only for checking if the whole number is greater than 0. The main problem is resolving the syntax error that I get.

CHECK SUBSTR(CAST(accommodatiecode, 5,4) AS INT)> 0;

Any suggestions?

Thanks in advance.

Body:
MySQL (historically) does not implement check constraints.  But the correct syntax is:

alter table t add constraint chk_t_col
    check (SUBSTR(accommodatiecode, 5, 4) + 0) > 0);

This, of course, does not check for even or odd.  That would be more like:

accomodatiecode regexp '[0-9]{4}[02468]$'


问:
How to copy a DOM node with event listeners?
I tried

```<code>node.cloneNode(true); // deep copy
</code>```

It doesn't seem to copy the event listeners that I added using node.addEventListener("click", someFunc);.

We use the Dojo library.

答:
This is what @JeromeJ was describing in a comment.  Create the initial element using this HTML code.

touch me

When you clone this element the result will have the same handler, and "this" will point to the cloned element.

It would be great if the ONCLICK handler could easily be added in JavaScript.  This approach means that you have to write some of your code in HTML.

Body:
I tried

node.cloneNode(true); // deep copy

It doesn't seem to copy the event listeners that I added using node.addEventListener("click", someFunc);.

We use the Dojo library.

Body:
This is what @JeromeJ was describing in a comment.  Create the initial element using this HTML code.

<DIV ONCLICK="doSomething(this)">touch me</DIV>

When you clone this element the result will have the same handler, and "this" will point to the cloned element.

It would be great if the ONCLICK handler could easily be added in JavaScript.  This approach means that you have to write some of your code in HTML.


问:
Gaussian Mixture Models for pixel clustering
I have a small set of aerial images where different terrains visible in the image have been have been labelled by human experts. For example, an image may contain vegetation, river, rocky mountains, farmland etc. Each image may have one or more of these labelled regions. Using this small labeled dataset, I would like to fit a gaussian mixture model for each of the known terrain types. After this is complete, I would have N number of GMMs for each N types of terrains that I might encounter in an image.

Now, given a new image, I would like to determine for each pixel, which terrain it belongs to by assigning the pixel to the most probable GMM.
Is this the correct line of thought ? And if yes, how can I go about clustering an image using GMMs

答:
Intuitively, your thought process is correct. If you already have the labels that makes this a lot easier.

For example, let's pick on a very well known and non-parametric algorithm like Known Nearest Neighbors https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm

In this algorithm, you would take your new "pixels" which would then find the closest k-pixels like the one you are currently evaluating; where closest is determined by some distance function (usually Euclidean). From there, you would then assign this new pixel to the most frequently occurring classification label.

I am not sure if you are looking for a specific algorithm recommendation, but KNN would be a very good algorithm to begin testing this type of exercise out on. I saw you tagged sklearn, scikit learn has a very good KNN implementation I suggest you read up on.


问:
Laravel update json column in postgresql
In postgresql db I have a column type json call it "activities". I would like to add there new (key -> value) pair. Without delete existing data.

At this moment my code look like this:

```<code>$user = User::with('userLife')->where(['id' =>$id])->first();
    $user->userLife->confirmation_token = null;
    $user->userLife->activities = ['emailConfirmed' => Carbon::now()->timestamp];
    $user->email_confirmed = true;
    $user->push();
</code>```

In my Model I added:

```<code>protected $casts = [
        'activities' => 'array',
    ];
</code>```

But when I use this code all other data in column is removed and only 'emailConfirmed' appeared there.

So how to do it properly to just add new value in column without removing previous?
Thank you.

答:
You should add it as new element through another variable:</p>

```<code>$activities = $user->userLife->activities;

$activities['emailConfirmed'] = Carbon::now()->timestamp;

$user->userLife->activities = $activities;
</code>```

Body:
In postgresql db I have a column type json call it "activities". I would like to add there new (key -> value) pair. Without delete existing data.

At this moment my code look like this:

$user = User::with('userLife')->where(['id' =>$id])->first();
    $user->userLife->confirmation_token = null;
    $user->userLife->activities = ['emailConfirmed' => Carbon::now()->timestamp];
    $user->email_confirmed = true;
    $user->push();

In my Model I added:

protected $casts = [
        'activities' => 'array',
    ];

But when I use this code all other data in column is removed and only 'emailConfirmed' appeared there.

So how to do it properly to just add new value in column without removing previous?
Thank you.

Body:
You should add it as new element through another variable:

$activities = $user->userLife->activities;

$activities['emailConfirmed'] = Carbon::now()->timestamp;

$user->userLife->activities = $activities;


问:
Put time limit on Jest test?
I'm running a set of tests with Jest to demonstrate Big O using two different methods for Fibonacci.

```<code>const fastFib = require('./../fastFib');
const slowFib = require('./../slowFib');

test('Fast way of getting Fibonacci of 44', () => {
  expect(fastFib(44)).toBe(701408733);
});

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
});
</code>```

I'm wondering if there is a way to specify the maximum length of a test? I saw you can pass a third variable for an async timeout but it doesn't seem to have any effect on normal functions:

```<code>test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);
</code>```

Is there a way I can specify the maximum execution time for a function with Jest?

I will share slowFib.js for reference:

```<code>function fib(n) {
  return (n<=1) ? n : fib(n - 1) + fib(n - 2);
}

module.exports = fib;
</code>```

答:
I think you would need to implement your own timer (with setTimeout or using Promises). One alternative would be to use the async keyword for your function to make it work with the built-in parameter :</p>

```<code>test('Slow way of getting Fibonacci of 44', async () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);
</code>```

Title: Put time limit on Jest test?

Body:
I'm running a set of tests with Jest to demonstrate Big O using two different methods for Fibonacci.

const fastFib = require('./../fastFib');
const slowFib = require('./../slowFib');

test('Fast way of getting Fibonacci of 44', () => {
  expect(fastFib(44)).toBe(701408733);
});

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
});

I'm wondering if there is a way to specify the maximum length of a test? I saw you can pass a third variable for an async timeout but it doesn't seem to have any effect on normal functions:

test('Slow way of getting Fibonacci of 44', () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);

Is there a way I can specify the maximum execution time for a function with Jest?

I will share slowFib.js for reference:

function fib(n) {
  return (n<=1) ? n : fib(n - 1) + fib(n - 2);
}

module.exports = fib;

Body:
I think you would need to implement your own timer (with setTimeout or using Promises). One alternative would be to use the async keyword for your function to make it work with the built-in parameter :

test('Slow way of getting Fibonacci of 44', async () => {
  expect(slowFib(44)).toBe(701408733);
}, 5000);


问:
Create a new column in a dataframe out of previous rows from a factor variable
Given a dataframe like this:

```<code>game     team
zap.che  zap
zap.che  che
zap.che  zap
zap.che  zap
zap.che  che
bar.var  bar
bar.var  var
bar.var  var
bar.var  bar
bar.var  bar
</code>```

I'd like to add another new column, being my desired outcome something like this:

```<code>game     team    poss
zap.che  zap     1
zap.che  che     1
zap.che  zap     2
zap.che  zap     2
zap.che  che     2
bar.var  bar     1
bar.var  var     1
bar.var  var     1
bar.var  bar     2
bar.var  bar     2
</code>```

My purposes are:
a) assign the same value to all the consecutive occurrences of the same value in "team" column
b) count all the wrapped "team" values in "poss" column (1,2,3 and so on)
c) once in "game" column the value changes, restart the same process

答:
An option would be to group by 'game', then get the run-length-id based on the first level of 'team' and fill the NA elements with the previous non-NA elements

```<code>library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
    group_by(game = factor(game, levels = unique(game))) %>%
    mutate(poss = as.integer(factor(rleid(team != first(team)) *
          NA^(team != first(team))))) %>%
   fill(poss)
# A tibble: 10 x 3
# Groups:   game [2]
#   game    team   poss
#   <fct>   <chr> <int>
# 1 zap.che zap       1
# 2 zap.che che       1
# 3 zap.che zap       2
# 4 zap.che zap       2
# 5 zap.che che       2
# 6 bar.var bar       1
# 7 bar.var var       1
# 8 bar.var var       1
# 9 bar.var bar       2
#10 bar.var bar       2
</code>```

data

```<code>df1 <- structure(list(game = c("zap.che", "zap.che", "zap.che", "zap.che",
"zap.che", "bar.var", "bar.var", "bar.var", "bar.var", "bar.var"
), team = c("zap", "che", "zap", "zap", "che", "bar", "var",
"var", "bar", "bar")), class = "data.frame", row.names = c(NA,
-10L))
</code>```

Body:
Given a dataframe like this:

game     team
zap.che  zap
zap.che  che
zap.che  zap
zap.che  zap
zap.che  che
bar.var  bar
bar.var  var
bar.var  var
bar.var  bar
bar.var  bar

I'd like to add another new column, being my desired outcome something like this:

game     team    poss
zap.che  zap     1
zap.che  che     1
zap.che  zap     2
zap.che  zap     2
zap.che  che     2
bar.var  bar     1
bar.var  var     1
bar.var  var     1
bar.var  bar     2
bar.var  bar     2

My purposes are:
a) assign the same value to all the consecutive occurrences of the same value in "team" column
b) count all the wrapped "team" values in "poss" column (1,2,3 and so on)
c) once in "game" column the value changes, restart the same process

Body:
An option would be to group by 'game', then get the run-length-id based on the first level of 'team' and fill the NA elements with the previous non-NA elements

library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
    group_by(game = factor(game, levels = unique(game))) %>%
    mutate(poss = as.integer(factor(rleid(team != first(team)) *
          NA^(team != first(team))))) %>%
   fill(poss)
# A tibble: 10 x 3
# Groups:   game [2]
#   game    team   poss
#   <fct>   <chr> <int>
# 1 zap.che zap       1
# 2 zap.che che       1
# 3 zap.che zap       2
# 4 zap.che zap       2
# 5 zap.che che       2
# 6 bar.var bar       1
# 7 bar.var var       1
# 8 bar.var var       1
# 9 bar.var bar       2
#10 bar.var bar       2

data

df1 <- structure(list(game = c("zap.che", "zap.che", "zap.che", "zap.che",
"zap.che", "bar.var", "bar.var", "bar.var", "bar.var", "bar.var"
), team = c("zap", "che", "zap", "zap", "che", "bar", "var",
"var", "bar", "bar")), class = "data.frame", row.names = c(NA,
-10L))


问:
webdriveragentrunner iphoneos12.2-arm64.xctestrun doesn't exist
I want to automate ios app using appium.
The thing is that I am getting this error when I use appium inspector in order to open my installed application for the first time:
xcodebuild failure: "xcodebuild failed with code 65"

I followed different solutions I found online (like enable automatically manage signings in webdriveragent project, code signing identity...) but I am still getting this error.
Seems that this path does't exist in my computer.
Is there a way to fix this issue?

Thanks

答:
You need to walk through Appium XCUITest Driver Real Device Setup article and perhaps Real device security settings chapter of the appium-xcuitest-driver documentation.

Most probably you have wrong XCode configuration with regards to signing mobile application packages

The easiest option would be considering using Appium Studio which has a simple wizard allowing creation of iOS provisioning profile in few clicks.


问:
Powershell script works but not in vb.net code
I need to run a powershell script from vb.net. I wrote it and tried it in powershell ISE and the powershell console and it's working properly.

But when I try to use it in my vb.net code, nothing happens.

The script put into text file citrix session from some user.

here is my powershell script :

```<code>$username = 'domain\myusername'
$password = 'mypassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential $credential -NoNewWindow -ArgumentList "add-pssnapin citrix*`nGet-BrokerSession -AdminAddress 'ipadresshere' | Out-File -FilePath C:\inetpub\wwwroot\gestusers\ajax\data\arrays.txt"
</code>```

and here's my vb.net code :

```<code>Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()

        ' open it
        MyRunSpace.Open()

        ' create a pipeline and feed it the script text
        Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()

        MyPipeline.Commands.AddScript(scriptText)

        ' add an extra command to transform the script output objects into nicely formatted strings
        ' remove this line to get the actual objects that the script returns. For example, the script
        ' "Get-Process" returns a collection of System.Diagnostics.Process instances.
        MyPipeline.Commands.Add("Out-String")

        ' execute the script
        Dim results As Collection(Of PSObject) = MyPipeline.Invoke()

        ' close the runspace
        MyRunSpace.Close()

        ' convert the script result into a single string
        Dim MyStringBuilder As New StringBuilder()

        For Each obj As PSObject In results
            MyStringBuilder.AppendLine(obj.ToString())
        Next

        ' return the results of the script that has
        ' now been converted to text
        Return MyStringBuilder.ToString()
</code>```

When I try to use a smaller script like :

```<code>$test = "blablabla"
$test | Out-File -filepath "C:\inetpub\wwwroot\gestusers\ajax\data\arrays.txt"
</code>```

it works so I don't really understand why the first script is not working .. if you have some suggestion I would be thankful

答:
I finaly found a solution to my problem.
I am running my web app on a IIS server and when I was launching my script it was the default user "IIS default/application_pool" which was lauching it although I specified a specific user to run it, it was like my script doesn't work.

So I choosed to go in my IIS server params and I just made an other app_pool with my specific user. I put my app under this pool and now it works perfectly.

Here's how to make a specific pool on IIS Server : https://www.developer.com/net/asp/article.php/2245511/IIS-and-ASPNET-The-Application-Pool.htm

cya

Body:
I need to run a powershell script from vb.net. I wrote it and tried it in powershell ISE and the powershell console and it's working properly.

But when I try to use it in my vb.net code, nothing happens.

The script put into text file citrix session from some user.

here is my powershell script :

$username = 'domain\myusername'
$password = 'mypassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential $credential -NoNewWindow -ArgumentList "add-pssnapin citrix*`nGet-BrokerSession -AdminAddress 'ipadresshere' | Out-File -FilePath C:\inetpub\wwwroot\gestusers\ajax\data\arrays.txt"

and here's my vb.net code :

Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()

        ' open it
        MyRunSpace.Open()

        ' create a pipeline and feed it the script text
        Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()

        MyPipeline.Commands.AddScript(scriptText)

        ' add an extra command to transform the script output objects into nicely formatted strings
        ' remove this line to get the actual objects that the script returns. For example, the script
        ' "Get-Process" returns a collection of System.Diagnostics.Process instances.
        MyPipeline.Commands.Add("Out-String")

        ' execute the script
        Dim results As Collection(Of PSObject) = MyPipeline.Invoke()

        ' close the runspace
        MyRunSpace.Close()

        ' convert the script result into a single string
        Dim MyStringBuilder As New StringBuilder()

        For Each obj As PSObject In results
            MyStringBuilder.AppendLine(obj.ToString())
        Next

        ' return the results of the script that has
        ' now been converted to text
        Return MyStringBuilder.ToString()

When I try to use a smaller script like :

$test = "blablabla"
$test | Out-File -filepath "C:\inetpub\wwwroot\gestusers\ajax\data\arrays.txt"

it works so I don't really understand why the first script is not working .. if you have some suggestion I would be thankful


问:
Get total length of pipe per date interval
I have a table containing pipes that are installed at a location.
Installed dates are always filled in, removed dates can be NULL

```<code>Type   Installed     Removed     Length
PT2    01/01/2011    NULL        2000
PT2    01/01/2011    NULL        2000
PT1    01/01/2011    NULL        1200
PT1    01/01/2011    NULL        1200
PT1    15/02/2011    25/02/2011  1000
PT1    15/02/2011    25/02/2011  1000
</code>```

Now I need an overview of the total length per type that was installed for a given month, so the result should be for example from 01/02/2011 to 28/02/2011:

```<code> Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     15/02/2011   24/02/2011    4400 Edit: (starts on 15 not 14)
 PT1     25/02/2011   28/02/2011    2400
</code>```

EDIT: Clarification on this expected result.
In the end this will be used to see the total length of pipe at any given moment during the requested month. So if you look at the table above, during February 2 PT2 pipes were installed. They were installed in January, but are still present, so during the entire month there is a total length of 4000.

Same for PT1: From the start of February 2 PT1 pipes are installed, so 2400. However on the 15th an extra 2 PT1 pipes of length 1000 are installed so during the 15th to the 25th the total length of PT1 pipes is 4400.

These 2 pipes are removed on the 25th so 25 to end of month it's 2400 again.

I hope this makes a little more sense now.

I'm struggling with how to do this in SQL, It's for a report, and generally there are hundreds of these pipes installed in any given month.

It's for use in a Powerbuilder application, so if you know any datawindow trickery that might help feel free to share.

答:
Do you mean that in February (your dates are in DDMMYYY format) the length for PT1 should be a negative number, so that if you were to run the report for the first quarter of the year, the 2000 feet removed in February would be subtracted from the 2400 feet of PT1 installed in January, for a net installed length of 400 feet for PT1 over the quarter?  If so, you could do this as the intersection of two inline or persistent views, one for the installs one for the removals, type and (extracted) time period being the join columns, subtracting removed length per type per period from installed length per type per period to get the net installed length per type per period. A left join between installs and removals.

If you also needed to track the removal of pipe that wasn't necessarily installed by your company -- e.g. there's a record of PT77 being removed but no record of PT77 being installed, you could address this as the UNION of two inline or persistent views, one for installs, one for removals, the removals being cast to negative lengths; then you would make that UNION ALL query itself into an inline view, where you'd group by type by period and sum the length.

Body:
I have a table containing pipes that are installed at a location.
Installed dates are always filled in, removed dates can be NULL

Type   Installed     Removed     Length
PT2    01/01/2011    NULL        2000
PT2    01/01/2011    NULL        2000
PT1    01/01/2011    NULL        1200
PT1    01/01/2011    NULL        1200
PT1    15/02/2011    25/02/2011  1000
PT1    15/02/2011    25/02/2011  1000

Now I need an overview of the total length per type that was installed for a given month, so the result should be for example from 01/02/2011 to 28/02/2011:

 Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     15/02/2011   24/02/2011    4400 Edit: (starts on 15 not 14)
 PT1     25/02/2011   28/02/2011    2400

EDIT: Clarification on this expected result.
In the end this will be used to see the total length of pipe at any given moment during the requested month. So if you look at the table above, during February 2 PT2 pipes were installed. They were installed in January, but are still present, so during the entire month there is a total length of 4000.

Same for PT1: From the start of February 2 PT1 pipes are installed, so 2400. However on the 15th an extra 2 PT1 pipes of length 1000 are installed so during the 15th to the 25th the total length of PT1 pipes is 4400.

These 2 pipes are removed on the 25th so 25 to end of month it's 2400 again.

I hope this makes a little more sense now.

I'm struggling with how to do this in SQL, It's for a report, and generally there are hundreds of these pipes installed in any given month.

It's for use in a Powerbuilder application, so if you know any datawindow trickery that might help feel free to share.


问:
How to Python Web Crawl (No tags, No div name, No class name)
I know need a name tag for web crawling. (ex: class='abcd')
But now the  I'm trying to have does not have this name.

enter image description here

I want to extract 1 in (span)1(span) from the image value.
how to this?

always thank the users of stackoverflow.

答:
With bs4 4.7.1 you can use :has pseudo selector to specify span with sibling span having class .point-scale

```<code>soup.select_one('span:has(~ .point-scale)').text
</code>```

That is a general sibling. You can also be more specific with adjacent sibling

```<code>soup.select_one('span:has(+ .point-scale)').text
</code>```

Use select and list comprehension for multiple matches:

```<code>ratings = [item.text for item in soup.select('span:has(~ .point-scale)')]
</code>```

Combinators (Quotes from Mozilla dev pages)

Adjacent sibling combinator:

The adjacent sibling combinator (+) separates two selectors and
  matches the second element only if it immediately follows the first
  element, and both are children of the same parent element.

General sibling combinator:

The general sibling combinator (~) separates two selectors and matches
  the second element only if it follows the first element (though not
  necessarily immediately), and both are children of the same parent
  element.

Body:
With bs4 4.7.1 you can use :has pseudo selector to specify span with sibling span having class .point-scale

soup.select_one('span:has(~ .point-scale)').text

That is a general sibling. You can also be more specific with adjacent sibling

soup.select_one('span:has(+ .point-scale)').text

Use select and list comprehension for multiple matches:

ratings = [item.text for item in soup.select('span:has(~ .point-scale)')]

Combinators (Quotes from Mozilla dev pages)

Adjacent sibling combinator:

The adjacent sibling combinator (+) separates two selectors and
  matches the second element only if it immediately follows the first
  element, and both are children of the same parent element.

General sibling combinator:

The general sibling combinator (~) separates two selectors and matches
  the second element only if it follows the first element (though not
  necessarily immediately), and both are children of the same parent
  element.


问:
NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>'
I'm currently trying to create a Spring Shell Application in Scala.
It works in IntelliJ but does not work when creating the jar.

I have a working proof of concept in Java, that does also successfully create a running jar.

However, my Scala version fails with several:

```<code>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterValidationExceptionResultHandler': Unsatisfied dependency expressed through field 'parameterResolvers'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

I've tried several minimal examples, moving the classes around (same package) and different Spring annotations (like @SpringBootApplication for both).

Java version:

```<code>@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@ShellComponent
public class MyCommands {

    @ShellMethod("Add two integers together.")
    public int add(int a, int b) {
        return a + b;
    }
}
</code>```

Scala Version:

```<code>@EnableAutoConfiguration
@ComponentScan
class DemoApplication

object Scark extends App {
  SpringApplication.run(classOf[DemoApplication], args:_*)
}

@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(a: Int, b: Int): Int = a + b
}
</code>```

I expect to also be able to successfully build a jar from the Scala version.

Edit: I've uploaded the minimal example:
https://github.com/Zethson/Scala-Spring-Shell-Example/tree/feature/minimal_scala_issues_SO

答:
It does not matter at which path you have placed your component(Bean) if you are using component scan first it will check it in current package and then to its sub packages. If your component is placed at different path then include the path in @ComponentScan("Path")

Also make sure to check after applying DEBUG mode in application.properties in java for Spring Boot whether your component is being scanned or not , if not try using @Component just above the component wherever it is , since @SpringBootApplication scans the same while startup.

If I answered incorrectly , do let me know your response and elaborate further.
Happy Coding :)

Body:
I'm currently trying to create a Spring Shell Application in Scala.
It works in IntelliJ but does not work when creating the jar.

I have a working proof of concept in Java, that does also successfully create a running jar.

However, my Scala version fails with several:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterValidationExceptionResultHandler': Unsatisfied dependency expressed through field 'parameterResolvers'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.shell.ParameterResolver>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I've tried several minimal examples, moving the classes around (same package) and different Spring annotations (like @SpringBootApplication for both).

Java version:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@ShellComponent
public class MyCommands {

    @ShellMethod("Add two integers together.")
    public int add(int a, int b) {
        return a + b;
    }
}

Scala Version:

@EnableAutoConfiguration
@ComponentScan
class DemoApplication

object Scark extends App {
  SpringApplication.run(classOf[DemoApplication], args:_*)
}

@ShellComponent class MyCommands {
  @ShellMethod("Add two integers together.") def add(a: Int, b: Int): Int = a + b
}

I expect to also be able to successfully build a jar from the Scala version.

Edit: I've uploaded the minimal example:
https://github.com/Zethson/Scala-Spring-Shell-Example/tree/feature/minimal_scala_issues_SO


问:
How to create dataframe of output
I run a query to a webserver with certain added criteria.
I specify a date range which alters the date in the url.
I then pull the data line for specified symbols and I get a list of short volume etc. for the specified stock and time frame.
However, I want to be able to get the output as a dataframe.
The dataframe is now still the stored dataframe from the last ran url, and not of the output.

I tried to use list_.append which I did not get to work.

```<code>import pandas as pd
from datetime import datetime
import urllib

symbols = ['AABA']

start_date = datetime(2019, 5, 10 )
end_date = datetime(2019, 5, 15 )

datelist = pd.date_range(start_date, periods=(end_date-start_date).days+1).tolist()

for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)].to_string(index=False, header=False)
            print(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue
</code>```

The result is now:

```<code>20190510  AABA  2300.0  0.0  14617.0  N
20190513  AABA  2816.0  0.0  39128.0  N
20190514  AABA  1761.0  0.0  26191.0  N
20190515  AABA  24092.0  0.0  62745.0  N
</code>```

I want the result to be in a dataframe so that I can directly export the result to csv

答:
stocks is a dataframe before you convert it to a string. Just keep it as a dataframe, store it in a list and just concat that list to obtain a full dataframe:

```<code>dflist = []
for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)]
            print(stocks.to_string(index=False, header=False))
            dflist.append(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue

df = pd.concat(dflist)
</code>```

Title: How to create dataframe of output

Body:
I run a query to a webserver with certain added criteria.
I specify a date range which alters the date in the url.
I then pull the data line for specified symbols and I get a list of short volume etc. for the specified stock and time frame.
However, I want to be able to get the output as a dataframe.
The dataframe is now still the stored dataframe from the last ran url, and not of the output.

I tried to use list_.append which I did not get to work.

import pandas as pd
from datetime import datetime
import urllib

symbols = ['AABA']

start_date = datetime(2019, 5, 10 )
end_date = datetime(2019, 5, 15 )

datelist = pd.date_range(start_date, periods=(end_date-start_date).days+1).tolist()

for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)].to_string(index=False, header=False)
            print(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue

The result is now:

20190510  AABA  2300.0  0.0  14617.0  N
20190513  AABA  2816.0  0.0  39128.0  N
20190514  AABA  1761.0  0.0  26191.0  N
20190515  AABA  24092.0  0.0  62745.0  N

I want the result to be in a dataframe so that I can directly export the result to csv

Body:
stocks is a dataframe before you convert it to a string. Just keep it as a dataframe, store it in a list and just concat that list to obtain a full dataframe:

dflist = []
for date in datelist:
    url =  f"http://regsho.finra.org/FNYXshvol{date.strftime('%Y%m%d')}.txt"

    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbles)):
            stocks = df[df['Symbol'].isin(symbols)]
            print(stocks.to_string(index=False, header=False))
            dflist.append(stocks)
        else:
            print(f'No stock found for {date.date()}' )
    except urllib.error.HTTPError:
         continue

df = pd.concat(dflist)


问:
How to split a long number into pairs of digits
I have a string of a long number 12345678 and want to convert it to an array like this :

```<code>["12", "34", "56", "78"].
</code>```

I have tried array.split(//).map { |e| e.to_i  }  but it does

```<code>["1", "2", "3", "4", "5", "6", "7", "8"]
</code>```

答:
The simplest way would be to use String#scan with the Regexp /../, which matches any pair of characters:

```<code>n = 12345678

arr = n.to_s.scan(/../)
# => ["12", "34", "56", "78"]
</code>```

If you need to handle odd numbers of digits and keep the last digit, use /..?/ instead:

```<code>n = 123456789

arr = n.to_s.scan(/..?/)
# => ["12", "34", "56", "78", "9"]
</code>```

An alternative approach would be to map over the range 0...n.to_s.size using the Range#step method:

```<code>n = 123456789
str = n.to_s

arr = (0...str.size).step(2).map {|i| str[i, 2] }
# => ["12", "34", "56", "78", "9"]
</code>```

You can see all three approaches in action on repl.it: https://repl.it/@jrunning/BlissfulAcclaimedStrategy

Body:
I have a string of a long number 12345678 and want to convert it to an array like this :

["12", "34", "56", "78"].

I have tried array.split(//).map { |e| e.to_i  }  but it does

["1", "2", "3", "4", "5", "6", "7", "8"]

Body:
The simplest way would be to use String#scan with the Regexp /../, which matches any pair of characters:

n = 12345678

arr = n.to_s.scan(/../)
# => ["12", "34", "56", "78"]

If you need to handle odd numbers of digits and keep the last digit, use /..?/ instead:

n = 123456789

arr = n.to_s.scan(/..?/)
# => ["12", "34", "56", "78", "9"]

An alternative approach would be to map over the range 0...n.to_s.size using the Range#step method:

n = 123456789
str = n.to_s

arr = (0...str.size).step(2).map {|i| str[i, 2] }
# => ["12", "34", "56", "78", "9"]

You can see all three approaches in action on repl.it: https://repl.it/@jrunning/BlissfulAcclaimedStrategy


问:
Optimise a simple double for loop for IE
```<code>array.sort(function(left, right) {
    return index(otherArray, left) < index(otherArray, right);
});
</code>```

This is O(len(array) ^ 2) so for a reasonable size array of len = 1000 this takes constant * 1 million operations which easily overshoots the IE 5 million operators cap.

Thus IE throws a script is taking too long even though this is fast.

The problem is that IE does not have it's own Array.prototype.indexOf so I can't reduce the operation count down to O(len(array) and rely instead end up using a double for loop instead of a single for loop.

I considered array.join and using String.prototype.indexOf but the objects in the arrays are DOM elements and you can't convert them to a string (easily).

Telling IE users to remove this default cap is not an option.

答:
You could try making an index lookup object. This should greatly increase performance too.</p>

```<code>var otherArrayLookup = {};
for ( var i=0; i<otherArray.length; i++ ) {
    otherArrayLookup[otherArray[i]] = i;
}

array.sort(function(left, right) {
    return otherArrayLookup[left] < otherArrayLookup[right];
});
</code>```

Body:
array.sort(function(left, right) {
    return index(otherArray, left) < index(otherArray, right);
});

This is O(len(array) ^ 2) so for a reasonable size array of len = 1000 this takes constant * 1 million operations which easily overshoots the IE 5 million operators cap.

Thus IE throws a script is taking too long even though this is fast.

The problem is that IE does not have it's own Array.prototype.indexOf so I can't reduce the operation count down to O(len(array) and rely instead end up using a double for loop instead of a single for loop.

I considered array.join and using String.prototype.indexOf but the objects in the arrays are DOM elements and you can't convert them to a string (easily).

Telling IE users to remove this default cap is not an option.

Body:
You could try making an index lookup object. This should greatly increase performance too.

var otherArrayLookup = {};
for ( var i=0; i<otherArray.length; i++ ) {
    otherArrayLookup[otherArray[i]] = i;
}

array.sort(function(left, right) {
    return otherArrayLookup[left] < otherArrayLookup[right];
});