问:
Derived typenames
I have plenty of different functions, which does quite similar operations, where the type and the size is encoded through the function names like the following:

```<code>int * operation_0_0_i( int a ) {
   int * result = new int[4];
   /* ... */
   return result;
}
int * operation_0_1_i( int a ) {
   int * result = new int[8];
   /* ... */
   return result;
}

float * operation_0_0_f( float a ) {
   float * result = new float[4];
   /* ... */
   return result;
}

float * operation_0_1_f( float a )  {
   float * result = new float[4];
   /* ... */
   return result;
}
</code>```

Instead of having this confusingly amount of different functions I thought about using templates. My first try where templated structs, to realize derived type:

```<code>template< typename T >
struct A {
  using type = T;
  using array = std::array< T, 4 >;
};

template< typename T >
struct B {
   using type = T;
   using array = std::array< T, 8 >;
};
</code>```

So that I can do something like that:

```<code>template< class U, typename T >
T* operation0( T a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();   // I know, that this is unsafe. Its just for this example
}

template< class U, typename T >
T* operation1( T a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();
}

int main() {
   int * res1 = operation1<A, int>( 3 );
   int * res2 = operation2<B, int>( 8 );
   /* ... */
   return 0;
}
</code>```

Unfortunately this does not compile. The g++ tells me that

```<code>In function ‘T* operation0(T)’: error: expected nested-name-specifier before ‘U’ typename U<T>::array a;
</code>```

Obviously the typename specifier is wrong at this position. But if I delete that specifier, g++ complains that

```<code>‘U’ is not a template U<T>::array a;
</code>```

Does anyone knows, what I am doing wrong? And is there maybe an even better approach, maybe by using std::variant? Thanks for your time ;)

Sincerely

答:
you need to tell that your U class is template and take 1 parameter:</p>

```<code>template<template <class > class U, typename T >
T* operation0( T _a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();
}
</code>```

Title: Derived typenames

Body:
I have plenty of different functions, which does quite similar operations, where the type and the size is encoded through the function names like the following:

int * operation_0_0_i( int a ) {
   int * result = new int[4];
   /* ... */
   return result;
}
int * operation_0_1_i( int a ) {
   int * result = new int[8];
   /* ... */
   return result;
}

float * operation_0_0_f( float a ) {
   float * result = new float[4];
   /* ... */
   return result;
}

float * operation_0_1_f( float a )  {
   float * result = new float[4];
   /* ... */
   return result;
}

Instead of having this confusingly amount of different functions I thought about using templates. My first try where templated structs, to realize derived type:

template< typename T >
struct A {
  using type = T;
  using array = std::array< T, 4 >;
};

template< typename T >
struct B {
   using type = T;
   using array = std::array< T, 8 >;
};

So that I can do something like that:

template< class U, typename T >
T* operation0( T a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();   // I know, that this is unsafe. Its just for this example
}

template< class U, typename T >
T* operation1( T a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();
}

int main() {
   int * res1 = operation1( 3 );
   int * res2 = operation2( 8 );
   /* ... */
   return 0;
}

Unfortunately this does not compile. The g++ tells me that

In function ‘T* operation0(T)’: error: expected nested-name-specifier before ‘U’ typename U<T>::array a;

Obviously the typename specifier is wrong at this position. But if I delete that specifier, g++ complains that

‘U’ is not a template U<T>::array a;

Does anyone knows, what I am doing wrong? And is there maybe an even better approach, maybe by using std::variant? Thanks for your time ;)

Sincerely

Body:
you need to tell that your U class is template and take 1 parameter:

template<template <class > class U, typename T >
T* operation0( T _a ) {
  typename U<T>::array a;
  /* ... */
  return a.data();
}


来源: stackexchange

问:
How to make a layout fit for any Desktop screen? Website HTML CSS
This is my design:

```<code><style>
body {
  background: linear-gradient(rgba(0,0,0, .5), rgba(0,0,0,.5)), url('https://www.gamewallpapers.com/wallpapers_slechte_compressie/wallpaper_rune
scape_02_1920x1080.jpg') no-repeat;
  background-attachment: fixed;
  background-position: center center;
  background-size: cover;
  margin: 0;
}
/* IE 6 */
* html #footer {
   position:absolute;
   top:expression((0-(footer.offsetHeight)+
(document.documentElement.clientHeight ? document.documentElement.clientHeight :
document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ?
document.documentElement.scrollTop : document.body.scrollTop))+'px');
}

.nav {
  background: rgba(0,0,0,0.6);
  height: 10%;
  width: 100%;
  position: fixed;
}
.footer {
  background: rgba(0,0,0,0.6);
  position:fixed;
  left:0px;
  bottom:0px;
  height:5%;
  width:100%;
}
.side-bar {
  position: fixed;
  width: 200px;
  height: 85%;
  background: #000;
  margin-bottom: 2%; margin-top: 4.7%;
}
</style>

<html>
<head>
<title>RuneStake</title>
</head>
<body>
<div class="nav">
</div>

<div class="side-bar">
</div>

<div class="footer">
</div>
</body>
</html>
</code>```

This design works on my browser but it starts going out of proportion on other desktops/browsers. How do I fix this so all the lengths work with all desktops/browsers?

It currently appears like this : www.runestake.x10.bz/home.php

Thanks

答:
You could use top: 10% instead of margin-top: 4.7%. If you use margin as a percentage, it will be calculated from the height of the element itself, not its parent (margin-top: 4.7% would be 4.7% of 85% of the body height, where top: 10% would be 10% of the body height).

