问:
Predicate<T> method equals()
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

```<code>    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));
</code>```

Thanks in advance for your Help,

答:
In order to get this to print true, you would have to override the equals method on these classes. Your custom equals would have to check if the parameter is an instance of either of these classes. Since they are anonymous, you'd have no way of referencing them, so you can't really do that.

My suggestion would be to make a non-anonymous class (say, IntegerCheckingPredicate), and make predicateD and predicateM instances of that class. Then your equals method might look like:

```<code>public boolean equals(Object o) {
    if (o instanceof IntegerCheckPredicate) {
        return true;
    }

    return false;
}
</code>```

Then this test would pass:

```<code>@Test
public void testPredicatesWithEqualsOverriddenAreEqual() {
    IntegerCheckPredicate predicateM = new IntegerCheckPredicate();
    IntegerCheckPredicate predicateD = new IntegerCheckPredicate();
    assertEquals(predicateM, predicateD);
}
</code>```

Title: Predicate<T> method equals()

Body:
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));

Thanks in advance for your Help,

Body:
In order to get this to print true, you would have to override the equals method on these classes. Your custom equals would have to check if the parameter is an instance of either of these classes. Since they are anonymous, you'd have no way of referencing them, so you can't really do that.

My suggestion would be to make a non-anonymous class (say, IntegerCheckingPredicate), and make predicateD and predicateM instances of that class. Then your equals method might look like:

public boolean equals(Object o) {
    if (o instanceof IntegerCheckPredicate) {
        return true;
    }

    return false;
}

Then this test would pass:

@Test
public void testPredicatesWithEqualsOverriddenAreEqual() {
    IntegerCheckPredicate predicateM = new IntegerCheckPredicate();
    IntegerCheckPredicate predicateD = new IntegerCheckPredicate();
    assertEquals(predicateM, predicateD);
}


来源: stackexchange

问:
How a c++ program (.cpp) work with header(.h) and libtool (.la)?
I have create a folder in linux called helloworld.
Inside this folder have sub-directory:

include

lib

src

include/
In this directory I have create a header file called helloworld.h
content are:

```<code>class helloworld{
public:

       void getvalue();

};
</code>```

lib/
In lib directory I have create a cpp file called helloworld.cpp
content are mainly functions:

```<code>#include<iostream>
#include<helloworld.h>
using namespace std;

void helloworld::getvalue() {

}
</code>```

src/
In src directory I have create a main cpp file called main.cpp
content are main:

```<code>#include<iostream>
#include<helloworld.h>

int main()
{
helloworld a;
a.getvalue();
}
</code>```

but after I autoconf, automake, ./configure, and when make
it has a error:

helloworld/src/main.cpp:8: undefined reference to `helloworld::getvalue()'

All I want is to use helloworld.cpp's functions in main.cpp. I've spend a lot of time searching and try and error. Please help.

Added the Makefiles.am

in parent directory,
 I have two files Makefile.am and configure.ac:

Makefile.am

```<code>AUTOMAKE_OPTIONS = foreign
SUBDIRS=src lib

</code>```

configure.ac

```<code>AC_INIT([helloworld], [0.1], [helloworld@gmail.com])
AM_INIT_AUTOMAKE
AC_PROG_RANLIB
AC_LANG(C++)
AC_PROG_CC
AC_PROG_CXX
AC_CONFIG_MACRO_DIR([m4])
AC_PROG_LIBTOOL
AC_DISABLE_STATIC
AC_CONFIG_FILES([Makefile lib/Makefile src/Makefile])
AC_SUBST([CC])
LT_INIT
AC_OUTPUT

</code>```

In lib directory has one Makefile.am

```<code>INCDIR=../include
INCPATH=-I. -I$(INCDIR)
AM_CPPFLAGS=$(INCPATH)
lib_LTLIBRARIES=libhelloworld.la
libhelloworld_la_SOURCES=helloworld.cpp

</code>```

In src directory has one Makefile.am

```<code>INCDIR=../include
INCPATH=-I. -I$(INCDIR)
AM_CPPFLAGS=$(INCPATH)
helloworld_LDADD=-L/lib/libhelloworld.la
bin_PROGRAMS=helloworld
helloworld_SOURCES=main.cpp
</code>```

Compiled success if I take out the
a.getvalue();

答:
If you insist on using recursive make, you will need to add a special rule to src/Makefile.am to make sure the lib/Makefile.am rules for rebuilding the library are applied (untested here, but used in other projects).

This now means that a normal recursive build will build ., include, lib, src, and then lib again. I would strongly recommend ditching recursive make and use the one Makefile.am solution I have laid out in my other answer.

```<code>bin_PROGRAMS        = helloworld
helloworld_CPPFLAGS = $(top_srcdir)/include
helloworld_LDADD    = $(top_builddir)/lib/libhelloworld.la
helloworld_SOURCES  = main.cpp

$(top_builddir)/lib/libhelloworld.la:
        cd $(top_builddir)/lib && $(MAKE) libhelloworld.la
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have create a folder in linux called helloworld.
Inside this folder have sub-directory:

include

lib

src

include/
In this directory I have create a header file called helloworld.h
content are:

class helloworld{
public:

       void getvalue();

};

lib/
In lib directory I have create a cpp file called helloworld.cpp
content are mainly functions:

#include<iostream>
#include<helloworld.h>
using namespace std;

void helloworld::getvalue() {

}

src/
In src directory I have create a main cpp file called main.cpp
content are main:

#include<iostream>
#include<helloworld.h>

int main()
{
helloworld a;
a.getvalue();
}

but after I autoconf, automake, ./configure, and when make
it has a error:

helloworld/src/main.cpp:8: undefined reference to `helloworld::getvalue()'

All I want is to use helloworld.cpp's functions in main.cpp. I've spend a lot of time searching and try and error. Please help.

Added the Makefiles.am

in parent directory,
 I have two files Makefile.am and configure.ac:

Makefile.am

AUTOMAKE_OPTIONS = foreign
SUBDIRS=src lib

configure.ac

AC_INIT([helloworld], [0.1], [helloworld@gmail.com])
AM_INIT_AUTOMAKE
AC_PROG_RANLIB
AC_LANG(C++)
AC_PROG_CC
AC_PROG_CXX
AC_CONFIG_MACRO_DIR([m4])
AC_PROG_LIBTOOL
AC_DISABLE_STATIC
AC_CONFIG_FILES([Makefile lib/Makefile src/Makefile])
AC_SUBST([CC])
LT_INIT
AC_OUTPUT

In lib directory has one Makefile.am

INCDIR=../include
INCPATH=-I. -I$(INCDIR)
AM_CPPFLAGS=$(INCPATH)
lib_LTLIBRARIES=libhelloworld.la
libhelloworld_la_SOURCES=helloworld.cpp

In src directory has one Makefile.am

INCDIR=../include
INCPATH=-I. -I$(INCDIR)
AM_CPPFLAGS=$(INCPATH)
helloworld_LDADD=-L/lib/libhelloworld.la
bin_PROGRAMS=helloworld
helloworld_SOURCES=main.cpp

Compiled success if I take out the
a.getvalue();

Body:
If you insist on using recursive make, you will need to add a special rule to src/Makefile.am to make sure the lib/Makefile.am rules for rebuilding the library are applied (untested here, but used in other projects).

This now means that a normal recursive build will build ., include, lib, src, and then lib again. I would strongly recommend ditching recursive make and use the one Makefile.am solution I have laid out in my other answer.

bin_PROGRAMS        = helloworld
helloworld_CPPFLAGS = $(top_srcdir)/include
helloworld_LDADD    = $(top_builddir)/lib/libhelloworld.la
helloworld_SOURCES  = main.cpp

$(top_builddir)/lib/libhelloworld.la:
        cd $(top_builddir)/lib && $(MAKE) libhelloworld.la


问:
Printing integers in the ascending order recursively
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

```<code>public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}
</code>```

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

答:
You can do it like this:

public class IntegerAscendingOrder {
    public static void main(String[] args) throws Exception {
        printIntegersAscendingOrder(n);
    }

    private static void printIntegersAscendingOrder(int i) {
        if (i < 1) {
            return;
        }

        printIntegersAscendingOrder(i-1);
        System.out.println(i);
    }
}
```

You don't need the counter variable in the class, using recursion you can limit the method call within the method itself.

Notice the if (i < 1) {return;} line, this will terminate the recursive method call(s).

This article should help you Getting started with recursion

Body:
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

Body:
You can do it like this:

public class IntegerAscendingOrder {
    public static void main(String[] args) throws Exception {
        printIntegersAscendingOrder(n);
    }

    private static void printIntegersAscendingOrder(int i) {
        if (i < 1) {
            return;
        }

        printIntegersAscendingOrder(i-1);
        System.out.println(i);
    }
}

You don't need the counter variable in the class, using recursion you can limit the method call within the method itself.

Notice the if (i < 1) {return;} line, this will terminate the recursive method call(s).

This article should help you Getting started with recursion


问:
JavaScript Debugging
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You

答:
I think the idea is to use  the Attach to process option of the Debug menu; but to be honest, I've never had much luck getting VS to do this fluidly (though I remember it working at times, success is spasmodic at best), maybe tabbed browsing has made this an issue - I'm unsure.

One thing I can recommend, however, and we might get a few hecklers, are the Developer Tools of IE9. If nothing else, IE9 has become an invaluable tool for me recently simply because of its Javascript debugging capabilities. Here's an MSDN article to get you started with this.

ContentLicense: CC BY-SA 3.0

Title: JavaScript Debugging


问:
Export Graphics with exact size and font size
I need to export graphics from R for the use in different publications formats, i.e., scientific poster, Journal Articel, Powerpoint presentation. As Long as I'm not aware of using R-Markdown and Latex, Or Sweave to produce pdf slides, i need to use Microsoft applications.

I do graphics in R with ggplot2.

My MWE

