问:
Window opened won't close
I have a window which opens on click.

```<code>function PopupManager() {
this.name = "_popupmanager_";
this.windows = {};
};

PopupManager.prototype.open = function(url, option, size, name) {
var url = "http://google.com"
var option = "null, status=no, toolbar=no, menubar=no, titlebar=no,
location=no, scrollbars=no, resizable=no"
var size = 'height=200, width = 814'
this.windows[name] = window.open(url, option, size, name);
this.windows[name].focus();
};

PopupManager.prototype.closeAll = function() {
for (name in this.windows) {
  this.closeWindow(name);
}
 }

 PopupManager.prototype.closeWindow = function(name) {
if (this.windows[name]) {
    if (!this.windows[name].closed) {
        this.windows[name].opener.name="indexpage";
        this.windows[name].close();
    }
    delete this.windows[name];
 }
 };
</code>```

//init

```<code> document.getElementById("popupManager").onclick = function (e) {
 e.preventDefault();
 var popupManager = new PopupManager();
 popupManager.open('http://www.google.com', 'google');

}
</code>```

And I am thinking this should close the same window.

```<code> document.getElementById("closeIt").onclick = function (e) {
 e.preventDefault();
 var popupManager = new PopupManager();
 popupManager.closeAll();
 popupManger.closeWindow();

 }
</code>```

No console error & nothing happens.  Just won't close.

I was trying to use same  tag to open & close the window using if else statement but I couldn't figure it out.  So now I am trying to use two different   tag, (yes, I know that's dumb) one to open & one to close but I can't even do that.

I can't even figure out what I am doing wrong here.

Any help will be greatly appreciated it. sigh...

答:
Just define a variable outside the popupManager that holds the windows, so you have access them later for closing.

You could wrap it an IIFE to create a closure as well.

var windows = {};

function PopupManager() {
  this.name = "_popupmanager_";
};

PopupManager.prototype.open = function(url, option, size, name) {
  var url = "http://google.com"
  var option = "null, status=no, toolbar=no, menubar=no, titlebar=no, location = no, scrollbars = no, resizable = no ";
  var size = 'height=200, width = 814'
  windows[name] = window.open(url, option, size, name);
  windows[name].focus();
};

PopupManager.prototype.closeAll = function() {
  for (name in windows) {
    this.closeWindow(name);
  }
}

PopupManager.prototype.closeWindow = function(name) {
  if (windows[name]) {
    if (!windows[name].closed) {
      windows[name].opener.name = "indexpage";
      windows[name].close();
    }
    delete windows[name];
  }
};

document.getElementById("popupManager").onclick = function(e) {
  e.preventDefault();
  var popupManager = new PopupManager();
  popupManager.open('http://www.google.com', 'google');

}

document.getElementById("closeIt").onclick = function(e) {
  e.preventDefault();
  var popupManager = new PopupManager();
  popupManager.closeAll();
  popupManager.closeWindow();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="popupManager">Open</button>
<br />
<button id="closeIt">Close</button></code>```

Another option would be to use

```<code>PopupManager.prototype.windows = {};
</code>```

To keep the same variable accessible across instances.

Title: Window opened won't close

Body:
I have a window which opens on click.

function PopupManager() {
this.name = "_popupmanager_";
this.windows = {};
};

PopupManager.prototype.open = function(url, option, size, name) {
var url = "http://google.com"
var option = "null, status=no, toolbar=no, menubar=no, titlebar=no,
location=no, scrollbars=no, resizable=no"
var size = 'height=200, width = 814'
this.windows[name] = window.open(url, option, size, name);
this.windows[name].focus();
};

PopupManager.prototype.closeAll = function() {
for (name in this.windows) {
  this.closeWindow(name);
}
 }

 PopupManager.prototype.closeWindow = function(name) {
if (this.windows[name]) {
    if (!this.windows[name].closed) {
        this.windows[name].opener.name="indexpage";
        this.windows[name].close();
    }
    delete this.windows[name];
 }
 };

//init

 document.getElementById("popupManager").onclick = function (e) {
 e.preventDefault();
 var popupManager = new PopupManager();
 popupManager.open('http://www.google.com', 'google');

}

And I am thinking this should close the same window.

 document.getElementById("closeIt").onclick = function (e) {
 e.preventDefault();
 var popupManager = new PopupManager();
 popupManager.closeAll();
 popupManger.closeWindow();

 }

No console error & nothing happens.  Just won't close.

I was trying to use same  tag to open & close the window using if else statement but I couldn't figure it out.  So now I am trying to use two different   tag, (yes, I know that's dumb) one to open & one to close but I can't even do that.

I can't even figure out what I am doing wrong here.

Any help will be greatly appreciated it. sigh...

Body:
Just define a variable outside the popupManager that holds the windows, so you have access them later for closing.

You could wrap it an IIFE to create a closure as well.

var windows = {};

function PopupManager() {
  this.name = "_popupmanager_";
};

PopupManager.prototype.open = function(url, option, size, name) {
  var url = "http://google.com"
  var option = "null, status=no, toolbar=no, menubar=no, titlebar=no, location = no, scrollbars = no, resizable = no ";
  var size = 'height=200, width = 814'
  windows[name] = window.open(url, option, size, name);
  windows[name].focus();
};

PopupManager.prototype.closeAll = function() {
  for (name in windows) {
    this.closeWindow(name);
  }
}

PopupManager.prototype.closeWindow = function(name) {
  if (windows[name]) {
    if (!windows[name].closed) {
      windows[name].opener.name = "indexpage";
      windows[name].close();
    }
    delete windows[name];
  }
};

document.getElementById("popupManager").onclick = function(e) {
  e.preventDefault();
  var popupManager = new PopupManager();
  popupManager.open('http://www.google.com', 'google');

}

document.getElementById("closeIt").onclick = function(e) {
  e.preventDefault();
  var popupManager = new PopupManager();
  popupManager.closeAll();
  popupManager.closeWindow();

}

<button id="popupManager">Open</button>
<br />
<button id="closeIt">Close</button>

Another option would be to use

PopupManager.prototype.windows = {};

To keep the same variable accessible across instances.


来源: stackexchange

问:
"For" loop Python code - does this look right/acceptable?
I would like to create a "for" loop (in Python 2). I have a list of obstacles and for each obstacle, if they are true (i.e. exist and appear in the list) I would like to append them to a list called "tests" and call a function called "obstacle_detection" (which deals with what happens when an obstacle is detected) (and I use "tests" later). This is part of a much larger program and I can't quite tell whether it's working, so I was wondering if anyone would be able to tell me if it makes sense? Or advise me of a better way there might be of doing this? </p>

```<code>obstacles = [obstacle, obstacle1, obstacle2]
tests = []

counter = 0

for obstacle in obstacles:
    tests.append(0)
    tests[counter] = obstacle_detection(obstacle, pos)
    counter = counter + 1
</code>```

答:
Your code possibly makes sense, depending on how you define obstacles and obstacle_detection.

As it is, you could write your code this way :

```<code>tests = [obstacle_detection(obstacle, pos) for obstacle in obstacles]
</code>```

It creates a new list automatically, with the same length as obstacles and filled with obstacle_detection values for each obstacle.

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a "for" loop (in Python 2). I have a list of obstacles and for each obstacle, if they are true (i.e. exist and appear in the list) I would like to append them to a list called "tests" and call a function called "obstacle_detection" (which deals with what happens when an obstacle is detected) (and I use "tests" later). This is part of a much larger program and I can't quite tell whether it's working, so I was wondering if anyone would be able to tell me if it makes sense? Or advise me of a better way there might be of doing this?

obstacles = [obstacle, obstacle1, obstacle2]
tests = []

counter = 0

for obstacle in obstacles:
    tests.append(0)
    tests[counter] = obstacle_detection(obstacle, pos)
    counter = counter + 1

Body:
Your code possibly makes sense, depending on how you define obstacles and obstacle_detection.

As it is, you could write your code this way :

tests = [obstacle_detection(obstacle, pos) for obstacle in obstacles]

It creates a new list automatically, with the same length as obstacles and filled with obstacle_detection values for each obstacle.


问:
Segmentation fault issue while reversing linked list in c
```<code>#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *insert(struct node *link, int data) {
    if (link == NULL) {
        link = (struct node *)malloc(sizeof(struct node));
        link->data = data;
        link->next = NULL;
    } else {
        struct node *newlink = (struct node *)malloc(sizeof(struct node));

        newlink->data = data;
        newlink->next = link;
        link = newlink;
    }
    return link;
}

void reverse(struct node *link) {
    int i, j = 0;
    int arr1[100], arr2[100];
    struct node *current;
    int count = 0;

    current = link;

    while (current != NULL) {
        arr1[i] = current->data;
        i = i + 1;
        count = count + 1;
        current = current->next;
    }

    printf("\n");
    i = 0;
    j = 0;

    for (i = count - 1; i >= 0; i--) {
        arr2[j] = arr1[i];
        j = j + 1;
    }

    printf("The elements in the linked list are: ");

    for (i = 0; i < count; i++) {
        printf("%d ", arr1[i]);
    }

    printf("The elements in the reversed linked list are: ");

    for (j = 0; j < count; i++) {
        printf("%d ", arr2[j]);
    }
}

