问:
_tkinter.TclError: no display name and no $DISPLAY environment variable for new OS X Mavericks
This is my first post so please be forgiving.

I am trying to create an animation using matplotlib, and I could do this perfectly well until a few days ago, until I upgraded to OS X Mavericks, upon which all hell broke loose. Note, the below code worked in OS X Lion.

Suddenly I was getting an error message whilst trying to run this code in Mavericks:

```<code>import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import mpl_toolkits.mplot3d.axes3d as p3

#----->READ AND FORMAT DATA-----------------------------------------------#
.
.
.
.

#-------------------------------------------------------------------------#

# Set up figure & 3D axis for animation
fig = plt.figure(figsize=(10,10))
ax = fig.add_axes([0, 0, 1, 1], projection='3d') # Correct way to make 3D plots

# set up lines and points
lines = sum([ax.plot([], [], [], '-')], [])
pts = sum([ax.plot([], [], [], 'o')], [])

# Setting the axes properties
ax.set_xlim3d([-2000, 2000])
ax.set_xlabel('X')
ax.set_ylim3d([1350, 1400])
ax.set_ylabel('Y')
ax.set_zlim3d([-340, 600])
ax.set_zlabel('Z')

# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(40, 0)
ax.set_title('animation')
ax.grid() # add grid

# Initialisation function: plot the background of each frame
def init():
    for line, pt in zip(lines, pts):
        # Lines
        line.set_data([], [])
        line.set_3d_properties([])
        # Points
        pt.set_data([], [])
        pt.set_3d_properties([])
    return lines + pts

# Animation function.  This will be called sequentially with the frame number
def animate(i):
    # we'll step two time-steps per frame.  This leads to nice results.
    i = (2.5 * i)

    for line, pt, dat in zip(lines, pts, data):
        x, y, z = dat[:i].T
        # Lines
        line.set_data(x, y)
        line.set_3d_properties(z)
        # Points
        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])

    ax.view_init(45, i)
    fig.canvas.draw()
    return lines + pts

#----->ANIMATION-----------------------------------------------------------#

# Creating the Animation object
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=120, interval=30, blit=True)
# Save as mp4. This requires mplayer or ffmpeg to be installed
# anim.save('one_marker_3D.mp4', fps=15, extra_args=['-vcodec', 'libx264'])

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

This produces the following error message:

```<code>Traceback (most recent call last):
  File "shoulder_animation_walking_straight_3D.py", line 26, in <module>
    fig = plt.figure(figsize=(10,10))
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 423, in figure
    **kwargs)
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
</code>```

Now as you can hopefully see, I have attempted to use the TkAgg backend instead of the 'Agg' backend, as recommended by the documentation (https://wiki.python.org/moin/TkInter). This seems to cause problems with the new version of OS X because X11 is not supported anymore, and XQuartz has to be installed instead. This I have done too. But it still give me that same error.

I also tried installing py33-tkinter using macports, but that didn't work either, but perhaps I did not do it properly. I simply did

```<code>sudo port py33-tkinter
</code>```

I am still fairly new to python and unix in general.

UPDATE (22/12/13):

I did the following

```<code>Python 2.7.5 |Anaconda 1.8.0 (x86_64)| (default, Oct 24 2013, 07:02:20)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import Tkinter
</code>```

Then ran the Tkinter test

```<code>>>> Tkinter._test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 3770, in _test
    root = Tk()
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
>>>
</code>```

Might be helpful to someone who knows this better than me.

答:
This was solved by doing the following

matplotlib.use('Agg')

import matplotlib as mpl

import numpy as np

import matplotlib.pyplot as plt

import matplotlib

matplotlib.use('Agg')

above this two lines must be in the top codes

Body:
This is my first post so please be forgiving.

I am trying to create an animation using matplotlib, and I could do this perfectly well until a few days ago, until I upgraded to OS X Mavericks, upon which all hell broke loose. Note, the below code worked in OS X Lion.

Suddenly I was getting an error message whilst trying to run this code in Mavericks:

import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import mpl_toolkits.mplot3d.axes3d as p3

#----->READ AND FORMAT DATA-----------------------------------------------#
.
.
.
.

#-------------------------------------------------------------------------#

# Set up figure & 3D axis for animation
fig = plt.figure(figsize=(10,10))
ax = fig.add_axes([0, 0, 1, 1], projection='3d') # Correct way to make 3D plots

# set up lines and points
lines = sum([ax.plot([], [], [], '-')], [])
pts = sum([ax.plot([], [], [], 'o')], [])

# Setting the axes properties
ax.set_xlim3d([-2000, 2000])
ax.set_xlabel('X')
ax.set_ylim3d([1350, 1400])
ax.set_ylabel('Y')
ax.set_zlim3d([-340, 600])
ax.set_zlabel('Z')

# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(40, 0)
ax.set_title('animation')
ax.grid() # add grid

# Initialisation function: plot the background of each frame
def init():
    for line, pt in zip(lines, pts):
        # Lines
        line.set_data([], [])
        line.set_3d_properties([])
        # Points
        pt.set_data([], [])
        pt.set_3d_properties([])
    return lines + pts

# Animation function.  This will be called sequentially with the frame number
def animate(i):
    # we'll step two time-steps per frame.  This leads to nice results.
    i = (2.5 * i)

    for line, pt, dat in zip(lines, pts, data):
        x, y, z = dat[:i].T
        # Lines
        line.set_data(x, y)
        line.set_3d_properties(z)
        # Points
        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])

    ax.view_init(45, i)
    fig.canvas.draw()
    return lines + pts

#----->ANIMATION-----------------------------------------------------------#

# Creating the Animation object
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=120, interval=30, blit=True)
# Save as mp4. This requires mplayer or ffmpeg to be installed
# anim.save('one_marker_3D.mp4', fps=15, extra_args=['-vcodec', 'libx264'])

plt.show()

This produces the following error message:

Traceback (most recent call last):
  File "shoulder_animation_walking_straight_3D.py", line 26, in <module>
    fig = plt.figure(figsize=(10,10))
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 423, in figure
    **kwargs)
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/Users/me/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

Now as you can hopefully see, I have attempted to use the TkAgg backend instead of the 'Agg' backend, as recommended by the documentation (https://wiki.python.org/moin/TkInter). This seems to cause problems with the new version of OS X because X11 is not supported anymore, and XQuartz has to be installed instead. This I have done too. But it still give me that same error.

I also tried installing py33-tkinter using macports, but that didn't work either, but perhaps I did not do it properly. I simply did

sudo port py33-tkinter

I am still fairly new to python and unix in general.

UPDATE (22/12/13):

I did the following

Python 2.7.5 |Anaconda 1.8.0 (x86_64)| (default, Oct 24 2013, 07:02:20)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import Tkinter

Then ran the Tkinter test

>>> Tkinter._test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 3770, in _test
    root = Tk()
  File "/Users/me/anaconda/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
>>>

Might be helpful to someone who knows this better than me.


来源: stackexchange

问:
Stata twoway bar graph - how to make the bars actually touch the bottom
When I am making a twoway bar, I get floating bars, this code:

```<code>twoway bar b a
</code>```

gives me this:

I would prefer the bars to touch the bottom, as the code below does:

```<code>graph bar b, over(a)
</code>```

which makes the following plot:

because I am actually plotting two different things on the same plot, I think I must use the twoway setting, but it just bugs me that the bars float!

Thanks for any help

答:
Just wanted to post the answer for anyone who might see this. It was from a comment below the question. This works</p>

```<code>twoway bar a b, plotregion(margin(zero))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I am making a twoway bar, I get floating bars, this code:

twoway bar b a

gives me this:

I would prefer the bars to touch the bottom, as the code below does:

graph bar b, over(a)

which makes the following plot:

because I am actually plotting two different things on the same plot, I think I must use the twoway setting, but it just bugs me that the bars float!

Thanks for any help

Body:
Just wanted to post the answer for anyone who might see this. It was from a comment below the question. This works

twoway bar a b, plotregion(margin(zero))


问:
Open-source YouTube-style UITableViewController
Does anyone know of any open-source UITableViewController implementations that are styled like the ones in the youtube application?</p>

答: Check out the three20 project: https://github.com/facebook/three20. If you try the TTCatalog demo app, you'll see something much like YouTube's UITableViewController implementation.

ContentLicense: CC BY-SA 2.5


问:
TaskWarrior Port not Opening Externally
I run a Debian 9 server (recently upgraded from Debian 8 where similar problems occurred). I have a task warrior instance up and running and it works internally, I am unable to sync to it externally however. I run a UFW firewall instance.

/var/taskd/config:

```<code>    confirmation=1
    extensions=/usr/local/libexec/taskd
    ip.log=on
    log=/var/taskd/taskd.log
    pid.file=/var/taskd/taskd.pid
    queue.size=10
    request.limit=1048576
    root=/var/taskd
    server=hub.home:53589
    trust=strict
    verbose=1
    client.cert=/var/taskd/client.cert.pem
    client.key=/var/taskd/client.key.pem
    server.cert=/var/taskd/server.cert.pem
    server.key=/var/taskd/server.key.pem
    server.crl=/var/taskd/server.crl.pem
    ca.cert=/var/taskd/ca.cert.pem
</code>```

/etc/systemd/system/taskd.service

```<code>    [Unit]
    Description=Secure server providing multi-user, multi-client access to Taskwarrior data
    Requires=network.target
    After=network.target
    Documentation=http://taskwarrior.org/docs/#taskd

    [Service]
    ExecStart=/usr/local/bin/taskd server --data /var/taskd
    Type=simple
    User=<myusername>
    Group=<mygroupname>
    WorkingDirectory=/var/taskd
    PrivateTmp=true
    InaccessibleDirectories=/home /root /boot /opt /mnt /media
    ReadOnlyDirectories=/etc /usr

    [Install]
    WantedBy=multi-user.target
</code>```

systemctl status taskd.service:

```<code>    ● taskd.service - Secure server providing multi-user, multi-client access to Taskwarrior data
       Loaded: loaded (/etc/systemd/system/taskd.service; enabled; vendor preset: enabled)
       Active: active (running) since Tue 2017-07-04 10:21:42 BST; 28min ago
         Docs: http://taskwarrior.org/docs/#taskd
     Main PID: 3964 (taskd)
        Tasks: 1 (limit: 4915)
       CGroup: /system.slice/taskd.service
               └─3964 /usr/local/bin/taskd server --data /var/taskd
</code>```

sufo ufw status:

```<code>    Status: active

    To                         Action      From
    --                         ------      ----
    ...
    53589                      ALLOW       Anywhere
    53589 (v6)                 ALLOW       Anywhere (v6)
    ...
</code>```

nmap localhost -p 53589 -Pn (from host)

```<code>    ...
    PORT      STATE  SERVICE
    53589/tcp closed unknown
    ...
</code>```

nmap hub.home -p 53589 -Pn (from host)

```<code>    ...
    PORT      STATE  SERVICE
    53589/tcp open  unknown
    ...
</code>```

nmap hub.home -p 53589 -Pn (from client)

```<code>    ...
    PORT      STATE  SERVICE
    53589/tcp closed  unknown
    ...
</code>```

taskd server --debug --debug.tls=2

```<code>    s: INFO Client certificate will be verified.
    s: INFO IPv4: 127.0.1.1
    s: INFO Server listening.
</code>```

The sync works internally but not externally.
Many thanks