```<code>df1 <- expand.grid(Year = c(2000, 2010),
                   Treat = c("TreatA","TreatB"),
                   Location = c("Berlin", "Munich", "Kansas", "Paris"),
                   rep = c(1,2,3,4,5,6,7,8,9,10))
df1 <- cbind(df1,
             Var1 = runif(160, -10,25) + rnorm(160,8,4))
</code>```

My Graphics Code:

```<code>p1 <- ggplot(aes(y = Var1, x = Treat,  na.rm=TRUE, fill=Location), data = df1) +
  stat_boxplot(geom ='errorbar', width= 0.5) +
  geom_boxplot(outlier.shape = 1, outlier.size = 2, linetype="solid", size = 1) +
  facet_grid( Year ~ Location) +
  scale_y_continuous(limits=c(-20,60))  +
  scale_fill_manual(values=c("#E69F00", "#009E73", "#0072B2", "#D55E00")) +
  ylab("Magic Skills") +
  xlab("Magic Juice") +
  theme(text=element_text(family="Arial", size=18),
        axis.text.x = element_text(angle = 30, hjust = 1),
        line=element_line(size=1),
        rect=element_rect(colour="red", size=1),
        panel.background=element_rect(colour="black",fill="white", size=1),
        strip.background=element_rect(colour="dark grey", fill="black"),
        strip.text=element_text(face="bold", colour="white"),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        legend.position="none");p1
</code>```

How I save the graph:

```<code>ggsave(p1, file="Results/Figures/Abb2_Boxplots_LarvenPuppen2.svg", width=35, height=20, units = "cm", dpi=500)
</code>```

I set the font size with "theme(text=element_text(family="Arial", size=18)" for the whole graph.
During ggsave I adjust the height and width, for the Poster the height should be 20 cm and width 35 cm. I save in .svg since I made best experience with the quality of the graph, furthermore I can edit anything at anytime in Inkscape, that's great!

So far so good, yet, it appears, that the text is by no means 18 pt, later in the powerpoint-poster, after exporting the graph (without editing!) as .png from Inkscape. It is even not 20 x 35 cm, I found that i loose about 5 cm or more during the saving and export process.

I guess R is doing write, when i say save 20x35 cm R will do it. Where in the whole process were my settings changed, and how can I handle it?

Best regards,
Pharcyde