void print(struct node *link) {
    struct node *temp = link;

    printf("The elements in the linked list are: ");

    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
}

void main() {
    int value;

    printf("Enter the value:\n");
    scanf("%d", &value);
    struct node *link = NULL;

    link = insert(link, value);
    char ans[3] = "yes";

    while (ans[0] == 'y') {
        printf("Do you want to add another node? Type Yes/No\n");
        scanf("%s", ans);

        if (ans[0] == 'y') {
            printf("Enter the value:\n");
            scanf("%d", &value);
            link = insert(link, value);
        } else {
            reverse(link);
        }
    }
}
</code>```

Here is the code I wrote to reverse a single linked list in C. I seem to try different combinations of the program but while doing it by array method, I am unable to get rid of the segmentation fault, and hence it doesn't give output.

答:
There are some problems in your code:

i is uninitialized when used in the while loop in function reverse, causing undefined behavior which could explain the segmentation fault.

j is not modified in the loop at the end of the reverse function, causing an infinite loop:

```<code>for (j = 0; j < count; i++) {
    printf("%d ", arr2[j]);
}
</code>```

you are not reversing the list, you just print the list contents in reverse order, and assume its length is at most 100.  This is probably not what you are expected to do.

in function main, the array ans should be made larger to accommodate at least the word yes, and you should prevent scanf() from storing more characters into it than would fit. Also reorganize the code to avoid duplication:

```<code>int main(void) {
    struct node *link = NULL;

    for (;;) {
        char ans[80];
        int value;

        printf("Enter the value:\n");
        if (scanf("%d", &value) != 1)
            break;
        link = insert(link, value);
        printf("Do you want to add another node? Type Yes/No\n");
        if (scanf("%79s", ans) != 1 || ans[0] != 'y') {
            break;
        }
    }
    reverse(link);
    return 0;
}
</code>```

Most of the above problems would have been spotted immediately by increasing the compiler warning level (for example gcc -Wall -Werror or clang -Weverything -Werror).

Here is a simpler version that reads numbers and allocates the list in the same order as you do, inserting each new element before the previous one, then reverses the list and finally prints it. As expected, the list is printed in the order of entry.

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

struct node {
    int data;
    struct node *next;
};

struct node *insert(struct node *head, int data) {
    struct node *newlink = malloc(sizeof(*newlink));
    newlink->data = data;
    newlink->next = head;
    return newlink;
}

struct node *reverse(struct node *link) {
    struct node *prev = NULL;
    while (link) {
        struct node *temp = link->next;
        link->next = prev;
        prev = link;
        link = temp;
    }
    return prev;
}

void print(struct node *link) {
    printf("The elements in the linked list are: ");

    for (struct node *n = link; n; n = n->next) {
        printf("%d ", n->data);
    }
    printf("\n");
}

int main(void) {
    struct node *link = NULL;
    int value;

    printf("Enter the values, end the list with 0:\n");
    while (scanf("%d", &value) == 1 && value != 0) {
        link = insert(link, value);
    }
    link = reverse(link);
    print(link);
    return 0;
}
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *insert(struct node *link, int data) {
    if (link == NULL) {
        link = (struct node *)malloc(sizeof(struct node));
        link->data = data;
        link->next = NULL;
    } else {
        struct node *newlink = (struct node *)malloc(sizeof(struct node));

        newlink->data = data;
        newlink->next = link;
        link = newlink;
    }
    return link;
}

void reverse(struct node *link) {
    int i, j = 0;
    int arr1[100], arr2[100];
    struct node *current;
    int count = 0;

    current = link;

    while (current != NULL) {
        arr1[i] = current->data;
        i = i + 1;
        count = count + 1;
        current = current->next;
    }

    printf("\n");
    i = 0;
    j = 0;

    for (i = count - 1; i >= 0; i--) {
        arr2[j] = arr1[i];
        j = j + 1;
    }

    printf("The elements in the linked list are: ");

    for (i = 0; i < count; i++) {
        printf("%d ", arr1[i]);
    }

    printf("The elements in the reversed linked list are: ");

    for (j = 0; j < count; i++) {
        printf("%d ", arr2[j]);
    }
}

void print(struct node *link) {
    struct node *temp = link;

    printf("The elements in the linked list are: ");

    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
}

void main() {
    int value;

    printf("Enter the value:\n");
    scanf("%d", &value);
    struct node *link = NULL;

    link = insert(link, value);
    char ans[3] = "yes";

    while (ans[0] == 'y') {
        printf("Do you want to add another node? Type Yes/No\n");
        scanf("%s", ans);

        if (ans[0] == 'y') {
            printf("Enter the value:\n");
            scanf("%d", &value);
            link = insert(link, value);
        } else {
            reverse(link);
        }
    }
}

Here is the code I wrote to reverse a single linked list in C. I seem to try different combinations of the program but while doing it by array method, I am unable to get rid of the segmentation fault, and hence it doesn't give output.

Body:
There are some problems in your code:

i is uninitialized when used in the while loop in function reverse, causing undefined behavior which could explain the segmentation fault.

j is not modified in the loop at the end of the reverse function, causing an infinite loop:

for (j = 0; j < count; i++) {
    printf("%d ", arr2[j]);
}

you are not reversing the list, you just print the list contents in reverse order, and assume its length is at most 100.  This is probably not what you are expected to do.

in function main, the array ans should be made larger to accommodate at least the word yes, and you should prevent scanf() from storing more characters into it than would fit. Also reorganize the code to avoid duplication:

int main(void) {
    struct node *link = NULL;

    for (;;) {
        char ans[80];
        int value;

        printf("Enter the value:\n");
        if (scanf("%d", &value) != 1)
            break;
        link = insert(link, value);
        printf("Do you want to add another node? Type Yes/No\n");
        if (scanf("%79s", ans) != 1 || ans[0] != 'y') {
            break;
        }
    }
    reverse(link);
    return 0;
}

Most of the above problems would have been spotted immediately by increasing the compiler warning level (for example gcc -Wall -Werror or clang -Weverything -Werror).

Here is a simpler version that reads numbers and allocates the list in the same order as you do, inserting each new element before the previous one, then reverses the list and finally prints it. As expected, the list is printed in the order of entry.

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *insert(struct node *head, int data) {
    struct node *newlink = malloc(sizeof(*newlink));
    newlink->data = data;
    newlink->next = head;
    return newlink;
}

struct node *reverse(struct node *link) {
    struct node *prev = NULL;
    while (link) {
        struct node *temp = link->next;
        link->next = prev;
        prev = link;
        link = temp;
    }
    return prev;
}

void print(struct node *link) {
    printf("The elements in the linked list are: ");

    for (struct node *n = link; n; n = n->next) {
        printf("%d ", n->data);
    }
    printf("\n");
}

int main(void) {
    struct node *link = NULL;
    int value;

    printf("Enter the values, end the list with 0:\n");
    while (scanf("%d", &value) == 1 && value != 0) {
        link = insert(link, value);
    }
    link = reverse(link);
    print(link);
    return 0;
}


问:
AngluarJS Reuse Functions (Where do i put them)
Lets say i want to reuse a function in angularjs that returns a specific value  but i want to call it in other parts controllers of the app so i don't rewrite it in other places (dry) , where would i put that function in an angularjs app? Would i make a service of factory for this?

Say i have two controllers and in those two controllers i want to call function foo() that returns a certain number when i pass a variable through it. Where would i put function foo() in my angular structure?

答:
With Angular 1.x you would need to create a service to make something reusable or like a utility. You can inject this to the controller you want to in a similar fashion as you would do for a http service for example. Taken from the AngularJS website, a service is defined as -

AngularJS services are substitutable objects that are wired together
  using dependency injection (DI). You can use services to organize and
  share code across your app.

You can find a very simple servic being implemented here - an example by w3schools


问:
Can I 'drop' a PHP request without replying?
I am not completely sure that this is possible from within PHP or even the HTTP protocol in depth. Is it possible to receive PHP script to run when it is requested but then the script drops the connection? Without replying?

Hopefully my question makes sense.

(I am using Apache)

答: You can use exit() or die() in the script to stop script execution, would that do what you want?

ContentLicense: CC BY-SA 2.5


问:
AddressBook like Outlook
I would like to implement a sort of AddressBook like the one in outlook as in the following picture

Can somebody help with markup and style for the address card?

答:
I made a quick example for you: You can see it live here on jsFiddle.net.

HTML:

```<code><div class="outl-add">
    <div class="outl-add-top">
       Duck, Daffy
    </div>
    <div class="outl-add-left-vert">

    </div>
    <div class="outl-add-right-info">
        <p class="info-top">
        <span class="user-name">Daffy Duck</span>
        <span>ACME International</span>
        <span>Manager</span>
        </p>
        <p class="address-info"></p>
        <span> +122323i9092<span class="grey-text">UIofcio</span>
        <p>daffy@acme.org</p>
        <p>666, 5th Avenue</p>
        <p>New York</p>
        <p>www.daffysite.com</p>
    </div>
</div>
</code>```

CSS:

```<code>.outl-add
{
    width: 400px;
    border: 1px solid #000;
}

.outl-add-top
{
    height: 25px;
    background-color: orange;
}

.outl-add-left-vert
{
    float: left;
    height: 200px;
    width: 35px;
    background-color: #ccc;
}