答:
I ran into the same issue.  For me, ensuring /etc/hosts was set with the externally facing IP addresses and setting the server taskd config variable to the fqdn with port, then setting the family=IPv4 worked (it wouldn't work with IPv6 for me).  The only thing I don't see is the family in your config...

Though in your config it looks like the INFO IPv4: 127.0.1.1 doesn't match the comment you made about taskd.server=192.*.  That looks like a localhost loopback.

Maybe if you edit /etc/hosts with the fully qualified domain name & hostname and specify the IP address and IP family in the config it will give taskwarrior the info it needs to bind to the right external IP and port and permit the use of the self signed cert?

When I run with the debug server, I get:

taskd@(host):~$ taskd server --debug --debug.tls=2
s: INFO Client certificate will be verified.
s: INFO IPv4: (my external IPv4 address)
s: INFO Server listening.

Title: TaskWarrior Port not Opening Externally

Body:
I run a Debian 9 server (recently upgraded from Debian 8 where similar problems occurred). I have a task warrior instance up and running and it works internally, I am unable to sync to it externally however. I run a UFW firewall instance.

/var/taskd/config:

    confirmation=1
    extensions=/usr/local/libexec/taskd
    ip.log=on
    log=/var/taskd/taskd.log
    pid.file=/var/taskd/taskd.pid
    queue.size=10
    request.limit=1048576
    root=/var/taskd
    server=hub.home:53589
    trust=strict
    verbose=1
    client.cert=/var/taskd/client.cert.pem
    client.key=/var/taskd/client.key.pem
    server.cert=/var/taskd/server.cert.pem
    server.key=/var/taskd/server.key.pem
    server.crl=/var/taskd/server.crl.pem
    ca.cert=/var/taskd/ca.cert.pem

/etc/systemd/system/taskd.service

    [Unit]
    Description=Secure server providing multi-user, multi-client access to Taskwarrior data
    Requires=network.target
    After=network.target
    Documentation=http://taskwarrior.org/docs/#taskd

    [Service]
    ExecStart=/usr/local/bin/taskd server --data /var/taskd
    Type=simple
    User=<myusername>
    Group=<mygroupname>
    WorkingDirectory=/var/taskd
    PrivateTmp=true
    InaccessibleDirectories=/home /root /boot /opt /mnt /media
    ReadOnlyDirectories=/etc /usr

    [Install]
    WantedBy=multi-user.target

systemctl status taskd.service:

    ● taskd.service - Secure server providing multi-user, multi-client access to Taskwarrior data
       Loaded: loaded (/etc/systemd/system/taskd.service; enabled; vendor preset: enabled)
       Active: active (running) since Tue 2017-07-04 10:21:42 BST; 28min ago
         Docs: http://taskwarrior.org/docs/#taskd
     Main PID: 3964 (taskd)
        Tasks: 1 (limit: 4915)
       CGroup: /system.slice/taskd.service
               └─3964 /usr/local/bin/taskd server --data /var/taskd

sufo ufw status:

    Status: active

    To                         Action      From
    --                         ------      ----
    ...
    53589                      ALLOW       Anywhere
    53589 (v6)                 ALLOW       Anywhere (v6)
    ...

nmap localhost -p 53589 -Pn (from host)

    ...
    PORT      STATE  SERVICE
    53589/tcp closed unknown
    ...

nmap hub.home -p 53589 -Pn (from host)

    ...
    PORT      STATE  SERVICE
    53589/tcp open  unknown
    ...

nmap hub.home -p 53589 -Pn (from client)

    ...
    PORT      STATE  SERVICE
    53589/tcp closed  unknown
    ...

taskd server --debug --debug.tls=2

    s: INFO Client certificate will be verified.
    s: INFO IPv4: 127.0.1.1
    s: INFO Server listening.

The sync works internally but not externally.
Many thanks


问:
Stop node.js program from command line
I have a simple TCP server that listens on a port.

```<code>var net = require("net");

var server = net.createServer(function(socket) {
    socket.end("Hello!\n");
});

server.listen(7777);
</code>```

I start it with node server.js and then close it with Ctrl + Z on Mac. When I try to run it again with node server.js I get this error message:

```<code>node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
          ^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)
</code>```

Am I closing the program the wrong way? How can I prevent this from happening?

答:
I ran into an issue where I have multiple node servers running, and I want to just kill one of them and redeploy it from a script.

Note: This example is in a bash shell on Mac.

To do so I make sure to make my node call as specific as possible. For example rather than calling node server.js from the apps directory, I call node app_name_1/app/server.js

Then I can kill it using:

kill -9 $(ps aux | grep 'node\ app_name_1/app/server.js' | awk '{print $2}')

This will only kill the node process running app_name_1/app/server.js.

If you ran node app_name_2/app/server.js this node process will continue to run.

If you decide you want to kill them all you can use killall node as others have mentioned.

Title: Stop node.js program from command line

Body:
I have a simple TCP server that listens on a port.

var net = require("net");

var server = net.createServer(function(socket) {
    socket.end("Hello!\n");
});

server.listen(7777);

I start it with node server.js and then close it with Ctrl + Z on Mac. When I try to run it again with node server.js I get this error message:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
          ^
Error: listen EADDRINUSE
at errnoException (net.js:670:11)
at Array.0 (net.js:771:26)
at EventEmitter._tickCallback (node.js:192:41)

Am I closing the program the wrong way? How can I prevent this from happening?


问:
How do I move sprites in random directions but with uniform speed python/pygame?
I try to move a set of balls in random movement, but with uniform speed. My code lets the balls move in random directions, but with different speeds. I think it is because the random.uniform function gives different values, some close to 0 which, multiplied with the speed and time, gives lower values than the ones closer to 1. But in the animation the speed doesn't seem to be tied with the direction the balls travel (which should be the case if the values of dx and dy are the cause). I know anout normalization, but I think random.uniform gives the same values as a normalized vector?

My questions are:

Is the random value of dx and dy the culprit of the difference in speed?

What is the way to make all the balls move in the same speed?

My code:

```<code>self.timer = pygame.time.Clock()
self.time_passed = self.timer.tick()
self.speed = 0.5
self.dx = random.uniform(-1, 1)
self.dy = random.uniform(-1, 1)
displacement = Vector2(
                       self.dx * (self.speed * self.time_passed),
                       self.dy * (self.speed * self.time_passed)
                       )

self.pos += displacement #both vector objects
</code>```

Thanks for any help!

答:
Just start with a vector with the desired length (speed) and rotate it by a random angle.

```<code>self.velocity = Vector2(5, 0).rotate(random.randrange(360))
</code>```

Regarding question 1, since you give the vector random x and y values, the resulting vectors will all have completely different lengths/magnitudes, therefore the sprites move with different speeds. For example you could get a Vector2(0, 0) and a Vector2(1, 1) (it's obvious that they don't have the same length).

You could actually normalize the vectors and then scale them, but better use the rotate method. (Vectors of length zero can't be normalized.)

Body:
I try to move a set of balls in random movement, but with uniform speed. My code lets the balls move in random directions, but with different speeds. I think it is because the random.uniform function gives different values, some close to 0 which, multiplied with the speed and time, gives lower values than the ones closer to 1. But in the animation the speed doesn't seem to be tied with the direction the balls travel (which should be the case if the values of dx and dy are the cause). I know anout normalization, but I think random.uniform gives the same values as a normalized vector?

My questions are:

Is the random value of dx and dy the culprit of the difference in speed?

What is the way to make all the balls move in the same speed?

My code:

self.timer = pygame.time.Clock()
self.time_passed = self.timer.tick()
self.speed = 0.5
self.dx = random.uniform(-1, 1)
self.dy = random.uniform(-1, 1)
displacement = Vector2(
                       self.dx * (self.speed * self.time_passed),
                       self.dy * (self.speed * self.time_passed)
                       )

self.pos += displacement #both vector objects

Thanks for any help!

Body:
Just start with a vector with the desired length (speed) and rotate it by a random angle.

self.velocity = Vector2(5, 0).rotate(random.randrange(360))

Regarding question 1, since you give the vector random x and y values, the resulting vectors will all have completely different lengths/magnitudes, therefore the sprites move with different speeds. For example you could get a Vector2(0, 0) and a Vector2(1, 1) (it's obvious that they don't have the same length).

You could actually normalize the vectors and then scale them, but better use the rotate method. (Vectors of length zero can't be normalized.)


问:
How do I ensure that these rows of content stack when the screen size changes?
I want to ensure that the content in each column stacks when it reaches a certain screen size e.g 768px

```<code><template>

    <div>

    <div class = "edit">

        <h1 class =  "md-display-3">Connect to be more</h1>
        <h2 class = "md-subhead">Always be aware of the state of your business </h2>

    </div>

<div class = "designGeneral">

        <md-layout md-row md-md-columns>

                <md-layout md-column = "3" >

                <h1 class = "md-display-1" id = "responsive"> Connect Soft documents </h1>

                  <p class = "" id = "responsive" >Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.</p>

              </md-layout>

              <md-layout md-column = "7"  >

                <p id = "responsive>
                    ------
                </p>

              </md-layout>

        </md-layout>

        <hr>

        <md-layout md-row md-md-columns >

           <md-layout md-column = "7">

        <p>
            ------
        </p>

      </md-layout>

           <md-layout md-column = "5" style = "padding-right : 30px">

                <h1 class = "md-display-1"> Improve decision models</h1>

                  <p class = "" >Use statistical modelling to identify patterns and anomalies in the data that can help you.</p>

              </md-layout>

                </md-layout>

<hr>

                <md-layout md-row md-md-columns>

                <md-layout md-column = "5">

                <h1 class = "md-display-1">  Search. Get what is important to You!</h1>

                  <p class = "" style = "">All notifications and documents are indexed and archived so that you can find what is needed at all times.</p>

              </md-layout>

              <md-layout md-column = "7">

                <p>
                    ------
                </p>

              </md-layout>

    </md-layout>

       <hr>
                    <md-layout md-row md-md-columns>

                    <md-layout md-column = "5">

                  </md-layout>

                  <md-layout md-column = "7">

                   <h1 class = "md-display-1">Collaborate with other apps!</h1>

                      <p class = "">Connect to the tools you need to prevent wasting time using so many apps.</p>

                  </md-layout>

            </md-layout>

</div>
</code>```

In the below md-layout  I added an id = "responsive" to reference the elements.

```<code><md-layout md-row md-md-columns>

                    <md-layout md-column = "3" >

                    <h1 class = "md-display-1" id = "responsive"> Connect Soft documents </h1>

                      <p class = "" id = "responsive" >Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.</p>

                  </md-layout>

                  <md-layout md-column = "7" id = "responsive" >

                    <p>
                        ------
                    </p>

                  </md-layout>

            </md-layout>
</code>```

Then I added the following media query

```<code>@media screen and (max-width : 768px ) {

float: none !important;
 margin: auto;
text-align : center;

}
</code>```

It is not working though

It squashes and overflows

答:
HTML id's are supposed to be unique. If you want to reference multiple elements with the same name, use the class attribute.

Vue material uses a flexbox grid system. It defines a set of screen sizes that your components can respond to.

http://vuematerial.io/#/ui-elements/layout

For example, if you want an element to take 100% on small screens, you would put
 md-flex-small="100" as an attribute.

Body:
I want to ensure that the content in each column stacks when it reaches a certain screen size e.g 768px

<template>

Connect to be more

Always be aware of the state of your business

        <md-layout md-row md-md-columns>

                <md-layout md-column = "3" >

 Connect Soft documents

Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.

              </md-layout>

              <md-layout md-column = "7"  >

                    ------

              </md-layout>

        </md-layout>

        <md-layout md-row md-md-columns >

           <md-layout md-column = "7">

            ------

      </md-layout>

           <md-layout md-column = "5" style = "padding-right : 30px">

 Improve decision models

Use statistical modelling to identify patterns and anomalies in the data that can help you.

              </md-layout>

                </md-layout>

                <md-layout md-row md-md-columns>

                <md-layout md-column = "5">

  Search. Get what is important to You!

All notifications and documents are indexed and archived so that you can find what is needed at all times.

              </md-layout>

              <md-layout md-column = "7">

                    ------

              </md-layout>

    </md-layout>

                    <md-layout md-row md-md-columns>

                    <md-layout md-column = "5">

                  </md-layout>

                  <md-layout md-column = "7">

Collaborate with other apps!

Connect to the tools you need to prevent wasting time using so many apps.

                  </md-layout>

            </md-layout>

In the below md-layout  I added an id = "responsive" to reference the elements.

<md-layout md-row md-md-columns>

                    <md-layout md-column = "3" >

 Connect Soft documents

Allow documents that feed into each other to provide a consistent, untainted view of what your institution is doing.

                  </md-layout>

                  <md-layout md-column = "7" id = "responsive" >

                        ------

                  </md-layout>

            </md-layout>

Then I added the following media query

@media screen and (max-width : 768px ) {

float: none !important;
 margin: auto;
text-align : center;

}

It is not working though

It squashes and overflows


问:
should I configure my server to use the latest version of PHP?
I'm looking at some things in my cPanel and noticed that my server is using PHP 5.4. Should I change it to PHP 7.1? Is it a good idea to always use the latest version? Is there a big difference in performance between 5.4 and 7x?</p>

答: You need to test for incompatibilities but PHP 7.1 is much faster, so barring some other reason not to, yes, you should.</p>


问:
Elegant way to combine multiple collections of elements?
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

```<code>public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}
</code>```

Which I'd then call like this:

```<code>var combined = Combine(foo, bar);
</code>```

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.

答:
You can use Union as follows:

```<code>var combined=foo.Union(bar).Union(baz)...
</code>```

This will remove identical elements, though, so if you have those, you might want to use Concat, instead.

Body:
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}

Which I'd then call like this:

var combined = Combine(foo, bar);

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.

Body:
You can use Union as follows:

var combined=foo.Union(bar).Union(baz)...

This will remove identical elements, though, so if you have those, you might want to use Concat, instead.


问:
How to determine the observations when they are mashed for a PCA plot
I've done a PCA with R using the function princomp and the ggfortify package. I cannot determine the all the observations at the 4th component (where there is an X25 and 2-4 other observations). Is there a way for me to do this more smoothly where I can distinguish them? I don't care what package to use, I'd just like to see what the observations are much better.

答:
You can use label.repel=TRUE from the ggfortify package.

An example using the mtcars dataset:

Overlapping labels:

```<code>autoplot(prcomp(mtcars),
                  label=T)
</code>```

Repelled labels:

```<code>autoplot(prcomp(mtcars),
         label=T,label.repel=T)
</code>```

Body:
You can use label.repel=TRUE from the ggfortify package.

An example using the mtcars dataset:

Overlapping labels:

autoplot(prcomp(mtcars),
                  label=T)

Repelled labels:

autoplot(prcomp(mtcars),
         label=T,label.repel=T)


问:
Laravel 5,4 JavaScript function with ajax
I have a java script function with ajax in it. I call function in laravel blade loop, and I have a form which submitting sells. I need to pass sell for each product separately but to use the same ajax code.

My form looks like this:

Here is my blade file script:

```<code>@if($inventories)

<a href="{{ url('/inventory') }}" type="button" class="btn btn-sm btn-primary"> <<- Back To Inventory</a>
<div class="text-center"><b>Search Page</b></div>
<br>
<br>

<div class="search">
    <div class="col-md-12">
        @include(env('THEME').'.search_box')
    </div>
</div>

<table>

    @foreach($inventories as $inventory)
    <tr >
        <td class="part_img" rowspan="3"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}"><img src="{{ asset(env('THEME')) }}/images/inventory/{{$inventory->main_img}}"></a></td>
    </tr>
    <tr>
        <td class="inventory_part_title" colspan="8">
            <div style="float: left; margin: 0 30px;">{{ $inventory->part_number }}</div>
            <div style="float: left;"><a href="{{ route('inventory.show',['slug' => $inventory->slug]) }}">{{ $inventory->title }}</a></div>
            <div style="float: right; margin-right: 50px;">{{ $inventory->upc_number }}</div>
        </td>
    </tr>
    <tr>
        <td><b>Location:</b> {{ $inventory->storage_location }}</td>
        <td><b>Brand:</b> {{ $inventory->brand }}</td>
        <td><b>Supplier:</b> {{ $inventory->supplier }}</td>
        <td><b>GBP:</b> £{{ $inventory->unit_price_gbp }}</td>
        <td><b>USD:</b> ${{ $inventory->unit_price_usd }}</td>
        <td><b>In Stock:</b> {{ $inventory->unit_in_stock }}</td>
        <td><b>Sold:</b> {{ $inventory->unit_sold }}</td>
        <td>
            <div class="onpage-sold-input">
                {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                    {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                    <input type="hidden" name="part_id" value="{{ $inventory->id }}">
                    <!--<input type="hidden" name="_token" value="{{ csrf_token() }}">-->
                    {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit']) !!}
                {!! Form::close() !!}
            </div>

            <script type="text/javascript">
                var product_id = {{ $inventory->id }};
                ajax_search_sold(product_id);
            </script>

        </td>
        <!--<td><button type="button" class="btn btn-sm btn-success">Edit</button></td>-->
    </tr>
    <tr>
        <td colspan="8"></td>
    </tr>
    @endforeach

</table>

@else
<p>Inventory is empty!</p>
@endif
</code>```

And here is my JavaScript function which is contains AJAX script:

```<code>function ajax_search_sold(product_id){

    jQuery.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
        }
    });

    $('#sold-button-'+product_id).on('click', function (e) {
        e.preventDefault();

        var form = $('#search-sold-button-'+product_id),
            data = form.serialize(),
            ajax_url = form.attr('action'),
            alert_section = $('.alert-section');

            console.log(ajax_url);
            console.log(data);

        $.post(ajax_url, data, function (resp) {
            alert_section.fadeIn().find('.alert').html(resp);
            setTimeout(function () {
                alert_section.fadeOut();
            }, 3000)
        })
    });
}
</code>```

How can I write a function with AJAX in it to pass data for each sell in loop?

答:
Right now, you mixed 2 possible ways into one.

apply onclick event to fire the function.

create jquery which apply to button to do the ajax call.

What you did is apply the jquery button event into function which never been call. To fix this pick one of the above, for example

Add onClick parameter to button

```<code> {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit','onClick'=>'ajax_search_sold('.$inventory->id.')']) !!}
</code>```

then, remove

```<code> $('#sold-button-'+product_id).on('click', function (e) {
</code>```

so that your process can be run when function get call.

Body:
I have a java script function with ajax in it. I call function in laravel blade loop, and I have a form which submitting sells. I need to pass sell for each product separately but to use the same ajax code.

My form looks like this:

Here is my blade file script:

@if($inventories)

 <<- Back To Inventory

Search Page

        @include(env('THEME').'.search_box')

    @foreach($inventories as $inventory)

         $inventory->slug]) }}">main_img}}">