答:
The font size used by ggplot matches font size in word the problem is that the figure gets resized during saving, during importing, or both. The best solution for me has been to set a graphics window to the size the figure will be in the document (5.33" x 4" usually looks good in Word; 7.5" x 10" for a 4:3 PowerPoint), and then save the figure as that size. You may need to play around with file types (.tif doesn't play nice in PowerPoint and gets resized for some reason). That said, if you use this method and be sure that the figure isn't resized after it is exported from R it will have the exact size font as you had when you made your ggplot.

Here is the code I use,

```<code>dev.new(width = 10, height = 7.5, unit="in", noRStudioGD = T);last_plot() #Set new windo size and replot whatever plot you just made.
ggsave("workingdirectory/plot.png",width = dev.size()[1],height = dev.size()[2]);dev.off() #Save the plot and set the size using `dev.siz()` so you don't have to ever change that part and cannot possibly have a typo.
</code>```

And here is a full example with output that you can bring into a 4:3 PowerPoint and see for yourself that it works.

```<code>measure1<-as.numeric(1:50)
category<-rep(c("a","b","c","d","e"),each=10)

df<-data.frame(measure1,category)

library(ggplot2)
library(extrafont)
ggplot(df, aes(x = category , y = measure1, fill = category, colour = category)) +
  geom_boxplot(outlier.shape = NA, show.legend = F, notch = F) +
  geom_point(aes(),size = 3, shape=16, colour="white", alpha=.6) +
  stat_summary(fun.y=mean, show.legend = FALSE, geom="point", shape=18, size=5, colour = "white", na.rm = TRUE) +
  ylab("Measure") +
  xlab("Category") +
  ggtitle("") +
  scale_y_continuous (limits = c(0,50), expand = c(0,0), breaks=seq(0,50,5))+
  scale_x_discrete(limits=c("a","b","c","d","e")) +
  scale_fill_manual(values = rep("black",5))+
  scale_colour_manual(values = rep("white",5))+
  theme_bw() +
  theme (text=element_text(size=24,  family="Times New Roman"),
         axis.title.y=element_text(size=24, vjust=2, colour="white"),
         axis.title.x=element_text(size=24, hjust=0.5, colour="white"),
         panel.border = element_blank(),
         plot.title=element_blank(),
         plot.margin = unit(c(.5, .5, .5, .5), "cm"),
         panel.background = element_rect(fill = "black"),
         plot.background = element_rect(fill = "black"),
         panel.grid.major = element_blank(),
         panel.grid.minor = element_blank(),
         legend.position = "none",
         axis.ticks = element_line(size=0.8, colour = "white"),
         axis.ticks.length=unit(0.2,"cm"),
         axis.text.x=element_text(colour="white",size=24,angle=0,hjust=.5),
         axis.text.y=element_text(colour="white",size=24),
         axis.line = element_line(colour="white", size=0.8, lineend = "square"))

dev.new(width = 10, height = 7.5, unit="in", noRStudioGD = T);last_plot()
ggsave("C:/Users/s39f171/Documents/plot.png",width = dev.size()[1],height = dev.size()[2]);dev.off()
</code>```

Body:
I need to export graphics from R for the use in different publications formats, i.e., scientific poster, Journal Articel, Powerpoint presentation. As Long as I'm not aware of using R-Markdown and Latex, Or Sweave to produce pdf slides, i need to use Microsoft applications.

I do graphics in R with ggplot2.

My MWE

df1 <- expand.grid(Year = c(2000, 2010),
                   Treat = c("TreatA","TreatB"),
                   Location = c("Berlin", "Munich", "Kansas", "Paris"),
                   rep = c(1,2,3,4,5,6,7,8,9,10))
df1 <- cbind(df1,
             Var1 = runif(160, -10,25) + rnorm(160,8,4))

My Graphics Code:

p1 <- ggplot(aes(y = Var1, x = Treat,  na.rm=TRUE, fill=Location), data = df1) +
  stat_boxplot(geom ='errorbar', width= 0.5) +
  geom_boxplot(outlier.shape = 1, outlier.size = 2, linetype="solid", size = 1) +
  facet_grid( Year ~ Location) +
  scale_y_continuous(limits=c(-20,60))  +
  scale_fill_manual(values=c("#E69F00", "#009E73", "#0072B2", "#D55E00")) +
  ylab("Magic Skills") +
  xlab("Magic Juice") +
  theme(text=element_text(family="Arial", size=18),
        axis.text.x = element_text(angle = 30, hjust = 1),
        line=element_line(size=1),
        rect=element_rect(colour="red", size=1),
        panel.background=element_rect(colour="black",fill="white", size=1),
        strip.background=element_rect(colour="dark grey", fill="black"),
        strip.text=element_text(face="bold", colour="white"),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        legend.position="none");p1

How I save the graph:

ggsave(p1, file="Results/Figures/Abb2_Boxplots_LarvenPuppen2.svg", width=35, height=20, units = "cm", dpi=500)

I set the font size with "theme(text=element_text(family="Arial", size=18)" for the whole graph.
During ggsave I adjust the height and width, for the Poster the height should be 20 cm and width 35 cm. I save in .svg since I made best experience with the quality of the graph, furthermore I can edit anything at anytime in Inkscape, that's great!

So far so good, yet, it appears, that the text is by no means 18 pt, later in the powerpoint-poster, after exporting the graph (without editing!) as .png from Inkscape. It is even not 20 x 35 cm, I found that i loose about 5 cm or more during the saving and export process.

I guess R is doing write, when i say save 20x35 cm R will do it. Where in the whole process were my settings changed, and how can I handle it?

Best regards,
Pharcyde

Body:
The font size used by ggplot matches font size in word the problem is that the figure gets resized during saving, during importing, or both. The best solution for me has been to set a graphics window to the size the figure will be in the document (5.33" x 4" usually looks good in Word; 7.5" x 10" for a 4:3 PowerPoint), and then save the figure as that size. You may need to play around with file types (.tif doesn't play nice in PowerPoint and gets resized for some reason). That said, if you use this method and be sure that the figure isn't resized after it is exported from R it will have the exact size font as you had when you made your ggplot.

Here is the code I use,

dev.new(width = 10, height = 7.5, unit="in", noRStudioGD = T);last_plot() #Set new windo size and replot whatever plot you just made.
ggsave("workingdirectory/plot.png",width = dev.size()[1],height = dev.size()[2]);dev.off() #Save the plot and set the size using `dev.siz()` so you don't have to ever change that part and cannot possibly have a typo.

And here is a full example with output that you can bring into a 4:3 PowerPoint and see for yourself that it works.

measure1<-as.numeric(1:50)
category<-rep(c("a","b","c","d","e"),each=10)

df<-data.frame(measure1,category)

library(ggplot2)
library(extrafont)
ggplot(df, aes(x = category , y = measure1, fill = category, colour = category)) +
  geom_boxplot(outlier.shape = NA, show.legend = F, notch = F) +
  geom_point(aes(),size = 3, shape=16, colour="white", alpha=.6) +
  stat_summary(fun.y=mean, show.legend = FALSE, geom="point", shape=18, size=5, colour = "white", na.rm = TRUE) +
  ylab("Measure") +
  xlab("Category") +
  ggtitle("") +
  scale_y_continuous (limits = c(0,50), expand = c(0,0), breaks=seq(0,50,5))+
  scale_x_discrete(limits=c("a","b","c","d","e")) +
  scale_fill_manual(values = rep("black",5))+
  scale_colour_manual(values = rep("white",5))+
  theme_bw() +
  theme (text=element_text(size=24,  family="Times New Roman"),
         axis.title.y=element_text(size=24, vjust=2, colour="white"),
         axis.title.x=element_text(size=24, hjust=0.5, colour="white"),
         panel.border = element_blank(),
         plot.title=element_blank(),
         plot.margin = unit(c(.5, .5, .5, .5), "cm"),
         panel.background = element_rect(fill = "black"),
         plot.background = element_rect(fill = "black"),
         panel.grid.major = element_blank(),
         panel.grid.minor = element_blank(),
         legend.position = "none",
         axis.ticks = element_line(size=0.8, colour = "white"),
         axis.ticks.length=unit(0.2,"cm"),
         axis.text.x=element_text(colour="white",size=24,angle=0,hjust=.5),
         axis.text.y=element_text(colour="white",size=24),
         axis.line = element_line(colour="white", size=0.8, lineend = "square"))

dev.new(width = 10, height = 7.5, unit="in", noRStudioGD = T);last_plot()
ggsave("C:/Users/s39f171/Documents/plot.png",width = dev.size()[1],height = dev.size()[2]);dev.off()


问:
Disabling macOS focus ring in SwiftUI
Is it possible to disable the focus ring around a TextField in swiftUI for Mac?

答:
As stated in an answer by Asperi to a similar question here, it's not possible (yet) to turn off the focus ring for a specific field using SwiftUI; however, the following workaround will disable the focus ring for all NSTextField instances in the app:

```<code>extension NSTextField {
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}
</code>```

Not ideal, but it does provide one option that doesn't require stepping too far outside of SwiftUI.

Title: Disabling macOS focus ring in SwiftUI

Body:
As stated in an answer by Asperi to a similar question here, it's not possible (yet) to turn off the focus ring for a specific field using SwiftUI; however, the following workaround will disable the focus ring for all NSTextField instances in the app:

extension NSTextField {
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

Not ideal, but it does provide one option that doesn't require stepping too far outside of SwiftUI.


问:
css margin:auto not centering div in webkit browsers (Chrome and Safari) when maximised/full screen
I have been unable to determine the cause of this problem, so I can not display a test case,
instead I have narrowed down my code to a page that still contains the fault without too much extra.

Here is the link:

http://www.richard-walsh.limewebs.com/Disk-Edits/index.html

The problem is that the content div (id=content), is not centering in Chrome and Safari.

It is positioned to the right.

The content div is surrounded by a div called bottom, whose width:100%; and height:auto;.

```<code>#bottom{
    width:100%;
    height:auto;
    padding:0px;
    margin:0px;
}

#content{
    width:862.4px;
    height:402px;
    margin:auto;
    padding-left:10px;
    padding-right:10px;
    padding-top:5px;
    padding-bottom:5px;
    background-color:#030303;
    background-image:url(images/main.png);
    -moz-border-radius:15px;
    border-radius:15px;
    border-style:solid;
    border-color:#181818;
    border-width:4px;
    margin-top:60px;
    -moz-box-shadow: 1px 1px 20px 4px black;
    -webkit-box-shadow: 1px 1px 20px 4px black;
    box-shadow: 1px 1px 20px 4px black;
    overflow:hidden;
}
</code>```

I have found that if I remove overflow:hidden from the content css then it centers correctly.
But I need this (for parts not shown in the link)

I have also found that it works if I remove the menu entirely.
So I think that there must be something in the menu css that has caused this.
It works fine in Firefox(4).

I'm running Chrome 11.0.696.68
and Safari 5.0.5

Oh! I have just noticed that this only happens when Chrome is maximised, when it is in 'window mode' (for lack of a better name) it centers perfectly, even if the window is stretched to the full size of the screen.

I have also noticed that if you remove #copyright, then #content is rendered on the left, and if both #copyright and #choice is removed then the content div renders in the centre, and if you only remove #choice it still renders on the right.

If you remove #menu_all then it centers correctly.

Any help would be much appreciated,

Thanks

答:
```<code><div id="content" class="post"></div>
</code>```

Is not in #middle, it's in #bottom.
If you move this up the layout appears to work correctly.

Body:
I have been unable to determine the cause of this problem, so I can not display a test case,
instead I have narrowed down my code to a page that still contains the fault without too much extra.

Here is the link:

http://www.richard-walsh.limewebs.com/Disk-Edits/index.html

The problem is that the content div (id=content), is not centering in Chrome and Safari.

It is positioned to the right.

The content div is surrounded by a div called bottom, whose width:100%; and height:auto;.

#bottom{
    width:100%;
    height:auto;
    padding:0px;
    margin:0px;
}

#content{
    width:862.4px;
    height:402px;
    margin:auto;
    padding-left:10px;
    padding-right:10px;
    padding-top:5px;
    padding-bottom:5px;
    background-color:#030303;
    background-image:url(images/main.png);
    -moz-border-radius:15px;
    border-radius:15px;
    border-style:solid;
    border-color:#181818;
    border-width:4px;
    margin-top:60px;
    -moz-box-shadow: 1px 1px 20px 4px black;
    -webkit-box-shadow: 1px 1px 20px 4px black;
    box-shadow: 1px 1px 20px 4px black;
    overflow:hidden;
}

I have found that if I remove overflow:hidden from the content css then it centers correctly.
But I need this (for parts not shown in the link)

I have also found that it works if I remove the menu entirely.
So I think that there must be something in the menu css that has caused this.
It works fine in Firefox(4).

I'm running Chrome 11.0.696.68
and Safari 5.0.5

Oh! I have just noticed that this only happens when Chrome is maximised, when it is in 'window mode' (for lack of a better name) it centers perfectly, even if the window is stretched to the full size of the screen.

I have also noticed that if you remove #copyright, then #content is rendered on the left, and if both #copyright and #choice is removed then the content div renders in the centre, and if you only remove #choice it still renders on the right.

If you remove #menu_all then it centers correctly.

Any help would be much appreciated,

Thanks

Body:
<div id="content" class="post"></div>

Is not in #middle, it's in #bottom.
If you move this up the layout appears to work correctly.


问:
Implementing Postgres Sql in Apache Airflow
I have Apache-Airflow implemented on an Ubuntu version 18.04.3 server. When I set it up, I used the sql lite generic database, and this uses the sequential executor. I did this just to play around and get used to the system. Now I'm trying to use the Local Executor, and will need to transition my database from sqlite to the recommended postgres sql. </p>

<p>Does anybody know how to make this transition? All of the tutorials I've found entail setting up Airflow with postgres sql from the beginning. I know there are a ton of moving parts and I'm scared of messsing up what I currently have running. Anybody who knows how to do this or can point me at where to look is much appreciated. Thanks!   </p>

答:
Just to complete @lalligood answer with some commands:

In airflow.cfg file look for sql_alchemy_conn and update it to point to your PostgreSQL serv:

```<code>sql_alchemy_conn = postgresql+psycopg2://user:pass@hostadress:port/database
</code>```

For instance:

```<code>sql_alchemy_conn = postgresql+psycopg2://airflow:airflow@localhost:5432/airflow
</code>```

As indicated in the above line you need both user and database called airflow, therefore you need to create that. To do so, open your psql command line and type the following commands to create a user and database called airflow and give all privileges over database airflow to user airflow:

```<code>CREATE USER airflow;
CREATE DATABASE airflow;
GRANT ALL PRIVILEGES ON DATABASE airflow TO airflow;
</code>```

Now you are ready to init the airflow application using postgres:

airflow initdb

If everything was right, access the psql command line again, enter in airflow database with \c airflow command and type \dt command to list all tables of that database. You should see a list of airflow tables, currently it is 23.

Body:
I have Apache-Airflow implemented on an Ubuntu version 18.04.3 server. When I set it up, I used the sql lite generic database, and this uses the sequential executor. I did this just to play around and get used to the system. Now I'm trying to use the Local Executor, and will need to transition my database from sqlite to the recommended postgres sql.

Does anybody know how to make this transition? All of the tutorials I've found entail setting up Airflow with postgres sql from the beginning. I know there are a ton of moving parts and I'm scared of messsing up what I currently have running. Anybody who knows how to do this or can point me at where to look is much appreciated. Thanks!

Body:
Just to complete @lalligood answer with some commands:

In airflow.cfg file look for sql_alchemy_conn and update it to point to your PostgreSQL serv:

sql_alchemy_conn = postgresql+psycopg2://user:pass@hostadress:port/database

For instance:

sql_alchemy_conn = postgresql+psycopg2://airflow:airflow@localhost:5432/airflow

As indicated in the above line you need both user and database called airflow, therefore you need to create that. To do so, open your psql command line and type the following commands to create a user and database called airflow and give all privileges over database airflow to user airflow:

CREATE USER airflow;
CREATE DATABASE airflow;
GRANT ALL PRIVILEGES ON DATABASE airflow TO airflow;

Now you are ready to init the airflow application using postgres:

airflow initdb

If everything was right, access the psql command line again, enter in airflow database with \c airflow command and type \dt command to list all tables of that database. You should see a list of airflow tables, currently it is 23.


问:
Add class in jquery
I am using jquery 3.3.1 to create a html element, like the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-id': 1,
  'data-options': '[test1, test2, test3]',
  'data-all': '[test0, test-1, test-2]',
  'html': $('', {
    'text': "test"
  })
});

console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

I would like to add the bootstrap class class="badge badge-info" to my two span elements.

Any suggestions how to add this directly via jquery?

答:
You can just the class same as you did for the data attributes for also you can use addClass

var $elem = $('', {
  'data-function': "addSynonym",
  'data-id': 1,
  'data-options': '[test1, test2, test3]',
  'class': 'badge badge-info',
  'data-all': '[test0, test-1, test-2]',
  'html': $('', {
    'text': "test",
    'class': 'badge badge-info'
  })
});

console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Add class in jquery

Body:
I am using jquery 3.3.1 to create a html element, like the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-id': 1,
  'data-options': '[test1, test2, test3]',
  'data-all': '[test0, test-1, test-2]',
  'html': $('', {
    'text': "test"
  })
});

console.log($elem[0]);
console.log($elem[0].innerHTML);

I would like to add the bootstrap class class="badge badge-info" to my two span elements.

Any suggestions how to add this directly via jquery?

Body:
You can just the class same as you did for the data attributes for also you can use addClass