.outl-add-right-info
{
    height: 200px;
    float; left;
    background-color: #eee;
}

p.info-top
{
    margin-bottom: 10px;
}

p.info-top span
{
    display: block;
}

.user-name
{
    font-weight: bold;
}

.grey-text
{
    color: #ccc;
}
</code>```

Hope that helps you out some. If you have any questions about anything used here, ask them in comments or a new question relative to the problem you have :)

Title: AddressBook like Outlook

Body:
I made a quick example for you: You can see it live here on jsFiddle.net.

HTML:

<div class="outl-add">
    <div class="outl-add-top">
       Duck, Daffy
    </div>
    <div class="outl-add-left-vert">
       &nbsp;
    </div>
    <div class="outl-add-right-info">
        <p class="info-top">
        <span class="user-name">Daffy Duck</span>
        <span>ACME International</span>
        <span>Manager</span>
        </p>
        <p class="address-info"></p>
        <span> +122323i9092<span class="grey-text">UIofcio</span>
        <p>daffy@acme.org</p>
        <p>666, 5th Avenue</p>
        <p>New York</p>
        <p>www.daffysite.com</p>
    </div>
</div>

CSS:

.outl-add
{
    width: 400px;
    border: 1px solid #000;
}

.outl-add-top
{
    height: 25px;
    background-color: orange;
}

.outl-add-left-vert
{
    float: left;
    height: 200px;
    width: 35px;
    background-color: #ccc;
}

.outl-add-right-info
{
    height: 200px;
    float; left;
    background-color: #eee;
}

p.info-top
{
    margin-bottom: 10px;
}

p.info-top span
{
    display: block;
}

.user-name
{
    font-weight: bold;
}

.grey-text
{
    color: #ccc;
}

Hope that helps you out some. If you have any questions about anything used here, ask them in comments or a new question relative to the problem you have :)


问:
Spring Cloud DataFlow Local-Server 1.2.2 fails to startup on Windows 10
I'm attempting to follow the spring cloud data flow tutorial at this link http://cloud.spring.io/spring-cloud-dataflow/#quick-start.

When at Step 2, executing the following line

```<code>java -jar spring-cloud-dataflow-server-local-1.2.2.RELEASE.jar
</code>```

Results in the following exception:

2017-07-01 16:21:00.218  WARN 3224 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService' defined in class path resource [org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.class]: Unsatisfied dependency expressed through method 'taskService' parameter 5; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskLauncher' defined in class path resource [org/springframework/cloud/deployer/spi/local/LocalDeployerAutoConfiguration.class]: Unsatisfied dependency expressed through method 'taskLauncher' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.cloud.deployer.local-org.springframework.cloud.deployer.spi.local.LocalDeployerProperties': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.deployer.spi.local.LocalDeployerProperties]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Java executable discovered via 'java.home' system property 'C:\Program Files\Java\jdk1.8.0_131\jre' is not executable or does not exist.

I think the key is the 'c:\program files\java\jdk1.8.0_131\jre' appears to be the wrong path to the java binaries. I would expect this to be the %JRE_HOME%\bin directory.

I wrote a small program to dump the system properties which produced the following:

java.home: C:\Program Files\Java\jdk1.8.0_131\jre

My JAVA_HOME, JRE_HOME, CLASSPATH and JDK_HOME environment variables are set as following

```<code>JAVA_HOME C:\Program Files\Java\jdk1.8.0_131
JDK_HOME %JAVA_HOME%
JRE_HOME %JAVA_HOME%\jre
CLASSPATH .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
</code>```

The PATH variable is set to %JAVA_HOME%\bin

I have restarted my command prompt several times.

When I run the following command for the 1.1.4 version, the server starts up without error:

```<code>java -jar spring-cloud-dataflow-server-local-1.1.4.RELEASE.jar
</code>```

I have tried to remove the JRE_HOME variable and have CLASSPATH set to .

Update: Adding output of dir c:\java.exe /s /b

```<code>c:\Program Files\Java\jdk1.8.0_131\bin\java.exe
c:\Program Files\Java\jdk1.8.0_131\jre\bin\java.exe
c:\Program Files\Java\jre1.8.0_131\bin\java.exe
c:\Program Files (x86)\Java\jre1.8.0_131\bin\java.exe
c:\ProgramData\Oracle\Java\javapath\java.exe
c:\ProgramData\Oracle\Java\javapath_target_260505593\java.exe
c:\Users\All Users\Oracle\Java\javapath\java.exe
c:\Users\All Users\Oracle\Java\javapath_target_260505593\java.exe
</code>```

答:
This is a bug: (impacts 1.2.2.RELEASE only and is fixed by 1.2.3.RELEASE)

https://github.com/spring-cloud/spring-cloud-deployer-local/issues/58

"Work around" solution is to goto the JRE path of java on your system and to run the following command

(note to other users to find your java path type echo %JAVA_HOME% in command prompt window, if there is a 'jdk' in the java home path make sure to alter it to 'jre' for the 'cd' command below. We need to navigate to the jre dir not jdk we also appended '\bin')

Navigate to the JRE's bin directory

cd C:\Program Files\Java\jre1.8.0_131\bin    (notice: in the path "jre1.8" not jdk)

Make a copy of 'java.exe' called 'java' in this this same directory

copy java.exe java

Summary of Bug/Workaround:

the bug is basically... the developers were expecting the java executable to be called java and not java.exe as it is named on Windows OS. So the workaround is to make a copy of java.exe and name it java in that JRE's bin directory...

not sure how something like this makes it to production release though... :/

Body:
I'm attempting to follow the spring cloud data flow tutorial at this link http://cloud.spring.io/spring-cloud-dataflow/#quick-start.

When at Step 2, executing the following line

java -jar spring-cloud-dataflow-server-local-1.2.2.RELEASE.jar

Results in the following exception:

2017-07-01 16:21:00.218  WARN 3224 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService' defined in class path resource [org/springframework/cloud/dataflow/server/config/features/TaskConfiguration.class]: Unsatisfied dependency expressed through method 'taskService' parameter 5; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskLauncher' defined in class path resource [org/springframework/cloud/deployer/spi/local/LocalDeployerAutoConfiguration.class]: Unsatisfied dependency expressed through method 'taskLauncher' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.cloud.deployer.local-org.springframework.cloud.deployer.spi.local.LocalDeployerProperties': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.deployer.spi.local.LocalDeployerProperties]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Java executable discovered via 'java.home' system property 'C:\Program Files\Java\jdk1.8.0_131\jre' is not executable or does not exist.

I think the key is the 'c:\program files\java\jdk1.8.0_131\jre' appears to be the wrong path to the java binaries. I would expect this to be the %JRE_HOME%\bin directory.

I wrote a small program to dump the system properties which produced the following:

java.home: C:\Program Files\Java\jdk1.8.0_131\jre

My JAVA_HOME, JRE_HOME, CLASSPATH and JDK_HOME environment variables are set as following

JAVA_HOME C:\Program Files\Java\jdk1.8.0_131
JDK_HOME %JAVA_HOME%
JRE_HOME %JAVA_HOME%\jre
CLASSPATH .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib

The PATH variable is set to %JAVA_HOME%\bin

I have restarted my command prompt several times.

When I run the following command for the 1.1.4 version, the server starts up without error:

java -jar spring-cloud-dataflow-server-local-1.1.4.RELEASE.jar

I have tried to remove the JRE_HOME variable and have CLASSPATH set to .

Update: Adding output of dir c:\java.exe /s /b

c:\Program Files\Java\jdk1.8.0_131\bin\java.exe
c:\Program Files\Java\jdk1.8.0_131\jre\bin\java.exe
c:\Program Files\Java\jre1.8.0_131\bin\java.exe
c:\Program Files (x86)\Java\jre1.8.0_131\bin\java.exe
c:\ProgramData\Oracle\Java\javapath\java.exe
c:\ProgramData\Oracle\Java\javapath_target_260505593\java.exe
c:\Users\All Users\Oracle\Java\javapath\java.exe
c:\Users\All Users\Oracle\Java\javapath_target_260505593\java.exe


问:
How to undelete file in git and keep his original blame history ?
I'v accidentally removed a file (I wasn't his creator) and commit and push it to the remote. Now I want to make git to undelete this change but when I use git revert #mistaken commit it works BUT blame information points at me as the creator of this file not for his original creator. Can anyone knows how to undelete this file in git and keep its original blame history ?
Thanks in advance for any help.
Adam</p>

答:
Sure... you revert but the file is "new" (it didn't exist on the previous revision... so who's to blame for the new lines? Of course it's you). If you want to keep the file as it was (with blame and everything) why don't you just amend the revision where you deleted it? Say you have something like this:

REV1--REV2--REV3--REV4--REV5--REV6--REV7--REV8

Say it was on REV3 where you deleted it and on REV6 you reverted REV3. Try this instead:

```<code>git checkout REV3
git checkout HEAD~1 -- <path-to-file> # get file back from its ashes
git commit --amend --no-edit # created a new REV3 revision that has the file
git cherry-pick REV3..REV5
git cherry-pick REV6..REV8
</code>```

when you amend REV3 you will get a different ID for the revision from the original REV3. When you cherry-pick on the following command make sure to use the original REV3 ID, not the new one. REV6 won't be applied (because you don't need it anymore). When you are done now you have an alternate branch where the file was never gone and now blame should show you the original revisions for the lines. Feel free to push the new branch if you like it better.

Body:
Sure... you revert but the file is "new" (it didn't exist on the previous revision... so who's to blame for the new lines? Of course it's you). If you want to keep the file as it was (with blame and everything) why don't you just amend the revision where you deleted it? Say you have something like this:

REV1--REV2--REV3--REV4--REV5--REV6--REV7--REV8

Say it was on REV3 where you deleted it and on REV6 you reverted REV3. Try this instead:

git checkout REV3
git checkout HEAD~1 -- <path-to-file> # get file back from its ashes
git commit --amend --no-edit # created a new REV3 revision that has the file
git cherry-pick REV3..REV5
git cherry-pick REV6..REV8

when you amend REV3 you will get a different ID for the revision from the original REV3. When you cherry-pick on the following command make sure to use the original REV3 ID, not the new one. REV6 won't be applied (because you don't need it anymore). When you are done now you have an alternate branch where the file was never gone and now blame should show you the original revisions for the lines. Feel free to push the new branch if you like it better.


问:
size of array of integer pointers
```<code>#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}
</code>```

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?

答:
You are on a 16 bit system

All three numbers are consistent with each other. But you seem to be using a 16 bit system. So your pointers use 2 bytes. And 5 elements times 2 bytes each equals 10 bytes in total.

Title: size of array of integer pointers

Body:
#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?


问:
Tensorflow doesn't seem to see my gpu
I've tried tensorflow on both cuda 7.5 and 8.0, w/o cudnn (my GPU is old, cudnn doesn't support it).

When I execute device_lib.list_local_devices(), there is no gpu in the output. Theano sees my gpu, and works fine with it, and examples in /usr/share/cuda/samples work fine as well.

I installed tensorflow through pip install. Is my gpu too old for tf to support it? gtx 460

答:
I came across this same issue in jupyter notebooks. This could be an easy fix.

```<code>$ pip uninstall tensorflow
$ pip install tensorflow-gpu
</code>```

You can check if it worked with:

```<code>tf.test.gpu_device_name()
</code>```

Update 2020

It seems like tensorflow 2.0+ comes with gpu capabilities therefore
pip install tensorflow should be enough

Title: Tensorflow doesn't seem to see my gpu

Body:
I came across this same issue in jupyter notebooks. This could be an easy fix.

$ pip uninstall tensorflow
$ pip install tensorflow-gpu

You can check if it worked with:

tf.test.gpu_device_name()

Update 2020

It seems like tensorflow 2.0+ comes with gpu capabilities therefore
pip install tensorflow should be enough

ContentLicense: CC BY-SA 4.0


问:
change Geom_smooth default legend color
I am using geom_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom_smooth legend line?

for example, I wand to change the legend colour to black for line type in the following plot

```<code>      library(reshape2)
    library(ggplot2)