{{ $inventory->part_number }}

 $inventory->slug]) }}">{{ $inventory->title }}

{{ $inventory->upc_number }}

        Location: {{ $inventory->storage_location }}
        Brand: {{ $inventory->brand }}
        Supplier: {{ $inventory->supplier }}
        GBP: £{{ $inventory->unit_price_gbp }}
        USD: ${{ $inventory->unit_price_usd }}
        In Stock: {{ $inventory->unit_in_stock }}
        Sold: {{ $inventory->unit_sold }}

                {!! Form::open(['url' => route('sold.sold'),'class'=>'contact-form', 'id'=>'search-sold-button-'.$inventory->id,'method'=>'POST']) !!}
                    {!! Form::text('sold', old('sold'), array('class'=>'form-control', 'placeholder'=>'Qty.')) !!}
                    <input type="hidden" name="part_id" value="{{ $inventory->id }}">

                    {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit']) !!}
                {!! Form::close() !!}

    @endforeach

@else

Inventory is empty!

@endif

And here is my JavaScript function which is contains AJAX script:

function ajax_search_sold(product_id){

    jQuery.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
        }
    });

    $('#sold-button-'+product_id).on('click', function (e) {
        e.preventDefault();

        var form = $('#search-sold-button-'+product_id),
            data = form.serialize(),
            ajax_url = form.attr('action'),
            alert_section = $('.alert-section');

            console.log(ajax_url);
            console.log(data);

        $.post(ajax_url, data, function (resp) {
            alert_section.fadeIn().find('.alert').html(resp);
            setTimeout(function () {
                alert_section.fadeOut();
            }, 3000)
        })
    });
}

How can I write a function with AJAX in it to pass data for each sell in loop?

Body:
Right now, you mixed 2 possible ways into one.

apply onclick event to fire the function.

create jquery which apply to button to do the ajax call.

What you did is apply the jquery button event into function which never been call. To fix this pick one of the above, for example

Add onClick parameter to button

 {!! Form::button('Sold', ['class' => 'btn btn-sm btn-success sold-button', 'id'=>'sold-button-'.$inventory->id,'type'=>'submit','onClick'=>'ajax_search_sold('.$inventory->id.')']) !!}

then, remove

 $('#sold-button-'+product_id).on('click', function (e) {

so that your process can be run when function get call.


答: if only for security reasons you should, but for resolving common bugs too and performance</p>

Title: should I configure my server to use the latest version of PHP?

Body: I'm looking at some things in my cPanel and noticed that my server is using PHP 5.4. Should I change it to PHP 7.1? Is it a good idea to always use the latest version? Is there a big difference in performance between 5.4 and 7x?


问:
Angular Platform-Server Respond with custom http status code
I am using SSR Platform-Server with ExpressJS
I want to change the HTTP status code from 200 to 404 for page not found

I create a route object as follow

```<code>[
  { path: '', component: HomeComponent },
  { path: '**', component: NotFoundComponent, pathMatch: 'full' }
]
</code>```

it is working fine in client side but I don't have any idea to change the status code in NodeJS

I try to throw an error and handle it in ExpressJS

so in NotFoundComponent, in OnInit I throw an error but angular capture the error and again I get status = 200

any idea?

答:
I am using @nguniversal/express-engine

you can inject custom providers to your app from [express-engine]
and you can modify rendered result
and you can handle errors

https://github.com/angular/universal/tree/master/modules/ng-express-engine

but request and response is already injected

https://github.com/angular/universal/blob/master/modules/ng-express-engine/src/main.ts#L66

and request and response are expressjs objects

so you can use it like this:

```<code>import { RESPONSE } from '@nguniversal/express-engine/tokens'
</code>```

and in your controller or service

```<code>constructor(.... OtherDependencies....., @Optional() @Inject(RESPONSE) private readonly res: any) { }
</code>```

and somewhere in your code like ngOnInit

```<code>if(this.res) {
    this.res.status(404)
}
</code>```

and if you want to stop angular

```<code>return this.res.end();
</code>```

or you can add any other valid ExpressJs res code here

======= UPDATE =======

This topic is old and Angular-Universal changes a lot. but still, this topic is valid with no change

new Angular Universal document for expessjs can be found here
Angular Express Engine

Body:
I am using SSR Platform-Server with ExpressJS
I want to change the HTTP status code from 200 to 404 for page not found

I create a route object as follow

[
  { path: '', component: HomeComponent },
  { path: '**', component: NotFoundComponent, pathMatch: 'full' }
]

it is working fine in client side but I don't have any idea to change the status code in NodeJS

I try to throw an error and handle it in ExpressJS

so in NotFoundComponent, in OnInit I throw an error but angular capture the error and again I get status = 200

any idea?

Body:
I am using @nguniversal/express-engine

you can inject custom providers to your app from [express-engine]
and you can modify rendered result
and you can handle errors

https://github.com/angular/universal/tree/master/modules/ng-express-engine

but request and response is already injected

https://github.com/angular/universal/blob/master/modules/ng-express-engine/src/main.ts#L66

and request and response are expressjs objects

so you can use it like this:

import { RESPONSE } from '@nguniversal/express-engine/tokens'

and in your controller or service

constructor(.... OtherDependencies....., @Optional() @Inject(RESPONSE) private readonly res: any) { }

and somewhere in your code like ngOnInit

if(this.res) {
    this.res.status(404)
}

and if you want to stop angular

return this.res.end();

or you can add any other valid ExpressJs res code here

======= UPDATE =======

This topic is old and Angular-Universal changes a lot. but still, this topic is valid with no change

new Angular Universal document for expessjs can be found here
Angular Express Engine

ContentLicense: CC BY-SA 4.0


问:
joining rows in tall arrays in MATLAB
I have a large set of data, its first row look like

```<code>02.06.2016 11;04;30.832404 1.2 3.3
02.06.2016 11;04;30.832504 2.4 2.3
02.06.2016 11;04;30.832604 6.1 7.1
</code>```

I'm using tall arrays in MATLAB. I want to be able to use the timerange function to select data between different time ranges (see my previous questions:
Selecting rows of data between time and date range in tall array in MATLAB
 ).

However, if I'm not mistaken the time and the date must be in the same row. I was therefore, trying to combine the two into one row. I've tried different functions such as "join", but I was unable to find anything that works with tall arrays. Is there a way round this?

Thanks,

答:
The timerange function does not support tall timetables currently (R2017a).

Still, it's worth your time to create a tall datetime variable in your table using your existing variables of time information since that should make indexing easier.

Title: joining rows in tall arrays in MATLAB

Body:
I have a large set of data, its first row look like

02.06.2016 11;04;30.832404 1.2 3.3
02.06.2016 11;04;30.832504 2.4 2.3
02.06.2016 11;04;30.832604 6.1 7.1

I'm using tall arrays in MATLAB. I want to be able to use the timerange function to select data between different time ranges (see my previous questions:
Selecting rows of data between time and date range in tall array in MATLAB
 ).

However, if I'm not mistaken the time and the date must be in the same row. I was therefore, trying to combine the two into one row. I've tried different functions such as "join", but I was unable to find anything that works with tall arrays. Is there a way round this?

Thanks,


答:
Use Enumerable.Concat:

```<code>var query = foo.Concat(bar);
</code>```

Title: Elegant way to combine multiple collections of elements?

Body:
Use Enumerable.Concat:

var query = foo.Concat(bar);


问:
Python, sqlalchemy, Select with WHERE IN clause
Using Python and sqlalchemy:

How can I achieve the following MySQL statement with a WHERE ... IN clause using a tuple?

SELECT * FROM mytable WHERE (symbol, volume) IN (('ES', 238 ),('GB', 500 ),('OH', 800 ));

in sqlalchemy core (ie not the ORM version)

I looked in the documentation and generally on SO/google, this is nowhere to be found...

答:
```<code>from sqlalchemy import tuple_
stmt = select([mytable]).where(tuple_(mytable.c.symbol,mytable.c.volume)
                               .in_([('ES',238),('GB',500),('OH',800)]))
</code>```


问:
Reading ".dot" files in R with attribute information
How can one read in a .dot file representing a graph into R and include attribute information?

I can read in a .dot file using sna::read.dot. But this just returns an adjacency matrix without any of the attribute labels, as far as I can tell.

Using igraph::write.graph, I can write a file in the dot format...but igraph::read.graph does not allow dot files.

答:
If this was created by Graphviz then I suggest agread() from Rgraphviz provided by Bioconductor.

```<code> agwrite(graph, filename)
 agread(filename, layoutType="dot", layout=TRUE)
</code>```

Related: https://support.bioconductor.org/p/48598/

Body:
If this was created by Graphviz then I suggest agread() from Rgraphviz provided by Bioconductor.

 agwrite(graph, filename)
 agread(filename, layoutType="dot", layout=TRUE)

Related: https://support.bioconductor.org/p/48598/


问:
Building and running app via Gradle and Android Studio is slower than via Eclipse
I have a multi-project (~10 modules) of which building takes about 20-30 seconds each time. When I press Run in Android Studio, I have to wait every time to rebuild the app, which is extremely slow.

Is it possible to automate building process in Android Studio? Or do you have any advice on how to make this process faster?

In Eclipse, thanks to automatic building, running the same project on an emulator takes about 3-5 seconds.

This is my build.gradle file (app module):

```<code>buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':libraries:SharedLibs')
    compile project(':libraries:actionbarsherlock')
    compile project(':libraries:FacebookSDK')
    compile project(':libraries:GooglePlayServices')
    compile project(':libraries:HorizontalGridView')
    compile project(':libraries:ImageViewTouch')
    compile project(':libraries:SlidingMenu')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}
</code>```

答:
According to the android documentation, add this in the gradle file of app module.</p>

```<code>android {
    ...
    dexOptions {
    preDexLibraries true
    maxProcessCount 8
    }
}
</code>```