var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-id': 1,
  'data-options': '[test1, test2, test3]',
  'class': 'badge badge-info',
  'data-all': '[test0, test-1, test-2]',
  'html': $('<span>', {
    'text': "test",
    'class': 'badge badge-info'
  })
});

console.log($elem[0]);
console.log($elem[0].innerHTML);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
SDWebImage - how to extend download timeout
I'm using SDWebImage in my application and it works great on WiFi and 'good' 3G connections. However under slow network connections (e.g. poor 3G) it always fails downloading images because it looks like there's a 10 second timeout limit.

Can I extend such timeout so that the download can take longer before failing?

I could not find any 'timeout' property on the SDWebImage headers and I just found some hardcoded values such as

NSMutableURLRequest *request = [NSMutableURLRequest.alloc initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:15];

Before I used SDWebImage my low-end users were able to download images successfully (just by waiting a bit more), now the download always fails. (I'm using 'http://mschrag.github.io' to simulate slow network conditions)

答:
here is a solution for swift developer</p>

```<code>SDWebImageDownloader.shared.config.downloadTimeout = 300
</code>```

Body:
here is a solution for swift developer

SDWebImageDownloader.shared.config.downloadTimeout = 300


问:
Passing params in React Navigation 5
I'm trying to pass a few params between a Tab Navigator. Below is the structure of my program. In bold are the routes

App(Tab Navigator): { Main(stack) & Filter(screen) }

Main(Stack Navigator): { Home(screen) & MediaDetails(screen) }

I have a button on the screen associated with Filter which has an onPress() function. I'm passing a few params(but let's only consider the param to for the sake of this question).

```<code>this.props.navigation.navigate('Home', {
    to: this.state.to,
}
</code>```

Now in the screen associated with Home, I'm reading the param inside the state like this:

```<code>state = {
    to: this.props.route.params.to
}
</code>```

Inside App.js, I've set the initial value of to to be '2020' like this:

```<code><Stack.Screen
    name="Home"
    component={HomeScreen}
    initialParams={{
       to: '2020'
    }}
/>
</code>```

The initial value is indeed set to 2020. I press the button. Let's say I'm setting to to 1900. Just before this.props.navigation.navigate executes, I console.log(this.state.to) the value and it is indeed updated to 1900. However, as the screen changes to Home, the value reverts back to 2020(observed via console.log)

Could someone point out the cause for this spooky behavior? I've been trying to debug this for many hours with no luck. React Navigation 5 is pretty new as well so couldn't find anything similar online. Any help will be greatly appreciated. Thank you for reading all the way.

Edit: Issue has been resolved and full code has been removed!

答:
I solved this problem by updating the state in shouldComponentUpdate().

This bug was due to the state not being updated as the screen remained mounted.

This was possible because of ravirajn22 on GitHub who explained to me the reasoning behind this bug and a possible solution.

Link to the answer: https://github.com/react-navigation/react-navigation/issues/6863

Title: Passing params in React Navigation 5

Body:
I'm trying to pass a few params between a Tab Navigator. Below is the structure of my program. In bold are the routes

App(Tab Navigator): { Main(stack) & Filter(screen) }

Main(Stack Navigator): { Home(screen) & MediaDetails(screen) }

I have a button on the screen associated with Filter which has an onPress() function. I'm passing a few params(but let's only consider the param to for the sake of this question).

this.props.navigation.navigate('Home', {
    to: this.state.to,
}

Now in the screen associated with Home, I'm reading the param inside the state like this:

state = {
    to: this.props.route.params.to
}

Inside App.js, I've set the initial value of to to be '2020' like this:

<Stack.Screen
    name="Home"
    component={HomeScreen}
    initialParams={{
       to: '2020'
    }}
/>

The initial value is indeed set to 2020. I press the button. Let's say I'm setting to to 1900. Just before this.props.navigation.navigate executes, I console.log(this.state.to) the value and it is indeed updated to 1900. However, as the screen changes to Home, the value reverts back to 2020(observed via console.log)

Could someone point out the cause for this spooky behavior? I've been trying to debug this for many hours with no luck. React Navigation 5 is pretty new as well so couldn't find anything similar online. Any help will be greatly appreciated. Thank you for reading all the way.

Edit: Issue has been resolved and full code has been removed!


问:
Compiling C/C++ in VS Code
I'm trying to compile C/C++ code in VS Code using cl (installed via visual studio 2019). I've set up the json files like the MS website suggests,

https://code.visualstudio.com/docs/cpp/config-msvc,

but I still get the error:

```<code>cl.exe : The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
</code>```

Here are my json files:

```<code>{
"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "windowsSdkVersion": "10.0.17763.0",
        "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.21.27702/bin/Hostx64/x64/cl.exe",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "msvc-x64"
    }
],
"version": 4
</code>```

}

```<code>{
"version": "2.0.0",
"tasks": [
    {
        "label": "msvc build",
        "type": "shell",
        "command": "cl.exe",
        "args": [
            "/EHsc",
            "/Zi",
            "/Fe:",
            "helloworld.exe",
            "test.c"
        ],
        "group":  {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            "reveal":"always"
        },
        "problemMatcher": "$msCompile"
    }
]
</code>```

}

答:
I have struggled in the same problem as following the instructions in Configure VS Code for Microsoft C++. Thankfully I found this question and @Romen's great answer.

However, here are some itchy points in his solution:

He hard-coded the executable name and the file name so that you have to change it every time you make a new project.

He put the .bat in the folder of the compiled file but not the .vscode folder so that we couldn't copy one folder directly while making new projects.

For this two flecks, I modified his codes a little bit so that it's more convenient to make new projects debugging with Microsoft C++.

In the build.bat file, change the command

cl.exe /EHsc /Zi /Fe: helloworld.exe helloworld.cpp

to

cl.exe /EHsc /Zi /Fe: %1.exe %1.cpp

Move the build.bat to .vscode folder and change "command": "build.bat" to "command": ".\\.vscode\\build.bat ${fileBasenameNoExtension}".

This is trivial, but I hope it could help some newbies like me and inspire better solutions for more complicated cases :)

Title: Compiling C/C++ in VS Code

Body:
I'm trying to compile C/C++ code in VS Code using cl (installed via visual studio 2019). I've set up the json files like the MS website suggests,

https://code.visualstudio.com/docs/cpp/config-msvc,

but I still get the error:

cl.exe : The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Here are my json files:

{
"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "windowsSdkVersion": "10.0.17763.0",
        "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.21.27702/bin/Hostx64/x64/cl.exe",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "msvc-x64"
    }
],
"version": 4

}

{
"version": "2.0.0",
"tasks": [
    {
        "label": "msvc build",
        "type": "shell",
        "command": "cl.exe",
        "args": [
            "/EHsc",
            "/Zi",
            "/Fe:",
            "helloworld.exe",
            "test.c"
        ],
        "group":  {
            "kind": "build",
            "isDefault": true
        },
        "presentation": {
            "reveal":"always"
        },
        "problemMatcher": "$msCompile"
    }
]

}


问:
Retrieve text after last back slash using SSIS Derived Column transformation
Using SQL Server 2014.

I have a field that contains a string that contains a full file path i.e.

```<code>\\Server\Folder1\Folder2\Folder3\File21.csv
</code>```

I only want what is after the last backslash i.e.

```<code>File21.csv
</code>```

So in the world of SQL I would use:

```<code>Select RIGHT([FileName],charindex('\',reverse([FileName]),1)-1) as FileNameNew from mytable
</code>```

However, how do I do this in a Derived Column in SSIS?  There is no CHARINDEX so you have to use FINDSTRING.  This is my expression:

```<code>RIGHT( [FileName] , FINDSTRING('\', REVERSE( [FileName] ) ,1)  -1)
</code>```

But it is not working, it keeps saying the single quotation mark was not expected.  I've also tried double quotes to no avail.

答:
I think you have your parameters backwards. FINDSTRING() wants the thing you're searching first, then the thing you're searching for. And you will need double quotes and an escaped backslash. This should work:

```<code>RIGHT( [FileName] , FINDSTRING(REVERSE( [FileName] ), "\\" ,1)  -1)
</code>```

Body:
Using SQL Server 2014.

I have a field that contains a string that contains a full file path i.e.

\\Server\Folder1\Folder2\Folder3\File21.csv

I only want what is after the last backslash i.e.

File21.csv

So in the world of SQL I would use:

Select RIGHT([FileName],charindex('\',reverse([FileName]),1)-1) as FileNameNew from mytable

However, how do I do this in a Derived Column in SSIS?  There is no CHARINDEX so you have to use FINDSTRING.  This is my expression:

RIGHT( [FileName] , FINDSTRING('\', REVERSE( [FileName] ) ,1)  -1)

But it is not working, it keeps saying the single quotation mark was not expected.  I've also tried double quotes to no avail.

Body:
I think you have your parameters backwards. FINDSTRING() wants the thing you're searching first, then the thing you're searching for. And you will need double quotes and an escaped backslash. This should work:

RIGHT( [FileName] , FINDSTRING(REVERSE( [FileName] ), "\\" ,1)  -1)


问:
How to structure many-to-many relationships in cosmos db
I'm working on a new project and it was recommended to me that I have a look at Cosmos DB to use for my data store for it because it's going to be a global SaaS application servicing potentially hundreds of thousands of users.

As this is my first foray into NoSQL databases I've inevitably run into a lot of things I have to learn but I feel like I've been slowly getting it and have actually become quite excited about it.

Now here comes the kicker: I have a relatively simple data structure that I just can't seem to wrap my head around how you'd implement and I've pretty much resigned to the fact that it might just be a workload which doesn't really work well in non-relational databases. But as I said I'm completely green so I'm here for a sanity check in case there's something obvious that I'm missing

I have a data structure consisting of a "user" object and a "post" object and I need to relate them based on unbounded arrays of tags to basically create customized feeds they look like this

User:

```<code>{
    id: 1,
    name: "username",
    interests: [
        "fishing",
        "photography",
        "stargazing",
    ]
}
</code>```

Post:

```<code>{
    id: 1,
    title: "My post title",
    body: "My post content",
    tags: [
        "tennis",
        "sport",
        "photography",
    ]
}
</code>```

I want to return a list of all posts which has one or more of a given users interests in their tags so basically a query like this:

```<code>SELECT DISTINCT VALUE Posts FROM Posts
JOIN tag IN Posts.Tags
WHERE tag IN <<user.interests>>
</code>```

In SQL I'd create a table of users and a table of posts and join them based on shared tags/interests but I can't for the life of me figure out how to denormalize this (if possible). Have I really run into one of the impossible flows of NoSQL on my first attempt with only 2 objects? Or am I just being a total noob?

答:
You're on the right track! There are two really good articles that describe how to model data for NoSQL. Definitely worth a read if you're new to this type of data store.

Data modeling in Azure Cosmos DB, in particular the section on many-to-many relationships.

and

How to model and partition data on Azure Cosmos DB using a real-world example

Hope you find this helpful.

Body:
I'm working on a new project and it was recommended to me that I have a look at Cosmos DB to use for my data store for it because it's going to be a global SaaS application servicing potentially hundreds of thousands of users.

As this is my first foray into NoSQL databases I've inevitably run into a lot of things I have to learn but I feel like I've been slowly getting it and have actually become quite excited about it.

Now here comes the kicker: I have a relatively simple data structure that I just can't seem to wrap my head around how you'd implement and I've pretty much resigned to the fact that it might just be a workload which doesn't really work well in non-relational databases. But as I said I'm completely green so I'm here for a sanity check in case there's something obvious that I'm missing

I have a data structure consisting of a "user" object and a "post" object and I need to relate them based on unbounded arrays of tags to basically create customized feeds they look like this

User:

{
    id: 1,
    name: "username",
    interests: [
        "fishing",
        "photography",
        "stargazing",
    ]
}

Post:

{
    id: 1,
    title: "My post title",
    body: "My post content",
    tags: [
        "tennis",
        "sport",
        "photography",
    ]
}

I want to return a list of all posts which has one or more of a given users interests in their tags so basically a query like this:

SELECT DISTINCT VALUE Posts FROM Posts
JOIN tag IN Posts.Tags
WHERE tag IN <<user.interests>>

In SQL I'd create a table of users and a table of posts and join them based on shared tags/interests but I can't for the life of me figure out how to denormalize this (if possible). Have I really run into one of the impossible flows of NoSQL on my first attempt with only 2 objects? Or am I just being a total noob?


问:
How to copy a Excel column to a Java list
I would like to extract the entire column from an excel worksheet to a Java array using the Aspose library. How do I do that? In many of the examples, I see how to copy a column/row from one worksheet to another only. Can Aspose extract data?</p>

答:
Yes, data can be easily exported to an Array using the exportArray method, see the sample code for your reference:

Example

```<code>// Instantiating a Workbook object
Workbook workbook = new Workbook("Book1.xlsx");

// Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);

// Exporting the contents of 100 rows and 1 column starting from 1st cell (i.e., A1:A100)
// to Array. you may update the method parameters for your needs
Object dataTable[][] = worksheet.getCells().exportArray(0, 0, 100, 1);

// Printing number of rows after exporting worksheet data
System.out.println("No. Of Rows Imported: " + dataTable.length);

.....
</code>```

PS. I am working as Support developer/ Evangelist at Aspose.

Body:
Yes, data can be easily exported to an Array using the exportArray method, see the sample code for your reference:

Example

// Instantiating a Workbook object
Workbook workbook = new Workbook("Book1.xlsx");

// Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);

// Exporting the contents of 100 rows and 1 column starting from 1st cell (i.e., A1:A100)
// to Array. you may update the method parameters for your needs
Object dataTable[][] = worksheet.getCells().exportArray(0, 0, 100, 1);

// Printing number of rows after exporting worksheet data
System.out.println("No. Of Rows Imported: " + dataTable.length);

.....

PS. I am working as Support developer/ Evangelist at Aspose.


问:
Scrape html data using beautifulsoup and Python
I am trying to scrape school names from the following url: https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1.

I want to scrape 10 pages, hence the for loop. I have never used beautifulsoup before and the documentation hasn't solved my problem. Ultimately, I want to scrape the  since that's where the school names reside. Below is the small amount of code I have. Any help would be extremely helpful! Thanks!

```<code>import bs4 as bs
import requests

numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

names = []
for number in numbers:
    resp = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page='+number)
    soup = bs.BeautifulSoup(resp.text, "lxml")
    school_names = soup.find('div', {'class':'"search-results"'})
    for school_name in school_names:
        school = school_name.find('h2')
        if school:
            print (school.text)
</code>```

答:
The webpage you are trying to scrape has CAPTCHA which makes it difficult to collect data. Take a look at this link:

https://sqa.stackexchange.com/questions/17022/how-to-fill-captcha-using-test-automation

Body:
I am trying to scrape school names from the following url: https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1.

I want to scrape 10 pages, hence the for loop. I have never used beautifulsoup before and the documentation hasn't solved my problem. Ultimately, I want to scrape the  since that's where the school names reside. Below is the small amount of code I have. Any help would be extremely helpful! Thanks!

import bs4 as bs
import requests

numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

names = []
for number in numbers:
    resp = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page='+number)
    soup = bs.BeautifulSoup(resp.text, "lxml")
    school_names = soup.find('div', {'class':'"search-results"'})
    for school_name in school_names:
        school = school_name.find('h2')
        if school:
            print (school.text)


答:
Try this with passing the headers. Using https://curl.trillworks.com/ as a helper, I get:

```<code>import requests

headers = {
    'authority': 'fonts.gstatic.com',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
    'sec-fetch-dest': 'font',
    'accept': '*/*',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-user': '?1',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': '_pxhd=120bcbd3ded2e33c1496a0ff505f52a169b1f9c1db59a881c1cd00495b9442ee:62dfdf81-5341-11ea-95d7-e144631f0943; xid=6fef7398-e61d-46d2-be72-ee8e8fecc13d; navigation=%7B%22location%22%3A%7s%22%3A%7B%22colleges%22%3A%22%2Fs%2Findiana%2F%22%2C%22graduate-schools%22%3A%22%2Fs%2Findiana%2F%22%2C%22k12%22%3A%22%2Fs%2Findiana%2F%22%2C%22places-to-live%22%3A%22%2Fs%2Findiana%2F%22%2C%22places-to-work%22%3A%22%2Fs%2Findiana%2F%22%7D%7D; experiments=%5E%5E%5E%24%5D; recentlyViewed=entityHistory%7CsearchHistory%7CentityName%7CIndiana%7CentityGuid%7Cad8b4b4c-f8d2-4015-8b22-c0f002a720bb%7CentityType%7CState%7CentityFragment%7Cindiana%5E%5E%5E%240%7C%40%5D%7C1%7C%40%242%7C3%7C4%7C5%7C6%7C7%7C8%7C9%5D%5D%5D; hintSeenLately=second_hint',
    'Connection': 'keep-alive',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
    'Sec-Fetch-Dest': 'image',
    'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'no-cors',
    'Referer': 'https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1',
    'Accept-Language': 'en-US,en;q=0.9',
    'x-client-data': 'CI+2yQEIorbJAQjBtskBCKmdygEIy67KAQi8sMoBCJa1ygEIm7XKAQjstcoBCI66ygEIsL3KARirpMoB',
    'referer': 'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700',
    'origin': 'https://www.niche.com',
    'Origin': 'https://www.niche.com',
}

params = (
    ('page', '1'),
)

response = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/', headers=headers, params=params)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1', headers=headers)
</code>```

This gives me a 200 now and not a 403. The above headers are verbose of course (I copied this from my browser), you could probably use trial-and-error to see which headers are actually required (I'm guessing it's only a handful) to guarantee a 200 OK.

Title: Scrape html data using beautifulsoup and Python

Body:
Try this with passing the headers. Using https://curl.trillworks.com/ as a helper, I get:

import requests

headers = {
    'authority': 'fonts.gstatic.com',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
    'sec-fetch-dest': 'font',
    'accept': '*/*',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-user': '?1',
    'accept-language': 'en-US,en;q=0.9',
    'cookie': '_pxhd=120bcbd3ded2e33c1496a0ff505f52a169b1f9c1db59a881c1cd00495b9442ee:62dfdf81-5341-11ea-95d7-e144631f0943; xid=6fef7398-e61d-46d2-be72-ee8e8fecc13d; navigation=%7B%22location%22%3A%7s%22%3A%7B%22colleges%22%3A%22%2Fs%2Findiana%2F%22%2C%22graduate-schools%22%3A%22%2Fs%2Findiana%2F%22%2C%22k12%22%3A%22%2Fs%2Findiana%2F%22%2C%22places-to-live%22%3A%22%2Fs%2Findiana%2F%22%2C%22places-to-work%22%3A%22%2Fs%2Findiana%2F%22%7D%7D; experiments=%5E%5E%5E%24%5D; recentlyViewed=entityHistory%7CsearchHistory%7CentityName%7CIndiana%7CentityGuid%7Cad8b4b4c-f8d2-4015-8b22-c0f002a720bb%7CentityType%7CState%7CentityFragment%7Cindiana%5E%5E%5E%240%7C%40%5D%7C1%7C%40%242%7C3%7C4%7C5%7C6%7C7%7C8%7C9%5D%5D%5D; hintSeenLately=second_hint',
    'Connection': 'keep-alive',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
    'Sec-Fetch-Dest': 'image',
    'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'no-cors',
    'Referer': 'https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1',
    'Accept-Language': 'en-US,en;q=0.9',
    'x-client-data': 'CI+2yQEIorbJAQjBtskBCKmdygEIy67KAQi8sMoBCJa1ygEIm7XKAQjstcoBCI66ygEIsL3KARirpMoB',
    'referer': 'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700',
    'origin': 'https://www.niche.com',
    'Origin': 'https://www.niche.com',
}

params = (
    ('page', '1'),
)

response = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/', headers=headers, params=params)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.get('https://www.niche.com/k12/search/best-public-high-schools/s/indiana/?page=1', headers=headers)

This gives me a 200 now and not a 403. The above headers are verbose of course (I copied this from my browser), you could probably use trial-and-error to see which headers are actually required (I'm guessing it's only a handful) to guarantee a 200 OK.


问:
Change old React app to work with React Dev Tools
I am new to React apps so please excuse me if my question has an easy answer. I have spent the last few days with Google and have not found a solution for my question.

At my new position, I have been asked to modify a current React app. The short of it is that this app was built before my time and is old. The app does not permit for a dev build. And since it does not allow for a dev build our development team can not see the component layout, props, or state along with any other goodies provided by the React Dev Tools.

My question is how do I make my app work properly with the React Dev Tools?

Other details that may help:
Files are located in ABC/app/src/common
Normally here at my employer, this would translate into a URL of:
www.ABC.com/app/. Yet for some reason, this is not how things are set up.

Instead the app is served from a URL subdomain:
app.XYZ.com
Also, note that the URL www.XYZ.com is not a React app - (not sure this is relevant)

Basically the build scripts create the bundle and the .min files are moved from the ABC/app/src/common folder to app.XYZ/.

package.JSON:

```<code>  "name": "ABC-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.0-14",
    "@fortawesome/free-solid-svg-icons": "^5.1.0-11",
    "@fortawesome/react-fontawesome": "0.1.0-11",
    "ajv": "^6.0.0",
    "alertifyjs": "^1.11.2",
    "axios": "^0.18.0",
    "babel-polyfill": "^6.26.0",
    "connected-react-router": "^4.4.1",
    "dateformat": "^3.0.3",
    "deep-freeze": "0.0.1",
    "fast-deep-equal": "^2.0.1",
    "fuse.js": "^3.4.6",
    "history": "^4.7.2",
    "i": "^0.3.6",
    "moment": "^2.22.2",
    "node-sass-chokidar": "^1.3.3",
    "npm": "^6.2.0",
    "prop-types": "^15.6.2",
    "react": "^16.5.0",
    "react-collapse": "^4.0.3",
    "react-dom": "^16.4.1",
    "react-html-parser": "^2.0.2",
    "react-loading": "^2.0.3",
    "react-motion": "^0.5.2",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^4.0.8",
    "react-scripts": "^1.1.4",
    "react-select": "^2.0.0",
    "react-table-container": "^2.0.1",
    "react-topbar-progress-indicator": "^2.0.0",
    "react-transition-group": "^2.4.0",
    "react-virtualized": "^9.20.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start": "yarn run build-css && react-scripts build && yarn run move-js && yarn run move-css",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "commit": "react-scripts build && yarn run move-js && yarn run move-css",
    "move-js": "cp ./build/static/js/main.*.js ../../app.XYZ.com/assets/js/main.js",
    "move-css": "cp ./build/static/css/main.*.css ../../app.XYZ.com/assets/css/main.css"
  },
  "proxy": "http://dev-app.XYZ.com/",
  "devDependencies": {
    "eslint": "^5.7.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.1.2",
    "eslint-plugin-react": "^7.11.1",
    "redux-devtools": "^3.4.1",
    "redux-logger": "^3.0.6",
    "why-did-you-update": "^0.1.1"
  },
  "browserslist": {
    "development": [
      "last 2 chrome versions",
      "last 2 firefox versions",
      "last 2 edge versions"
    ],
    "production": [
      ">0.25%",
      "not op_mini all",
      "ie 11"
    ]
  }
}
</code>```

答:
After some investigation and thanks to @JonathanIrwin and @DrewReese, I noticed that with in package.json file, inside the scripts sub-object there is scripts.start. This overwrites the default start command. Thus when the command npm start or yarn run start is executed node is running scripts.start which reads:

```<code>"start": "yarn run build-css && react-scripts build && yarn run move-js && yarn run move-css",
</code>```

To fix this, adding a new script reading:

```<code>"dev-start": "react-scripts start",
</code>```

does the job. To execute this script anyone can run the command yarn run dev-start or npm dev-start from the terminal.

Body:
I am new to React apps so please excuse me if my question has an easy answer. I have spent the last few days with Google and have not found a solution for my question.

At my new position, I have been asked to modify a current React app. The short of it is that this app was built before my time and is old. The app does not permit for a dev build. And since it does not allow for a dev build our development team can not see the component layout, props, or state along with any other goodies provided by the React Dev Tools.

My question is how do I make my app work properly with the React Dev Tools?

Other details that may help:
Files are located in ABC/app/src/common
Normally here at my employer, this would translate into a URL of:
www.ABC.com/app/. Yet for some reason, this is not how things are set up.

Instead the app is served from a URL subdomain:
app.XYZ.com
Also, note that the URL www.XYZ.com is not a React app - (not sure this is relevant)

Basically the build scripts create the bundle and the .min files are moved from the ABC/app/src/common folder to app.XYZ/.

package.JSON:

  "name": "ABC-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.0-14",
    "@fortawesome/free-solid-svg-icons": "^5.1.0-11",
    "@fortawesome/react-fontawesome": "0.1.0-11",
    "ajv": "^6.0.0",
    "alertifyjs": "^1.11.2",
    "axios": "^0.18.0",
    "babel-polyfill": "^6.26.0",
    "connected-react-router": "^4.4.1",
    "dateformat": "^3.0.3",
    "deep-freeze": "0.0.1",
    "fast-deep-equal": "^2.0.1",
    "fuse.js": "^3.4.6",
    "history": "^4.7.2",
    "i": "^0.3.6",
    "moment": "^2.22.2",
    "node-sass-chokidar": "^1.3.3",
    "npm": "^6.2.0",
    "prop-types": "^15.6.2",
    "react": "^16.5.0",
    "react-collapse": "^4.0.3",
    "react-dom": "^16.4.1",
    "react-html-parser": "^2.0.2",
    "react-loading": "^2.0.3",
    "react-motion": "^0.5.2",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^4.0.8",
    "react-scripts": "^1.1.4",
    "react-select": "^2.0.0",
    "react-table-container": "^2.0.1",
    "react-topbar-progress-indicator": "^2.0.0",
    "react-transition-group": "^2.4.0",
    "react-virtualized": "^9.20.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "build-css": "node-sass-chokidar src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start": "yarn run build-css && react-scripts build && yarn run move-js && yarn run move-css",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "commit": "react-scripts build && yarn run move-js && yarn run move-css",
    "move-js": "cp ./build/static/js/main.*.js ../../app.XYZ.com/assets/js/main.js",
    "move-css": "cp ./build/static/css/main.*.css ../../app.XYZ.com/assets/css/main.css"
  },
  "proxy": "http://dev-app.XYZ.com/",
  "devDependencies": {
    "eslint": "^5.7.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.1.2",
    "eslint-plugin-react": "^7.11.1",
    "redux-devtools": "^3.4.1",
    "redux-logger": "^3.0.6",
    "why-did-you-update": "^0.1.1"
  },
  "browserslist": {
    "development": [
      "last 2 chrome versions",
      "last 2 firefox versions",
      "last 2 edge versions"
    ],
    "production": [
      ">0.25%",
      "not op_mini all",
      "ie 11"
    ]
  }
}

Body:
After some investigation and thanks to @JonathanIrwin and @DrewReese, I noticed that with in package.json file, inside the scripts sub-object there is scripts.start. This overwrites the default start command. Thus when the command npm start or yarn run start is executed node is running scripts.start which reads:

"start": "yarn run build-css && react-scripts build && yarn run move-js && yarn run move-css",

To fix this, adding a new script reading:

"dev-start": "react-scripts start",

does the job. To execute this script anyone can run the command yarn run dev-start or npm dev-start from the terminal.


问:
List comprehension where the condition depends on the list being generated
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)
```

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

答:
You cannot do it that way in a list comprehension as you cannot compare against the list lz that does not yet exist - assuming you are trying to avoid duplicates in the resulting list as in your example.

Instead, you can use the python set which will enforce only a single instance of each value:

lz = set(x for x in lx if x in ly)
```

<p>And if what you are really after is a set intersection (elements in common):</p>

<pre class="lang-py prettyprint-override"><code>lz = set(lx) & set(ly)
</code>```

UPDATE:
As pointed out by @Błotosmętek in the comments - using the set will not retain the order of the elements as the set is, by definition, unordered. If the order of the elements is significant a different strategy will be necessary.

Body:
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

Body:
You cannot do it that way in a list comprehension as you cannot compare against the list lz that does not yet exist - assuming you are trying to avoid duplicates in the resulting list as in your example.

Instead, you can use the python set which will enforce only a single instance of each value:

lz = set(x for x in lx if x in ly)

And if what you are really after is a set intersection (elements in common):

lz = set(lx) & set(ly)

UPDATE:
As pointed out by @Błotosmętek in the comments - using the set will not retain the order of the elements as the set is, by definition, unordered. If the order of the elements is significant a different strategy will be necessary.


问:
Webpack: Error: Can't resolve 'MyCustomPath/'
My webpack.config.js :

```<code>
module.exports = {
    entry: './app/components/App.js',
    resolve: {
        alias: {
          Base: './app/components/Base',
          Modules: './app/components/Modules',
          Screens: './app/components/Screens',
          Units: './app/components/Units'
        }
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
            },
        }
      ]
    }
  };