```<code>.side-bar {
  position: fixed;
  top: 10%;
  width: 200px;
  height: 85%;
  background: #000;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my design:

<title>RuneStake</title>

This design works on my browser but it starts going out of proportion on other desktops/browsers. How do I fix this so all the lengths work with all desktops/browsers?

It currently appears like this : www.runestake.x10.bz/home.php

Thanks

Body:
You could use top: 10% instead of margin-top: 4.7%. If you use margin as a percentage, it will be calculated from the height of the element itself, not its parent (margin-top: 4.7% would be 4.7% of 85% of the body height, where top: 10% would be 10% of the body height).

.side-bar {
  position: fixed;
  top: 10%;
  width: 200px;
  height: 85%;
  background: #000;
}


问:
How to address "Packages cannot be nested" error
I'm having a problem with Flex 4 beta 2...

I can't call a class using: <fx:Script source:"myClass"/>

For some reason, no matter what I do, the error is always the same:

Packages cannot be nested

I found links to help.adobe.com, but they were all broken links.

So, is this a Flex bug or there is a new way to use external classes in Flash Builder 4?

答:
Thanks NSP!

I removed the package and class declarations from my .as file (along with the scope brackets '{' and '}).

I used the '=' symbol as the assignment operator (as you suggested).

E.G.:

```<code><fx:Script source="Greeter.as">
</code>```

That did the trick.

Body:
Thanks NSP!

I removed the package and class declarations from my .as file (along with the scope brackets '{' and '}).

I used the '=' symbol as the assignment operator (as you suggested).

E.G.:

<fx:Script source="Greeter.as">

That did the trick.


问:
How to convert a list of characters to ASCII in python?
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

```<code>string = input(“Enter a line of text: “)
l = list(string)
return(l)
</code>```

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

答:
You might use a list comprehension, like so:

```<code>string = input(“Enter a line of text: “)
list_of_characters = list(string)
list_of_ord_values = [ord(character) for character in list_of_characters]
</code>```

Note that, since strings are iterable, you can skip the intermediate step:

```<code>list_of_ord_values = [ord(character) for character in string]
</code>```

Body:
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

string = input(“Enter a line of text: “)
l = list(string)
return(l)

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

Body:
You might use a list comprehension, like so:

string = input(“Enter a line of text: “)
list_of_characters = list(string)
list_of_ord_values = [ord(character) for character in list_of_characters]

Note that, since strings are iterable, you can skip the intermediate step:

list_of_ord_values = [ord(character) for character in string]


问:
Persist Nested Entity Spring Rest Data
I have a User Class

```<code>@Entity(name = "users")
@Table(name = "users")
public class User implements UserDetails {

static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", nullable = false)
private Long id;

@Column(name = "username", nullable = false, unique = true)
private String username;

@Column(name = "password", nullable = false)
private String password;
}
</code>```

Tied to a simple Repository

```<code>public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
</code>```

And I have an Instructor Class that has a nested User object

```<code>@Entity
@Table(name = "instructors")
public class Instructor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "instructor_id", nullable = false, updatable = false)
private Long id;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "course_id")
private List<Course> courses;
</code>```

}

It is saved with the following repository

```<code>public interface InstructorRepository extends PagingAndSortingRepository<Instructor, Long> {
</code>```

}

The JSON I am posting

```<code>{
"user": {
    "id": 1
}
}
</code>```

When I try to do a POST to /instructors . User is coming in null.  Is there something I am missing to get JPA to tie the two together?  I have tried adding CascadeType.ALL onto the field and that only throws a detached persist exception.

答:
Leave the CascadeType.ALL to Instructor like you already tried:

```<code>@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
</code>```

In addition add the following to User. Seems to work with me. It provides the mapping information and makes JPA treat User managed

```<code>@OneToMany(mappedBy="user")//, cascade=CascadeType.ALL)
private List<Instructor> instructors = new ArrayList<>();
</code>```

I have commented out the cascadeType in the above  but it might be useful if you want to persist User wit all of its Instructors.

Title: Persist Nested Entity Spring Rest Data

Body:
I have a User Class

@Entity(name = "users")
@Table(name = "users")
public class User implements UserDetails {

static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", nullable = false)
private Long id;

@Column(name = "username", nullable = false, unique = true)
private String username;

@Column(name = "password", nullable = false)
private String password;
}

Tied to a simple Repository

public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}

And I have an Instructor Class that has a nested User object

@Entity
@Table(name = "instructors")
public class Instructor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "instructor_id", nullable = false, updatable = false)
private Long id;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "course_id")
private List<Course> courses;

}

It is saved with the following repository

public interface InstructorRepository extends PagingAndSortingRepository<Instructor, Long> {

}

The JSON I am posting

{
"user": {
    "id": 1
}
}

When I try to do a POST to /instructors . User is coming in null.  Is there something I am missing to get JPA to tie the two together?  I have tried adding CascadeType.ALL onto the field and that only throws a detached persist exception.

Body:
Leave the CascadeType.ALL to Instructor like you already tried:

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;

In addition add the following to User. Seems to work with me. It provides the mapping information and makes JPA treat User managed

@OneToMany(mappedBy="user")//, cascade=CascadeType.ALL)
private List<Instructor> instructors = new ArrayList<>();

I have commented out the cascadeType in the above  but it might be useful if you want to persist User wit all of its Instructors.


问:
QGraphicsView RubberBandDrag leaves artifacts
I have a QGraphicsView and a QGraphicsScene set up without any properties changed but

```<code>view->setDragMode(QGraphicsView::RubberBandDrag);
view->setRenderHint(QPainter::Antialiasing, true);
</code>```

When dragging arround for a bit the RubberBandDrag leaves artifacts and the RubberBand itself is often rendered incorrectly, missing the sides:

Also other graphics items such as a regular QGraphicsRectItem leave these traces. I tried without the antialias but that seems to make it even worse.

Do I have to set specific properties of the view/scene such as disabling optimization flags?

Or is this just a bug of Qt? (I am using 5.9.2)
At least I couldn't find a report of this.

答:
I had similar problem. After I play around these two calls, things got fixed.</p>

```<code>QGraphicsView.setCacheMode(QGraphicsView::CacheBackground);

QGraphicsView.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
</code>```

Body:
I have a QGraphicsView and a QGraphicsScene set up without any properties changed but

view->setDragMode(QGraphicsView::RubberBandDrag);
view->setRenderHint(QPainter::Antialiasing, true);

When dragging arround for a bit the RubberBandDrag leaves artifacts and the RubberBand itself is often rendered incorrectly, missing the sides:

Also other graphics items such as a regular QGraphicsRectItem leave these traces. I tried without the antialias but that seems to make it even worse.

Do I have to set specific properties of the view/scene such as disabling optimization flags?

Or is this just a bug of Qt? (I am using 5.9.2)
At least I couldn't find a report of this.

Body:
I had similar problem. After I play around these two calls, things got fixed.

QGraphicsView.setCacheMode(QGraphicsView::CacheBackground);

QGraphicsView.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);


问:
A program that prints even and odd characters from a string
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

```<code>#include <stdio.h>
#include <string.h>

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}
</code>```

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

答:
this declaration is wrong:

```<code>char *str[41];
</code>```

you're declaring 41 uninitialized strings. You want:

```<code>char str[41];
</code>```

then, scanf("%40s" , str);, no & and limit the input size (safety)

then the loop (where your while (str[i]<41) is wrong, it probably ends at once since letters start at 65 (ascii code for "A"). You wanted to test i against 41 but test str[i] against \0 instead, else you get all the garbage after nul-termination char in one of odd or even strings if the string is not exactly 40 bytes long)

```<code>while (str[i]) {
    if (i % 2 == 0) {
        odd[j++] = str[i];
    } else {
        even[k++] = str[i];
    }
    i++;
}
</code>```

if you want to use a pointer (assignement requirement), just define str as before:

```<code>char str[41];
</code>```

scan the input value on it as indicated above, then point on it:

```<code>char *p = str;
</code>```

And now that you defined a pointer on a buffer, if you're required to use deference instead of index access you can do:

```<code>while (*p) { // test end of string termination
    if (i % 2 == 0) {  // if ((p-str) % 2 == 0) { would allow to get rid of i
        odd[j++] = *p;
    } else {
        even[k++] = *p;
    }
    p++;
    i++;
}
</code>```

(we have to increase i for the even/odd test, or we would have to test p-str evenness)

aaaand last classical mistake (thanks to last-minute comments), even & odd aren't null terminated so the risk of getting garbage at the end when printing them, you need:

```<code>even[k] = odd[j] = '\0';
</code>```

(as another answer states, check the concept of even & odd, the expected result may be the other way round)

Body:
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

#include <stdio.h>
#include <string.h>

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

Body:
this declaration is wrong:

char *str[41];

you're declaring 41 uninitialized strings. You want:

char str[41];

then, scanf("%40s" , str);, no & and limit the input size (safety)

then the loop (where your while (str[i]<41) is wrong, it probably ends at once since letters start at 65 (ascii code for "A"). You wanted to test i against 41 but test str[i] against \0 instead, else you get all the garbage after nul-termination char in one of odd or even strings if the string is not exactly 40 bytes long)

while (str[i]) {
    if (i % 2 == 0) {
        odd[j++] = str[i];
    } else {
        even[k++] = str[i];
    }
    i++;
}

if you want to use a pointer (assignement requirement), just define str as before:

char str[41];

scan the input value on it as indicated above, then point on it:

char *p = str;

And now that you defined a pointer on a buffer, if you're required to use deference instead of index access you can do:

while (*p) { // test end of string termination
    if (i % 2 == 0) {  // if ((p-str) % 2 == 0) { would allow to get rid of i
        odd[j++] = *p;
    } else {
        even[k++] = *p;
    }
    p++;
    i++;
}

(we have to increase i for the even/odd test, or we would have to test p-str evenness)

aaaand last classical mistake (thanks to last-minute comments), even & odd aren't null terminated so the risk of getting garbage at the end when printing them, you need:

even[k] = odd[j] = '\0';

(as another answer states, check the concept of even & odd, the expected result may be the other way round)


问:
how do you organize your programming work
I'm a newbie in the field, but in the near future I have to develop an application for a friend(I've already did some work of the app and the friend is happy).

I assume that I need 3 places to store my work, but I'm not sure if this is the best approach. I need your advice, opinion, link,book, blog about this subject.

I plan to have:

a place where I develop the application

a place where I keep a back-up of the application

a place with the application ready for use

I'll use git in the development stage, but for the later I don't know what tools to use, or which are the good practices. Can you give me an advice?

PS: at this moment I'm using cakephp to build some webapps, but I play with C++ from time to time too.

答:
I have found a minimal set of code is development and release.  Some sort of version control is essential.  I use HEAD for development, and branch on release.  Backup your repository, or at very least have it on a different disk from the one(s) used for development and building.

I prefer to have three sets of code: development, testing, and release.  Each should have an automated build environment.  These are build environments.  For development, only a single set is needed.

Release code is used for changes to released code that are applied prior to the next release. Any changes done here are either merged back to development. or redeveloped (in case of a quick fix).

Testing code is release for testing. This provides a relatively stable environment for testers. Builds are usually tagged, but not branched.  The tag is used as the base for the release branch.

Development should build automatically at least daily.  This ensures the code can build outside the development environment.

You can use GIT for development and production, but the workflow is different than you would have with CVS or subversion.  Look at the ProGIT online book to understand the flow.

Avoid coding in the environment to the application.  Any environment dependencies should come from the configuration of the environment.  It is nice to display some indication of the build and environment in the interface.

ContentLicense: CC BY-SA 2.5


问:
rxjs - delay function return until a stream value meets a condition and is unsubscribed
I have a method that is triggering a server request. It has access to a stream from the redux-store and should execute a callback as soon as the result of the request is found in the mentioned stream. So basically:

```<code>private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    store.dispatchHttpRequest(args);
    // this should only be executed when resultStream$ emits true
    callback();
}
</code>```

How do I make callback(); to be called only when resultStream$ emits true AND I have unsubscribed from the stream, so there is no memory leak?

I have tried takeWhile(), putting the dispatchHttpRequest the setter of a conditional (for takeWhile) and the callback itself in the subscription() but it seems I am doing something wrong because I get bugs in my app. To be precise, the callback is only executed when doFetch() is called more than once, so the first request receives no callback-response.

答:
try this: </p>

```<code>private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    this.resultStream$.filter(r => r).take(1).subscribe(e => callback());

    store.dispatchHttpRequest(args);
}
</code>```

Body:
I have a method that is triggering a server request. It has access to a stream from the redux-store and should execute a callback as soon as the result of the request is found in the mentioned stream. So basically:

private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    store.dispatchHttpRequest(args);
    // this should only be executed when resultStream$ emits true
    callback();
}

How do I make callback(); to be called only when resultStream$ emits true AND I have unsubscribed from the stream, so there is no memory leak?

I have tried takeWhile(), putting the dispatchHttpRequest the setter of a conditional (for takeWhile) and the callback itself in the subscription() but it seems I am doing something wrong because I get bugs in my app. To be precise, the callback is only executed when doFetch() is called more than once, so the first request receives no callback-response.

Body:
try this:

private resultStream$: Observable<boolean>;
doFetch(args, callback) {
    this.resultStream$.filter(r => r).take(1).subscribe(e => callback());

    store.dispatchHttpRequest(args);
}


问:
boxPoints returns a negative y value
I'm trying to draw the minimum box outline on a simple image.

Original Image

However, one of the points returned from the boxPoints() function gives me a negative y value. When drawing this contour, this corner is drawn off the image.

Resulting Outline

I'm not sure why it returns a negative y value. I am using a binary version of the image, so the largest contour should be the outline of the postIt note. One of the other corners is not picked up correctly either. Not too sure how to go about fixing this. See code below:

```<code>def contours(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    gray = cv2.dilate(gray, None)  # fill some holes
    gray = cv2.dilate(gray, None)
    gray = cv2.erode(gray, None)  # dilate made our shape larger, revert that
    gray = cv2.erode(gray, None)

    # first threshold the image to create a binary image of black and white
    ret, thresh = cv2.threshold(gray, 127, 255, 0)

    # contours output var is a list of each coordinate in the contour
    # use CHAIN_APPROX_SIMPLE to pick only necessary contour points rather than all points on the contour
    img,cnt,hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # get the min area rect
    rect = cv2.minAreaRect(cnt[0])
    print(rect)
    box = cv2.boxPoints(rect)
    print(box)
    # convert all coordinates floating point values to int
    box = np.int32(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255))
    cv2.imshow('Corners1', image)
    cv2.waitKey(0)