Body:
I have a multi-project (~10 modules) of which building takes about 20-30 seconds each time. When I press Run in Android Studio, I have to wait every time to rebuild the app, which is extremely slow.

Is it possible to automate building process in Android Studio? Or do you have any advice on how to make this process faster?

In Eclipse, thanks to automatic building, running the same project on an emulator takes about 3-5 seconds.

This is my build.gradle file (app module):

buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':libraries:SharedLibs')
    compile project(':libraries:actionbarsherlock')
    compile project(':libraries:FacebookSDK')
    compile project(':libraries:GooglePlayServices')
    compile project(':libraries:HorizontalGridView')
    compile project(':libraries:ImageViewTouch')
    compile project(':libraries:SlidingMenu')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}

Body:
According to the android documentation, add this in the gradle file of app module.

android {
    ...
    dexOptions {
    preDexLibraries true
    maxProcessCount 8
    }
}


问:
Cygwin + git permission problems when trying to create a commit message
When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT_EDITMSG) does exist and even contains:

```<code># Please enter the commit message for your changes.
# (Comment lines starting with '#' will not be included)
# etc...
</code>```

How can I troubleshoot this problem further?

答:
You are using mingw or msysgit git in cygwin (windows native). This will not work when using a cygwin editor (gvim). The \ is no path seperator in POSIX, it rather escapes the next character.

You need to install the cygwin git package or use a proper mingw/msysgit editor.

It might also be that the mingw git.exe is in the PATH before /usr/bin. Fix your PATH then.

Such questions are usually handled via http://cygwin.com/problems.html, esp. cygcheck -s -v -r > cygcheck.out in the mailinglist. Then we could see more.

OwnerDisplayName: Terence Lewis

Body:
When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT_EDITMSG) does exist and even contains:

# Please enter the commit message for your changes.
# (Comment lines starting with '#' will not be included)
# etc...

How can I troubleshoot this problem further?


问:
VUE + google map how include api google
I started using vue. How can I include Google API to my page? This is my code:

```<code><template>
    <div id="map"></div>
</template>

 <script>

export default {
methods: {
  init () {
    var map
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 16,
      center: new google.maps.LatLng(-33.91722, 151.23064),
      mapTypeId: 'roadmap'
    })
  }
}
}

</script>
</code>```

Where can I set

```<code><script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
</code>```

答:
The script element goes in your index.html file, for example:

```<code><!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
</html>
</code>```

If this doesnt work for you, try removing the callback from the end of the

Then in your vue instance, call your init() function once the App component has mounted. See below:

```<code>export default {
  mounted () {
    this.init()
  },
  methods: {
    init () {
      var map
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(-33.91722, 151.23064),
        mapTypeId: 'roadmap'
      })
    }
  }
}
</code>```

Title: VUE + google map how include api google

Body:
I started using vue. How can I include Google API to my page? This is my code:

<template>

</template>

Where can I set

Body:
The script element goes in your index.html file, for example:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
</html>

If this doesnt work for you, try removing the callback from the end of the <script> element's src attribute as well as the async and defer keywords, so it looks like:

<script src="https://maps.googleapis.com/maps/api/js?key=YourKey"></script>

Then in your vue instance, call your init() function once the App component has mounted. See below:

export default {
  mounted () {
    this.init()
  },
  methods: {
    init () {
      var map
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(-33.91722, 151.23064),
        mapTypeId: 'roadmap'
      })
    }
  }
}


问:
Conflict while rendering nested components with React Router 4
I have a problem with my routing using React Router 4. When using "nested" routes, one of the top routes renders a component that is matching the route but I don't want it to be rendered. I'll put the important pieces of code here and will explain what I'm trying to achieve. Here is my main/top level routing, I've removed some lines of code that are irrelevant to the issue:

This is my App.js file:

```<code>import React, {Component} from 'react';
import {Route} from 'react-router-dom';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import {mapStateToProps, mapDispatchToProps} from './selector';
import HomeView from './packages/home-view';
import HardwareView from './packages/hardware-view';
import HardwareAddView from './packages/hardware-add-view';
import HardwareTypesAddView from './packages/hardware-types-add-view';

class App extends Component {
    render() {
        return (
            <div className="App">
                <main>
                    <Route exact path="/" component={HomeView} />
                    <Route path="/hardware" component={HardwareView} />
                    <Route exact path="/hardware/add" component={HardwareAddView} />
                    <Route exact path="/hardware/types/add" component={HardwareTypesAddView} />
                </main>
            </div>
        );
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
</code>```

HomeView component only renders an empty
 for the moment.

Now lets move into the HardwareView component. Inside this component I am rendering a <Tabs/> component from material-ui. This <Tabs/> component will have 2 tabs, and each of those tabs will have its own component as content. So to illustrate, It can be seen as this:

```<code>App.js (div.App -> main)
+--------------------------------------------------------------------------+
|                                                                          |
|     hardware-view.js (Tabs component)                                    |
|    +---------------------------------------------------------------+     |
|    |              Hardware          |        Hardware Types        |     |
|    |       (Link to="/hardware")    | (Link to="/hardware/types")  |     |
|    +---------------------------------------------------------------+     |
|    |  Tab Content:                                                 |     |
|    |                                                               |     |
|    | A table that is served only when the exact path is "/hardware"|     |
|    | if the Hardware tab is selected. Or the content from          |     |
|    | "/hardware/types" if the Hardware Types tab is selected       |     |
|    |                                                               |     |
|    | - HardwareList for "/hardware"                                |     |
|    | - HardwareTypesList for "/hardware/types"                     |     |
|    +---------------------------------------------------------------+     |
+--------------------------------------------------------------------------+
</code>```

Both of the Tab Content components (HardwareList or HardwareTypesList) that gets rendered when any tab is selected, will include a link button that will navigate to either /hardware/add or /hardware/types/add. This is were the problem comes in. When I navigate to either /hardware/add or /hardware/types/add, I want to render a complete new view without the <Tabs/> component, but that is not possible since the route <Route path="/hardware" component={HardwareView} /> is matching /hardware/add or /hardware/types/add because it doesn't have the exact property.

Here is my packages/hardware-view/index.js file that contains the HardwareView component:

```<code>import React, {Component} from 'react';
import Paper from 'material-ui/Paper';
import {Tabs, Tab} from 'material-ui/Tabs';
import {Route, Link} from 'react-router-dom';
import HardwareList from '../hardware-list';
import HardwareTypesList from '../hardware-types-list';

export default class HardwareView extends Component {
    render() {
        const {location} = this.props;
        const {pathname} = location;

        return (
            <div className="hardware-view-component">
                <Paper zDepth={2}>
                    <Tabs value={pathname}>
                        <Tab label="Hardware" containerElement={<Link to="/hardware" />} value="/hardware">
                            <div className="tab-content">
                                <Route exact path="/hardware" component={HardwareList} />
                            </div>
                        </Tab>
                        <Tab label="Hardware Types" containerElement={<Link to="/hardware/types" />} value="/hardware/types">
                            <div className="tab-content">
                                <Route exact path="/hardware/types" component={HardwareTypesList} />
                            </div>
                        </Tab>
                    </Tabs>
                </Paper>
            </div>
        );
    }
}
</code>```

I've tried using the Layouts approach as described here but had no luck. I know I may be overthinking this and there is a more clean approach for this. Any suggestions or guide on how to achieve what I'm looking for?

TLDR;
Trying to render a route inside a route, but because of the paths for the routes, the base path of the URL is rendering the top level component. For example /foo renders "Component A", /foo/bar renders "Component A" and has "Component B" inside the A, but I want for /foo/bar/baz to render ONLY "Component C" and It's rendering "Component A" and "Component C".

答:
Switch renders the first child <Route> or <Redirect> that matches the location (source: docs)

```<code><Switch>
  <Route exact path="/" component={HomeView} />
  <Route exact path="/hardware/add" component={HardwareAddView} />
  <Route exact path="/hardware/types/add" component={HardwareTypesAddView} />
  <Route path="/hardware" component={HardwareView} />
</Switch>
</code>```

Body:
I have a problem with my routing using React Router 4. When using "nested" routes, one of the top routes renders a component that is matching the route but I don't want it to be rendered. I'll put the important pieces of code here and will explain what I'm trying to achieve. Here is my main/top level routing, I've removed some lines of code that are irrelevant to the issue:

This is my App.js file:

import React, {Component} from 'react';
import {Route} from 'react-router-dom';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import {mapStateToProps, mapDispatchToProps} from './selector';
import HomeView from './packages/home-view';
import HardwareView from './packages/hardware-view';
import HardwareAddView from './packages/hardware-add-view';
import HardwareTypesAddView from './packages/hardware-types-add-view';