</code>```

In App.js i'm trying to import like this:

```<code>import NotifyModal from 'Modules/NotifyModal';
import Preloader from 'Base/Elements/Preloader';
</code>```

But i get the following error:

```<code>ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Base/Elements/Preloader' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 34:0-56 163:29-42

ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Modules/NotifyModal' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 51:0-46 124:29-36
</code>```

Tell me, please, what am I doing wrong? There are a lot of aliases in my application, but they do not work

答:
I haven't had much success using webpack's alias feature, it never worked for me. Instead, I use this babel plugin: babel-plugin-module-resolver.

To use it, you create a custom babel.config.js file like so:

```<code>module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver",
                {
                   // put your aliases here; I use a tilde (~) to represent
                   // that the folder is aliased, but you don't have to
                    alias: {
                        ~actions: "./src/actions",
                        ~components: "./src/components",
                        ~containers: "./src/containers",
                        ~pages: "./src/pages",
                        ~reducers: "./src/reducers",
                        ~root: "./src/root",
                        ~routes: "./src/routes",
                        ~sagas: "./src/sagas",
                        ~styles: "./src/styles",
                        ~types: "./src/types",
                        ~utils: "./src/utils",
                    },
                },
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};
</code>```

Then you can reference one of the aliased folders like so: import App from "~components/App" (assuming App is a folder that contains an index.js file).

However, as you can you see, the above approach is pretty repetitive, where you have to manually add aliases. So I created this function to traverse a specific folder and alias all the top-level folders within them:

```<code>const { readdirSync, statSync } = require("fs");
const { resolve } = require("path");