</code>```

The printed minAreaRect and boxPoints are the following:

```<code>((182.83834838867188, 139.0049591064453), (208.65762329101562, 247.1478271484375), -31.165145874023438)
[[ 157.5166626   298.73544312]
 [  29.61603546   87.25617981]
 [ 208.16003418  -20.7255249 ]
 [ 336.06066895  190.7537384 ]]
</code>```

答: It looks like you are using a box function in this library. You can see, on the resulting image, all the angles are 90 degrees, so what you need to do is make a polygon not a rectangle. The negative y-value is a result of this right-angled box.</p>

Title: boxPoints returns a negative y value

Body:
I'm trying to draw the minimum box outline on a simple image.

Original Image

However, one of the points returned from the boxPoints() function gives me a negative y value. When drawing this contour, this corner is drawn off the image.

Resulting Outline

I'm not sure why it returns a negative y value. I am using a binary version of the image, so the largest contour should be the outline of the postIt note. One of the other corners is not picked up correctly either. Not too sure how to go about fixing this. See code below:

def contours(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    gray = cv2.dilate(gray, None)  # fill some holes
    gray = cv2.dilate(gray, None)
    gray = cv2.erode(gray, None)  # dilate made our shape larger, revert that
    gray = cv2.erode(gray, None)

    # first threshold the image to create a binary image of black and white
    ret, thresh = cv2.threshold(gray, 127, 255, 0)

    # contours output var is a list of each coordinate in the contour
    # use CHAIN_APPROX_SIMPLE to pick only necessary contour points rather than all points on the contour
    img,cnt,hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # get the min area rect
    rect = cv2.minAreaRect(cnt[0])
    print(rect)
    box = cv2.boxPoints(rect)
    print(box)
    # convert all coordinates floating point values to int
    box = np.int32(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255))
    cv2.imshow('Corners1', image)
    cv2.waitKey(0)

The printed minAreaRect and boxPoints are the following:

((182.83834838867188, 139.0049591064453), (208.65762329101562, 247.1478271484375), -31.165145874023438)
[[ 157.5166626   298.73544312]
 [  29.61603546   87.25617981]
 [ 208.16003418  -20.7255249 ]
 [ 336.06066895  190.7537384 ]]


问:
Matplotlib basemap: zoom into orthographic projection
I'm trying to plot an area in orthographic projection in order to layer it together with an image from satellite like this one

So I've tried to zoom into an orthographic projection like here

Using this code:

```<code>fig = plt.figure(figsize = (5,5))

map = Basemap(projection = 'ortho', lon_0 = 15, lat_0 = 68,\
               resolution = 'c')

lllon = 7
urlon = 21
lllat = 67
urlat = 70

xmin, ymin = map(lllon, lllat)
xmax, ymax = map(urlon, urlat)

ax = plt.gca()

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

map.drawcoastlines(linewidth = .1)
map.drawmeridians(np.arange(-180,180,1), linewidth = .01)
map.drawparallels(np.arange(-80,80,.25), linewidth = .01)
</code>```

and some more to plot lines, but that results in an image that is correct in center and proportion but not cropped to the area specified, like this:

Does anyone have an idea how to solve this?

答:
The code from the question produces a full orthographic projection as seen in the example.

The orthographic projection displays the earth as a satellite (in an orbit infinitely high above the earth) would see it.

In order to show only part of it, you can supply the edges of the map to the Basemap call.

Unfortunately, you cannot use the lat/lon values for this, but instead need to use the x,y values.

The following would hence work:

```<code>from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize = (5,5))

m = Basemap(projection = 'ortho', lon_0 = 0, lat_0 = 10,
            llcrnrx=-3000000, llcrnry=1000000, urcrnrx=3000000, urcrnry=6000000,
            resolution = 'c')

m.drawcoastlines(linewidth = 1)
m.drawcountries()

plt.show()
</code>```

A different option is shown in this thread which is to set axes limits after the map is drawn.

```<code>from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize = (5,5))

map = Basemap(projection = 'ortho', lon_0 = 15, lat_0 = 68,\
               resolution = 'l')

map.drawcoastlines(linewidth = 1)
map.drawmeridians(np.arange(-180,180,1), linewidth = 1)
map.drawparallels(np.arange(-80,80,.25), linewidth = 1)

lllon = 7
urlon = 21
lllat = 67
urlat = 70