d1<-melt(mtcars,id=c("mpg","cyl"))
        p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl))
        p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
          scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3))
</code>```

答:
Per my comment, if you add an override to your legend you can change how the color displays. This should work:

```<code>p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
  scale_linetype_manual("line type",labels = c("100 yr", "50 yr", "25 yr"), values=c(1,5,4,3)) +
  guides(linetype = guide_legend(override.aes= list(color = "black")))
</code>```

And the resulting plot is:

Title: change Geom_smooth default legend color

Body:
I am using geom_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom_smooth legend line?

for example, I wand to change the legend colour to black for line type in the following plot

      library(reshape2)
    library(ggplot2)
d1<-melt(mtcars,id=c("mpg","cyl"))
        p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl))
        p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
          scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3))

Body:
Per my comment, if you add an override to your legend you can change how the color displays. This should work:

p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5,  inherit.aes = T)+
  scale_linetype_manual("line type",labels = c("100 yr", "50 yr", "25 yr"), values=c(1,5,4,3)) +
  guides(linetype = guide_legend(override.aes= list(color = "black")))

And the resulting plot is:


问:
Oracle Preparations
I am new to oracle.can anyone tell me the books and web sites suitable to learn oracle ?</p>

答:
The Oracle manual:
http://www.oracle.com/pls/db111/portal.all_books</p>

Title: Oracle Preparations


问:
mypy: Cannot infer type argument 1 of "map"
When trying to check the following code using mypy:

```<code>import itertools
from typing import Sequence, Union, List

DigitsSequence = Union[str, Sequence[Union[str, int]]]

def normalize_input(digits: DigitsSequence) -> List[str]:
    try:
        new_digits = list(map(str, digits))  # <- Line 17
        if not all(map(str.isdecimal, new_digits)):
            raise TypeError
    except TypeError:
        print("Digits must be an iterable containing strings.")
        return []
    return new_digits