class App extends Component {
    render() {
        return (

                    <Route exact path="/" component={HomeView} />
                    <Route path="/hardware" component={HardwareView} />
                    <Route exact path="/hardware/add" component={HardwareAddView} />
                    <Route exact path="/hardware/types/add" component={HardwareTypesAddView} />

        );
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

HomeView component only renders an empty
 for the moment.

Now lets move into the HardwareView component. Inside this component I am rendering a <Tabs/> component from material-ui. This <Tabs/> component will have 2 tabs, and each of those tabs will have its own component as content. So to illustrate, It can be seen as this:

App.js (div.App -> main)
+--------------------------------------------------------------------------+
|                                                                          |
|     hardware-view.js (Tabs component)                                    |
|    +---------------------------------------------------------------+     |
|    |              Hardware          |        Hardware Types        |     |
|    |       (Link to="/hardware")    | (Link to="/hardware/types")  |     |
|    +---------------------------------------------------------------+     |
|    |  Tab Content:                                                 |     |
|    |                                                               |     |
|    | A table that is served only when the exact path is "/hardware"|     |
|    | if the Hardware tab is selected. Or the content from          |     |
|    | "/hardware/types" if the Hardware Types tab is selected       |     |
|    |                                                               |     |
|    | - HardwareList for "/hardware"                                |     |
|    | - HardwareTypesList for "/hardware/types"                     |     |
|    +---------------------------------------------------------------+     |
+--------------------------------------------------------------------------+

Both of the Tab Content components (HardwareList or HardwareTypesList) that gets rendered when any tab is selected, will include a link button that will navigate to either /hardware/add or /hardware/types/add. This is were the problem comes in. When I navigate to either /hardware/add or /hardware/types/add, I want to render a complete new view without the <Tabs/> component, but that is not possible since the route <Route path="/hardware" component={HardwareView} /> is matching /hardware/add or /hardware/types/add because it doesn't have the exact property.

Here is my packages/hardware-view/index.js file that contains the HardwareView component:

import React, {Component} from 'react';
import Paper from 'material-ui/Paper';
import {Tabs, Tab} from 'material-ui/Tabs';
import {Route, Link} from 'react-router-dom';
import HardwareList from '../hardware-list';
import HardwareTypesList from '../hardware-types-list';

export default class HardwareView extends Component {
    render() {
        const {location} = this.props;
        const {pathname} = location;

        return (

                <Paper zDepth={2}>
                    <Tabs value={pathname}>
                        <Tab label="Hardware" containerElement={<Link to="/hardware" />} value="/hardware">

                                <Route exact path="/hardware" component={HardwareList} />

                        </Tab>
                        <Tab label="Hardware Types" containerElement={<Link to="/hardware/types" />} value="/hardware/types">

                                <Route exact path="/hardware/types" component={HardwareTypesList} />

                        </Tab>
                    </Tabs>
                </Paper>

        );
    }
}

I've tried using the Layouts approach as described here but had no luck. I know I may be overthinking this and there is a more clean approach for this. Any suggestions or guide on how to achieve what I'm looking for?

TLDR;
Trying to render a route inside a route, but because of the paths for the routes, the base path of the URL is rendering the top level component. For example /foo renders "Component A", /foo/bar renders "Component A" and has "Component B" inside the A, but I want for /foo/bar/baz to render ONLY "Component C" and It's rendering "Component A" and "Component C".

Body:
Switch renders the first child <Route> or <Redirect> that matches the location (source: docs)

<Switch>
  <Route exact path="/" component={HomeView} />
  <Route exact path="/hardware/add" component={HardwareAddView} />
  <Route exact path="/hardware/types/add" component={HardwareTypesAddView} />
  <Route path="/hardware" component={HardwareView} />
</Switch>


问:
answer repeating in the foor-loop
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

```<code>        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7
</code>```

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

```<code>MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime
</code>```

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

答: I'd guess it has something to do with you taking the max across an entire array, and thus you getting an entire array full of max values and then adding it onto your list. I would try either doing append instead of extend, or since they're all the same value you could just set maxTime = maxTime[0] </p>

Title: answer repeating in the foor-loop

Body:
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!


问:
hadoop nodemanager killed by SIGSEGV
every time I execute a big hive query, my hadoop nodemanager killed by SEGSEGV. I'm using hadoop 2.8.0 and oracle jdk 1.8.0_131

The yarn java error file snippet as follow:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f4b766818b1, pid=10904, tid=0x00007f4b33fff700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libc.so.6+0x1628b1]  __strlen_sse2_pminub+0x11
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x00007f4b727d2800):  JavaThread "ContainersLauncher #10" [_thread_in_native, id=16663, stack(0x00007f4b33eff000,0x00007f4b34000000)]

siginfo: si_signo: 11 (SIGSEGV), si_code: 1 (SEGV_MAPERR), si_addr: 0x000000000000000f

Registers:
RAX=0x0000000000000000, RBX=0x00000000000000b3, RCX=0x000000000000000f, RDX=0x0000000000000006
RSP=0x00007f4b33ffbdf8, RBP=0x00007f4b381b7e70, RSI=0x00007f4b33ffc2d0, RDI=0x000000000000000f
R8 =0x00007f4b33ffbe60, R9 =0x0000000000000008, R10=0x00000000fffff000, R11=0x00007f4b766963f4
R12=0x0000000000000022, R13=0x00007f4b381b7f10, R14=0x00007f4b77123840, R15=0x0000000000000004
RIP=0x00007f4b766818b1, EFLAGS=0x0000000000010283, CSGSFS=0x0000000000000033, ERR=0x0000000000000004
  TRAPNO=0x000000000000000e

Top of Stack: (sp=0x00007f4b33ffbdf8)
0x00007f4b33ffbdf8:   00007f4b76f1cbed 0000000000000000
0x00007f4b33ffbe08:   00007f4b33ffc6d0 00007f4b33ffc6d0
0x00007f4b33ffbe18:   00007f4b76f200e4 00007f4b76f200ed
0x00007f4b33ffbe28:   00007f4b33ffbe60 00000000016f0520
0x00007f4b33ffbe38:   00007f4b33ffbed0 0000000000000004
0x00007f4b33ffbe48:   00007f4b76f1bbe8 00007f4b33ffc6d0
0x00007f4b33ffbe58:   00007f4b33ffc2d0 00656e696c646d63
0x00007f4b33ffbe68:   0000000000000000 333030305f363938
0x00007f4b33ffbe78:   303030304bb40058 0000000000000000
0x00007f4b33ffbe88:   0000000000000000 0000000000000000
0x00007f4b33ffbe98:   0000000000000000 0000000000000000
0x00007f4b33ffbea8:   0000000000000000 0000000000000000
0x00007f4b33ffbeb8:   0000000000000000 0000000000000000
0x00007f4b33ffbec8:   0000000000000000 6d616e6500203a5d
0x00007f4b33ffbed8:   0000000000003a65 0000000000000000
0x00007f4b33ffbee8:   0000000000000000 0000000000000000
0x00007f4b33ffbef8:   0000000000000000 0000000000000000
0x00007f4b33ffbf08:   0000000000000000 0000000000000000
0x00007f4b33ffbf18:   0000000000000000 0000000000000000
0x00007f4b33ffbf28:   0000000000000000 0000000000000000
0x00007f4b33ffbf38:   0000000000000000 0000000000000000
0x00007f4b33ffbf48:   0000000000000000 0000000000000000
0x00007f4b33ffbf58:   0000000000000000 0000000000000000
0x00007f4b33ffbf68:   0000000000000000 0000000000000000
0x00007f4b33ffbf78:   0000000000000000 0000000000000000
0x00007f4b33ffbf88:   0000000000000000 0000000000000000
0x00007f4b33ffbf98:   0000000000000000 0000000000000000
0x00007f4b33ffbfa8:   0000000000000000 0000000000000000
0x00007f4b33ffbfb8:   0000000000000000 0000000000000000
0x00007f4b33ffbfc8:   0000000000000000 0000000000000000
0x00007f4b33ffbfd8:   0000000000000000 0000000000000000
0x00007f4b33ffbfe8:   0000000000000000 0000000000000000

Instructions: (pc=0x00007f4b766818b1)
0x00007f4b76681891:   c0 c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 00 48
0x00007f4b766818a1:   31 c0 89 f9 83 e1 3f 66 0f ef c0 83 f9 30 77 1d
0x00007f4b766818b1:   f3 0f 6f 0f 66 0f 74 c1 66 0f d7 d0 85 d2 0f 85
0x00007f4b766818c1:   4e 02 00 00 48 89 f8 48 83 e0 f0 eb 24 48 89 f8

Register to memory mapping:

RAX=0x0000000000000000 is an unknown value
RBX=0x00000000000000b3 is an unknown value
RCX=0x000000000000000f is an unknown value
RDX=0x0000000000000006 is an unknown value
RSP=0x00007f4b33ffbdf8 is pointing into the stack for thread: 0x00007f4b727d2800
RBP=0x00007f4b381b7e70 is pointing into the stack for thread: 0x00007f4b73bd4800
RSI=0x00007f4b33ffc2d0 is pointing into the stack for thread: 0x00007f4b727d2800
RDI=0x000000000000000f is an unknown value
R8 =0x00007f4b33ffbe60 is pointing into the stack for thread: 0x00007f4b727d2800
R9 =0x0000000000000008 is an unknown value
R10=0x00000000fffff000 is an unknown value
R11=0x00007f4b766963f4: <offset 0x1773f4> in /lib64/libc.so.6 at 0x00007f4b7651f000
R12=0x0000000000000022 is an unknown value
R13=0x00007f4b381b7f10 is pointing into the stack for thread: 0x00007f4b73bd4800
R14=0x00007f4b77123840: snoopy_inputdatastorage_data+0 in /usr/local/snoopy/lib/libsnoopy.so at 0x00007f4b76f16000
R15=0x0000000000000004 is an unknown value