xmin, ymin = map(lllon, lllat)
xmax, ymax = map(urlon, urlat)

ax = plt.gca()

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

plt.show()
</code>```

Body:
I'm trying to plot an area in orthographic projection in order to layer it together with an image from satellite like this one

So I've tried to zoom into an orthographic projection like here

Using this code:

fig = plt.figure(figsize = (5,5))

map = Basemap(projection = 'ortho', lon_0 = 15, lat_0 = 68,\
               resolution = 'c')

lllon = 7
urlon = 21
lllat = 67
urlat = 70

xmin, ymin = map(lllon, lllat)
xmax, ymax = map(urlon, urlat)

ax = plt.gca()

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

map.drawcoastlines(linewidth = .1)
map.drawmeridians(np.arange(-180,180,1), linewidth = .01)
map.drawparallels(np.arange(-80,80,.25), linewidth = .01)

and some more to plot lines, but that results in an image that is correct in center and proportion but not cropped to the area specified, like this:

Does anyone have an idea how to solve this?

Body:
The code from the question produces a full orthographic projection as seen in the example.

The orthographic projection displays the earth as a satellite (in an orbit infinitely high above the earth) would see it.

In order to show only part of it, you can supply the edges of the map to the Basemap call.

Unfortunately, you cannot use the lat/lon values for this, but instead need to use the x,y values.

The following would hence work:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize = (5,5))

m = Basemap(projection = 'ortho', lon_0 = 0, lat_0 = 10,
            llcrnrx=-3000000, llcrnry=1000000, urcrnrx=3000000, urcrnry=6000000,
            resolution = 'c')

m.drawcoastlines(linewidth = 1)
m.drawcountries()

plt.show()

A different option is shown in this thread which is to set axes limits after the map is drawn.

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

fig = plt.figure(figsize = (5,5))

map = Basemap(projection = 'ortho', lon_0 = 15, lat_0 = 68,\
               resolution = 'l')

map.drawcoastlines(linewidth = 1)
map.drawmeridians(np.arange(-180,180,1), linewidth = 1)
map.drawparallels(np.arange(-80,80,.25), linewidth = 1)

lllon = 7
urlon = 21
lllat = 67
urlat = 70

xmin, ymin = map(lllon, lllat)
xmax, ymax = map(urlon, urlat)

ax = plt.gca()

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

plt.show()


问:
separating single authentication file into multiple files in react , now no display of login button
Learning from react router authentication example,  I have split the single file code into separate files but now never seeing the login page.
 even no text for protected page

On landing page, there are 3 links

 - Home

 - Public

 - Protected

but when I click on Protected Link URL changes to /login but bot displaying any text or login button like in the example

instead getting an error in console

login Failed to load resource: the server responded with a status of 404 (Not Found).  ... login

here is the relevant code

PrivateRoute.js

```<code>  import React from 'react'

  import { Route, Redirect } from 'react-router-dom'

  import { fakeAuth } from './fakeAuth'

  export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      fakeAuth.isAuthenticated ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }}/>
      )
    )}/>
  )
</code>```

fakeAuth.js

```<code>    export const fakeAuth = {
      isAuthenticated: false,
      authenticate(cb) {
        console.log('is authenticated');
        this.isAuthenticated = true
        setTimeout(cb, 100) // fake async
      },
      signout(cb) {
         console.log('signout');
        this.isAuthenticated = false
        setTimeout(cb, 100)
      }
    }
</code>```

AuthButton.js

```<code>    import React from 'react'
    import { withRouter } from 'react-router-dom'
    import { fakeAuth } from './fakeAuth'

    export const AuthButton = withRouter(({ history }) => (
      fakeAuth.isAuthenticated ? (
        <p>
          Welcome! <button onClick={() => {
            fakeAuth.signout(() => history.push('/'))
          }}>Sign out</button>
        </p>
      ) : (
        <p>You are not logged in.</p>
      )
    ))
</code>```

Login.js

```<code>  import React from 'react'

  import { Redirect } from 'react-router-dom';

  import { fakeAuth } from './fakeAuth'

  class Login extends React.Component {
    constructor(props) {
      super(props);
      this.state = { redirectToReferrer: false };
    }

    login() {
      fakeAuth.authenticate(() => {
        this.setState({ redirectToReferrer: true })
      })
    }

    render() {
      const { from } = this.props.location.state || { from: { pathname: '/' } }
      const { redirectToReferrer } = this.state
      console.log("redirectToReferrer", redirectToReferrer);

      if (redirectToReferrer) {
        return (
          <Redirect to={from}/>
        )
      }

      return (
        <div>
          <p>You must log in to view the page at {from.pathname}</p>
          <button onClick={this.login}>Log in</button>
        </div>
      )
    }
  }

  export default Login
</code>```

index.jsx

```<code>    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'

    import { BrowserRouter, Route, Link } from 'react-router-dom'

    import { AuthButton } from './AuthButton'

    import { Login } from './Login'

    import { PrivateRoute } from './PrivateRoute'

    const Public = () => <h3>Public</h3>
    const Protected = () => <h3>Protected</h3>

    ReactDOM.render(
        <BrowserRouter>
        <div>
        <App />
        <AuthButton />
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/public">Public Page</Link></li>
            <li><Link to="/protected">Protected Page</Link></li>
          </ul>
          <hr/>
          <Route path="/public" component={Public} />
          <Route path="/login" component={Login} />
          <PrivateRoute path="/protected" component={Protected} />
        </div>
        </BrowserRouter>,
      document.getElementById('root')
  );
</code>```

App.js

```<code>    import React, { Component } from 'react';
    import logo from '../logo.svg';
    import '../App.css';

    class App extends Component {
      render() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h1 className="App-title">Welcome to React</h1>
            </header>
          </div>
        );
      }
    }

    export default App;