</code>```

mypy throws the following errors:

calculate.py:17: error: Cannot infer type argument 1 of "map"

Why does this error occur? How can I fix it?

Thanks :)

Edit: It was actually a bug in mypy, and it's fixed now.

答:
As you may already know, mypy depends on typeshed to stub the classes and functions in Python's standard library. I believe your issue this has to do with typeshed's stubbing of map:

```<code>@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ...
</code>```

And that the current state of mypy is such that its type inference is not unbounded. (The project also has over 600 open issues.)

I believe your problem may be related to issue #1855. I believe this to be the case because DigitsSequence = str and DigitsSequence = Sequence[int] both work whereas DigitsSequence = Union[str, Sequence[int]] does not.

Some workarounds:

Use a lambda expression instead:

```<code>new_digits = list(map(lambda s: str(s), digits))
</code>```

Re-cast to a new variable:

```<code>any_digits = digits # type: Any
new_digits = list(map(str, any_digits))
</code>```

Ask mypy to ignore the line:

```<code>new_digits = list(map(str, digits)) # type: ignore
</code>```

Body:
When trying to check the following code using mypy:

import itertools
from typing import Sequence, Union, List

DigitsSequence = Union[str, Sequence[Union[str, int]]]

def normalize_input(digits: DigitsSequence) -> List[str]:
    try:
        new_digits = list(map(str, digits))  # <- Line 17
        if not all(map(str.isdecimal, new_digits)):
            raise TypeError
    except TypeError:
        print("Digits must be an iterable containing strings.")
        return []
    return new_digits

mypy throws the following errors:

calculate.py:17: error: Cannot infer type argument 1 of "map"

Why does this error occur? How can I fix it?

Thanks :)

Edit: It was actually a bug in mypy, and it's fixed now.

Body:
As you may already know, mypy depends on typeshed to stub the classes and functions in Python's standard library. I believe your issue this has to do with typeshed's stubbing of map:

@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ...

And that the current state of mypy is such that its type inference is not unbounded. (The project also has over 600 open issues.)

I believe your problem may be related to issue #1855. I believe this to be the case because DigitsSequence = str and DigitsSequence = Sequence[int] both work whereas DigitsSequence = Union[str, Sequence[int]] does not.

Some workarounds:

Use a lambda expression instead:

new_digits = list(map(lambda s: str(s), digits))

Re-cast to a new variable:

any_digits = digits # type: Any
new_digits = list(map(str, any_digits))

Ask mypy to ignore the line:

new_digits = list(map(str, digits)) # type: ignore


问:
How to normalize the datasets in R programming?
I implemented the below code to normalize my data frame in R. But I am getting the below error

```<code>for(i in 1:56){
  clean_data[(clean_data[,i]),i] <-(clean_data[,i] - min(clean_data[,i])) / (max(clean_data[,i]) - min(clean_data[,i]))
}
</code>```

Error

```<code>Error: cannot allocate vector of size 9.9 Gb
</code>```

Is there any other way to implement the normalization? can anyone help me?

答:
You could use this snippet as an improvement to your code

```<code>max_col <- apply(clean_data[,-1], 2, max)
min_col <- apply(clean_data[,-1], 2, min)
clean_data_scaled <- as.data.frame(scale(clean_data[,-1], center = min_col, scale = max_col - min_col))
</code>```

OR

```<code>clean_data_scaled <- scale(clean_data[, -1])
</code>```

Body:
I implemented the below code to normalize my data frame in R. But I am getting the below error

for(i in 1:56){
  clean_data[(clean_data[,i]),i] <-(clean_data[,i] - min(clean_data[,i])) / (max(clean_data[,i]) - min(clean_data[,i]))
}

Error

Error: cannot allocate vector of size 9.9 Gb

Is there any other way to implement the normalization? can anyone help me?

Body:
You could use this snippet as an improvement to your code

max_col <- apply(clean_data[,-1], 2, max)
min_col <- apply(clean_data[,-1], 2, min)
clean_data_scaled <- as.data.frame(scale(clean_data[,-1], center = min_col, scale = max_col - min_col))

OR

clean_data_scaled <- scale(clean_data[, -1])


问:
Special cases for table.remove
The reference manual of table.remove says:

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].

The last two special cases where pos is 0 or #list + 1 interests me.

Example code of pos being 0:

```<code>local t1 = {[0] = 'foo'}
table.remove(t1, 0)
</code>```

In this case, the element t1[0] is removed.

Example code of pos being #list + 1:

```<code>local t2 = {'foo', 'bar', 'baz'}
table.remove(t2, #t2 + 1)
</code>```

In this case, nothing is changed, except that the statement won't raise error.

Is my understanding correct? When are theses two special cases useful in practice?

I also noted that the two cases are added since Lua 5.2

答:
The last two special cases help set and define boundaries in the 5.2 version.  There are other changes to table.remove that are relevant to why this is done.  Take a look!

```<code>-- Lua 5.1 version
t = {'foo', 'bar' , 'baz'}

local v = table.remove(t, 1)
print(v)
>>nil
table.remove(t, 7)
-- no crash or error message
</code>```

```<code>-- Lua 5.2 version
t = {'foo', 'bar' , 'baz'}

local v = table.remove(t, 1)
print(v)
>>foo
table.remove(t, 7)
>>stdin:1 bad argument #1 to 'remove' (position out of bounds)
</code>```

When the user calls table.remove in 5.2, the value is removed from the table and is returned.  In 5.1, the value is only removed.
 Additionally in the 5.2 version an error message is generated when the user tries to remove an element from a position that is out of bounds.

What does this have to do with the special cases?  Well for one if they didn't include

The index pos can also be 0 when #list is 0

to the argument, then when using table.remove(t) on an empty table it would crash.  Keep in mind that tables are heterogeneous and in a lot of cases are used both as an array and hash map at the same time!  Sometimes it is desired to get rid of the array portion while retaining the hash map.  To that end,

```<code>while table.remove(t) do end  -- ends when the t runs out of elements at t[0]
</code>```

There is a caveat though!  If #list > 0 when using table.remove(list, 0) it will crash!  The #list has to be equal to 0.

```<code>-- Lua 5.2 version
t = {'foo', 'bar' , 'baz'}

table.remove(t, 0) -- #t is 3
>>stdin:1 bad argument #1 to 'remove' (position out of bounds)
table.remove(t)    -- baz
table.remove(t)    -- bar
table.remove(t)    -- foo
-- #t is now 0
table.remove(t, 0) -- nil
-- nothing happens
</code>```

The last special case #list + 1 is just to make the syntax cleaner when trimming a list.  Instead of having to do a for loop to erase elements to pos you can just,

```<code>-- 7 is just a random number I picked
while table.remove(t, 7) do end  -- this will end when the t[7] = nil (aka #t + 1)
</code>```

Hopefully this was helpful!

Title: Special cases for table.remove

Body:
The reference manual of table.remove says:

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].

The last two special cases where pos is 0 or #list + 1 interests me.

Example code of pos being 0:

local t1 = {[0] = 'foo'}
table.remove(t1, 0)

In this case, the element t1[0] is removed.

Example code of pos being #list + 1:

local t2 = {'foo', 'bar', 'baz'}
table.remove(t2, #t2 + 1)

In this case, nothing is changed, except that the statement won't raise error.

Is my understanding correct? When are theses two special cases useful in practice?

I also noted that the two cases are added since Lua 5.2

Body:
The last two special cases help set and define boundaries in the 5.2 version.  There are other changes to table.remove that are relevant to why this is done.  Take a look!

-- Lua 5.1 version
t = {'foo', 'bar' , 'baz'}

local v = table.remove(t, 1)
print(v)
>>nil
table.remove(t, 7)
-- no crash or error message

-- Lua 5.2 version
t = {'foo', 'bar' , 'baz'}

local v = table.remove(t, 1)
print(v)
>>foo
table.remove(t, 7)
>>stdin:1 bad argument #1 to 'remove' (position out of bounds)

When the user calls table.remove in 5.2, the value is removed from the table and is returned.  In 5.1, the value is only removed.
 Additionally in the 5.2 version an error message is generated when the user tries to remove an element from a position that is out of bounds.

What does this have to do with the special cases?  Well for one if they didn't include

The index pos can also be 0 when #list is 0

to the argument, then when using table.remove(t) on an empty table it would crash.  Keep in mind that tables are heterogeneous and in a lot of cases are used both as an array and hash map at the same time!  Sometimes it is desired to get rid of the array portion while retaining the hash map.  To that end,

while table.remove(t) do end  -- ends when the t runs out of elements at t[0]

There is a caveat though!  If #list > 0 when using table.remove(list, 0) it will crash!  The #list has to be equal to 0.

-- Lua 5.2 version
t = {'foo', 'bar' , 'baz'}

table.remove(t, 0) -- #t is 3
>>stdin:1 bad argument #1 to 'remove' (position out of bounds)
table.remove(t)    -- baz
table.remove(t)    -- bar
table.remove(t)    -- foo
-- #t is now 0
table.remove(t, 0) -- nil
-- nothing happens

The last special case #list + 1 is just to make the syntax cleaner when trimming a list.  Instead of having to do a for loop to erase elements to pos you can just,

-- 7 is just a random number I picked
while table.remove(t, 7) do end  -- this will end when the t[7] = nil (aka #t + 1)

Hopefully this was helpful!


问:
Bottom navigation view text
I have a bottom navigation view in my Main Activity and I want to change it to show the icon and the text only for the selected item and to show only the icons of the other 2 items.
I had an idea to change it in the code on click and set the other to items to empty string with this code:

```<code>    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                //set text to home
                return true;
            case R.id.navigation_dashboard:
                //set to empty string
                return true;
            case R.id.navigation_notifications:
                //set to empty string
                return true;
        }
        return false;
    }
</code>```

But I can't get to the textview of the item from the code...
What can I do?

答:
Well, Here is what you want, Set other two text empty while selecting the current text :</p>

```<code>@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.navigation_home:
            //set text to home
            //set dashbord empty
            //set notification empty
            return true;
        case R.id.navigation_dashboard:
            //set text to dashbord
            //set home empty
            //set notification empty
            return true;
        case R.id.navigation_notifications:
            //set text to notification
            //set dashbord empty
            //set home empty
            return true;
    }
    return false;
}
</code>```

Title: Bottom navigation view text

Body:
I have a bottom navigation view in my Main Activity and I want to change it to show the icon and the text only for the selected item and to show only the icons of the other 2 items.
I had an idea to change it in the code on click and set the other to items to empty string with this code:

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                //set text to home
                return true;
            case R.id.navigation_dashboard:
                //set to empty string
                return true;
            case R.id.navigation_notifications:
                //set to empty string
                return true;
        }
        return false;
    }

But I can't get to the textview of the item from the code...
What can I do?

Body:
Well, Here is what you want, Set other two text empty while selecting the current text :

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.navigation_home:
            //set text to home
            //set dashbord empty
            //set notification empty
            return true;
        case R.id.navigation_dashboard:
            //set text to dashbord
            //set home empty
            //set notification empty
            return true;
        case R.id.navigation_notifications:
            //set text to notification
            //set dashbord empty
            //set home empty
            return true;
    }
    return false;
}


问:
host ansible tower behind nginx
On the official page, it is said that to host ansible tower behind nginx, you need to provide headers in the /etc/tower/conf.d/remote_host_headers.py file.

But, in my /etc/tower/ folder, there is no conf.d/remote_host_headers.py file.

```<code>awx@server:/etc/tower$ tree
.
├── conf.d
│   ├── caching.py
│   ├── celeryd.py
│   ├── ha.py
│   ├── postgres.py
│   └── rabbitmq.py
├── SECRET_KEY
├── settings.py
├── settings.py.20170629122404
├── tower.cert
└── tower.key
</code>```

How can I host ansible tower via nginx  ?

答:
I'm not sure why you don't have that file, but I do:

This is it's content:

```<code># HTTP headers and meta keys to search to determine remote host name or IP. Add
# additional items to this list, such as "HTTP_X_FORWARDED_FOR", if behind a
# reverse proxy.
# Note: The headers will be searched in order and the first found remote host
# name or IP will be used.
#
# In the below example 8.8.8.7 would be the chosen IP address.
# X-Forwarded-For: 8.8.8.7, 192.168.2.1, 127.0.0.1
# Host: 127.0.0.1
# REMOTE_HOST_HEADERS = ['HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'REMOTE_HOST']

# This setting is now configured via the Tower API.
# REMOTE_HOST_HEADERS = ['REMOTE_ADDR', 'REMOTE_HOST']