Stack: [0x00007f4b33eff000,0x00007f4b34000000],  sp=0x00007f4b33ffbdf8,  free space=1011k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [libc.so.6+0x1628b1]  __strlen_sse2_pminub+0x11

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  java.lang.UNIXProcess.forkAndExec(I[B[B[BI[BI[B[IZ)I+0
j  java.lang.UNIXProcess.<init>([B[BI[BI[B[IZ)V+30
j  java.lang.ProcessImpl.start([Ljava/lang/String;Ljava/util/Map;Ljava/lang/String;[Ljava/lang/ProcessBuilder$Redirect;Z)Ljava/lang/Process;+433
j  java.lang.ProcessBuilder.start()Ljava/lang/Process;+161
j  org.apache.hadoop.util.Shell.runCommand()V+136
j  org.apache.hadoop.util.Shell.run()V+23
j  org.apache.hadoop.util.Shell$ShellCommandExecutor.execute()V+67
j  org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(Lorg/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext;)I+492
j  org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call()Ljava/lang/Integer;+1166
j  org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call()Ljava/lang/Object;+1
J 4490 C1 java.util.concurrent.FutureTask.run()V (126 bytes) @ 0x00007f4b5e50acdc [0x00007f4b5e50aa80+0x25c]
j  java.util.concurrent.ThreadPoolExecutor.runWorker(Ljava/util/concurrent/ThreadPoolExecutor$Worker;)V+95
j  java.util.concurrent.ThreadPoolExecutor$Worker.run()V+5
j  java.lang.Thread.run()V+11
v  ~StubRoutines::call_stub
</code>```

the completed log can be downloaded here yarn_hs_error.log

it seems like a hadoop or jdk bug?

答:
Finally I solved the problem, it's because snoopy, I disable it and it works good now.</p>

```<code>/usr/local/snoopy/sbin/snoopy-disable
</code>```

Title: hadoop nodemanager killed by SIGSEGV

Body:
every time I execute a big hive query, my hadoop nodemanager killed by SEGSEGV. I'm using hadoop 2.8.0 and oracle jdk 1.8.0_131

The yarn java error file snippet as follow:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f4b766818b1, pid=10904, tid=0x00007f4b33fff700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libc.so.6+0x1628b1]  __strlen_sse2_pminub+0x11
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x00007f4b727d2800):  JavaThread "ContainersLauncher #10" [_thread_in_native, id=16663, stack(0x00007f4b33eff000,0x00007f4b34000000)]

siginfo: si_signo: 11 (SIGSEGV), si_code: 1 (SEGV_MAPERR), si_addr: 0x000000000000000f

Registers:
RAX=0x0000000000000000, RBX=0x00000000000000b3, RCX=0x000000000000000f, RDX=0x0000000000000006
RSP=0x00007f4b33ffbdf8, RBP=0x00007f4b381b7e70, RSI=0x00007f4b33ffc2d0, RDI=0x000000000000000f
R8 =0x00007f4b33ffbe60, R9 =0x0000000000000008, R10=0x00000000fffff000, R11=0x00007f4b766963f4
R12=0x0000000000000022, R13=0x00007f4b381b7f10, R14=0x00007f4b77123840, R15=0x0000000000000004
RIP=0x00007f4b766818b1, EFLAGS=0x0000000000010283, CSGSFS=0x0000000000000033, ERR=0x0000000000000004
  TRAPNO=0x000000000000000e

Top of Stack: (sp=0x00007f4b33ffbdf8)
0x00007f4b33ffbdf8:   00007f4b76f1cbed 0000000000000000
0x00007f4b33ffbe08:   00007f4b33ffc6d0 00007f4b33ffc6d0
0x00007f4b33ffbe18:   00007f4b76f200e4 00007f4b76f200ed
0x00007f4b33ffbe28:   00007f4b33ffbe60 00000000016f0520
0x00007f4b33ffbe38:   00007f4b33ffbed0 0000000000000004
0x00007f4b33ffbe48:   00007f4b76f1bbe8 00007f4b33ffc6d0
0x00007f4b33ffbe58:   00007f4b33ffc2d0 00656e696c646d63
0x00007f4b33ffbe68:   0000000000000000 333030305f363938
0x00007f4b33ffbe78:   303030304bb40058 0000000000000000
0x00007f4b33ffbe88:   0000000000000000 0000000000000000
0x00007f4b33ffbe98:   0000000000000000 0000000000000000
0x00007f4b33ffbea8:   0000000000000000 0000000000000000
0x00007f4b33ffbeb8:   0000000000000000 0000000000000000
0x00007f4b33ffbec8:   0000000000000000 6d616e6500203a5d
0x00007f4b33ffbed8:   0000000000003a65 0000000000000000
0x00007f4b33ffbee8:   0000000000000000 0000000000000000
0x00007f4b33ffbef8:   0000000000000000 0000000000000000
0x00007f4b33ffbf08:   0000000000000000 0000000000000000
0x00007f4b33ffbf18:   0000000000000000 0000000000000000
0x00007f4b33ffbf28:   0000000000000000 0000000000000000
0x00007f4b33ffbf38:   0000000000000000 0000000000000000
0x00007f4b33ffbf48:   0000000000000000 0000000000000000
0x00007f4b33ffbf58:   0000000000000000 0000000000000000
0x00007f4b33ffbf68:   0000000000000000 0000000000000000
0x00007f4b33ffbf78:   0000000000000000 0000000000000000
0x00007f4b33ffbf88:   0000000000000000 0000000000000000
0x00007f4b33ffbf98:   0000000000000000 0000000000000000
0x00007f4b33ffbfa8:   0000000000000000 0000000000000000
0x00007f4b33ffbfb8:   0000000000000000 0000000000000000
0x00007f4b33ffbfc8:   0000000000000000 0000000000000000
0x00007f4b33ffbfd8:   0000000000000000 0000000000000000
0x00007f4b33ffbfe8:   0000000000000000 0000000000000000

Instructions: (pc=0x00007f4b766818b1)
0x00007f4b76681891:   c0 c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 00 48
0x00007f4b766818a1:   31 c0 89 f9 83 e1 3f 66 0f ef c0 83 f9 30 77 1d
0x00007f4b766818b1:   f3 0f 6f 0f 66 0f 74 c1 66 0f d7 d0 85 d2 0f 85
0x00007f4b766818c1:   4e 02 00 00 48 89 f8 48 83 e0 f0 eb 24 48 89 f8

Register to memory mapping:

RAX=0x0000000000000000 is an unknown value
RBX=0x00000000000000b3 is an unknown value
RCX=0x000000000000000f is an unknown value
RDX=0x0000000000000006 is an unknown value
RSP=0x00007f4b33ffbdf8 is pointing into the stack for thread: 0x00007f4b727d2800
RBP=0x00007f4b381b7e70 is pointing into the stack for thread: 0x00007f4b73bd4800
RSI=0x00007f4b33ffc2d0 is pointing into the stack for thread: 0x00007f4b727d2800
RDI=0x000000000000000f is an unknown value
R8 =0x00007f4b33ffbe60 is pointing into the stack for thread: 0x00007f4b727d2800
R9 =0x0000000000000008 is an unknown value
R10=0x00000000fffff000 is an unknown value
R11=0x00007f4b766963f4: <offset 0x1773f4> in /lib64/libc.so.6 at 0x00007f4b7651f000
R12=0x0000000000000022 is an unknown value
R13=0x00007f4b381b7f10 is pointing into the stack for thread: 0x00007f4b73bd4800
R14=0x00007f4b77123840: snoopy_inputdatastorage_data+0 in /usr/local/snoopy/lib/libsnoopy.so at 0x00007f4b76f16000
R15=0x0000000000000004 is an unknown value

Stack: [0x00007f4b33eff000,0x00007f4b34000000],  sp=0x00007f4b33ffbdf8,  free space=1011k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [libc.so.6+0x1628b1]  __strlen_sse2_pminub+0x11

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  java.lang.UNIXProcess.forkAndExec(I[B[B[BI[BI[B[IZ)I+0
j  java.lang.UNIXProcess.<init>([B[BI[BI[B[IZ)V+30
j  java.lang.ProcessImpl.start([Ljava/lang/String;Ljava/util/Map;Ljava/lang/String;[Ljava/lang/ProcessBuilder$Redirect;Z)Ljava/lang/Process;+433
j  java.lang.ProcessBuilder.start()Ljava/lang/Process;+161
j  org.apache.hadoop.util.Shell.runCommand()V+136
j  org.apache.hadoop.util.Shell.run()V+23
j  org.apache.hadoop.util.Shell$ShellCommandExecutor.execute()V+67
j  org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(Lorg/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext;)I+492
j  org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call()Ljava/lang/Integer;+1166
j  org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call()Ljava/lang/Object;+1
J 4490 C1 java.util.concurrent.FutureTask.run()V (126 bytes) @ 0x00007f4b5e50acdc [0x00007f4b5e50aa80+0x25c]
j  java.util.concurrent.ThreadPoolExecutor.runWorker(Ljava/util/concurrent/ThreadPoolExecutor$Worker;)V+95
j  java.util.concurrent.ThreadPoolExecutor$Worker.run()V+5
j  java.lang.Thread.run()V+11
v  ~StubRoutines::call_stub

the completed log can be downloaded here yarn_hs_error.log

it seems like a hadoop or jdk bug?

Body:
Finally I solved the problem, it's because snoopy, I disable it and it works good now.

/usr/local/snoopy/sbin/snoopy-disable


问:
Is there any updated documentation about the System.AddIn namespace
Everything is in the question, I am trying to make an extensible application by means of add-ins, so other teams can developpe add-in independently of the team that developpe the core application.
While I was looking for documentation I found this which seems to be up to date but the links to the Pipeline requirement are broken. I fount another doc on the MSDN but it's for the .Net 3.5 framework.
And If anyone can point me out to a good tutorial or a book about this framework It will be highly appreciated.

Thank you in advance for help.

答: There is not much out there.  The 3.5 documentation still works and MAF is still functional in .Net 4.6, but there are very few people using it.  Based on feedback from Microsoft, they do not appear to be considering it for a port to .Net Core, so if you have any plans on targeting that in the future, you should look into alternatives.</p>


问:
Delete first character from a text file

I have a text file in which the first character - I want to delete, but I am not getting either its a CR or LF character, how Can I delete the file character from the entire file.

答:
If the first character that you want to delete is on the first line only, use the tail command. tail -c +2 will do the job.

```<code><oldFile tail -c +2 >newFile
</code>```

If the first character that you want to delete is on every line of the file, use the sed command. sed -e 's/^.//' will do the job.

```<code><oldFile sed -e 's/^.//' >newFile
</code>```

If the first character that you want to delete is on some lines of the file, and it is a specific character, again use the sed command. For example, you might want to remove a leading space from each line that has leading space.

```<code><oldFile sed -e 's/^ //' >newFile
</code>```

Title: Delete first character from a text file

Body:
If the first character that you want to delete is on the first line only, use the tail command. tail -c +2 will do the job.

<oldFile tail -c +2 >newFile

If the first character that you want to delete is on every line of the file, use the sed command. sed -e 's/^.//' will do the job.

<oldFile sed -e 's/^.//' >newFile

If the first character that you want to delete is on some lines of the file, and it is a specific character, again use the sed command. For example, you might want to remove a leading space from each line that has leading space.

<oldFile sed -e 's/^ //' >newFile


答:
I think you might be looking for LINQ's .Concat()?

```<code>var combined = foo.Concat(bar).Concat(foobar).Concat(...);
</code>```

Alternatively, .Union() will remove duplicate elements.

Body:
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}

Which I'd then call like this:

var combined = Combine(foo, bar);

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.

Body:
I think you might be looking for LINQ's .Concat()?

var combined = foo.Concat(bar).Concat(foobar).Concat(...);

Alternatively, .Union() will remove duplicate elements.


问:
Why Is It That Some FAKE Methods Don't Work Within Target Functions?
Consider the following:

```<code>#r @"FakeLib.dll"

open Fake
open Fake.StringHelper
open Fake.ProcessHelper

Shell.Exec("mkdir","exampleDirectory")

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
)

Target "Clean" ( fun () ->
    trace  "Cleaning..."
)

Target "Deploy" (fun () ->
    trace  "Deploying..."
)

"DoStuff"
    ==>"Clean"
    ==>"Deploy"

RunTargetOrDefault "Deploy"
</code>```

The above script works fine, but when I move the Shell.Exec within a Target like this:

```<code>#r @"FakeLib.dll"

open Fake
open Fake.StringHelper
open Fake.ProcessHelper

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    Shell.Exec("mkdir","exampleDirectory")
)

Target "Clean" ( fun () ->
    trace  "Cleaning..."
)

Target "Deploy" (fun () ->
    trace  "Deploying..."
)

"DoStuff"
    ==>"Clean"
    ==>"Deploy"

RunTargetOrDefault "Deploy"
</code>```

I end up with a an error:

```<code>FsiEvaluationException:

Error:

        DeployScript.fsx(10,5): error FS0001: This expression was expected to have type
            unit
        but here has type
            int

Output: [Loading C:\Users\myusername\Desktop\SomeFolder\DeployScript.fsx]

Input: C:\Users\myusername\Desktop\SomeFolder\DeployScript.fsx
\Arguments:
  C:\fsi.exe

Exception: Yaaf.FSharp.Scripting.FsiEvaluationException: Error while compiling or executing fsharp snippet. ---> System.Exception: Operation failed. The error text has been print the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.commitResult[a,b](FSharpChoice`2 res)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.EvalScript(String filePath)
   at Yaaf.FSharp.Scripting.Helper.evalScript@1303.Invoke(String arg00) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1303
   at Yaaf.FSharp.Scripting.Helper.save_@1276-2.Invoke(Unit unitVar0) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1277
   at Yaaf.FSharp.Scripting.Helper.consoleCapture[a](TextWriter out, TextWriter err, FSharpFunc`2 f) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1221
   at Yaaf.FSharp.Scripting.Helper.redirectOut@1247[a](Boolean preventStdOut, OutStreamHelper out, OutStreamHelper err, FSharpFunc`2 f) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1254
   at Yaaf.FSharp.Scripting.Helper.save_@1275-1.Invoke(String text) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1276
   --- End of inner exception stack trace ---
   at Yaaf.FSharp.Scripting.Helper.save_@1275-1.Invoke(String text) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1284
   at Yaaf.FSharp.Scripting.Helper.session@1306.Yaaf-FSharp-Scripting-IFsiSession-EvalScriptWithOutput(String ) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1308
   at Fake.FSIHelper.runScriptUncached(Boolean useCache, String scriptPath, IEnumerable`1 fsiOptions, Boolean printDetails, CacheInfo cacheInfo, TextWriter out, TextWriter err) in C:\code\fake\src\app\FakeLib\FSIHelper.fs:line 471
DeployScript.fsx(10,5): error FS0001: This expression was expected to have type
</code>```

The point here is I'm trying to do a shell command only under a certain target.  Pay no attention to the mkdir command as I actually would like to use the schtasks command.  I just used mkdir for simplicity purposes.  Maybe there's a nuance that I'm missing here.  I've also noticed this same behavior with using environVarOrFail. Thanks in advance to all who reply.

答:
Shell.Exec returns an int, but Target expects a function that returns a unit.

Try this:

let returnUnit() = ()
let return42() = 42

Target "One" returnUnit // works
Target "Two" return42 // fails: expected to have type unit, but here has type int
```

<p>The target "Two" fails to compile, because its second argument is a function that returns an <code>int</code>, whereas a function returning <code>unit</code> is expected.</p>

<p>This error is there to keep you from forgetting function return values: the compiler helpfully tells you "Hey, are you sure you don't want to do anything with this int? Then why did you call the function in the first place?"</p>

<p>Sometimes, however, it makes sense to throw away the return value. For example, in this particular case, you're calling <code>Shell.Exec</code> for its side effect, and its return value does not interest you. This situation occurs surprisingly often, so often that there is a special function for it - <code>ignore</code>.</p>

<pre class="lang-fs prettyprint-override"><code>Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    Shell.Exec("mkdir","exampleDirectory") |> ignore // compiles fine
)
</code>```

This function takes any value, throws it away, and returns a unit. By applying it to the result of Shell.Exec, you tell the compiler: "Yes, I'm sure I don't need this value, please ignore it."

That said, I would strongly recommend using specialized functions instead of generic system calls. This will make your script more readable, and might even help you catch an occasional error early. For example, to create a directory, use FileUtils.mkdir:

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    FileUtils.mkdir "exampleDirectory"  // no need for `ignore`, mkdir already returns `unit`
)
```

Body:
Consider the following:

#r @"FakeLib.dll"

open Fake
open Fake.StringHelper
open Fake.ProcessHelper

Shell.Exec("mkdir","exampleDirectory")

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
)

Target "Clean" ( fun () ->
    trace  "Cleaning..."
)

Target "Deploy" (fun () ->
    trace  "Deploying..."
)

"DoStuff"
    ==>"Clean"
    ==>"Deploy"

RunTargetOrDefault "Deploy"

The above script works fine, but when I move the Shell.Exec within a Target like this:

#r @"FakeLib.dll"

open Fake
open Fake.StringHelper
open Fake.ProcessHelper

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    Shell.Exec("mkdir","exampleDirectory")
)

Target "Clean" ( fun () ->
    trace  "Cleaning..."
)

Target "Deploy" (fun () ->
    trace  "Deploying..."
)

"DoStuff"
    ==>"Clean"
    ==>"Deploy"

RunTargetOrDefault "Deploy"

I end up with a an error:

FsiEvaluationException:

Error:

        DeployScript.fsx(10,5): error FS0001: This expression was expected to have type
            unit
        but here has type
            int

Output: [Loading C:\Users\myusername\Desktop\SomeFolder\DeployScript.fsx]

Input: C:\Users\myusername\Desktop\SomeFolder\DeployScript.fsx
\Arguments:
  C:\fsi.exe

Exception: Yaaf.FSharp.Scripting.FsiEvaluationException: Error while compiling or executing fsharp snippet. ---> System.Exception: Operation failed. The error text has been print the error stream. To return the corresponding FSharpErrorInfo use the EvalInteractionNonThrowing, EvalScriptNonThrowing or EvalExpressionNonThrowing
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.commitResult[a,b](FSharpChoice`2 res)
   at Microsoft.FSharp.Compiler.Interactive.Shell.FsiEvaluationSession.EvalScript(String filePath)
   at Yaaf.FSharp.Scripting.Helper.evalScript@1303.Invoke(String arg00) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1303
   at Yaaf.FSharp.Scripting.Helper.save_@1276-2.Invoke(Unit unitVar0) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1277
   at Yaaf.FSharp.Scripting.Helper.consoleCapture[a](TextWriter out, TextWriter err, FSharpFunc`2 f) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1221
   at Yaaf.FSharp.Scripting.Helper.redirectOut@1247[a](Boolean preventStdOut, OutStreamHelper out, OutStreamHelper err, FSharpFunc`2 f) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1254
   at Yaaf.FSharp.Scripting.Helper.save_@1275-1.Invoke(String text) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1276
   --- End of inner exception stack trace ---
   at Yaaf.FSharp.Scripting.Helper.save_@1275-1.Invoke(String text) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1284
   at Yaaf.FSharp.Scripting.Helper.session@1306.Yaaf-FSharp-Scripting-IFsiSession-EvalScriptWithOutput(String ) in C:\code\fake\paket-files\matthid\Yaaf.FSharp.Scripting\src\source\Yaaf.FSharp.Scripting\YaafFSharpScripting.fs:line 1308
   at Fake.FSIHelper.runScriptUncached(Boolean useCache, String scriptPath, IEnumerable`1 fsiOptions, Boolean printDetails, CacheInfo cacheInfo, TextWriter out, TextWriter err) in C:\code\fake\src\app\FakeLib\FSIHelper.fs:line 471
DeployScript.fsx(10,5): error FS0001: This expression was expected to have type

The point here is I'm trying to do a shell command only under a certain target.  Pay no attention to the mkdir command as I actually would like to use the schtasks command.  I just used mkdir for simplicity purposes.  Maybe there's a nuance that I'm missing here.  I've also noticed this same behavior with using environVarOrFail. Thanks in advance to all who reply.

Body:
Shell.Exec returns an int, but Target expects a function that returns a unit.

Try this:

let returnUnit() = ()
let return42() = 42

Target "One" returnUnit // works
Target "Two" return42 // fails: expected to have type unit, but here has type int

The target "Two" fails to compile, because its second argument is a function that returns an int, whereas a function returning unit is expected.

This error is there to keep you from forgetting function return values: the compiler helpfully tells you "Hey, are you sure you don't want to do anything with this int? Then why did you call the function in the first place?"

Sometimes, however, it makes sense to throw away the return value. For example, in this particular case, you're calling Shell.Exec for its side effect, and its return value does not interest you. This situation occurs surprisingly often, so often that there is a special function for it - ignore.

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    Shell.Exec("mkdir","exampleDirectory") |> ignore // compiles fine
)

This function takes any value, throws it away, and returns a unit. By applying it to the result of Shell.Exec, you tell the compiler: "Yes, I'm sure I don't need this value, please ignore it."

That said, I would strongly recommend using specialized functions instead of generic system calls. This will make your script more readable, and might even help you catch an occasional error early. For example, to create a directory, use FileUtils.mkdir:

Target "DoStuff" ( fun () ->
    trace "Doing Stuff..."
    FileUtils.mkdir "exampleDirectory"  // no need for `ignore`, mkdir already returns `unit`
)