</code>```

My suspect is the mistake in Login.js as this is a class component but could not figure out what am I missing. Please help

答:
The main problem is that you are exporting Login as a default export and importing it as a named import. In index.jsx change:

```<code>import {Login} from './Login'
</code>```

to

```<code>import Login from './Login'
</code>```

This will still not work as there is a second bug, the this inside login() in Login is not the correct one, this can be solved by binding the function to the correct this in the constructor. In Login.js use this:

```<code>constructor(props) {
  super(props);
  this.state = { redirectToReferrer: false };
  this.login = this.login.bind(this); // Fix |this| inside login()
}
</code>```

Body:
Learning from react router authentication example,  I have split the single file code into separate files but now never seeing the login page.
 even no text for protected page

On landing page, there are 3 links

 - Home

 - Public

 - Protected

but when I click on Protected Link URL changes to /login but bot displaying any text or login button like in the example

instead getting an error in console

login Failed to load resource: the server responded with a status of 404 (Not Found).  ... login

here is the relevant code

PrivateRoute.js

  import React from 'react'

  import { Route, Redirect } from 'react-router-dom'

  import { fakeAuth } from './fakeAuth'

  export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      fakeAuth.isAuthenticated ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }}/>
      )
    )}/>
  )

fakeAuth.js

    export const fakeAuth = {
      isAuthenticated: false,
      authenticate(cb) {
        console.log('is authenticated');
        this.isAuthenticated = true
        setTimeout(cb, 100) // fake async
      },
      signout(cb) {
         console.log('signout');
        this.isAuthenticated = false
        setTimeout(cb, 100)
      }
    }

AuthButton.js

    import React from 'react'
    import { withRouter } from 'react-router-dom'
    import { fakeAuth } from './fakeAuth'

    export const AuthButton = withRouter(({ history }) => (
      fakeAuth.isAuthenticated ? (

          Welcome! <button onClick={() => {
            fakeAuth.signout(() => history.push('/'))
          }}>Sign out</button>

      ) : (

You are not logged in.

      )
    ))

Login.js

  import React from 'react'

  import { Redirect } from 'react-router-dom';

  import { fakeAuth } from './fakeAuth'

  class Login extends React.Component {
    constructor(props) {
      super(props);
      this.state = { redirectToReferrer: false };
    }

    login() {
      fakeAuth.authenticate(() => {
        this.setState({ redirectToReferrer: true })
      })
    }

    render() {
      const { from } = this.props.location.state || { from: { pathname: '/' } }
      const { redirectToReferrer } = this.state
      console.log("redirectToReferrer", redirectToReferrer);

      if (redirectToReferrer) {
        return (
          <Redirect to={from}/>
        )
      }

      return (

You must log in to view the page at {from.pathname}

          <button onClick={this.login}>Log in</button>

      )
    }
  }

  export default Login

index.jsx

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'

    import { BrowserRouter, Route, Link } from 'react-router-dom'

    import { AuthButton } from './AuthButton'

    import { Login } from './Login'

    import { PrivateRoute } from './PrivateRoute'

    const Public = () =>
Public

    const Protected = () =>
Protected

    ReactDOM.render(
        <BrowserRouter>

        <App />
        <AuthButton />

<Link to="/">Home</Link>

<Link to="/public">Public Page</Link>

<Link to="/protected">Protected Page</Link>

          <Route path="/public" component={Public} />
          <Route path="/login" component={Login} />
          <PrivateRoute path="/protected" component={Protected} />

        </BrowserRouter>,
      document.getElementById('root')
  );

App.js

    import React, { Component } from 'react';
    import logo from '../logo.svg';
    import '../App.css';

    class App extends Component {
      render() {
        return (

Welcome to React

        );
      }
    }

    export default App;

My suspect is the mistake in Login.js as this is a class component but could not figure out what am I missing. Please help

Body:
The main problem is that you are exporting Login as a default export and importing it as a named import. In index.jsx change:

import {Login} from './Login'

to

import Login from './Login'

This will still not work as there is a second bug, the this inside login() in Login is not the correct one, this can be solved by binding the function to the correct this in the constructor. In Login.js use this:

constructor(props) {
  super(props);
  this.state = { redirectToReferrer: false };
  this.login = this.login.bind(this); // Fix |this| inside login()
}


问:
Data not displaying in on load - only after page refresh
I'm new to React JS, and I've been working through a few tutorials to get my head around it.

The following code was taken from a tutorial on which comments are now closed, and I'm trying to resolve a problem with it.

When I run the app, the data from Firebase doesn't display, and I also can't add items to the list - nothing appears to happen for the user, although I can see the data being added in Firebase. If I reload the page, everything works fine.

I'm guessing this is something to do with componentDidMount, which I understand is only called on the first load of the page, so if the user isn't logged in, the data isn't loaded, and won't be, even after the user logs in - is that right?

Could anyone help me load the data as soon as the user logs in, rather than requiring a refresh of the page?

```<code> import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import firebase, { auth, provider } from './firebase.js';

class App extends Component {
  constructor() {
    super();
    this.state = {
      currentItem: '',
      username: '',
      datetime: '',
      items: [],
      user: null,
      profileImg: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
  }
  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }
  login() {
      auth.signInWithPopup(provider)
          .then((result) => {
              const user = result.user;
              this.setState({
                  user
              });
          });

  }
  logout() {
      auth.signOut()
          .then(() => {
              this.setState({
                  user: null
              });
          });
  }
  handleSubmit(e) {
    e.preventDefault();
    const itemsRef = firebase.database().ref('items');
    const item = {
        title: this.state.currentItem,
        user: this.state.user.displayName || this.state.user.email,
        profileImg: this.state.user.photoURL
    }
    itemsRef.push(item);
    this.setState({
      currentItem: '',
      username: '',
      profileImg: this.state.user.photoURL
    });
  }
  componentDidMount() {

    const itemsRef = firebase.database().ref('items');

    itemsRef.on('value', (snapshot) => {
      let items = snapshot.val();
      let newState = [];
      for (let item in items) {
        newState.push({
          id: item,
          title: items[item].title,
          user: items[item].user,
          profileImg: items[item].profileImg
        });
      }
      this.setState({
        items: newState
      });
    });

    auth.onAuthStateChanged((user) => {
        if (user) {
            this.setState({ user });
        }
    });
  }

  removeItem(itemId) {
    const itemRef = firebase.database().ref(`/items/${itemId}`);
    itemRef.remove();
  }
  render() {
      return (
          <div className='app'>
            <header>
              <div className="wrapper">
                <h1></h1>
                  {this.state.user ?
                      <button onClick={this.logout}>Logout</button>
                      :
                      <button onClick={this.login}>Log In</button>
                  }
              </div>
            </header>

              {this.state.user ?
                  <div>
                    <div className='user-profile'>
                      <img src={this.state.user.photoURL} alt={this.state.user.displayName} />
                    </div>
                    <div className='container'>
                        <section className='display-item'>
                            <div className="wrapper">
                                <ul>
                                    {this.state.items.reverse().map((item) => {
                                        return (
                                            <li key={item.id}>
                                                <h3>{item.title}</h3>
                                                <p>brought by: {item.user}
                                                    {item.user === this.state.user.displayName || item.user === this.state.user.email ?
                                                        <button onClick={() => this.removeItem(item.id)}>Remove Item</button> : null}

                                                    <img src={item.profileImg} alt={this.state.user.displayName} className={"profileImg"} />

                                                </p>
                                            </li>
                                        )
                                    })}
                                </ul>
                            </div>
                        </section>
                      <section className='add-item'>
                        <form onSubmit={this.handleSubmit}>
                          <input type="text" name="username" placeholder="What's your name?" onChange={this.handleChange} value={this.state.user.displayName || this.state.user.email} disabled />
                          <input type="text" name="currentItem" placeholder="What are you bringing?" onChange={this.handleChange} value={this.state.currentItem} />
                          <button>Add Item</button>
                        </form>
                      </section>
                    </div>
                    </div>
                  :
                  <div className='wrapper'>
                    <p>You must be logged in to see this page.</p>
                  </div>
              }

          </div>

      );
  }
}

export default App;
</code>```

Then is firebase.js I have:

```<code>import firebase from 'firebase'

var config = {
    apiKey: "xxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
    projectId: "xxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxx.appspot.com",
    messagingSenderId: "xxxxxxxxxxxx"
};

firebase.initializeApp(config);

export const provider = new firebase.auth.GoogleAuthProvider();
export const auth = firebase.auth();