// read all directories within the path specified below
// and reduce (loop) through them
const readDirectory = path =>
    readdirSync(path).reduce((acc, folder) => {
        // combine the path with the current folder name
        // for example: "./src/components"
        const dirPath = `${path}${folder}`;

        // check that the directory (dirPath) exists
        if (statSync(resolve(dirPath)).isDirectory()) {
            // add the folder as an alias, for example:
            // "~components": "./src/components"
            // to the accumulator (an object)
            acc[`~${folder.replace(/[^\w\s]/gi, "")}`] = dirPath;
        }

        // return the accumulated object of directories
        return acc;
    }, {});

// read all top-level directories within "./src/"
const alias = readDirectory("./src/");

module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver",
                { alias } // apply aliased folder to module resolver options object
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};
</code>```

On a side note, I personally avoid aliasing top-level root folders (folders that sit outside of src); however, if you want to, then you can tweak the function above to include a list folders to read and ignore (because you don't want to alias node_modules or .git folders). Again, not recommended nor needed if you just alias within the src folder.

Body:
My webpack.config.js :

module.exports = {
    entry: './app/components/App.js',
    resolve: {
        alias: {
          Base: './app/components/Base',
          Modules: './app/components/Modules',
          Screens: './app/components/Screens',
          Units: './app/components/Units'
        }
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
            },
        }
      ]
    }
  };

In App.js i'm trying to import like this:

import NotifyModal from 'Modules/NotifyModal';
import Preloader from 'Base/Elements/Preloader';

But i get the following error:

ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Base/Elements/Preloader' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 34:0-56 163:29-42

ERROR in ./app/components/App.js
Module not found: Error: Can't resolve 'Modules/NotifyModal' in '/home/cpt/Desktop/development/app/components'
 @ ./app/components/App.js 51:0-46 124:29-36

Tell me, please, what am I doing wrong? There are a lot of aliases in my application, but they do not work

Body:
I haven't had much success using webpack's alias feature, it never worked for me. Instead, I use this babel plugin: babel-plugin-module-resolver.

To use it, you create a custom babel.config.js file like so:

module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver",
                {
                   // put your aliases here; I use a tilde (~) to represent
                   // that the folder is aliased, but you don't have to
                    alias: {
                        ~actions: "./src/actions",
                        ~components: "./src/components",
                        ~containers: "./src/containers",
                        ~pages: "./src/pages",
                        ~reducers: "./src/reducers",
                        ~root: "./src/root",
                        ~routes: "./src/routes",
                        ~sagas: "./src/sagas",
                        ~styles: "./src/styles",
                        ~types: "./src/types",
                        ~utils: "./src/utils",
                    },
                },
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};

Then you can reference one of the aliased folders like so: import App from "~components/App" (assuming App is a folder that contains an index.js file).

However, as you can you see, the above approach is pretty repetitive, where you have to manually add aliases. So I created this function to traverse a specific folder and alias all the top-level folders within them:

const { readdirSync, statSync } = require("fs");
const { resolve } = require("path");

// read all directories within the path specified below
// and reduce (loop) through them
const readDirectory = path =>
    readdirSync(path).reduce((acc, folder) => {
        // combine the path with the current folder name
        // for example: "./src/components"
        const dirPath = `${path}${folder}`;

        // check that the directory (dirPath) exists
        if (statSync(resolve(dirPath)).isDirectory()) {
            // add the folder as an alias, for example:
            // "~components": "./src/components"
            // to the accumulator (an object)
            acc[`~${folder.replace(/[^\w\s]/gi, "")}`] = dirPath;
        }

        // return the accumulated object of directories
        return acc;
    }, {});

// read all top-level directories within "./src/"
const alias = readDirectory("./src/");

module.exports = function(api) {
    api.cache(true);

    return {
        presets: [ "@babel/preset-env", "@babel/preset-react"],
        plugins: [
            [
                "module-resolver",
                { alias } // apply aliased folder to module resolver options object
            ],
            "@babel/plugin-transform-runtime",
            "@babel/plugin-syntax-dynamic-import",
            ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
    };
};

On a side note, I personally avoid aliasing top-level root folders (folders that sit outside of src); however, if you want to, then you can tweak the function above to include a list folders to read and ignore (because you don't want to alias node_modules or .git folders). Again, not recommended nor needed if you just alias within the src folder.


问:
rails render_to_string problem
I`m trying to test my controller with rspec and always get an error.

users_controller.rb:

```<code>def update
    @user.update_attributes!(params[:user])

    redirect_to @user, :status => 202, :text => render_to_string(:partial => "users/show", :type => "json", :locals => {:user => @user})
    #notice, that redirect_to was reinitialized and :text is a parameter for response_body
end
</code>```

_show.tokamak

```<code>user {
  id user.id
  email user.email
  username user.username
}
</code>```

spec file

```<code>it "should NOT update user username" do
      username = @user.username
      put 'update', :id => @user.id, :user => {:username => username+"abc"}, :format => :json
      response.status.should be(202)
      response.headers["Location"].length.should be > 0
      puts response.body
      @user.reload
      @user.username.should eq(username)
      end
    end
</code>```

So I get an error:

Failure/Error: put 'update', :id =>
  @user.id, :user => {:username =>
  username+"abc"}, :format => :json
       ActionView::Template::Error:
         You have a nil object when you didn't expect it!
         You might have expected an instance of Array.
         The error occurred while evaluating nil.[]
       # C:/Users/makaroni4/free_frog/ffapi/app/views/users/_show.tokamak:1:in
  _app_views_users__show_tokamak___509498818
  _32151168_368311673'
       # C:/Users/makaroni4/XXX/XXX/app/controllers/users_controller.rb:22:in
  update'
       # ./users_controller_spec.rb:34:in
  `block (4 levels) in '

So may be I call render_to_string method wrong?

答:
Try stubbing out find?

```<code>mock_user = User.stub(:find).with(@user.id) {@user}
</code>```

To be honest I'd go a few steps further and make sure you mock and stub most of the relevant behavior of the User object (or whatever class @user is). Keep in mind you're only testing that the controller action returns what you expect if you give it valid input--not that the model itself does the right thing.

I had a lot of difficulty wrapping my head around the differences in model vs. controller specs...

I hope this helps...if not, I apologize in advance...

EDIT:

I'll take this a step futher and suggest this test is actually a model test. The actual controller test would be something like as the way your spec test should behave:

```<code>it "should NOT update user with invalid input" do
  mock_user = mock_model(User, {}).as_null_object
  User.stub(:find).with("12") {mock_user}
  User.stub(:update_attributes).with({}).and_return(false)
  put 'update', :id => "12"

  # test that your output is correct, or even if the render target is what you expect.

end
</code>```

Title: rails render_to_string problem

Body:
I`m trying to test my controller with rspec and always get an error.

users_controller.rb:

def update
    @user.update_attributes!(params[:user])

    redirect_to @user, :status => 202, :text => render_to_string(:partial => "users/show", :type => "json", :locals => {:user => @user})
    #notice, that redirect_to was reinitialized and :text is a parameter for response_body
end

_show.tokamak

user {
  id user.id
  email user.email
  username user.username
}

spec file

it "should NOT update user username" do
      username = @user.username
      put 'update', :id => @user.id, :user => {:username => username+"abc"}, :format => :json
      response.status.should be(202)
      response.headers["Location"].length.should be > 0
      puts response.body
      @user.reload
      @user.username.should eq(username)
      end
    end

So I get an error:

Failure/Error: put 'update', :id =>
  @user.id, :user => {:username =>
  username+"abc"}, :format => :json
       ActionView::Template::Error:
         You have a nil object when you didn't expect it!
         You might have expected an instance of Array.
         The error occurred while evaluating nil.[]
       # C:/Users/makaroni4/free_frog/ffapi/app/views/users/_show.tokamak:1:in
  _app_views_users__show_tokamak___509498818
  _32151168_368311673'
       # C:/Users/makaroni4/XXX/XXX/app/controllers/users_controller.rb:22:in
  update'
       # ./users_controller_spec.rb:34:in
  `block (4 levels) in '

So may be I call render_to_string method wrong?

Body:
Try stubbing out find?

mock_user = User.stub(:find).with(@user.id) {@user}

To be honest I'd go a few steps further and make sure you mock and stub most of the relevant behavior of the User object (or whatever class @user is). Keep in mind you're only testing that the controller action returns what you expect if you give it valid input--not that the model itself does the right thing.

I had a lot of difficulty wrapping my head around the differences in model vs. controller specs...

I hope this helps...if not, I apologize in advance...

EDIT:

I'll take this a step futher and suggest this test is actually a model test. The actual controller test would be something like as the way your spec test should behave:

it "should NOT update user with invalid input" do
  mock_user = mock_model(User, {}).as_null_object
  User.stub(:find).with("12") {mock_user}
  User.stub(:update_attributes).with({}).and_return(false)
  put 'update', :id => "12"

  # test that your output is correct, or even if the render target is what you expect.

end


问:
Length of last frame with AVAssetWriter
I'm trying to create a video from frames of CGImages, it works great but I'm trying to have the last frame stay on screen longer, iI tried setting the end of video time with endSessionAtSourceTime: but it still ends too quickly. I ended up adding the last frame a second time which fixed it but it doesn't seem like the right solution.

答: Yeah, that's not what endSessionAtSourceTime is for. You either need to set the duration of that last frame's sample to something longer than every other sample, (which makes the recording variable-frame rate which some software does not like), or simply keep adding that last sample over and over again with the same single-frame duration until you reach the desired total amount of time.</p>

Title: Length of last frame with AVAssetWriter


问:
How to import a module at each execution of python?
I need to run the command import numpy as np each time I run python. How to automatize it in linux. In other words, how do load a module each time python is launch with having to manually call it?

答:
The -i flag can help with that. See man python.

```<code>       -i     When  a  script  is  passed as first argument or the -c option is
              used, enter interactive mode after executing the  script  or  the
              command.   It does not read the $PYTHONSTARTUP file.  This can be
              useful to inspect global variables or a stack trace when a script
              raises an exception.