REMOTE_HOST_HEADERS = ['HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'REMOTE_HOST']
</code>```

This last line is what you want, specifically 'HTTP_X_FORWARDED_FOR' - it tells Tower what IP address is being used beyond your reverse proxy as Tower uses IP Addresses for Session association.

Documentation is here.

Michael

Title: host ansible tower behind nginx

Body:
On the official page, it is said that to host ansible tower behind nginx, you need to provide headers in the /etc/tower/conf.d/remote_host_headers.py file.

But, in my /etc/tower/ folder, there is no conf.d/remote_host_headers.py file.

awx@server:/etc/tower$ tree
.
├── conf.d
│   ├── caching.py
│   ├── celeryd.py
│   ├── ha.py
│   ├── postgres.py
│   └── rabbitmq.py
├── SECRET_KEY
├── settings.py
├── settings.py.20170629122404
├── tower.cert
└── tower.key

How can I host ansible tower via nginx  ?

Body:
I'm not sure why you don't have that file, but I do:

This is it's content:

# HTTP headers and meta keys to search to determine remote host name or IP. Add
# additional items to this list, such as "HTTP_X_FORWARDED_FOR", if behind a
# reverse proxy.
# Note: The headers will be searched in order and the first found remote host
# name or IP will be used.
#
# In the below example 8.8.8.7 would be the chosen IP address.
# X-Forwarded-For: 8.8.8.7, 192.168.2.1, 127.0.0.1
# Host: 127.0.0.1
# REMOTE_HOST_HEADERS = ['HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'REMOTE_HOST']

# This setting is now configured via the Tower API.
# REMOTE_HOST_HEADERS = ['REMOTE_ADDR', 'REMOTE_HOST']

REMOTE_HOST_HEADERS = ['HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'REMOTE_HOST']

This last line is what you want, specifically 'HTTP_X_FORWARDED_FOR' - it tells Tower what IP address is being used beyond your reverse proxy as Tower uses IP Addresses for Session association.

Documentation is here.

Michael


问:
Incorrrect Merge, Instead of merging A to B I merged B to A in GIT LAB
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

```<code>Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.
</code>```

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

```<code>Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.
</code>```

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2

答:
Just for the benefit of others that may tread on this thread, here is my spiel. Note: All manipulations were done in ** Local Repo although you can do this in ** remote Repo in Git Lab. Once the merge was complete as shown in diagram 1 in original thread:

Create a new branch from the merged branch BUT name it as Branch A or any name that you initially intended it to be. git branch <branch name e.g Branch A>

Checkout the branch git checkout <branch name eg Branch A>. Now your new checked out branch and your Branch B would essentially be the same since there are no code changes since the last merge of branches.

Delete the branch where the merges were from both Local and Remote. git push origin --delete <your remote branch name e.g feature A>  and follow it up with git branch -d <your local branch name e.g feature A>

Confirm if this is what you want before pushing it to remote repo by git branch --list and then git branch -a.
No worries about history even if you delete these branches since when you push in your commits next time it will show that there was a merge of code and your most recent branch Branch A will have all your changes in it just as you merged branch. It works almost like pointers in C language. The variable name is gone but since you copied the pointer to another name, the address of your change is still intact.

Body:
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2


问:
Is there a way to backup my docker environment
I am using Ubuntu 14.04 and running some docker containers and images with a python script.Now i have to reinstall that into another Ubuntu machine.

```<code>Ex: that machine is not even having docker installed
</code>```

Is there a way to backup complete docker engine from my configured machine to another machine

答:
The locations to backup vary on how you are running containers and what environment you are restoring to. Some directories to backup include:

/var/lib/docker: this includes all the images, containers, plugins, and swarm settings

/etc/docker: this includes any customizations in daemon.json and is commonly used for TLS certificates

/etc/systemd/system/docker*: you may have customized the startup scripts in this location

What this doesn't include are any container specific host volumes you've mounted to various locations on the host file system. You can look for these directories with:

```<code>$ docker ps -q | xargs docker inspect -f '{{.Name}}:
{{ range .HostConfig.Binds }}{{.}}
{{end}}
'
</code>```

If you are changing your target server in some way, e.g. changing the kernel running a different version of linux, there's a chance you'll change your storage driver, which will result in your old images and containers becoming inaccessible. In that case, to copy images I'd recommend using a registry server to push your images too and pull them down on the new host. The registry server can be run in a container fairly easily and is the preferred way to move images between hosts. If you cannot use a registry server for some reason, you can use docker save on the old host and docker load on the new host to save the images to a tar file and import them.

With a platform change, after copying images, you will still need to copy volumes in /var/lib/docker/volumes and any other host locations. Then you'll need to copy the container configuration, preferably with a docker-compose.yml, to restart the containers on the new host.

Body:
I am using Ubuntu 14.04 and running some docker containers and images with a python script.Now i have to reinstall that into another Ubuntu machine.

Ex: that machine is not even having docker installed

Is there a way to backup complete docker engine from my configured machine to another machine

Body:
The locations to backup vary on how you are running containers and what environment you are restoring to. Some directories to backup include:

/var/lib/docker: this includes all the images, containers, plugins, and swarm settings

/etc/docker: this includes any customizations in daemon.json and is commonly used for TLS certificates

/etc/systemd/system/docker*: you may have customized the startup scripts in this location

What this doesn't include are any container specific host volumes you've mounted to various locations on the host file system. You can look for these directories with:

$ docker ps -q | xargs docker inspect -f '{{.Name}}:
{{ range .HostConfig.Binds }}{{.}}
{{end}}
'

If you are changing your target server in some way, e.g. changing the kernel running a different version of linux, there's a chance you'll change your storage driver, which will result in your old images and containers becoming inaccessible. In that case, to copy images I'd recommend using a registry server to push your images too and pull them down on the new host. The registry server can be run in a container fairly easily and is the preferred way to move images between hosts. If you cannot use a registry server for some reason, you can use docker save on the old host and docker load on the new host to save the images to a tar file and import them.

With a platform change, after copying images, you will still need to copy volumes in /var/lib/docker/volumes and any other host locations. Then you'll need to copy the container configuration, preferably with a docker-compose.yml, to restart the containers on the new host.


问:
Cannot create directory /home/hadoop/hadoopinfra/hdfs/namenode/current
I get the error

```<code>Cannot create directory /home/hadoop/hadoopinfra/hdfs/namenode/current
</code>```

While trying to install hadoop on my local Mac.

What could be the reason for this? Just for reference, I'm putting my xml files down below:

mapred-site.xml:

```<code><configuration>

   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>
</code>```

hdfs-site.xml:

```<code><configuration>
    <property>
      <name>dfs.replication</name>
      <value>1</value>
    </property>

   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode </value>
   </property>

   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value>
   </property>
</configuration>
</code>```

core-site.xml:

```<code><configuration>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/usr/local/Cellar/hadoop/hdfs/tmp</value>
    <description>A base for other temporary directories.</description>
  </property>
  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
  </property>
</configuration>
</code>```

I think my problem lies in my hdfs-site.xml file, but I'm not sure how to pinpoint/change it.

I'm using this tutorial, and "hadoop" in the file path is replaced by my username.

答:
I had this problem too and it was a permission problem. I just did:

sudo chmod 777 /home/hadoop/hadoopinfra/hdfs/namenode/

and works!

Body:
I get the error

Cannot create directory /home/hadoop/hadoopinfra/hdfs/namenode/current

While trying to install hadoop on my local Mac.

What could be the reason for this? Just for reference, I'm putting my xml files down below:

mapred-site.xml:

<configuration>

   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>

hdfs-site.xml:

<configuration>
    <property>
      <name>dfs.replication</name>
      <value>1</value>
    </property>

   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode </value>
   </property>

   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode </value>
   </property>
</configuration>

core-site.xml:

<configuration>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/usr/local/Cellar/hadoop/hdfs/tmp</value>
    <description>A base for other temporary directories.</description>
  </property>
  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
  </property>
</configuration>

I think my problem lies in my hdfs-site.xml file, but I'm not sure how to pinpoint/change it.

I'm using this tutorial, and "hadoop" in the file path is replaced by my username.


问:
Why doesn't my selection sort algorithm do what it's supposed to (java)?
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

```<code>public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(c<A.length) {
            if(x>A[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}
</code>```

But I get a weird output:

```<code>0 0 0 0 0 2 2
</code>```

答:
Your findMIN function always returns min value of the myArray starting from ith index. You are getting first 5 values 0 because, myArray[4] contains 0. Then for the last two digits you are getting 2 because from myArray[5] to myArray[6] min value is 2.

Just after finding min value in your findMIN function you should swap this value with the initial index 'c' you passed into the function. In that case next time when you call findMIN function it will exclude that min value you got earlier.

As you did not want to see any implementation I try to say the solution in words. Hope it helps you.

Body:
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(cA[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}

But I get a weird output:

0 0 0 0 0 2 2


答:
You don't swap elements when you find the minimum.
Try this fix

```<code>static int findMIN(int[] A, int c) {
    int x = A[c];
    int min_index = c;
    for(int i=c; i<A.length; i++) {
        if(x>A[i]) {
            x=A[i];
            min_index = i;
        }
    }
    A[min_index] =  A[c];
    A[c] = A[min_index];
    return x;
}
</code>```

Also know that Selection Sort is an in place algorithm, so you don't need a separate empty array to sort.

Title: Why doesn't my selection sort algorithm do what it's supposed to (java)?

Body:
You don't swap elements when you find the minimum.
Try this fix

static int findMIN(int[] A, int c) {
    int x = A[c];
    int min_index = c;
    for(int i=c; i<A.length; i++) {
        if(x>A[i]) {
            x=A[i];
            min_index = i;
        }
    }
    A[min_index] =  A[c];
    A[c] = A[min_index];
    return x;
}

Also know that Selection Sort is an in place algorithm, so you don't need a separate empty array to sort.


问:
Spring Integration - Apache ActiveMQ to Kafka
I am using the below configuration for integrating activemq with kafka. I receive message from activemq and forwards it to kafka. However, i am noticing that messages are getting dequeued from JMS Queue but messages are not going to kafka.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />

    <integration:channel id="helloChannel" />

    <integration:service-activator id="sayHelloServiceActivator"
        input-channel="helloChannel" ref="sayHelloService" method="sayHello" />

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="template"
        auto-startup="false" sync="true" channel="helloChannel" topic="test1234"
        >
    </int-kafka:outbound-channel-adapter>

    <bean id="template" class="org.springframework.kafka.core.KafkaTemplate">
        <constructor-arg>
            <bean class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
                <constructor-arg>
                    <map>
                        <entry key="bootstrap.servers" value="localhost:9092" />
                        <!--entry key="retries" value="5" /> <entry key="batch.size" value="16384"
                            /> <entry key="linger.ms" value="1" /> <entry key="buffer.memory" value="33554432"
                            /> < entry key="key.serializer" value="org.apache.kafka.common.serialization.StringSerializer"
                            /> <entry key="value.serializer" value="org.apache.kafka.common.serialization.StringSerializer"
                            / -->
                    </map>
                </constructor-arg>
            </bean>
        </constructor-arg>
    </bean>

</beans>
</code>```

Also, in case there is any issue from Kafka, it is not even reporting any exception stack trace.

Did i miss anything ?

答:
Your messages are consumed by sayHelloServiceActivator.

So change your helloChannel channel type to

```<code><publish-subscribe-channel id="helloChannel"/>
</code>```

Default is DirectChannel

The DirectChannel has point-to-point semantics but otherwise is more
  similar to the PublishSubscribeChannel than any of the queue-based
  channel implementations described above. It implements the
  SubscribableChannel interface instead of the PollableChannel
  interface, so it dispatches Messages directly to a subscriber. As a
  point-to-point channel, however, it differs from the
  PublishSubscribeChannel in that it will only send each Message to a
  single subscribed MessageHandler.

Body:
I am using the below configuration for integrating activemq with kafka. I receive message from activemq and forwards it to kafka. However, i am noticing that messages are getting dequeued from JMS Queue but messages are not going to kafka.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />

    <integration:channel id="helloChannel" />

    <integration:service-activator id="sayHelloServiceActivator"
        input-channel="helloChannel" ref="sayHelloService" method="sayHello" />

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="template"
        auto-startup="false" sync="true" channel="helloChannel" topic="test1234"
        >
    </int-kafka:outbound-channel-adapter>

    <bean id="template" class="org.springframework.kafka.core.KafkaTemplate">
        <constructor-arg>
            <bean class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
                <constructor-arg>
                    <map>
                        <entry key="bootstrap.servers" value="localhost:9092" />

                    </map>
                </constructor-arg>
            </bean>
        </constructor-arg>
    </bean>

</beans>

Also, in case there is any issue from Kafka, it is not even reporting any exception stack trace.

Did i miss anything ?

Body:
Your messages are consumed by sayHelloServiceActivator.

So change your helloChannel channel type to

<publish-subscribe-channel id="helloChannel"/>

Default is DirectChannel

The DirectChannel has point-to-point semantics but otherwise is more
  similar to the PublishSubscribeChannel than any of the queue-based
  channel implementations described above. It implements the
  SubscribableChannel interface instead of the PollableChannel
  interface, so it dispatches Messages directly to a subscriber. As a
  point-to-point channel, however, it differs from the
  PublishSubscribeChannel in that it will only send each Message to a
  single subscribed MessageHandler.


问:
Is Event Sourcing applicable for batch inputs?
I have a use case where the inputs to the application comes in batches of XML files. For example, a nightly batch of bank transactions. I am trying to see if I can use event sourcing to create a log of events. Based on what I read so far, the examples seems to be based on user driven input (click streams, updates from a user interface etc.,). Is event sourcing using a distributed log mechanism(like Kafka) a valid approach for batch/file based inputs?

Below is the approach I would like to take:

Accept input as a batch in file/xml

Run some basic validations in the memory.

Convert the batch input into a series of events

Write the event log to a Kafka topic(s).

Use the event log to store the data into the database, send the events
to a search engine, update caches, run spark jobs to do aggregations
etc.,

Repeat the process for other incoming batches.

If this approach is not efficient, what other options are available for distributed processing of such inputs?

答: If each individual event in these xml files has a timestamp then you can think of the output to Kafka as just a steam of late arriving events. Kafka allows you to set the event time on these messages to be the timestamp of the event rather than the time it was ingested to Kafka. In that way, any downstream processing apps like Kafka Streams can put the event into the right temporal context and aggregate into the proper time windows or session windows or even join with other realtime inputs</p>


问:
Geolocation APIs for Rails
I am trying to show map for a location from my rails app.I tried checking YM4R/GM and GeoKit combination but not sure if there is something better for rails 3.</p>

答: You could also try RGeo. It looks nice, but I don't have any experience with it.</p>

Title: Geolocation APIs for Rails


问:
javascript - remove element from div when button inside is pressed
I have a div that looks like this:

```<code><div id="contact-segments">
    <div class="contact-segment-item doesnt-include">
        <div class="segment-content pull-left" style="width: 80%">
            <p>LOL</p>
        </div>
        <div class="pull-right">
            <a href="your link here">
                <i class="white-segment-icon fa fa-times"></i>
            </a>
        </div>
    </div>
</div>
</code>```

Whenever someone presses an add button, I add another contact-segment-item div to the contact-segments div through JavaScript with this function:

```<code>function createUserSegment(tags) {
    var div = document.createElement("div");
    div.className = 'contact-segment-item includes'
    div.innerHTML = "<div class='segment-content pull-left' style='width: 80%''> <p>" + tags + "</p> </div> <div class='pull-right'> <a href='your link here'> <i class='white-segment-icon  fa fa-times'></i></a> </div>";
    document.getElementById("contact-segments").appendChild(div);
}
</code>```

As you can see, the divs that are getting added through JavaScript have an a tag that shows a button with an "x".

How can I remove the contact-segment-item when the "x" is pressed inside of it?

Here's how each of them look so it's easier to picture.

I can link the "x" button click to javascript but how do I know which child of contact-segments to delete and also how do I get the p of it before it's deleted.

When the user presses the "x" on this div, I want to get the p or in this case Woop! so I can do something with it but then also delete that contact-segment-item

Thanks

答:
Instead of using .innerHTML we nest nodes with appendChild. Finally for our close i button we add onClick event handler. We pass there our div node, and use remove() method to remove the node.

EDIT:

Added css.

Do not use a if your anchors only needs to delete your segments. For example use only i without wrapping a and add a cursor: pointer style to it.

See working example:

function createUserSegment(tags){

  var div = document.createElement("div");
  div.className = 'contact-segment-item includes';

  var tagInfo = document.createElement("div");
  tagInfo.className = 'contact-segment-item__text';
  tagInfo.innerHTML = tags;

  var closeButton = document.createElement("i");
  closeButton.className = 'contact-segment-item__closeButton white-segment-icon fa fa-times';
  closeButton.onclick = function() {
    div.remove();
  };

  div.appendChild(tagInfo);
  div.appendChild(closeButton);

  document.getElementById("contact-segments").appendChild(div);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#contact-segments {
  max-width:350px;
  width: 100%;
}

.contact-segment-item {
  display: block;
  position: relative;
  width: 100%;
  background: #00B792;
  border-radius: 8px;
  line-height: 40px;
  clear: both;
  padding: 20px 30px;
  margin-bottom: 10px;
}

.contact-segment-item__anchor::after {
  clear: both;
}

.contact-segment-item__text {
  display: inline-block;
  color: #fff;
}

.contact-segment-item__closeButton {
  display: inline-block;
  cursor: pointer;
  color: #fff;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<button id="add-new" onClick="createUserSegment('new one')">Add new segment</button>

```

Body:
I have a div that looks like this:

LOL

Whenever someone presses an add button, I add another contact-segment-item div to the contact-segments div through JavaScript with this function:

function createUserSegment(tags) {
    var div = document.createElement("div");
    div.className = 'contact-segment-item includes'
    div.innerHTML = "

" + tags + "

";
    document.getElementById("contact-segments").appendChild(div);
}

As you can see, the divs that are getting added through JavaScript have an a tag that shows a button with an "x".

How can I remove the contact-segment-item when the "x" is pressed inside of it?

Here's how each of them look so it's easier to picture.

I can link the "x" button click to javascript but how do I know which child of contact-segments to delete and also how do I get the p of it before it's deleted.

When the user presses the "x" on this div, I want to get the p or in this case Woop! so I can do something with it but then also delete that contact-segment-item

Thanks

Body:
Instead of using .innerHTML we nest nodes with appendChild. Finally for our close i button we add onClick event handler. We pass there our div node, and use remove() method to remove the node.

EDIT:

Added css.

Do not use a if your anchors only needs to delete your segments. For example use only i without wrapping a and add a cursor: pointer style to it.

See working example:

function createUserSegment(tags){

  var div = document.createElement("div");
  div.className = 'contact-segment-item includes';

  var tagInfo = document.createElement("div");
  tagInfo.className = 'contact-segment-item__text';
  tagInfo.innerHTML = tags;

  var closeButton = document.createElement("i");
  closeButton.className = 'contact-segment-item__closeButton white-segment-icon fa fa-times';
  closeButton.onclick = function() {
    div.remove();
  };

  div.appendChild(tagInfo);
  div.appendChild(closeButton);

  document.getElementById("contact-segments").appendChild(div);

}

#contact-segments {
  max-width:350px;
  width: 100%;
}

.contact-segment-item {
  display: block;
  position: relative;
  width: 100%;
  background: #00B792;
  border-radius: 8px;
  line-height: 40px;
  clear: both;
  padding: 20px 30px;
  margin-bottom: 10px;
}

.contact-segment-item__anchor::after {
  clear: both;
}

.contact-segment-item__text {
  display: inline-block;
  color: #fff;
}

.contact-segment-item__closeButton {
  display: inline-block;
  cursor: pointer;
  color: #fff;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<button id="add-new" onClick="createUserSegment('new one')">Add new segment</button>

<br/>

<div id="contact-segments">

</div>


问:
Python "Function call with parameter: Converting measurements?"
I am taking my first programming course, so my apologies if this is a dumb question/possibly classified by the wrong category on this site. One of the exercise problems I am working on is the following:

Define a function print_total_inches, with parameters num_feet and num_inches, that prints the total number of inches. Note: There are 12 inches in a foot. Ex:

   print_total_inches(5, 8) prints:

Total inches: 68

The photo attached is the code that I did along with the error that I received. Any help/resources are greatly appreciated. Thanks!

答:
Your code fails at formatting the input (along with missing the calculations needed).

```<code>def print_total_inches (num_feet, num_inches):
    print('Total inches:', num_feet * 12 + num_inches)

print_total_inches(5, 8)
</code>```

or

```<code>def total_inches (num_feet, num_inches):
    return num_feet * 12 + num_inches

print('Total inches:', total_inches(5, 8))
</code>```

should do - and no need for return when there's nothing to return.

Body:
Your code fails at formatting the input (along with missing the calculations needed).

def print_total_inches (num_feet, num_inches):
    print('Total inches:', num_feet * 12 + num_inches)

print_total_inches(5, 8)

or

def total_inches (num_feet, num_inches):
    return num_feet * 12 + num_inches

print('Total inches:', total_inches(5, 8))

should do - and no need for return when there's nothing to return.


问:
xhr request 404 node and react js
I am making a simple login page in react which should get connected to a database by an ajax call to a node js file.

This is the node js code that I have:

```<code>var express=require('express');
var app=express();
var db=require('./db');
var bodyParser=require('body-parser');
var server=require('http').Server(app);
app.set('port',process.env.PORT||8080);

app.use(bodyParser.json());

app.set('views','views');
app.set('view engine','html');

app.use(express.static('./public'));

app.use(bodyParser.urlencoded({
    extended:true
}))

app.use(express.json());
app.use(express.urlencoded());

app.post('/newuser',function(req,res){
    console.log(req.body.username);
    console.log(req.body.password);
})
</code>```

And the ajax call from the react file looks something like this:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {MusicApp} from './music-app.js';

class Signup extends React.Component{

    constructor(props){
        super(props);
        this.state={
            isLoggedin:false
        }

        this.changePage=this.changePage.bind(this);
    }
    changePage(){

        var username=document.getElementById('username').value;
        var password=document.getElementById('password').value;
        var that=this;
        $.ajax({
            type:'POST',
            url:'/newuser',
            data:{
                username:username,
                password:password
            },
            success:function(){
                that.setState({
                    isLoggedin:true
                })
            }
        })

    }
    render(){
        if(this.state.isLoggedin){
            return(
                <MusicApp/>
                )
        }else{
            return(
                <div>
                <input type='text' id='username' placeholder='username'/>
                <input type='password' id='password' placeholder='password'/>
                <input type='button' id='signup' value='Signup' onClick={this.changePage}/>
                </div>

                )
        }
    }
}

ReactDOM.render(<Signup />,document.getElementById('container'));
</code>```

index.html

```<code> <!DOCTYPE html>
<html>
<head>
    <title>
        todo-app
    </title>
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
</head>
<body>
    <div id="container"> </div>

    <script type="text/javascript" src="http://localhost:8080/build/vendors.bundle.js"></script>
    <script type="text/javascript" src="http://localhost:8080/build/musicApp.bundle.js"></script>
</body>
</html>
</code>```

So, when I run the whole code on port number 8080, it gives me a 404 for xhr request not found.
The folder structure that I have is something like this:
 The ajax call is being made from signup.js. I have already done npm install --save express and npm install --save body-parser

What am I missing?

答:
you express server is not listening to any port, It has set the port, Its not listening on it.

Try with this

```<code>const express=require('express');
const bodyParser=require('body-parser');
const app = express();
const db = require('./db');

const PORT = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.set('views', 'views');
app.set('view engine', 'html');

app.use(express.static('./public'));

app.post('/newuser', function(req, res) {
    console.log(req.body.username);
    console.log(req.body.password);
    res.send({postedUserName: req.body.username});
});

if (!module.parent) {
  app.listen(PORT, () => {
    console.log(`Your application starts listening at Port ${PORT}`);
  });
}
</code>```

Title: xhr request 404 node and react js

Body:
I am making a simple login page in react which should get connected to a database by an ajax call to a node js file.

This is the node js code that I have:

var express=require('express');
var app=express();
var db=require('./db');
var bodyParser=require('body-parser');
var server=require('http').Server(app);
app.set('port',process.env.PORT||8080);

app.use(bodyParser.json());

app.set('views','views');
app.set('view engine','html');

app.use(express.static('./public'));

app.use(bodyParser.urlencoded({
    extended:true
}))

app.use(express.json());
app.use(express.urlencoded());

app.post('/newuser',function(req,res){
    console.log(req.body.username);
    console.log(req.body.password);
})

And the ajax call from the react file looks something like this:

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {MusicApp} from './music-app.js';

class Signup extends React.Component{

    constructor(props){
        super(props);
        this.state={
            isLoggedin:false
        }

        this.changePage=this.changePage.bind(this);
    }
    changePage(){

        var username=document.getElementById('username').value;
        var password=document.getElementById('password').value;
        var that=this;
        $.ajax({
            type:'POST',
            url:'/newuser',
            data:{
                username:username,
                password:password
            },
            success:function(){
                that.setState({
                    isLoggedin:true
                })
            }
        })

    }
    render(){
        if(this.state.isLoggedin){
            return(
                <MusicApp/>
                )
        }else{
            return(

                <input type='text' id='username' placeholder='username'/>
                <input type='password' id='password' placeholder='password'/>
                <input type='button' id='signup' value='Signup' onClick={this.changePage}/>

                )
        }
    }
}

ReactDOM.render(<Signup />,document.getElementById('container'));

index.html

 <!DOCTYPE html>

    <title>
        todo-app
    </title>
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">

So, when I run the whole code on port number 8080, it gives me a 404 for xhr request not found.
The folder structure that I have is something like this:
 The ajax call is being made from signup.js. I have already done npm install --save express and npm install --save body-parser

What am I missing?

Body:
you express server is not listening to any port, It has set the port, Its not listening on it.

Try with this

const express=require('express');
const bodyParser=require('body-parser');
const app = express();
const db = require('./db');

const PORT = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.set('views', 'views');
app.set('view engine', 'html');

app.use(express.static('./public'));

app.post('/newuser', function(req, res) {
    console.log(req.body.username);
    console.log(req.body.password);
    res.send({postedUserName: req.body.username});
});

if (!module.parent) {
  app.listen(PORT, () => {
    console.log(`Your application starts listening at Port ${PORT}`);
  });
}


答:
There is just some wonkiness to how you are asking it to do what you want it to do, if I understand your interpretation right:

You are asking the loop to save into each row of each column, the value of that row and column minus the minimum of that whole column (i) which is divided by the difference between the min and max for that column.

to do this, you should let it look at all the rows as well, working down each row(j) in each column(i) before moving on the the next column.

This is not how I would normalize my data personally, but to build on what you seem to be doing the way that you are doing it, this would be the way add a second loop and iterator:

```<code>for(i in 1:56){
  for(j in 1:nrow(clean_data)){
  clean_data[j ,i] <-(clean_data[j,i] - min(clean_data[,i])) / (max(clean_data[,i]) - min(clean_data[,i]))
  }
 }
</code>```

this takes the value from the current row, column combinations and adjusts it using your formula for the full column.

Title: How to normalize the datasets in R programming?

Body:
I implemented the below code to normalize my data frame in R. But I am getting the below error

for(i in 1:56){
  clean_data[(clean_data[,i]),i] <-(clean_data[,i] - min(clean_data[,i])) / (max(clean_data[,i]) - min(clean_data[,i]))
}

Error

Error: cannot allocate vector of size 9.9 Gb

Is there any other way to implement the normalization? can anyone help me?

Body:
There is just some wonkiness to how you are asking it to do what you want it to do, if I understand your interpretation right:

You are asking the loop to save into each row of each column, the value of that row and column minus the minimum of that whole column (i) which is divided by the difference between the min and max for that column.

to do this, you should let it look at all the rows as well, working down each row(j) in each column(i) before moving on the the next column.

This is not how I would normalize my data personally, but to build on what you seem to be doing the way that you are doing it, this would be the way add a second loop and iterator:

for(i in 1:56){
  for(j in 1:nrow(clean_data)){
  clean_data[j ,i] <-(clean_data[j,i] - min(clean_data[,i])) / (max(clean_data[,i]) - min(clean_data[,i]))
  }
 }

this takes the value from the current row, column combinations and adjusts it using your formula for the full column.