export default firebase;
</code>```

I'm fairly certain that this issue exists in the original tutorial, which can be viewed at https://css-tricks.com/firebase-react-part-2-user-authentication/.

Any help would be much appreciated.

Thanks,

John.

答:
Maybe just pull your firebase call out into a separate function, and call it after the user has logged in?:

```<code>login() {
  auth.signInWithPopup(provider)
      .then((result) => {
          this.callFirebaseFunction()
          const user = result.user;
          this.setState({
              user
          });
      });
</code>```

}

Body:
I'm new to React JS, and I've been working through a few tutorials to get my head around it.

The following code was taken from a tutorial on which comments are now closed, and I'm trying to resolve a problem with it.

When I run the app, the data from Firebase doesn't display, and I also can't add items to the list - nothing appears to happen for the user, although I can see the data being added in Firebase. If I reload the page, everything works fine.

I'm guessing this is something to do with componentDidMount, which I understand is only called on the first load of the page, so if the user isn't logged in, the data isn't loaded, and won't be, even after the user logs in - is that right?

Could anyone help me load the data as soon as the user logs in, rather than requiring a refresh of the page?

 import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import firebase, { auth, provider } from './firebase.js';

class App extends Component {
  constructor() {
    super();
    this.state = {
      currentItem: '',
      username: '',
      datetime: '',
      items: [],
      user: null,
      profileImg: ''
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
  }
  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }
  login() {
      auth.signInWithPopup(provider)
          .then((result) => {
              const user = result.user;
              this.setState({
                  user
              });
          });

  }
  logout() {
      auth.signOut()
          .then(() => {
              this.setState({
                  user: null
              });
          });
  }
  handleSubmit(e) {
    e.preventDefault();
    const itemsRef = firebase.database().ref('items');
    const item = {
        title: this.state.currentItem,
        user: this.state.user.displayName || this.state.user.email,
        profileImg: this.state.user.photoURL
    }
    itemsRef.push(item);
    this.setState({
      currentItem: '',
      username: '',
      profileImg: this.state.user.photoURL
    });
  }
  componentDidMount() {

    const itemsRef = firebase.database().ref('items');

    itemsRef.on('value', (snapshot) => {
      let items = snapshot.val();
      let newState = [];
      for (let item in items) {
        newState.push({
          id: item,
          title: items[item].title,
          user: items[item].user,
          profileImg: items[item].profileImg
        });
      }
      this.setState({
        items: newState
      });
    });

    auth.onAuthStateChanged((user) => {
        if (user) {
            this.setState({ user });
        }
    });
  }

  removeItem(itemId) {
    const itemRef = firebase.database().ref(`/items/${itemId}`);
    itemRef.remove();
  }
  render() {
      return (

                  {this.state.user ?
                      <button onClick={this.logout}>Logout</button>
                      :
                      <button onClick={this.login}>Log In</button>
                  }

              {this.state.user ?

                                    {this.state.items.reverse().map((item) => {
                                        return (

{item.title}

brought by: {item.user}
                                                    {item.user === this.state.user.displayName || item.user === this.state.user.email ?
                                                        <button onClick={() => this.removeItem(item.id)}>Remove Item</button> : null}

                                        )
                                    })}

                        <form onSubmit={this.handleSubmit}>
                          <input type="text" name="username" placeholder="What's your name?" onChange={this.handleChange} value={this.state.user.displayName || this.state.user.email} disabled />
                          <input type="text" name="currentItem" placeholder="What are you bringing?" onChange={this.handleChange} value={this.state.currentItem} />
                          <button>Add Item</button>
                        </form>

                  :

You must be logged in to see this page.

              }

      );
  }
}

export default App;

Then is firebase.js I have:

import firebase from 'firebase'

var config = {
    apiKey: "xxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
    projectId: "xxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxx.appspot.com",
    messagingSenderId: "xxxxxxxxxxxx"
};

firebase.initializeApp(config);

export const provider = new firebase.auth.GoogleAuthProvider();
export const auth = firebase.auth();

export default firebase;

I'm fairly certain that this issue exists in the original tutorial, which can be viewed at https://css-tricks.com/firebase-react-part-2-user-authentication/.

Any help would be much appreciated.

Thanks,

John.

Body:
Maybe just pull your firebase call out into a separate function, and call it after the user has logged in?:

login() {
  auth.signInWithPopup(provider)
      .then((result) => {
          this.callFirebaseFunction()
          const user = result.user;
          this.setState({
              user
          });
      });

}


问:
Error: app is in background uid null
I created a new Android project on IntelliJ CE 2017.2 and got this error. I added the maven section as described in the answer.

When I run the default app that is created with the new project I get the error

Error while executing: am startservice com.test.myapp/com.android.tools.fd.runtime.InstantRunService

Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.test.myapp/com.android.tools.fd.runtime.InstantRunService }

Error: app is in background uid null

I can still open the app manually on my phone and it works, but it doesn't start automatically and I get that error message.

答:
I've seen this error using android api 26/27 (Oreo).  In Oreo there are new background execution limits.  tl;dr you should run services in the foreground.

to start your service using adb, use adb shell am start-foreground-service

instead of adb shell am startservice.

Title: Error: app is in background uid null


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
I'd go for the list/bits solution of @OscarRyz, @Clint and @Sven, but here's another one:

```<code>
S1 = frozenset(['first', 'second', 'third', 'fourth'])
S2 = frozenset(['first', 'second', 'fifth', 'sixth'])
S3 = frozenset(['first', 'third', 'fifth', 'seventh'])
last = 'eighth'
empty = frozenset([])</p>

<p>def value(a, b, c):
    for r in (a and S1 or empty) & (b and S2 or empty) & (c and S3 or empty):
        return r
    return last</p>

<p>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
I'd go for the list/bits solution of @OscarRyz, @Clint and @Sven, but here's another one:

S1 = frozenset(['first', 'second', 'third', 'fourth'])
S2 = frozenset(['first', 'second', 'fifth', 'sixth'])
S3 = frozenset(['first', 'third', 'fifth', 'seventh'])
last = 'eighth'
empty = frozenset([])

def value(a, b, c):
    for r in (a and S1 or empty) & (b and S2 or empty) & (c and S3 or empty):
        return r
    return last


问:
Maven `help:effective-pom` only generating for a single project, not all projects
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

```<code><!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2017-11-12T09:56:26                  -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->

<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective POM for project                                              -->
<!-- 'org.gradle.test.performance:project:pom:1.0'                          -->
<!--                                                                        -->
<!-- ====================================================================== -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>
    <scriptSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\scripts</scriptSourceDirectory>
    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>
</code>```

答:
The EffectivePomMojo is an aggregator goal. Which means it's invoked only for the module that you run it for. But you're right that it should dump all the sub-projects as well. The reason it doesn't do this in your case is because of this line:

```<code>if ( projects.get( 0 ).equals( project ) && projects.size() > 1 )
</code>```

In your case the upper-most project is last in the graph (because there are no dependencies on it from any other module). If you add it as a parent to project0 (and only for that module), then it'd put your root pom at the 1st position in the graph and everything will work as you expect.

I can't come up with a justification for this behaviour. So if you raise an issue in the bugtracker everyone will benefit :) Please update us if/when you get the answer.

PS: such questions are easy to solve if you know how to debug Maven plugins. For this you can use mvnDebug instead of mvn and then open plugin's source code and attach to the debug session.

Body:
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>

    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>

Body:
The EffectivePomMojo is an aggregator goal. Which means it's invoked only for the module that you run it for. But you're right that it should dump all the sub-projects as well. The reason it doesn't do this in your case is because of this line:

if ( projects.get( 0 ).equals( project ) && projects.size() > 1 )

In your case the upper-most project is last in the graph (because there are no dependencies on it from any other module). If you add it as a parent to project0 (and only for that module), then it'd put your root pom at the 1st position in the graph and everything will work as you expect.

I can't come up with a justification for this behaviour. So if you raise an issue in the bugtracker everyone will benefit :) Please update us if/when you get the answer.

PS: such questions are easy to solve if you know how to debug Maven plugins. For this you can use mvnDebug instead of mvn and then open plugin's source code and attach to the debug session.


问:
Localtunnel alternative not working
I connect my app to Localtunnel. It was working very well until last week, but now it's not working:

答:
Edit: Localtunnel appears to be working again. (Of course depending when you're reading this it may not be. Please use your own judgment.)

Original answer:

The cloud-hosted part of Localtunnel is currently down. You'll have to wait until its maintainer brings it up again, or use another service like ngrok.

Some more issues tracking this:

https://github.com/localtunnel/server/issues/40#issuecomment-344038789

https://github.com/localtunnel/localtunnel/issues/198

https://github.com/localtunnel/localtunnel/issues/199

Title: Localtunnel alternative not working


答:
here is your solution :)

```<code>#include <stdio.h>
#include <string.h>

int main(void)
{

    char str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s" , str);

    while (i < strlen(str))
    {
        if (i % 2 == 0) {
                odd[j++] = str[i];
        } else {
                even[k++] = str[i];
        }
        i++;
    }
    odd[j] = '\0';
    even[k] = '\0';

    printf("The even string is:%s\n " , even);

    printf("The odd string is:%s\n " , odd);

    return 0;
}
</code>```

solved the mistake in the declaration, the scanning string value, condition of the while loop and assignment of element of array. :)

Title: A program that prints even and odd characters from a string

Body:
here is your solution :)

#include <stdio.h>
#include <string.h>

int main(void)
{

    char str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s" , str);

    while (i < strlen(str))
    {
        if (i % 2 == 0) {
                odd[j++] = str[i];
        } else {
                even[k++] = str[i];
        }
        i++;
    }
    odd[j] = '\0';
    even[k] = '\0';

    printf("The even string is:%s\n " , even);

    printf("The odd string is:%s\n " , odd);

    return 0;
}

solved the mistake in the declaration, the scanning string value, condition of the while loop and assignment of element of array. :)


问:
Recieve JSON data from link in whattomine without scraping HTML

Explanation