</code>```

So the below does what you want it to. Note that the -i flag needs to precede the -c otherwise it doesn't work.

```<code> python -i -c 'import numpy'
</code>```

Body:
The -i flag can help with that. See man python.

       -i     When  a  script  is  passed as first argument or the -c option is
              used, enter interactive mode after executing the  script  or  the
              command.   It does not read the $PYTHONSTARTUP file.  This can be
              useful to inspect global variables or a stack trace when a script
              raises an exception.

So the below does what you want it to. Note that the -i flag needs to precede the -c otherwise it doesn't work.

 python -i -c 'import numpy'


问:
Visual Studio / msbuild CopyToOutputDirectory - how does it work?
I am using Visual Studio Community:

```<code>Microsoft Visual Studio Community 2019
Version 16.4.5
VisualStudio.16.Release/16.4.5+29806.167
Microsoft .NET Framework
Version 4.8.03752
</code>```

I have a very simple ASP.Net Core website / app project, with the following directory structure:

```<code>website
 /bin
 /www
     /about
     /images
</code>```

NOTE: The webroot directory is NOT wwwroot, but instead just www

The project file (.csproj) contains the following (to copy all sub-directories/files to the output directory):

```<code>   <ItemGroup>
      <Content Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
   </ItemGroup>
</code>```

Using Visual Studio (Config = Debug)

```<code>   BUILD -> Rebuild Solution
</code>```

Result:

```<code>/bin
    /Debug
          /netcoreapp3.0
                        /Properties
                        /runtimes
</code>```

(missing /www and all sub-directories and files!) - WHY???

The same results are obtained if I use msbuild.exe from the developer command prompt; makes no difference with regard to configuration (Debug vs Release).

I assumed that the www directory (and all sub-directories) and files would be copied to the output directory -- but clearly, this is not happening.  I do not understand why the CopyToOutputDirectory is being ignored; I am missing something, but a search of the documentation did not yield any answers.

Any ideas / advice would be appreciated.

Thanks in advance.

答:
Update:

Just changed the following in the project (.csproj) file:

```<code>   <ItemGroup>
      <Content Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
   </ItemGroup>
</code>```

To:

```<code>   <ItemGroup>
      <None Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </None>
   </ItemGroup>
</code>```

Using Visual Studio: BUILD -> Rebuild Solution (success)

Also tried with msbuild.exe (success)

Now the www directory and all sub-directories / files are present in the output -- why? I suspect because I am not using the default "wwwroot" as the content directory, using <Content> does not work whereas <None> does; but that is only a theory; all I know is it works.

Also found this SO link useful in describing the differences between <Content> and <None>, for those who are curious:

What are the various "Build action" settings in Visual Studio project properties and what do they do?

Body:
I am using Visual Studio Community:

Microsoft Visual Studio Community 2019
Version 16.4.5
VisualStudio.16.Release/16.4.5+29806.167
Microsoft .NET Framework
Version 4.8.03752

I have a very simple ASP.Net Core website / app project, with the following directory structure:

website
 /bin
 /www
     /about
     /images

NOTE: The webroot directory is NOT wwwroot, but instead just www

The project file (.csproj) contains the following (to copy all sub-directories/files to the output directory):

   <ItemGroup>
      <Content Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
   </ItemGroup>

Using Visual Studio (Config = Debug)

   BUILD -> Rebuild Solution

Result:

/bin
    /Debug
          /netcoreapp3.0
                        /Properties
                        /runtimes

(missing /www and all sub-directories and files!) - WHY???

The same results are obtained if I use msbuild.exe from the developer command prompt; makes no difference with regard to configuration (Debug vs Release).

I assumed that the www directory (and all sub-directories) and files would be copied to the output directory -- but clearly, this is not happening.  I do not understand why the CopyToOutputDirectory is being ignored; I am missing something, but a search of the documentation did not yield any answers.

Any ideas / advice would be appreciated.

Thanks in advance.

Body:
Update:

Just changed the following in the project (.csproj) file:

   <ItemGroup>
      <Content Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
   </ItemGroup>

To:

   <ItemGroup>
      <None Update="www\**\*">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </None>
   </ItemGroup>

Using Visual Studio: BUILD -> Rebuild Solution (success)

Also tried with msbuild.exe (success)

Now the www directory and all sub-directories / files are present in the output -- why? I suspect because I am not using the default "wwwroot" as the content directory, using <Content> does not work whereas <None> does; but that is only a theory; all I know is it works.

Also found this SO link useful in describing the differences between <Content> and <None>, for those who are curious:

What are the various "Build action" settings in Visual Studio project properties and what do they do?


问:
Mysql, insert if not duplicate else replace - for an entire table
I have two tables, t1 and t2, I'd like to update t1 with the content of t2 on the condition that if t1 and t2 share the same unique key on a given row, then t2 is used and overwrites the t1 row, otherwise we add the non-duplicate t2 rows to t1.

So in short add columns from t2 to t1 when not duplicate, else, overwrite t1 with t2 duplicate rows.

I know MySQL has multiple approaches to doing this, but none appear to achieve merging over the entire table without having to explicitly list all columns to be replaced.

Both t1 and t2 have a lot of columns in my schema, so I'd rather not list them all out.

The approach I would adopt if I didn't have as many columns is as follows:

```<code>INSERT INTO t1(a, b, c)
SELECT d, e, f FROM t2
ON DUPLICATE KEY UPDATE b = t2.e, c = t2.f;
</code>```

Fine for 3 columns, but I have 18 of them!

Adapting the above to achieve a more general solution which doesn't require me to be explicit as to which columns to apply the changes to is my objective.

I have got as far as:

```<code>insert into t1
select * from t2
ON DUPLICATE KEY UPDATE
    t1.b = t2.b,
    t1.c = t2.c;
</code>```

But as seen above, I am still required to be explicit as to which columns to update when duplicates are found using the UPDATE keyword.

I'm sure there is an obvious way to avoid the issue of explicitly defining the columns to replace, but MySQL isn't my strongest language to say the least, so I'd appreciate an expert telling me how to solve this.

Update

I am forced to using MySQL 5.

答:
It seems you need simple REPLACE statement:

```<code>REPLACE INTO t1
TABLE t2
</code>```

Of course, the tables must have the same structure (including field names, types, order...).

If not, or if you use MySQL version more ancient then 8, then use REPLACE..SELECT:

```<code>REPLACE INTO t1(a, b, c)
SELECT d, e, f FROM t2
</code>```

Body:
I have two tables, t1 and t2, I'd like to update t1 with the content of t2 on the condition that if t1 and t2 share the same unique key on a given row, then t2 is used and overwrites the t1 row, otherwise we add the non-duplicate t2 rows to t1.

So in short add columns from t2 to t1 when not duplicate, else, overwrite t1 with t2 duplicate rows.

I know MySQL has multiple approaches to doing this, but none appear to achieve merging over the entire table without having to explicitly list all columns to be replaced.

Both t1 and t2 have a lot of columns in my schema, so I'd rather not list them all out.

The approach I would adopt if I didn't have as many columns is as follows:

INSERT INTO t1(a, b, c)
SELECT d, e, f FROM t2
ON DUPLICATE KEY UPDATE b = t2.e, c = t2.f;

Fine for 3 columns, but I have 18 of them!

Adapting the above to achieve a more general solution which doesn't require me to be explicit as to which columns to apply the changes to is my objective.

I have got as far as:

insert into t1
select * from t2
ON DUPLICATE KEY UPDATE
    t1.b = t2.b,
    t1.c = t2.c;

But as seen above, I am still required to be explicit as to which columns to update when duplicates are found using the UPDATE keyword.

I'm sure there is an obvious way to avoid the issue of explicitly defining the columns to replace, but MySQL isn't my strongest language to say the least, so I'd appreciate an expert telling me how to solve this.

Update

I am forced to using MySQL 5.

Body:
It seems you need simple REPLACE statement:

REPLACE INTO t1
TABLE t2

Of course, the tables must have the same structure (including field names, types, order...).

If not, or if you use MySQL version more ancient then 8, then use REPLACE..SELECT:

REPLACE INTO t1(a, b, c)
SELECT d, e, f FROM t2


问:
Is there a way to disable any use of cookies for my website?
I am trying to improve the security on a web application created in react.

I am completely sure that functionality wise there are no cookies used, but I keep on getting cookies when I go to the page. When I check Application tab in developer's tool I can see that my website is putting a cookie there.

Is there a general way to prevent my app from using/storing any cookies at all?

Disclaimer: There are no references to setting cookies in the project.

答: You can listen to any cookie related event with cookies.onChanged, so you can clear any cookie created</p>


问:
get previous row id using stored procedure
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

```<code>select * from table b where ID = 4
</code>```

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.

答:
The following query should get it for you:

```<code>select max(ID) from YourTable where ID < @YourID
</code>```

@YourID is a variable containing your recently inserted ID

Body:
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

select * from table b where ID = 4

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.

Body:
The following query should get it for you:

select max(ID) from YourTable where ID < @YourID

@YourID is a variable containing your recently inserted ID