This link is where you are sent to after entering in your hardware stats (hashrate, power, power cost, etc.). On the top bar (below the blue Twitter follow button) is a link to a JSON file created after the page loads with the hardware stats information entered; clicking on that JSON link redirects you to another URL (https://whattomine.com/asic.json).

Goal

My goal is to access that JSON file directly after manipulating the values in the URL string via the terminal. For example, if I would like to change hashrate from 100 to 150 in this portion of the URL:

[sha256_hr]=100& ---> [sha256_hr]=150&

After the URL manipulations (like above, but not limited to), I would like to receive the JSON output so that I can pick-out the desired data.

My Code

Advisory: I started Python programming ~June 2017, please forgive.

```<code>import json
import pandas as pd
import urllib2
import requests

hashrate_ghs = float(raw_input('Hash Rate (TH/s): '))
power_W = float(raw_input('Power of Miner (W): '))
electric_cost = float(raw_input('Cost of Power ($/kWh): '))
hashrate_ths = hashrate_ghs * 1000

initial_request = ('https://whattomine.com/asic?utf8=%E2%9C%93&sha256f=true&factor[sha256_hr]={0}&factor[sha256_p]={1}&factor[cost]={2}&sort=Profitability24&volume=0&revenue=24h&factor[exchanges][]=&factor[exchanges][]=bittrex&dataset=Main&commit=Calculate'.format(hashrate_ths, power_W, electric_cost))
data_stream_mine = urllib2.Request(initial_request)

json_data = requests.get('https://whattomine.com/asic.json')
print json_data
</code>```

Error from My Code

I am getting an HTTPS handshake error. This is where my Python freshness is second most blatantly visible:

```<code>Traceback (most recent call last):
  File "calc_1.py", line 16, in <module>
    s.get('https://whattomine.com/asic.json')
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 521, in get
    return self.request('GET', url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 506, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='whattomine.com', port=443): Max retries exceeded with url: /asic.json (Caused by SSLError(SSLError(1, u'[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)'),))
</code>```

Thank you for your help and time!

Please advise me of any changes or for more information concerning this question.

答:
It looks like a few others faced similar problems.

While for some it seemed to be like a pyOpenSSL version issue, uninstalling and reinstalling which has fixed the problem. Another older answer in SO asks to do the following.

Body:
Explanation

<a href="https://whattomine.com/asic?utf8=%E2%9C%93&sha256f=true&factor%5Bsha256_hr%5D=100&factor%5Bsha256_p%5D=100&factor%5Bscrypt_hash_rate%5D=500.0&factor%5Bscrypt_power%5D=800.0&factor%5Bx11_hr%5D=15000.0&factor%5Bx11_p%5D=1200.0&factor%5Bqk_hr%5D=450.0&factor%5Bqk_p%5D=75.0&factor%5Bqb_hr%5D=450.0&factor%5Bqb_p%5D=84.0&factor%5Bcost%5D=0.1&sort=Profitability24&volume=0&revenue=24h&factor%5Bexchanges%5D%5B%5D=&factor%5Bexchanges%5D%5B%5D=bittrex&dataset=Main&commit=Calculate" rel="nofollow noreferrer">This link is where you are sent to after entering in your hardware stats (hashrate, power, power cost, etc.). On the top bar (below the blue Twitter follow button) is a link to a JSON file created after the page loads with the hardware stats information entered; clicking on that JSON link redirects you to another URL (https://whattomine.com/asic.json).

Goal

My goal is to access that JSON file directly after manipulating the values in the URL string via the terminal. For example, if I would like to change hashrate from 100 to 150 in this portion of the URL:

[sha256_hr]=100& ---> [sha256_hr]=150&

After the URL manipulations (like above, but not limited to), I would like to receive the JSON output so that I can pick-out the desired data.

My Code

Advisory: I started Python programming ~June 2017, please forgive.

import json
import pandas as pd
import urllib2
import requests

hashrate_ghs = float(raw_input('Hash Rate (TH/s): '))
power_W = float(raw_input('Power of Miner (W): '))
electric_cost = float(raw_input('Cost of Power ($/kWh): '))
hashrate_ths = hashrate_ghs * 1000

initial_request = ('https://whattomine.com/asic?utf8=%E2%9C%93&sha256f=true&factor[sha256_hr]={0}&factor[sha256_p]={1}&factor[cost]={2}&sort=Profitability24&volume=0&revenue=24h&factor[exchanges][]=&factor[exchanges][]=bittrex&dataset=Main&commit=Calculate'.format(hashrate_ths, power_W, electric_cost))
data_stream_mine = urllib2.Request(initial_request)

json_data = requests.get('https://whattomine.com/asic.json')
print json_data

Error from My Code

I am getting an HTTPS handshake error. This is where my Python freshness is second most blatantly visible:

Traceback (most recent call last):
  File "calc_1.py", line 16, in <module>
    s.get('https://whattomine.com/asic.json')
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 521, in get
    return self.request('GET', url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 506, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='whattomine.com', port=443): Max retries exceeded with url: /asic.json (Caused by SSLError(SSLError(1, u'[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)'),))

Thank you for your help and time!

Please advise me of any changes or for more information concerning this question.


问:
Want to find specific pattern, without knowing the words it contains in Unix
Using grep in bash

```<code>    Sylvester,Stallone,+42 6944789099
    Tommy, Lee Jones,+37 6923441223
    Jean Claude,Van Damme,+44 6977654322
    Jose Maria,de Santo Agostinho,+30 6936130089
    Chuck, Norris, +30 6987543212
    Chuck,Norris,+32 6944221234
    Chuck1, Norris, +32 6944221234
</code>```

I have this file , and i want to find the lines where there is only whitespace in the phone number, how do i grep this desired pattern? For example the grep result should yield

```<code>Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234
</code>```

EDIT : I want to find the lines that contain exactly one space, and that space MUST be between the country code(ex. +42) and the number itself(6944789000)

答:
It is much easier with awk without using any regex:

```<code>awk 'NF==2' file

Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234
</code>```

By default awk splits fields on whitespaces

By using condition NF==2 we print a row that has 2 fields or a single whitespace.

If you specifically want to find lines with space between digits then use:

```<code>grep -P '^\S+\d+ \d+$' file

Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234
</code>```

Or by using POSIX classes:

```<code>grep -E '^[^[:blank:]]+[[:digit:]]+ [[:digit:]]+$' file
</code>```

Body:
Using grep in bash

    Sylvester,Stallone,+42 6944789099
    Tommy, Lee Jones,+37 6923441223
    Jean Claude,Van Damme,+44 6977654322
    Jose Maria,de Santo Agostinho,+30 6936130089
    Chuck, Norris, +30 6987543212
    Chuck,Norris,+32 6944221234
    Chuck1, Norris, +32 6944221234

I have this file , and i want to find the lines where there is only whitespace in the phone number, how do i grep this desired pattern? For example the grep result should yield

Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234

EDIT : I want to find the lines that contain exactly one space, and that space MUST be between the country code(ex. +42) and the number itself(6944789000)

Body:
It is much easier with awk without using any regex:

awk 'NF==2' file

Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234

By default awk splits fields on whitespaces

By using condition NF==2 we print a row that has 2 fields or a single whitespace.

If you specifically want to find lines with space between digits then use:

grep -P '^\S+\d+ \d+$' file

Sylvester,Stallone,+42 6944789099
Chuck,Norris,+32 6944221234

Or by using POSIX classes:

grep -E '^[^[:blank:]]+[[:digit:]]+ [[:digit:]]+$' file


问:
How to mount a host directory in a Docker container
I am trying to mount a host directory into a Docker container so that any updates done on the host is reflected into the Docker containers.

Where am I doing something wrong. Here is what I did:

```<code>kishore$ cat Dockerfile

FROM ubuntu:trusty
RUN apt-get update
RUN apt-get -y install git curl vim
CMD ["/bin/bash"]
WORKDIR /test_container
VOLUME ["/test_container"]
</code>```

```<code>kishore$ tree
.
├── Dockerfile
└── main_folder
    ├── tfile1.txt
    ├── tfile2.txt
    ├── tfile3.txt
    └── tfile4.txt</p>

<p>1 directory, 5 files
kishore$ pwd
/Users/kishore/tdock
</code>``````<code>kishore$ docker build --tag=k3_s3:latest .</p>

```Uploading context 7.168 kB
Uploading context
Step 0 : FROM ubuntu:trusty
 ---> 99ec81b80c55
Step 1 : RUN apt-get update
 ---> Using cache
 ---> 1c7282005040
Step 2 : RUN apt-get -y install git curl vim
 ---> Using cache
 ---> aed48634e300
Step 3 : CMD ["/bin/bash"]
 ---> Running in d081b576878d
 ---> 65db8df48595
Step 4 : WORKDIR /test_container
 ---> Running in 5b8d2ccd719d
 ---> 250369b30e1f
Step 5 : VOLUME ["/test_container"]
 ---> Running in 72ca332d9809
 ---> 163deb2b1bc5
Successfully built 163deb2b1bc5
Removing intermediate container b8bfcb071441
Removing intermediate container d081b576878d
Removing intermediate container 5b8d2ccd719d
Removing intermediate container 72ca332d9809
```

<p>kishore$ docker run -d -v /Users/kishore/main_folder:/test_container k3_s3:latest
<code>c9f9a7e09c54ee1c2cc966f15c963b4af320b5203b8c46689033c1ab8872a0ea</code></code>``````<code>kishore$ docker run -i -t k3_s3:latest /bin/bash</p>

```root@0f17e2313a46:/test_container# ls -al
total 8
drwx------  2 root root 4096 Apr 29 05:15 .
drwxr-xr-x 66 root root 4096 Apr 29 05:15 ..
```

<p>root@0f17e2313a46:/test_container# exit
exit</code>``````<code>kishore$ docker -v
Docker version 0.9.1, build 867b2a9</code>```

I don't know how to check boot2docker version

Questions, issues facing:

How do I need to link the main_folder to the test_container folder present inside the docker container?

I need to make this automatically. How do I to do that without really using the run -d -v command?

What happens if the boot2docker crashes? Where are the Docker files stored (apart from Dockerfile)?

答:
The user of this question was using Docker version 0.9.1, build 867b2a9, I will give you an answer for docker version >= 17.06.

What you want, keep local directory synchronized within container directory, is accomplished by mounting the volume with type bind. This will bind the source (your system) and the target (at the docker container) directories. It's almost the same as mounting a directory on linux.

According to Docker documentation, the appropriate command to mount is now mount instead of -v. Here's its documentation:

--mount: Consists of multiple key-value pairs, separated by commas. Each key/value pair takes the form of a <key>=<value> tuple. The --mount syntax is more verbose than -v or --volume, but the order of the keys is not significant, and the value of the flag is easier to understand.

The type of the mount, which can be bind, volume, or tmpfs. (We are going to use bind)

The source of the mount. For bind mounts, this is the path to the file or directory on the Docker daemon host. May be specified as source or src.

The destination takes as its value the path where the file or directory will be mounted in the container. May be specified as destination, dst, or target.

So, to mount the the current directory (source) with /test_container (target) we are going to use:

```<code>    docker run -it --mount src="$(pwd)",target=/test_container,type=bind k3_s3
</code>```

If these mount parameters have spaces you must put quotes around them. When I know they don't, I would use `pwd` instead:

```<code>    docker run -it --mount src=`pwd`,target=/test_container,type=bind k3_s3
</code>```

You will also have to deal with file permission, see this article.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to mount a host directory into a Docker container so that any updates done on the host is reflected into the Docker containers.

Where am I doing something wrong. Here is what I did:

kishore$ cat Dockerfile

FROM ubuntu:trusty
RUN apt-get update
RUN apt-get -y install git curl vim
CMD ["/bin/bash"]
WORKDIR /test_container
VOLUME ["/test_container"]

kishore$ tree
.
├── Dockerfile
└── main_folder
    ├── tfile1.txt
    ├── tfile2.txt
    ├── tfile3.txt
    └── tfile4.txt

1 directory, 5 files
kishore$ pwd
/Users/kishore/tdock

kishore$ docker build --tag=k3_s3:latest .

Uploading context 7.168 kB
Uploading context
Step 0 : FROM ubuntu:trusty
 ---> 99ec81b80c55
Step 1 : RUN apt-get update
 ---> Using cache
 ---> 1c7282005040
Step 2 : RUN apt-get -y install git curl vim
 ---> Using cache
 ---> aed48634e300
Step 3 : CMD ["/bin/bash"]
 ---> Running in d081b576878d
 ---> 65db8df48595
Step 4 : WORKDIR /test_container
 ---> Running in 5b8d2ccd719d
 ---> 250369b30e1f
Step 5 : VOLUME ["/test_container"]
 ---> Running in 72ca332d9809
 ---> 163deb2b1bc5
Successfully built 163deb2b1bc5
Removing intermediate container b8bfcb071441
Removing intermediate container d081b576878d
Removing intermediate container 5b8d2ccd719d
Removing intermediate container 72ca332d9809

kishore$ docker run -d -v /Users/kishore/main_folder:/test_container k3_s3:latest
c9f9a7e09c54ee1c2cc966f15c963b4af320b5203b8c46689033c1ab8872a0ea

kishore$ docker run -i -t k3_s3:latest /bin/bash

root@0f17e2313a46:/test_container# ls -al
total 8
drwx------  2 root root 4096 Apr 29 05:15 .
drwxr-xr-x 66 root root 4096 Apr 29 05:15 ..

root@0f17e2313a46:/test_container# exit
exit

kishore$ docker -v
Docker version 0.9.1, build 867b2a9

I don't know how to check boot2docker version

Questions, issues facing:

How do I need to link the main_folder to the test_container folder present inside the docker container?

I need to make this automatically. How do I to do that without really using the run -d -v command?

What happens if the boot2docker crashes? Where are the Docker files stored (apart from Dockerfile)?

Body:
The user of this question was using Docker version 0.9.1, build 867b2a9, I will give you an answer for docker version >= 17.06.

What you want, keep local directory synchronized within container directory, is accomplished by mounting the volume with type bind. This will bind the source (your system) and the target (at the docker container) directories. It's almost the same as mounting a directory on linux.

According to Docker documentation, the appropriate command to mount is now mount instead of -v. Here's its documentation:

--mount: Consists of multiple key-value pairs, separated by commas. Each key/value pair takes the form of a <key>=<value> tuple. The --mount syntax is more verbose than -v or --volume, but the order of the keys is not significant, and the value of the flag is easier to understand.

The type of the mount, which can be bind, volume, or tmpfs. (We are going to use bind)

The source of the mount. For bind mounts, this is the path to the file or directory on the Docker daemon host. May be specified as source or src.

The destination takes as its value the path where the file or directory will be mounted in the container. May be specified as destination, dst, or target.

So, to mount the the current directory (source) with /test_container (target) we are going to use:

    docker run -it --mount src="$(pwd)",target=/test_container,type=bind k3_s3

If these mount parameters have spaces you must put quotes around them. When I know they don't, I would use `pwd` instead:

    docker run -it --mount src=`pwd`,target=/test_container,type=bind k3_s3

You will also have to deal with file permission, see this article.


问:
Extracting text from multiple powerpoint files using python
I am trying to find a way to look in a folder and search the contents of all of the powerpoint documents within that folder for specific strings, preferably using Python. When those strings are found, I want to report out the text after that string as well as what document it was found in. I would like to compile the information and report it in a CSV file.

So far I've only come across the olefil package, https://bitbucket.org/decalage/olefileio_pl/wiki/Home. This provides all of the text contained in a specific document, which is not what I am looking to do. Please help.

答:
Actually working

If you want to extract text:

import Presentation from pptx (pip install python-pptx)

for each file in the directory (using glob module)

look in every slides and in every shape in each slide

if there is a shape with text attribute, print the shape.text

```<code>from pptx import Presentation
import glob

for eachfile in glob.glob("*.pptx"):
    prs = Presentation(eachfile)
    print(eachfile)
    print("----------------------")
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                print(shape.text)
</code>```

Body:
Actually working

If you want to extract text:

import Presentation from pptx (pip install python-pptx)

for each file in the directory (using glob module)

look in every slides and in every shape in each slide

if there is a shape with text attribute, print the shape.text

from pptx import Presentation
import glob

for eachfile in glob.glob("*.pptx"):
    prs = Presentation(eachfile)
    print(eachfile)
    print("----------------------")
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                print(shape.text)