问:
How does std::map operator[] cause memory leak with fundamental data types?
I'm using Visual Leak Detector to detect memory leaks, and have encountered many instances of memory leaks in lines such as:

```<code>class SomeClass
{
    // ...
    std::map<long,long> some_map;

    void func(long a_long, long b_long)
    {
        some_map[a_long] = b_long;  // here be a memory leak
    }
}
</code>```

How is this even possible? there are no pointers here, no object instantiation.

Could it be a memory leak that is a side-effect of having the program crash due to something else? Would a program crash or exit(1) cause the map to not be destructed cleanly?

答:
There's no memory leak there, but there are instantiations.

When you insert into a map, it needs to create a new node in its tree (a map is usually a red-black tree). Typically, the map will allocate dynamic memory for every insertion, and this is no different for primitive types, user-defined types or pointers.

ContentLicense: CC BY-SA 2.5

Body:
I'm using Visual Leak Detector to detect memory leaks, and have encountered many instances of memory leaks in lines such as:

class SomeClass
{
    // ...
    std::map<long,long> some_map;

    void func(long a_long, long b_long)
    {
        some_map[a_long] = b_long;  // here be a memory leak
    }
}

How is this even possible? there are no pointers here, no object instantiation.

Could it be a memory leak that is a side-effect of having the program crash due to something else? Would a program crash or exit(1) cause the map to not be destructed cleanly?


来源: stackexchange

问:
HTML tag form without "action" attribute
I'm using this HTML code in an HTML page:

```<code><form method="post">
  <div class="form-group">
    <input type="text" class="form-control" name="username">
  </div>
  <div class="form-group">
    <input type="password" class="form-control" name="password">
  </div>
  <input type="hidden" name="ref" value="post-ad.php"/>
  <button type="submit" name="submit" id="submit" class="btn">S'identifier</button>
</form>
</code>```

On clicking submit button which action will this form execute? I noticed that it execute the value of input named "ref" in this example "post-ad.php" or "index.php" or "dashboard.php". Is it normal?! As I know the action attribute is mandatory?

答:
without action attribute it will POST/GET to the same page
see here

ContentLicense: CC BY-SA 3.0

Body:
I'm using this HTML code in an HTML page:

<form method="post">

    <input type="text" class="form-control" name="username">

    <input type="password" class="form-control" name="password">

  <input type="hidden" name="ref" value="post-ad.php"/>
  <button type="submit" name="submit" id="submit" class="btn">S'identifier</button>
</form>

On clicking submit button which action will this form execute? I noticed that it execute the value of input named "ref" in this example "post-ad.php" or "index.php" or "dashboard.php". Is it normal?! As I know the action attribute is mandatory?


问:
Python regex library can't match even though it should
My script:

```<code>#!/usr/bin/env python
import os
import re

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))
</code>```

Supposed to loop through the lines in the file given and match the regex provided, if exists, append to res and eventually return res.

The content of /opt/conf/streaming.cfg contains a line:

```<code>SocketAcceptPort=8003
</code>```

Still prints []

How come?

答:
Checking the docs for re.match gives us this first sentence:

If zero or more characters at the beginning of string match

Notice the part about "beginning of string"? You need to use a different re function to match anywhere in the line. For example, further down in the docs for match is this note:

If you want to locate a match anywhere in string, use search() instead

Body:
My script:

#!/usr/bin/env python
import os
import re

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

print(grep('/opt/conf/streaming.cfg', 'Port='))

Supposed to loop through the lines in the file given and match the regex provided, if exists, append to res and eventually return res.

The content of /opt/conf/streaming.cfg contains a line:

SocketAcceptPort=8003

Still prints []

How come?


问:
How to change Android O / Oreo / api 26 app language
I want to change the language of the app and this works fine until API 26.

For api > 25 I put Locale.setDefault(Locale.Category.DISPLAY, mynewlanglocale); before setContentView(R.layout.activity_main); but nothing changes.

The docs don't explain too much about this.

答: You need to use getApplicationContext() instead of getContext()

ContentLicense: CC BY-SA 4.0


问:
Angular - code coverage for the views
While developing applications with Angular (2,4,5,...) people are using a lot of *ngIf="whatever_condition" and less often also ngSwitch

However I have not seen any tooling that would be able to provide information about how much of that code was actually tested..

Obviously for Typescript files there's istanbul loader to get the coverage, but I believe it gives false picture of having a high coverage in a sense that a big chunk of the logic sits in the views for which there is no measurement.. I.e. if I have branch coverage of 90% on Typescript, but still have two times as much branches in the views, the actual coverage might be somewhere between 45% and 90%.

Is there any tooling out there that is able to measure code coverage for Angular views and show it in a meaningful way?

答:
I have not looked into coverage on the template, but, you could look into component- vs unittest.

I usually do the following:

```<code>it('',()=>{
  component.whatever_condition = true;
  const el = fixture.debugElement.query(By.css('someElement'));

  fixture.detectChanges();

  expect(el).toBeDefined();
});
</code>```

I realise this doesn't give you coverage, but it provides tests for your template.

NB consider if an e2e test is what you need instead

I hope it helps

Title: Angular - code coverage for the views

Body:
I have not looked into coverage on the template, but, you could look into component- vs unittest.

I usually do the following:

it('',()=>{
  component.whatever_condition = true;
  const el = fixture.debugElement.query(By.css('someElement'));

  fixture.detectChanges();

  expect(el).toBeDefined();
});

I realise this doesn't give you coverage, but it provides tests for your template.

NB consider if an e2e test is what you need instead

I hope it helps


问:
Accessing Localhost and Virtualhost From Emulator in Android Studio?
I want to access localhost from android studio emulator or from genymotion without typing the IP address instead typing as localhost or as domain name.
If you are into web development you could under stand more like we assign domain for IP in the C:\Windows\System32\drivers\etc\hosts file in windows system.
I tried out steps from some blogs but couldn't figure it out.

Please do help me out. Thanks!

答:
You can try editing the hosts file from terminal of the android studio.

First go to terminal and launch the emulator
emulator -avd AVDNAME -partition-size 128

Second remount the AVD to make it writable
adb remount

Third pull the host file from emulator to your local machine
adb pull /etc/hosts

Fourth edit the host file using local editor based on the need
198.0.0.1 localhost

Finally, push the edited file from local machine back to emulator adb push hosts /etc/hosts

Now, type localhost or domain you assigned in the host file.

Hope this is enough!


问:
Do GraphDB Google Charts send my data anywhere besides my own server or client?
After running a SPARQL query in the GraphDB workbench, one can make some nice visualizations with Google Charts (in addition to an un-attributed "Pivot Table" tab.)

I have hospital records that are de-identified, but I still need to be as conservative as possible.

If I use either the Google Charts or Pivot Table tab offered in GraphDB, will the results of my query be sent to any computer besides my server and my client, in order to create the visualization?

If you don't know the definitive answer but can suggest a method for doing my own research, I would certainly try it on my own.  Maybe something with my browser's developer's tools?  I'm hoping to avoid using a packer sniffer application.

答:
I doubt that it is sending your data to some other server to render the chart or the pivot table. Google charts depends on .js being loaded (potentially from remote server), but rendering is done locally (client machine).

However, to make absolutely sure for yourself you can do the following on your server.

Load some test data (not your patient data, i.e. example data coming with graphdb) and draw something with Google charts. This is to ensure all .js libraries are loaded.

Disconnect from the network. Ensure both LAN and Wifi are disabled.

Now draw a different chart (to ensure cached chart is not re-displayed). If the chart can be drawn, it requires no external server to draw the chart.


问:
Application (service) self-upgrade?
I'm developing a .NET4-based application in C# which runs as a windows service.

I'd like this application to be able to upgrade itself when instructed to do so by a web-service that it connects to periodically.  Is there an accepted way to accomplish this?  Is it even possible?

The way I'm thinking of it is something like this:

The windows service (.exe) code downloads its replacement and supporting DLLs as a zip and extracts them to a temporary directory.  The zip also includes a small "upgrader" executable or script.

The service forks a child process to run the upgrader, passing the destination directory and any other required information on the command-line

The service shuts down

The upgrader process waits for the service to stop completely, then moves the necessary files (new .exe, DLLs) into the final installation directory, replacing the old file(s)

The upgrader restarts the windows service, which spawns the (upgraded) .exe and quits once it starts

Would this work?  You may detect from my terminology and approach that I'm from a UNIX background and not a windows background.  I've made this approach work on UNIX, but I have no idea what sort of windows gotchas may exist...

UPDATE: My main motivation for this question is around the technical feasibility of a self-updating .NET application (how to do an in-place replacement of .DLLs, etc).  As pointed out in the comments, there are a host of other considerations involved in implementing a feature like this, in particular security concerns around verifying the new software components being applied are in fact legitimate.  These are also important, but not specific to .NET or Windows (imo).  Comments on these areas are welcome of course, but they are not my primary concern at this time...

答:
This could be done using ClickOnce, but maybe not quite to the extent you want.

Take a look at this class

```<code>Imports System.Deployment.Application
Imports System.ComponentModel

Public Class UpdateChecker

    Public Enum UpdateType
        Automatic
        Manual
    End Enum

    Private Shared MyInstance As UpdateChecker
    Public Shared ReadOnly Property Current() As UpdateChecker
        Get
            If MyInstance Is Nothing Then
                MyInstance = New UpdateChecker
            End If
            Return MyInstance
        End Get
    End Property

    Private WithEvents CurrDeployment As ApplicationDeployment
    Private CurrType As UpdateType
    Private _checking As Boolean = False
    Private _lastErrorSentOnCheck As DateTime?

    Public ReadOnly Property LastUpdateCheck() As DateTime?
        Get
            If CurrDeployment IsNot Nothing Then
                Return CurrDeployment.TimeOfLastUpdateCheck
            End If
            Return Nothing
        End Get
    End Property

    Public Sub CheckAsync(ByVal checkType As UpdateType)
        Try
            Dim show As Boolean = (checkType = UpdateType.Manual)
            If ApplicationDeployment.IsNetworkDeployed AndAlso _
               Not WindowActive(show) AndAlso Not _checking AndAlso _
               (checkType = UpdateType.Manual OrElse Not LastUpdateCheck.HasValue OrElse LastUpdateCheck.Value.AddMinutes(60) <= Date.UtcNow) Then

                _checking = True

                CurrDeployment = ApplicationDeployment.CurrentDeployment
                CurrType = checkType

                Dim bw As New BackgroundWorker
                AddHandler bw.RunWorkerCompleted, AddressOf CurrDeployment_CheckForUpdateCompleted
                AddHandler bw.DoWork, AddressOf StartAsync

                If CurrType = UpdateType.Manual Then ShowWindow()

                bw.RunWorkerAsync()
            ElseIf checkType = UpdateType.Manual AndAlso _checking Then
                CurrType = checkType
                WindowActive(True)
            ElseIf checkType = UpdateType.Manual AndAlso Not ApplicationDeployment.IsNetworkDeployed Then
                MessageBox.Show(MainForm, "Cannot check for updates.", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            If Not _lastErrorSentOnCheck.HasValue OrElse _lastErrorSentOnCheck.Value.AddHours(1) <= Now Then
                _lastErrorSentOnCheck = Now
                My.Application.LogError(ex, New StringPair("Update Check", checkType.ToString))
            End If
        End Try
    End Sub

    Private Sub StartAsync(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        e.Result = CurrDeployment.CheckForDetailedUpdate
    End Sub

    Private Sub ShowWindow()
        My.Forms.frmUpdates.MdiParent = MainForm
        AddHandler My.Forms.frmUpdates.FormClosing, AddressOf frmUpdates_FormClosing
        My.Forms.frmUpdates.Show()
    End Sub

    Protected Sub frmUpdates_FormClosing(ByVal sender As Object, ByVal e As Windows.Forms.FormClosingEventArgs)
        My.Forms.frmUpdates = Nothing
    End Sub

    Private Function WindowActive(ByVal onTop As Boolean) As Boolean
        If Not My.Forms.frmUpdates Is Nothing Then
            If Not My.Forms.frmUpdates.Visible AndAlso onTop Then
                My.Forms.frmUpdates.MdiParent = MainForm
                My.Forms.frmUpdates.Show()
            ElseIf onTop Then
                My.Forms.frmUpdates.Activate()
            End If
            Return True
        End If
        Return False
    End Function

    Private Sub CurrDeployment_CheckForUpdateCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        If MainForm.InvokeRequired Then
            MainForm.Invoke(New RunWorkerCompletedEventHandler(AddressOf CurrDeployment_CheckForUpdateCompleted), sender, e)
        Else
            If e.Error IsNot Nothing Then
                If WindowActive(True) Then My.Forms.frmUpdates.ShowError("Please try again later.")

                If Not _lastErrorSentOnCheck.HasValue OrElse _lastErrorSentOnCheck.Value.AddHours(1) <= Now Then
                    _lastErrorSentOnCheck = Now
                    My.Application.LogError(e.Error, New StringPair("Update Check Async", CurrType.ToString))
                End If
            Else
                Dim updateInfo As UpdateCheckInfo = DirectCast(e.Result, UpdateCheckInfo)
                Select Case CurrType
                    Case UpdateType.Manual
                        If WindowActive(False) Then My.Forms.frmUpdates.ShowCheckComplete(updateInfo)
                    Case UpdateType.Automatic
                        If updateInfo.UpdateAvailable Then
                            If Not WindowActive(True) Then ShowWindow()
                            My.Forms.frmUpdates.ShowCheckComplete(updateInfo)
                        End If
                End Select
            End If
            _checking = False
            End If

        DirectCast(sender, BackgroundWorker).Dispose()
    End Sub

    Public Sub UpdateAsync()
        If ApplicationDeployment.IsNetworkDeployed Then
            CurrDeployment = ApplicationDeployment.CurrentDeployment

            Dim bw As New BackgroundWorker
            AddHandler bw.RunWorkerCompleted, AddressOf CurrDeployment_UpdateCompleted
            AddHandler bw.DoWork, AddressOf StartUpdateAsync

            My.Forms.frmUpdates.ShowUpdateStart()

            bw.RunWorkerAsync()
        End If
    End Sub

    Public Sub StartUpdateAsync()
        CurrDeployment.Update()
    End Sub

    Private Sub CurrDeployment_UpdateCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles CurrDeployment.UpdateCompleted
        If MainForm.InvokeRequired Then
            MainForm.Invoke(New AsyncCompletedEventHandler(AddressOf CurrDeployment_UpdateCompleted), sender, e)
        Else
            If e.Error IsNot Nothing Then
                If WindowActive(True) Then My.Forms.frmUpdates.ShowError("Please try again later or close and re-open the application to automatically retrieve updates.")
                My.Application.LogError(e.Error, New StringPair("Update Async", CurrType.ToString))
            Else
                If WindowActive(True) Then My.Forms.frmUpdates.ShowUpdateComplete()
            End If
        End If
    End Sub
End Class
</code>```

Here's the code to check if a new update is required. you'd run this on a timer, maybe every 5 minutes

```<code> UpdateChecker.Current.CheckAsync(UpdateChecker.UpdateType.Automatic)
</code>```

Then here's the code to download the update.

```<code> UpdateChecker.Current.UpdateAsync()
</code>```

The user would have to quit and start the application to get the new version or
after the update completes you could also use Application.Restart to restart the application

This wouldn't update when the program isn't running, but with ClickOnce you can have it check for updates when the program is launched.

Title: Application (service) self-upgrade?

Body:
This could be done using ClickOnce, but maybe not quite to the extent you want.

Take a look at this class

Imports System.Deployment.Application
Imports System.ComponentModel

Public Class UpdateChecker

    Public Enum UpdateType
        Automatic
        Manual
    End Enum

    Private Shared MyInstance As UpdateChecker
    Public Shared ReadOnly Property Current() As UpdateChecker
        Get
            If MyInstance Is Nothing Then
                MyInstance = New UpdateChecker
            End If
            Return MyInstance
        End Get
    End Property

    Private WithEvents CurrDeployment As ApplicationDeployment
    Private CurrType As UpdateType
    Private _checking As Boolean = False
    Private _lastErrorSentOnCheck As DateTime?

    Public ReadOnly Property LastUpdateCheck() As DateTime?
        Get
            If CurrDeployment IsNot Nothing Then
                Return CurrDeployment.TimeOfLastUpdateCheck
            End If
            Return Nothing
        End Get
    End Property

    Public Sub CheckAsync(ByVal checkType As UpdateType)
        Try
            Dim show As Boolean = (checkType = UpdateType.Manual)
            If ApplicationDeployment.IsNetworkDeployed AndAlso _
               Not WindowActive(show) AndAlso Not _checking AndAlso _
               (checkType = UpdateType.Manual OrElse Not LastUpdateCheck.HasValue OrElse LastUpdateCheck.Value.AddMinutes(60) <= Date.UtcNow) Then

                _checking = True

                CurrDeployment = ApplicationDeployment.CurrentDeployment
                CurrType = checkType

                Dim bw As New BackgroundWorker
                AddHandler bw.RunWorkerCompleted, AddressOf CurrDeployment_CheckForUpdateCompleted
                AddHandler bw.DoWork, AddressOf StartAsync

                If CurrType = UpdateType.Manual Then ShowWindow()

                bw.RunWorkerAsync()
            ElseIf checkType = UpdateType.Manual AndAlso _checking Then
                CurrType = checkType
                WindowActive(True)
            ElseIf checkType = UpdateType.Manual AndAlso Not ApplicationDeployment.IsNetworkDeployed Then
                MessageBox.Show(MainForm, "Cannot check for updates.", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            If Not _lastErrorSentOnCheck.HasValue OrElse _lastErrorSentOnCheck.Value.AddHours(1) <= Now Then
                _lastErrorSentOnCheck = Now
                My.Application.LogError(ex, New StringPair("Update Check", checkType.ToString))
            End If
        End Try
    End Sub

    Private Sub StartAsync(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        e.Result = CurrDeployment.CheckForDetailedUpdate
    End Sub

    Private Sub ShowWindow()
        My.Forms.frmUpdates.MdiParent = MainForm
        AddHandler My.Forms.frmUpdates.FormClosing, AddressOf frmUpdates_FormClosing
        My.Forms.frmUpdates.Show()
    End Sub

    Protected Sub frmUpdates_FormClosing(ByVal sender As Object, ByVal e As Windows.Forms.FormClosingEventArgs)
        My.Forms.frmUpdates = Nothing
    End Sub

    Private Function WindowActive(ByVal onTop As Boolean) As Boolean
        If Not My.Forms.frmUpdates Is Nothing Then
            If Not My.Forms.frmUpdates.Visible AndAlso onTop Then
                My.Forms.frmUpdates.MdiParent = MainForm
                My.Forms.frmUpdates.Show()
            ElseIf onTop Then
                My.Forms.frmUpdates.Activate()
            End If
            Return True
        End If
        Return False
    End Function

    Private Sub CurrDeployment_CheckForUpdateCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        If MainForm.InvokeRequired Then
            MainForm.Invoke(New RunWorkerCompletedEventHandler(AddressOf CurrDeployment_CheckForUpdateCompleted), sender, e)
        Else
            If e.Error IsNot Nothing Then
                If WindowActive(True) Then My.Forms.frmUpdates.ShowError("Please try again later.")

                If Not _lastErrorSentOnCheck.HasValue OrElse _lastErrorSentOnCheck.Value.AddHours(1) <= Now Then
                    _lastErrorSentOnCheck = Now
                    My.Application.LogError(e.Error, New StringPair("Update Check Async", CurrType.ToString))
                End If
            Else
                Dim updateInfo As UpdateCheckInfo = DirectCast(e.Result, UpdateCheckInfo)
                Select Case CurrType
                    Case UpdateType.Manual
                        If WindowActive(False) Then My.Forms.frmUpdates.ShowCheckComplete(updateInfo)
                    Case UpdateType.Automatic
                        If updateInfo.UpdateAvailable Then
                            If Not WindowActive(True) Then ShowWindow()
                            My.Forms.frmUpdates.ShowCheckComplete(updateInfo)
                        End If
                End Select
            End If
            _checking = False
            End If

        DirectCast(sender, BackgroundWorker).Dispose()
    End Sub

    Public Sub UpdateAsync()
        If ApplicationDeployment.IsNetworkDeployed Then
            CurrDeployment = ApplicationDeployment.CurrentDeployment

            Dim bw As New BackgroundWorker
            AddHandler bw.RunWorkerCompleted, AddressOf CurrDeployment_UpdateCompleted
            AddHandler bw.DoWork, AddressOf StartUpdateAsync

            My.Forms.frmUpdates.ShowUpdateStart()

            bw.RunWorkerAsync()
        End If
    End Sub

    Public Sub StartUpdateAsync()
        CurrDeployment.Update()
    End Sub

    Private Sub CurrDeployment_UpdateCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles CurrDeployment.UpdateCompleted
        If MainForm.InvokeRequired Then
            MainForm.Invoke(New AsyncCompletedEventHandler(AddressOf CurrDeployment_UpdateCompleted), sender, e)
        Else
            If e.Error IsNot Nothing Then
                If WindowActive(True) Then My.Forms.frmUpdates.ShowError("Please try again later or close and re-open the application to automatically retrieve updates.")
                My.Application.LogError(e.Error, New StringPair("Update Async", CurrType.ToString))
            Else
                If WindowActive(True) Then My.Forms.frmUpdates.ShowUpdateComplete()
            End If
        End If
    End Sub
End Class

Here's the code to check if a new update is required. you'd run this on a timer, maybe every 5 minutes

 UpdateChecker.Current.CheckAsync(UpdateChecker.UpdateType.Automatic)

Then here's the code to download the update.

 UpdateChecker.Current.UpdateAsync()

The user would have to quit and start the application to get the new version or
after the update completes you could also use Application.Restart to restart the application

This wouldn't update when the program isn't running, but with ClickOnce you can have it check for updates when the program is launched.


问:
Install pip3 package locally
Having used npm for some time, I'm struggling to understand why pip3 (i.e.: pip with Python 3) is so stubborn when it comes to manage permissions.

So far, I've been using pip3 with sudo as I'm the only one using this computer and I don't mind installing packages globally

Today I wanted to install the pep8 package and use it locally without sudo. pep8 can be used by IDEs and they would not be able to use it without sudo. Therefore, I'd like to run

```<code>pip3 install --user pep8
</code>```

However, command doesn't work without sudo. Console throws a traceback with a PermissionError:

```<code>PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.4/site-packages/pip/__init__.py'
</code>```

And if run with sudo, quite logically, pep8 is installed in /root

With 2.7, the workaround is to uninstall pip and then reinstall it locally with --user. At the moment, though, I'm unable to uninstall pip3. At least in Fedora 22, dependencies seem to be quite tight. My guess is that pip3 comes bundled with 3.4 and that makes matters worse.

And so, running

```<code>python3 get-pip.py --user
</code>```

gives a permission error because the script looks at current pip3 installations. If I run the command with sudo, the --user works (I believe it's still in testing mode?) but, logically, it installs it in the /root folder

In short, is there a way to use pip with Python3 to install packages locally?

答:
Within a console start your version of python you want to install the package for.
Run the python with the permission you want it to be installed with.
Python 3 and without sudo in this case.

python3

Thank in the python instance install the package you want.

```<code>import pip

#Ininstall the package
#This is the path to the setup and unzipped package. Path to the folder with setup.py.
path_to_setup = "/usr/lib/python3.4/site-packages/pep8"
#finelly runs the installation
pip.main (['install', path_to_setup])
#You will see some data processed.
#Now test it. In this case the package is pep8
import pep8
</code>```

Title: Install pip3 package locally

Body:
Having used npm for some time, I'm struggling to understand why pip3 (i.e.: pip with Python 3) is so stubborn when it comes to manage permissions.

So far, I've been using pip3 with sudo as I'm the only one using this computer and I don't mind installing packages globally

Today I wanted to install the pep8 package and use it locally without sudo. pep8 can be used by IDEs and they would not be able to use it without sudo. Therefore, I'd like to run

pip3 install --user pep8

However, command doesn't work without sudo. Console throws a traceback with a PermissionError:

PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.4/site-packages/pip/__init__.py'

And if run with sudo, quite logically, pep8 is installed in /root

With 2.7, the workaround is to uninstall pip and then reinstall it locally with --user. At the moment, though, I'm unable to uninstall pip3. At least in Fedora 22, dependencies seem to be quite tight. My guess is that pip3 comes bundled with 3.4 and that makes matters worse.

And so, running

python3 get-pip.py --user

gives a permission error because the script looks at current pip3 installations. If I run the command with sudo, the --user works (I believe it's still in testing mode?) but, logically, it installs it in the /root folder

In short, is there a way to use pip with Python3 to install packages locally?

Body:
Within a console start your version of python you want to install the package for.
Run the python with the permission you want it to be installed with.
Python 3 and without sudo in this case.

python3

Thank in the python instance install the package you want.

import pip

#Ininstall the package
#This is the path to the setup and unzipped package. Path to the folder with setup.py.
path_to_setup = "/usr/lib/python3.4/site-packages/pep8"
#finelly runs the installation
pip.main (['install', path_to_setup])
#You will see some data processed.
#Now test it. In this case the package is pep8
import pep8


问:
C++ with git and CMake: How to build submodules with specific parameters?
Consider a C++ project, organized in a git repository. Assume that the git repository has a submodule from which a library is built on which the (super)project depends. If the (super)project depends not only on the library but on the library built with specific (CMake) parameters, how can it be ensured that the submodule is built with these parameters when the (super)project is built?</p>

答:
CMake supports external projects wiht ExternalProject_Add where you can define compile flags anr more to your liking. Use it to build your submodules.

More details: https://cmake.org/cmake/help/v3.2/module/ExternalProject.html


问:
Alternative Y combinator definition
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

```<code>public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}
</code>```

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

```<code>public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}
</code>```

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?

答:
Anonymous recursion, i.e. with a fixed point combinator, is not often seen in imperative, strongly-typed languages, for the very simple reason that it is easier to name your [censored] function than to define an anonymous function that performs the same task. Also, OOA&D teaches us that code which has value in multiple places shouldn't be duplicated; it should be named and thus accessible from a common place. Lambdas are by their very nature a one-off; a way of specifying a few lines of very situation-specific code for use in a more general algorithm like looping constructs. Most recursive algorithms are things that have pretty general application (sorting, recursive series generation, etc), which generally lead to you making them more widely accessible.

Lambda calculus aside, in most programming languages an anonymous function F must exist before it can be used. That precludes the definition of a function in terms of itself. In some functional languages such as Erlang, the function F is defined using "overloads", where simpler functions are used as base cases for more complex ones:

```<code>Fact(0) -> 1

Fact(i) -> Fact(i-1) * i
</code>```

This would be fine, except that in Erlang-world this is now a named function "Fact", and when calling that method the program will "fall" through the overloads until it finds the first one for which the parameter(s) match. There isn't an equivalent in C# to this exact construct because C# doesn't support choosing an overload based on value.

The trick is to somehow get a reference to the function that can be passed to the function. There are many ways, all of which require a pre-existing reference SOMEWHERE. If you can't refer to the function by name, then the type of the FP-combinator function is Func<Func<Func<Func<Func<.... Konrad's method is the easiest, but in C# it ends up kind of a hack (it compiles but ReSharper still complains that it's a possible InvalidOperationException; can't invoke a null method pointer).

Here's something I use for simple cases, basically using the delegate workaround for not being able to implicitly type an implicitly-typed lambda:

```<code>public static class YCombinator
{
    public delegate TOut RLambda<TIn, TOut>(RLambda<TIn, TOut> rLambda, TIn a);
    public static Func<T,T> Curry<T>(this RLambda<T,T> rLambda)
    {
        return a => rLambda(rLambda, a);
    }
}

//usage
var curriedLambda = YCombinator.Curry<int>((f, i) => i <= 0 ? 1 : f(f, i - 1)*i)
var shouldBe120 = curriedLambda(5);
</code>```

You can declare a Curry<TIn, TOut> overload to handle cases where the input type isn't the output type, such as producing a list of the first N prime numbers; that function P can be recursively defined as the function which produces a list of all positive integers which are not divisible by any lesser prime number. The fixed point P(1) => 2 defines a base case from which a recursive algorithm can be defined (albeit not a very efficient one):

```<code>var curriedLambda =
            YCombinator.Curry<int, List<int>>(
                (p, i) => i == 1
                              ? new List<int>{2}
                              : p(p, i - 1)
                                    .Concat(new[]
                                                {
                                                    Enumerable.Range(p(p, i - 1)[i - 2],
                                                                     int.MaxValue - p(p, i - 1)[i - 2])
                                                        .First(x => p(p, i - 1).All(y => x%y != 0))
                                                }).ToList()
                );
        Assert.AreEqual(new []{2,3,5,7,11}, curriedLambda(5));
</code>```

And thus the conundrum presents itself; though you certainly CAN define everything as a higher-order function, this prime-finder would be MUCH faster if defined imperatively instead of functionally. The main speedup is simply defining p(p,i-1) at each level so it isn't evaluated 3 times per recursion level. A smarter language designed to work functionally would do that for you.

Title: Alternative Y combinator definition

Body:
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?

Body:
Anonymous recursion, i.e. with a fixed point combinator, is not often seen in imperative, strongly-typed languages, for the very simple reason that it is easier to name your [censored] function than to define an anonymous function that performs the same task. Also, OOA&D teaches us that code which has value in multiple places shouldn't be duplicated; it should be named and thus accessible from a common place. Lambdas are by their very nature a one-off; a way of specifying a few lines of very situation-specific code for use in a more general algorithm like looping constructs. Most recursive algorithms are things that have pretty general application (sorting, recursive series generation, etc), which generally lead to you making them more widely accessible.

Lambda calculus aside, in most programming languages an anonymous function F must exist before it can be used. That precludes the definition of a function in terms of itself. In some functional languages such as Erlang, the function F is defined using "overloads", where simpler functions are used as base cases for more complex ones:

Fact(0) -> 1

Fact(i) -> Fact(i-1) * i

This would be fine, except that in Erlang-world this is now a named function "Fact", and when calling that method the program will "fall" through the overloads until it finds the first one for which the parameter(s) match. There isn't an equivalent in C# to this exact construct because C# doesn't support choosing an overload based on value.

The trick is to somehow get a reference to the function that can be passed to the function. There are many ways, all of which require a pre-existing reference SOMEWHERE. If you can't refer to the function by name, then the type of the FP-combinator function is Func<Func<Func<Func<Func<.... Konrad's method is the easiest, but in C# it ends up kind of a hack (it compiles but ReSharper still complains that it's a possible InvalidOperationException; can't invoke a null method pointer).

Here's something I use for simple cases, basically using the delegate workaround for not being able to implicitly type an implicitly-typed lambda:

public static class YCombinator
{
    public delegate TOut RLambda<TIn, TOut>(RLambda<TIn, TOut> rLambda, TIn a);
    public static Func<T,T> Curry<T>(this RLambda<T,T> rLambda)
    {
        return a => rLambda(rLambda, a);
    }
}

//usage
var curriedLambda = YCombinator.Curry<int>((f, i) => i <= 0 ? 1 : f(f, i - 1)*i)
var shouldBe120 = curriedLambda(5);

You can declare a Curry<TIn, TOut> overload to handle cases where the input type isn't the output type, such as producing a list of the first N prime numbers; that function P can be recursively defined as the function which produces a list of all positive integers which are not divisible by any lesser prime number. The fixed point P(1) => 2 defines a base case from which a recursive algorithm can be defined (albeit not a very efficient one):

var curriedLambda =
            YCombinator.Curry<int, List<int>>(
                (p, i) => i == 1
                              ? new List<int>{2}
                              : p(p, i - 1)
                                    .Concat(new[]
                                                {
                                                    Enumerable.Range(p(p, i - 1)[i - 2],
                                                                     int.MaxValue - p(p, i - 1)[i - 2])
                                                        .First(x => p(p, i - 1).All(y => x%y != 0))
                                                }).ToList()
                );
        Assert.AreEqual(new []{2,3,5,7,11}, curriedLambda(5));

And thus the conundrum presents itself; though you certainly CAN define everything as a higher-order function, this prime-finder would be MUCH faster if defined imperatively instead of functionally. The main speedup is simply defining p(p,i-1) at each level so it isn't evaluated 3 times per recursion level. A smarter language designed to work functionally would do that for you.


问:
Time Complexity of 3 sum
I have provided a snippet of the code for solving the 3 sum problem below.

```<code>       int N = 10;

  for (int i = 0; i < N; i++)// this line gets executed N times
    for (int j = i+1; j < N; j++)// this line gets executed N(N-1) times
      for (int k = j+1; k < N; k++)// this line gets executed  N(N-1)(N-2) times
         if (a[i] + a[j] + a[k] == 0)// How many times does this line gets executed
             cnt++;
</code>```

The textbook I am using said that the line

```<code>if (a[i] + a[j] + a[k] == 0)
</code>```

gets executed (N(N-1)(N-2))/6 times.
but from my analysis, the statement gets executed (N(N-1)(N-2))

Why is there a division by 6, whats is the proof of that.

答: Your code is actually doing a permutation and composition problem: Take three different elements from n elements and see if their sum is zero. So how many combinations of three different elements are extracted from n elements?  Math tells you (N,3)=N*(N-1)(N-2)/3!=N(N-1)*(N-2)/6

Title: Time Complexity of 3 sum

Body:
I have provided a snippet of the code for solving the 3 sum problem below.

       int N = 10;

  for (int i = 0; i < N; i++)// this line gets executed N times
    for (int j = i+1; j < N; j++)// this line gets executed N(N-1) times
      for (int k = j+1; k < N; k++)// this line gets executed  N(N-1)(N-2) times
         if (a[i] + a[j] + a[k] == 0)// How many times does this line gets executed
             cnt++;

The textbook I am using said that the line

if (a[i] + a[j] + a[k] == 0)

gets executed (N(N-1)(N-2))/6 times.
but from my analysis, the statement gets executed (N(N-1)(N-2))

Why is there a division by 6, whats is the proof of that.


问:
tensorflow fail to initialize some variable
I use the following code to initialize some variable in tensorflow. To my surprise, I got variable 'V' as an empty list while other variables were reasonable numbers. Only If I comment the code for weights_W, I was able to get values for 'V'.

I am new to tensorflow. Did I mess anything up?

Code:

```<code>import math
import tensorflow as tf

layer_sizes = [4, 5, 3]
shapes = zip(layer_sizes[:-1], layer_sizes[1:])
L = len(layer_sizes)-1

def bi(inits, size, name):
    return tf.Variable(inits * tf.ones([size]), name=name)

def wi(shape, name):
    return tf.Variable(tf.random_normal(shape, name=name)) / math.sqrt(shape[0])

weights_W = {'W': [wi(s, "W") for s in shapes]}
weights_V = {'V': [wi(s[::-1], "V") for s in shapes]}
bias_b = {'beta': [bi(0.0, layer_sizes[l+1], "beta") for l in range(L)]}
bias_g = {'gamma': [bi(1.0, layer_sizes[l+1], "gamma") for l in range(L)]}

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(weights_W))
    print(sess.run(weights_V))
    print(sess.run(bias_b))
    print(sess.run(bias_g))
</code>```

Outputs:

```<code>{'W': [array([[ 0.87929118, -1.52028453, -0.25481933, -0.0707642 ,  0.21771625],
   [-0.46657208, -0.08346261,  0.18036443, -0.75888193,  0.41950777],
   [-0.7241388 ,  0.08610565, -0.6172654 , -0.40768555,  0.24912448],
   [ 0.38304791, -0.16632535,  1.0700382 , -0.06679908, -0.68657762]], dtype=float32), array([[-0.37793589, -0.14964254, -0.56092912],
   [-0.18630502, -0.31269881,  0.25770813],
   [-0.12167504, -0.20703614, -0.06239036],
   [ 0.35287923, -0.67617333, -0.01133266],
   [ 0.24189886, -0.34389392,  0.0007165 ]], dtype=float32)]}
{'V': []}
{'beta': [array([ 0.,  0.,  0.,  0.,  0.], dtype=float32), array([ 0.,  0.,  0.], dtype=float32)]}
{'gamma': [array([ 1.,  1.,  1.,  1.,  1.], dtype=float32), array([ 1.,  1.,  1.], dtype=float32)]}
</code>```

I am using tensorflow 1.2.1 in python 3.5.4 without GPUs.

Thanks for any help.

答:
It's because zip returns an iterator and you can iterate over it only once.

You can make a list of the zip and use that instead.

```<code>shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
</code>```

Body:
I use the following code to initialize some variable in tensorflow. To my surprise, I got variable 'V' as an empty list while other variables were reasonable numbers. Only If I comment the code for weights_W, I was able to get values for 'V'.

I am new to tensorflow. Did I mess anything up?

Code:

import math
import tensorflow as tf

layer_sizes = [4, 5, 3]
shapes = zip(layer_sizes[:-1], layer_sizes[1:])
L = len(layer_sizes)-1

def bi(inits, size, name):
    return tf.Variable(inits * tf.ones([size]), name=name)

def wi(shape, name):
    return tf.Variable(tf.random_normal(shape, name=name)) / math.sqrt(shape[0])

weights_W = {'W': [wi(s, "W") for s in shapes]}
weights_V = {'V': [wi(s[::-1], "V") for s in shapes]}
bias_b = {'beta': [bi(0.0, layer_sizes[l+1], "beta") for l in range(L)]}
bias_g = {'gamma': [bi(1.0, layer_sizes[l+1], "gamma") for l in range(L)]}

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(weights_W))
    print(sess.run(weights_V))
    print(sess.run(bias_b))
    print(sess.run(bias_g))

Outputs:

{'W': [array([[ 0.87929118, -1.52028453, -0.25481933, -0.0707642 ,  0.21771625],
   [-0.46657208, -0.08346261,  0.18036443, -0.75888193,  0.41950777],
   [-0.7241388 ,  0.08610565, -0.6172654 , -0.40768555,  0.24912448],
   [ 0.38304791, -0.16632535,  1.0700382 , -0.06679908, -0.68657762]], dtype=float32), array([[-0.37793589, -0.14964254, -0.56092912],
   [-0.18630502, -0.31269881,  0.25770813],
   [-0.12167504, -0.20703614, -0.06239036],
   [ 0.35287923, -0.67617333, -0.01133266],
   [ 0.24189886, -0.34389392,  0.0007165 ]], dtype=float32)]}
{'V': []}
{'beta': [array([ 0.,  0.,  0.,  0.,  0.], dtype=float32), array([ 0.,  0.,  0.], dtype=float32)]}
{'gamma': [array([ 1.,  1.,  1.,  1.,  1.], dtype=float32), array([ 1.,  1.,  1.], dtype=float32)]}

I am using tensorflow 1.2.1 in python 3.5.4 without GPUs.

Thanks for any help.

Body:
It's because zip returns an iterator and you can iterate over it only once.

You can make a list of the zip and use that instead.

shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))


问:
Why my gitlab ci configuration exit with code 1?
I'm new to Gitlab CI.

I tried to ssh and execute a ls command to check whether my gitlab CI configuration is correct or not.

Here's my .gitlab-ci.yml file configuration :

```<code>before_script:
  - eval $(ssh-agent -s)
  - apt-get update
  - apt-get install sshpass

stage_deploy:
  only:
    - testing
  script:
    - sshpass -p $STAGING_PRIVATE_KEY ssh -p 20000 root@1.2.3.4 "ls"
</code>```

Whenever I trigger the repository push, it always ends up with an Error Message ERROR: Job failed: exit code 1, here's the job result :

```<code>Running with gitlab-runner 10.2.0 (0a75cdd1)
  on docker-auto-scale (e11ae361)
 Using Docker executor with image ruby:2.1 ...
 Using docker image sha256:9f27f70631c32ca0e5946c012e80704061ee559b30cb89e652c0936852e93e86 for predefined container...
 Pulling docker image ruby:2.1 ...
 Using docker image ruby:2.1 ID=sha256:223d1eaa9523fa64e78f5a92b701c9c11cbc507f0ff62246dbbacdae395ffea3 for build container...
 section_start:1512460812:prepare_script
Running on runner-e11ae361-project-4813010-concurrent-0 via runner-e11ae361-srm-1512460662-97b95eb4...
section_end:1512460814:prepare_script
section_start:1512460814:get_sources
 Cloning repository...
Cloning into '/builds/budiantoip/cicd-demo'...
 Checking out dde5cdc4 as testing...
 Skipping Git submodules setup
section_end:1512460816:get_sources
section_start:1512460816:restore_cache
section_end:1512460818:restore_cache
section_start:1512460818:download_artifacts
section_end:1512460819:download_artifacts
section_start:1512460819:build_script
 $ eval $(ssh-agent -s)
Agent pid 11
 $ apt-get update
Get:1 http://security.debian.org jessie/updates InRelease [63.1 kB]
Ign http://deb.debian.org jessie InRelease
Get:2 http://deb.debian.org jessie-updates InRelease [145 kB]
Get:3 http://deb.debian.org jessie Release.gpg [2373 B]
Get:4 http://deb.debian.org jessie Release [148 kB]
Get:5 http://security.debian.org jessie/updates/main amd64 Packages [588 kB]
Get:6 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]
Get:7 http://deb.debian.org jessie/main amd64 Packages [9063 kB]
Fetched 10.0 MB in 6s (1563 kB/s)
Reading package lists...
 $ apt-get install sshpass
Reading package lists...
Building dependency tree...
Reading state information...
The following NEW packages will be installed:
  sshpass
0 upgraded, 1 newly installed, 0 to remove and 62 not upgraded.
Need to get 11.2 kB of archives.
After this operation, 65.5 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian/ jessie/main sshpass amd64 1.05-1 [11.2 kB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 11.2 kB in 0s (12.0 kB/s)
Selecting previously unselected package sshpass.
(Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 21168 files and directories currently installed.)
Preparing to unpack .../sshpass_1.05-1_amd64.deb ...
Unpacking sshpass (1.05-1) ...
Setting up sshpass (1.05-1) ...
sshpass -p $STAGING_PRIVATE_KEY ssh  root@1.2.3.4 "ls"
ERROR: Job failed: exit code 1
</code>```

Any clue on what's going on?

答:
What I think you're missing is the ~/.ssh/config file:

```<code>- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
</code>```

Have you tried the example provided by Gitlab themselves?

```<code>image: ruby:2.1
before_script:
# install ssh-agent
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

# run ssh-agent
- eval $(ssh-agent -s)

# add ssh key stored in SSH_PRIVATE_KEY variable to the agent store
- ssh-add <(echo "$SSH_PRIVATE_KEY")

# disable host key checking (NOTE: makes you susceptible to man-in-the-middle attacks)
# WARNING: use only in docker container, if you use it with shell you will overwrite your user's ssh config
- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

Test SSH:
  script:
  # try to connect to GitLab.com
  - ssh git@gitlab.com

  # try to clone yourself, the SSH_PRIVATE_KEY was added as deploy key to this repository
  - git clone git@gitlab.com:gitlab-examples/ssh-private-key.git
</code>```

This example is located here: https://gitlab.com/gitlab-examples/ssh-private-key/blob/master/.gitlab-ci.yml

Additionally, the docs provide more information about the SSH setup: https://docs.gitlab.com/ee/ci/ssh_keys/README.html

Body:
I'm new to Gitlab CI.

I tried to ssh and execute a ls command to check whether my gitlab CI configuration is correct or not.

Here's my .gitlab-ci.yml file configuration :

before_script:
  - eval $(ssh-agent -s)
  - apt-get update
  - apt-get install sshpass

stage_deploy:
  only:
    - testing
  script:
    - sshpass -p $STAGING_PRIVATE_KEY ssh -p 20000 root@1.2.3.4 "ls"

Whenever I trigger the repository push, it always ends up with an Error Message ERROR: Job failed: exit code 1, here's the job result :

Running with gitlab-runner 10.2.0 (0a75cdd1)
  on docker-auto-scale (e11ae361)
 Using Docker executor with image ruby:2.1 ...
 Using docker image sha256:9f27f70631c32ca0e5946c012e80704061ee559b30cb89e652c0936852e93e86 for predefined container...
 Pulling docker image ruby:2.1 ...
 Using docker image ruby:2.1 ID=sha256:223d1eaa9523fa64e78f5a92b701c9c11cbc507f0ff62246dbbacdae395ffea3 for build container...
 section_start:1512460812:prepare_script
Running on runner-e11ae361-project-4813010-concurrent-0 via runner-e11ae361-srm-1512460662-97b95eb4...
section_end:1512460814:prepare_script
section_start:1512460814:get_sources
 Cloning repository...
Cloning into '/builds/budiantoip/cicd-demo'...
 Checking out dde5cdc4 as testing...
 Skipping Git submodules setup
section_end:1512460816:get_sources
section_start:1512460816:restore_cache
section_end:1512460818:restore_cache
section_start:1512460818:download_artifacts
section_end:1512460819:download_artifacts
section_start:1512460819:build_script
 $ eval $(ssh-agent -s)
Agent pid 11
 $ apt-get update
Get:1 http://security.debian.org jessie/updates InRelease [63.1 kB]
Ign http://deb.debian.org jessie InRelease
Get:2 http://deb.debian.org jessie-updates InRelease [145 kB]
Get:3 http://deb.debian.org jessie Release.gpg [2373 B]
Get:4 http://deb.debian.org jessie Release [148 kB]
Get:5 http://security.debian.org jessie/updates/main amd64 Packages [588 kB]
Get:6 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]
Get:7 http://deb.debian.org jessie/main amd64 Packages [9063 kB]
Fetched 10.0 MB in 6s (1563 kB/s)
Reading package lists...
 $ apt-get install sshpass
Reading package lists...
Building dependency tree...
Reading state information...
The following NEW packages will be installed:
  sshpass
0 upgraded, 1 newly installed, 0 to remove and 62 not upgraded.
Need to get 11.2 kB of archives.
After this operation, 65.5 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian/ jessie/main sshpass amd64 1.05-1 [11.2 kB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 11.2 kB in 0s (12.0 kB/s)
Selecting previously unselected package sshpass.
(Reading database ...
(Reading database ... 5%
(Reading database ... 10%
(Reading database ... 15%
(Reading database ... 20%
(Reading database ... 25%
(Reading database ... 30%
(Reading database ... 35%
(Reading database ... 40%
(Reading database ... 45%
(Reading database ... 50%
(Reading database ... 55%
(Reading database ... 60%
(Reading database ... 65%
(Reading database ... 70%
(Reading database ... 75%
(Reading database ... 80%
(Reading database ... 85%
(Reading database ... 90%
(Reading database ... 95%
(Reading database ... 100%
(Reading database ... 21168 files and directories currently installed.)
Preparing to unpack .../sshpass_1.05-1_amd64.deb ...
Unpacking sshpass (1.05-1) ...
Setting up sshpass (1.05-1) ...
sshpass -p $STAGING_PRIVATE_KEY ssh  root@1.2.3.4 "ls"
ERROR: Job failed: exit code 1

Any clue on what's going on?

Body:
What I think you're missing is the ~/.ssh/config file:

- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

Have you tried the example provided by Gitlab themselves?

image: ruby:2.1
before_script:
# install ssh-agent
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

# run ssh-agent
- eval $(ssh-agent -s)

# add ssh key stored in SSH_PRIVATE_KEY variable to the agent store
- ssh-add <(echo "$SSH_PRIVATE_KEY")

# disable host key checking (NOTE: makes you susceptible to man-in-the-middle attacks)
# WARNING: use only in docker container, if you use it with shell you will overwrite your user's ssh config
- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

Test SSH:
  script:
  # try to connect to GitLab.com
  - ssh git@gitlab.com

  # try to clone yourself, the SSH_PRIVATE_KEY was added as deploy key to this repository
  - git clone git@gitlab.com:gitlab-examples/ssh-private-key.git

This example is located here: https://gitlab.com/gitlab-examples/ssh-private-key/blob/master/.gitlab-ci.yml

Additionally, the docs provide more information about the SSH setup: https://docs.gitlab.com/ee/ci/ssh_keys/README.html


答:
If I understood right you're asking about action attribute that goes inside <form>.

If you put nothing there, it'll send the POST to the same page it is right now. If that form is in "index.php" it'll send all <form> data to "index.php"

Title: HTML tag form without "action" attribute


问:
Convert a list of objects to an array of one of the object's properties
Say I have the following class:

```<code>public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}
</code>```

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

```<code>void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)
</code>```

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

答:
You are looking for

```<code>MyList.Select(x=>x.Name).ToArray();
</code>```

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.

Body:
Say I have the following class:

public class ConfigItemType
{
    public string Name { get; set; }
    public double SomeOtherThing { get; set; }
}

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

void AggregateValues(string someUnrelatedValue, params string[] listGoesHere)

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Body:
You are looking for

MyList.Select(x=>x.Name).ToArray();

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.


问:
Where is the digital signature stored when code signing a exe file in windows?
As stated in the question title. However, I am using a "trick" where i store extra data after the executable to be used at runtime (see here).

Signing my executable appears to break this 'trick' however, so my question is where is the signature stored in the exe (PE) file?

I am usingsigntool from microsoft to sign my executable.

答:
An embedded digital signature is always appended to the end of the executable file, whether or not you have custom data attached to it. The attached data is included in the hash of the signature.

The location and size of the signature is stored in the security directory of the PE header. Extracting that information goes like this:

Locate and read the IMAGE_OPTIONAL_HEADER of the PE file.

IMAGE_OPTIONAL_HEADER::DataDirectory is an array of IMAGE_DATA_DIRECTORY structures. Index it by IMAGE_DIRECTORY_ENTRY_SECURITY (undocumented but declared in winnt.h) to locate the entry of the security directory.

IMAGE_DATA_DIRECTORY::VirtualAddress contains the file offset (not the RVA) of the signature and IMAGE_DATA_DIRECTORY::Size contains the size of the signature.

References:

PE Format (MSDN)

Peering inside the PE (somewhat more readable, with examples)

IMAGE_DATA_DIRECTORY values

The Case of the Missing Digital Signatures Tab


问:
How to use Count SQL Server Query
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

```<code>PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1
</code>```

Would anyone help me write this query?
Thanks in advance.

答:
I guess you can try something like this

first setup some sample data:

```<code>declare @t_book table (Id int, IdPublisher int)
declare @t_publisher table (Id int, Name varchar(50))
declare @t_book_format table (IdBook int, idFormat int)
declare @t_format table (Id int, Description varchar(50))

insert into @t_book values (1, 1), (2, 1), (3, 2), (4, 2), (5, 2), (6, 2)
insert into @t_publisher values (1, 'examplename1'), (2, 'examplename2')
insert into @t_book_format values (1, 1), (2, 1), (3, 2), (4, 1), (5, 1), (6, 1)
insert into @t_format values (1 ,'pdf'), (2, 'book')
</code>```

now the query :

```<code>select p.Name as PublisherName,
       f.Description,
       count(f.Id) as numbers
from   @t_book b
  inner join @t_publisher p on b.idPublisher = p.Id
  inner join @t_book_format bf on b.Id = bf.idBook
  inner join @t_format f on bf.idFormat = f.Id
group by p.Name, f.Description
</code>```

But without sample data from all tables this is just guessing

The result is in a different format, but it still works if you add more formats in t_book_format and t_format

```<code>PublisherName   Description numbers
-------------   ----------- -------
examplename1    pdf         2
examplename2    book        1
examplename2    pdf         3
</code>```

If you want to have the list as in you question, you could do a pivot.

But when there is a new format, this new format will not be in the result, so you have to modify the query everytime a new format is added

```<code>select * from ( select p.Name,
                       f.Description,
                       count(f.Id) as numbers
                from   @t_book b
                  inner join @t_publisher p on b.idPublisher = p.Id
                  inner join @t_book_format bf on b.Id = bf.idBook
                  inner join @t_format f on bf.idFormat = f.Id
                group by p.Name, f.Description
              ) t
pivot
( sum(numbers)
  for Description in (pdf, book)
) piv
</code>```

the result now looks like this

```<code>Name            pdf book
----            --- ----
examplename1    2   null
examplename2    3   1
</code>```

I guess you could put this in a stored procedure and build the last query in dynamic sql, so it would still keep working when you add new formats

Title: How to use Count SQL Server Query

Body:
i write this post to ask for help on a query on the following schema:

Imagine having two formats, for example, PDF and EBOOK. My goal is to get the following result:

PushiblerName  |  Number_PDF   |  Numerber_BOOK  |
--------------------------------------------------
ExampleName1   |    2          |   0
ExampleName2   |    3          |   1

Would anyone help me write this query?
Thanks in advance.

Body:
I guess you can try something like this

first setup some sample data:

declare @t_book table (Id int, IdPublisher int)
declare @t_publisher table (Id int, Name varchar(50))
declare @t_book_format table (IdBook int, idFormat int)
declare @t_format table (Id int, Description varchar(50))

insert into @t_book values (1, 1), (2, 1), (3, 2), (4, 2), (5, 2), (6, 2)
insert into @t_publisher values (1, 'examplename1'), (2, 'examplename2')
insert into @t_book_format values (1, 1), (2, 1), (3, 2), (4, 1), (5, 1), (6, 1)
insert into @t_format values (1 ,'pdf'), (2, 'book')

now the query :

select p.Name as PublisherName,
       f.Description,
       count(f.Id) as numbers
from   @t_book b
  inner join @t_publisher p on b.idPublisher = p.Id
  inner join @t_book_format bf on b.Id = bf.idBook
  inner join @t_format f on bf.idFormat = f.Id
group by p.Name, f.Description

But without sample data from all tables this is just guessing

The result is in a different format, but it still works if you add more formats in t_book_format and t_format

PublisherName   Description numbers
-------------   ----------- -------
examplename1    pdf         2
examplename2    book        1
examplename2    pdf         3

If you want to have the list as in you question, you could do a pivot.

But when there is a new format, this new format will not be in the result, so you have to modify the query everytime a new format is added

select * from ( select p.Name,
                       f.Description,
                       count(f.Id) as numbers
                from   @t_book b
                  inner join @t_publisher p on b.idPublisher = p.Id
                  inner join @t_book_format bf on b.Id = bf.idBook
                  inner join @t_format f on bf.idFormat = f.Id
                group by p.Name, f.Description
              ) t
pivot
( sum(numbers)
  for Description in (pdf, book)
) piv

the result now looks like this

Name            pdf book
----            --- ----
examplename1    2   null
examplename2    3   1

I guess you could put this in a stored procedure and build the last query in dynamic sql, so it would still keep working when you add new formats


问:
Laravel Generate Migration from existing Model

How can I create migration file from existing model in Laravel or model from existing migration?
</p>

答: Model and migration are merely connected through naming convention. Models and migrations are created separately.</p>


问:
Create file with command line in Node
So I'm attempting to do this Node.js tutorial, and it says to create three .js files from the command line.

touch server.js client.js test.js

Except I get the following error:

'touch' is not recognized as an internal or external command, operable
  program or batch file.

Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly.

I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it?

What is the actual command to create a new file in the command line?

I'm using Windows 7.

答:
You can also use the following command:

copy con [filename.extension]

[Note: Don't include square brackets]

That's it!

Title: Create file with command line in Node


问:
Insert two comma splitted fields as rows to temp table at once
I am trying to insert two variables into same temp table at once but facing syntax error.

SQL Server Version used is 2012. Any possible ways of implementing this would be greatly appreciated.
I would prefer support with Azure and Server 2012 as well.

SOURCE DATA:

```<code>VARCHAR(MAX) ProgramName  AS 'SP1, SP2, SP3'
INT ProgramId AS 12,13,14
Id = Identity Column (TO be auto generated with init as 1 and seed as 1)
</code>```

DESIRED OUTPUT:

```<code>Id ---- ProgramName  --- ProgramId

1  ------ SP1   ---------  12

2 ------- SP2   ---------  13

3 ------- SP3   ---------- 14
</code>```

TRIED CODE:

```<code>IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable (
Id          INT IDENTITY(1,1),
ProgramName VARCHAR(50) NULL,
ProgramId   INT  NULL);

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @InsertStatement varchar(max) = 'insert into
#tempTable(ProgramName,ProgramId)
        values ('+REPLACE(@string,',',','+REPLACE(@new,',','),(')+',(')++')';
PRINT(@InsertStatement)
EXECUTE (@InsertStatement);

SELECT * FROM #tempTable;
</code>```

答:
I would like to use xml node method to split your data & insert them into temp table

```<code>;with cte as
(
    select
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') [string] from
    (
       select cast('<m>'+replace(@string, ',', '</m><m>')+'</m>' as xml) [string]
    ) as a cross apply string.nodes ('/m') as string(s)
), cte1 as
(
    select
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') new from
    (
       select cast('<m>'+replace(@new, ',', '</m><m>')+'</m>' as xml) [new]
    ) as a cross apply new.nodes ('/m') as string(s)
)

insert into #tempTable
select c.string, c1.new from cte c
join cte1 c1 on c1.rn = c.rn
</code>```

Result :

```<code>Id  ProgramName ProgramId
1   aa         1
2   dd         17
3   fe         25
4   grt        44
5   rge        46
6   lk         67
7   se         88
</code>```

Body:
I am trying to insert two variables into same temp table at once but facing syntax error.

SQL Server Version used is 2012. Any possible ways of implementing this would be greatly appreciated.
I would prefer support with Azure and Server 2012 as well.

SOURCE DATA:

VARCHAR(MAX) ProgramName  AS 'SP1, SP2, SP3'
INT ProgramId AS 12,13,14
Id = Identity Column (TO be auto generated with init as 1 and seed as 1)

DESIRED OUTPUT:

Id ---- ProgramName  --- ProgramId

1  ------ SP1   ---------  12

2 ------- SP2   ---------  13

3 ------- SP3   ---------- 14

TRIED CODE:

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable;

CREATE TABLE #tempTable (
Id          INT IDENTITY(1,1),
ProgramName VARCHAR(50) NULL,
ProgramId   INT  NULL);

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @InsertStatement varchar(max) = 'insert into
#tempTable(ProgramName,ProgramId)
        values ('+REPLACE(@string,',',','+REPLACE(@new,',','),(')+',(')++')';
PRINT(@InsertStatement)
EXECUTE (@InsertStatement);

SELECT * FROM #tempTable;

Body:
I would like to use xml node method to split your data & insert them into temp table

;with cte as
(
    select
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') [string] from
    (
       select cast('<m>'+replace(@string, ',', '</m><m>')+'</m>' as xml) [string]
    ) as a cross apply string.nodes ('/m') as string(s)
), cte1 as
(
    select
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') new from
    (
       select cast('<m>'+replace(@new, ',', '</m><m>')+'</m>' as xml) [new]
    ) as a cross apply new.nodes ('/m') as string(s)
)

insert into #tempTable
select c.string, c1.new from cte c
join cte1 c1 on c1.rn = c.rn

Result :

Id  ProgramName ProgramId
1   aa         1
2   dd         17
3   fe         25
4   grt        44
5   rge        46
6   lk         67
7   se         88


问:
Invariant Violation: View Config not Found for name li
I'm pretty sure that I'm missing something basic here, but I can't figure it out. I've been following this tutorial to render a list of elements, but I'm getting a "View Config not Found for name li" error, and for any other HTML element that I attempt to use in render(). Not sure where I'm going wrong here as all other similar questions had solutions that I've already included in my code (like including a return statement), so any advice would be appreciated.</p>

```<code>import React, { Component } from 'react';
import ReactList from 'react-list';
import { StyleSheet, Text, View, Navigator, AppRegistry, TextInput,
TouchableOpacity } from 'react-native';
const { createGame, addUserToGame } = require('./requestors');

class Players extends Component {
    constructor(props) {
    super(props);
    this.state = {
        players: [{
            name: 'Player1',
        }, {
            name: 'Player2',
        }],
    };
  }

  render() {
    return (
        <ul>
        {this.state.players.map(player => <li>{player.name}</li>)}
        </ul>
      );
  }
}

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

答: you cant render html component in react-native </p>

Body:
I'm pretty sure that I'm missing something basic here, but I can't figure it out. I've been following this tutorial to render a list of elements, but I'm getting a "View Config not Found for name li" error, and for any other HTML element that I attempt to use in render(). Not sure where I'm going wrong here as all other similar questions had solutions that I've already included in my code (like including a return statement), so any advice would be appreciated.

import React, { Component } from 'react';
import ReactList from 'react-list';
import { StyleSheet, Text, View, Navigator, AppRegistry, TextInput,
TouchableOpacity } from 'react-native';
const { createGame, addUserToGame } = require('./requestors');

class Players extends Component {
    constructor(props) {
    super(props);
    this.state = {
        players: [{
            name: 'Player1',
        }, {
            name: 'Player2',
        }],
    };
  }

  render() {
    return (

        {this.state.players.map(player =>
{player.name}
)}

      );
  }
}

module.exports = Players;


问:
Margin-Bottom from outer DIV does not work
I'd like to create an outer DIV, which contains several inner DIVs. At the moment, this works perfect.
But I have some troubles with the margin of the outer div. If the outer DIV has a fixed height (f.ex. height: 100px;), there will be a margin at the bottom. But if I set the height to auto (it should have only the height of all inner DIVs), the margin-bottom disappears.

Example:

Here, the margin-bottom applies normaly. The height of the outer-box is set to a fixed height:
https://jsfiddle.net/v81mehc5/3/

But changing the height of the outer DIV from a fixed height (75px) to auto, the margin-bottom of 40px disappears.
https://jsfiddle.net/v81mehc5/2/

What's missing in the second case? What's wrong overthere?

HTML

```<code>text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after
</code>```

CSS

```<code>.outer-box
{
  width: 200px;
  height: 75px; /*if height: auto > no margin-bottom will be applied*/
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}
</code>```

Thank you very much for your help.

答:
Nothing is missing but you are using floating elements inside the outer div. So height:auto means height:0 in you case so you are only seeing the margin-bottom (that you thought it's the height).

In order to fix this you need to add overflow:hidden to outer div.

.outer-box
{
  width: 200px;
  height: auto;
  overflow:auto;
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after</code>```

More questions related to the same issue for more details :

Why does overflow hidden stop floating elements escaping their container?

CSS overflow:hidden with floats

Body:
I'd like to create an outer DIV, which contains several inner DIVs. At the moment, this works perfect.
But I have some troubles with the margin of the outer div. If the outer DIV has a fixed height (f.ex. height: 100px;), there will be a margin at the bottom. But if I set the height to auto (it should have only the height of all inner DIVs), the margin-bottom disappears.

Example:

Here, the margin-bottom applies normaly. The height of the outer-box is set to a fixed height:
https://jsfiddle.net/v81mehc5/3/

But changing the height of the outer DIV from a fixed height (75px) to auto, the margin-bottom of 40px disappears.
https://jsfiddle.net/v81mehc5/2/

What's missing in the second case? What's wrong overthere?

HTML

text before

left

right

left

right

text after

CSS

.outer-box
{
  width: 200px;
  height: 75px; /*if height: auto > no margin-bottom will be applied*/
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}

Thank you very much for your help.

Body:
Nothing is missing but you are using floating elements inside the outer div. So height:auto means height:0 in you case so you are only seeing the margin-bottom (that you thought it's the height).

In order to fix this you need to add overflow:hidden to outer div.

.outer-box
{
  width: 200px;
  height: auto;
  overflow:auto;
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}

text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after

More questions related to the same issue for more details :

Why does overflow hidden stop floating elements escaping their container?

CSS overflow:hidden with floats


问:
Apache/PHP application sessions timing out
I am fairly new to PHP and am running an open source web application called GLPI.  We have several users that have the application open all day long and after a while they have to log back on the application.  Is this the Apache session timing out?  If so what is the default and how do I change it.</p>

答:
It's most likely the PHP session's lifetime.

Questions with solutions that might help you:

PHP session lifetime problem

PHP : What is the default lifetime of a session

it's impossible to tell where in your application you need to change or add this without knowing it, but you may be able to change the session.gc_maxlifetime setting in php.ini without touching the application at all.


答:
Try this:

```<code>select P.Name as PublisherName,
       SUM(case when F.Code = 'PDF' then 1 else 0 end) as Number_PDF,
       SUM(case when F.Code = 'BOOK' then 1 else 0 end) as Number_BOOK
from T_BOOK as B
join T_BOOK_FORMAT as BF on B.Id = BF.BookId
join T_FORMAT as F on BF.IdFormat = F.Id
join T_PUBLISHER as P on B.IdPublisher = P.Id
group by P.Name
</code>```

I assumed, that format of a book is held in T_FORMAT table in column Code (part with F.Code).

Title: How to use Count SQL Server Query

Body:
Try this:

select P.Name as PublisherName,
       SUM(case when F.Code = 'PDF' then 1 else 0 end) as Number_PDF,
       SUM(case when F.Code = 'BOOK' then 1 else 0 end) as Number_BOOK
from T_BOOK as B
join T_BOOK_FORMAT as BF on B.Id = BF.BookId
join T_FORMAT as F on BF.IdFormat = F.Id
join T_PUBLISHER as P on B.IdPublisher = P.Id
group by P.Name

I assumed, that format of a book is held in T_FORMAT table in column Code (part with F.Code).


问:
Undefined behavior while using vectors (STL), Please explain the below code output behind reason
This one may well work with some compilers/OS, and crash with others. Same code with "List" it's working fine, While using "vector" only I am facing undefined behavior output.
Is STL (vector) is safe??

Note: This is not a real-time code, I am just going through some sample programs that's it.

```<code>#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (vector<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}
</code>```

Output with vector:
1
0
3
4
0
0
4113
0
858851888
943206709
2617
.
.
1
2
3
4
5
5

```<code>#include <list>
#include <iostream>

using namespace std;

int main() {
  list<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (list<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}
</code>```

Output with list:
1
2
3
4
5

答:
The concept you are missing is "iterator invalidation". std::vector is just a dynamic array with a finite capacity. When adding a new element results in an array size greater than the capacity, a reallocation needs to happen, and this invalidates all the iterators of the vector. This is defined in the standard draft, under section "23.3.7.5 vector modifiers", which talks about insert and push_back:

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens,
  all the iterators and references before the insertion point remain valid.

std::list on the other hand, is a doubly-linked list. So no reallocations need to happen to any of the elements already in the list, and only the std::list<T>::end() iterator is invalidated. But, since you are calling that method in the loop condition, your code just happens to work.

Body:
This one may well work with some compilers/OS, and crash with others. Same code with "List" it's working fine, While using "vector" only I am facing undefined behavior output.
Is STL (vector) is safe??

Note: This is not a real-time code, I am just going through some sample programs that's it.

#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (vector<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}

Output with vector:
1
0
3
4
0
0
4113
0
858851888
943206709
2617
.
.
1
2
3
4
5
5

#include <list>
#include <iostream>

using namespace std;

int main() {
  list<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  for (list<int>::iterator i = v.begin();
       i != v.end(); i++) {
    cout << *i << endl;
    if (*i == 1) {
      v.push_back(5);
    }
  }
}

Output with list:
1
2
3
4
5


问:
Saving numpy array in mongodb
I have a couple of MongoDB documents wherein one my the fields is best represented as a matrix (numpy array). I would like to save this document to MongoDB, how do I do this?</p>

```<code>{
'name' : 'subject1',
'image_name' : 'blah/foo.png',
'feature1' : np.array(...)
}
</code>```

Title: Saving numpy array in mongodb

Body:
I have a couple of MongoDB documents wherein one my the fields is best represented as a matrix (numpy array). I would like to save this document to MongoDB, how do I do this?

{
'name' : 'subject1',
'image_name' : 'blah/foo.png',
'feature1' : np.array(...)
}

Body:
Have you try MongoWrapper, i think it simple :

Declare connection to mongodb server and collection to save your np.

import monogowrapper as mdb
db = mdb.MongoWrapper(dbName='test',
                      collectionName='test_collection',
                      hostname="localhost",
                      port="27017")
my_dict = {"name": "Important experiment",
            "data":np.random.random((100,100))}

The dictionary's just as you'd expect it to be:

print my_dict
{'data': array([[ 0.773217,  0.517796,  0.209353, ...,  0.042116,  0.845194,
         0.733732],
       [ 0.281073,  0.182046,  0.453265, ...,  0.873993,  0.361292,
         0.551493],
       [ 0.678787,  0.650591,  0.370826, ...,  0.494303,  0.39029 ,
         0.521739],
       ...,
       [ 0.854548,  0.075026,  0.498936, ...,  0.043457,  0.282203,
         0.359131],
       [ 0.099201,  0.211464,  0.739155, ...,  0.796278,  0.645168,
         0.975352],
       [ 0.94907 ,  0.363454,  0.912208, ...,  0.480943,  0.810243,
         0.217947]]),
 'name': 'Important experiment'}

Save data to mongo :

db.save(my_dict)

To load back data :

my_loaded_dict = db.load({"name":"Important experiment"})


问:
Role of Webpack in Angular's ng serve
I am new to Angular and was wondering what role does Webpack play behind the scene when we ng serve the application. During initial impressions, I have come to know that webpack acts as a build and package tool that groups all the required JS files into separate bundles. I could not, however, find the webpack configuration file and could not figure how angular and webpack come together in the picture.

So when I serve the angular 4 app, this is what is printed on the terminal. Can't exactly understand what is happening behind the scenes.

```<code>webpack: Compiling...
Date: 2017-12-05T07:13:25.436Z
Hash: a6d360a858a29480ebbc
Time: 310ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry]
chunk {main} main.bundle.js, main.bundle.js.map (main) 35.4 kB {vendor} [initial] [rendered]
kB {vendor} [initial] [rendered]                            ap (polyfills) 200 kB {inline} [initial]chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB {inline} [initial]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 195 kB {inline} [initial]chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.65 MB [initial]
webpack: Compiled successfully.
</code>```

Any help would be appreciated.

答:
Angular CLI effectively puts together a Webpack config file on the fly based on the project configuration options you pass in.

You can find the main piece of the code that generates this config here, and the code that passes it to Webpack when you run ng serve here.

Title: Role of Webpack in Angular's ng serve

Body:
I am new to Angular and was wondering what role does Webpack play behind the scene when we ng serve the application. During initial impressions, I have come to know that webpack acts as a build and package tool that groups all the required JS files into separate bundles. I could not, however, find the webpack configuration file and could not figure how angular and webpack come together in the picture.

So when I serve the angular 4 app, this is what is printed on the terminal. Can't exactly understand what is happening behind the scenes.

webpack: Compiling...
Date: 2017-12-05T07:13:25.436Z
Hash: a6d360a858a29480ebbc
Time: 310ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry]
chunk {main} main.bundle.js, main.bundle.js.map (main) 35.4 kB {vendor} [initial] [rendered]
kB {vendor} [initial] [rendered]                            ap (polyfills) 200 kB {inline} [initial]chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB {inline} [initial]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 195 kB {inline} [initial]chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.65 MB [initial]
webpack: Compiled successfully.

Any help would be appreciated.


问:
Multi Tenancy in Microsoft bot framework webchat
I have successfully hosted an instance of microsoft's Botframework web chat using directline on public domain, I want to make  a chatbot in such a way that my customers can have their own channels completely separated from each other and I cannot find any kind of documentation anywhere, Kindly suggest me if this is possible and how?

I have  written the complete code in Node.js and have very less idea about c#.

答:
It seems that there is no such feature for uniform customized chat channel in bot framework. So we can leverage new builder.Message().address(address) to send messages to specific users from the official sample at https://github.com/Microsoft/BotBuilder-Samples/blob/master/Node/core-proactiveMessages/simpleSendMessage/index.js.

So I had a quick test which will save the users' addresses into an address list in server memory as a "customize channel", and trigger a key work to send message to these addresses in list as a broadcast in this "customize channel":

```<code>let channel_address = [];
bot.dialog('joinChannel',(session)=>{
    channel_address.push(session.message.address);
}).triggerAction({
    matches:/join/i
})

bot.dialog('broadcast',(session)=>{
    channel_address.forEach((address)=>{
        bot.send(
            new builder.Message(session).address(address).text(session.message.text)
        )
    })
}).triggerAction({
    matches:/^broadcast: .*/
})
</code>```

Test Step:

Open two emulators connect to your local bot

in both emulators, type "join"

in either emulator, type text like broadcast: hi there

Body:
It seems that there is no such feature for uniform customized chat channel in bot framework. So we can leverage new builder.Message().address(address) to send messages to specific users from the official sample at https://github.com/Microsoft/BotBuilder-Samples/blob/master/Node/core-proactiveMessages/simpleSendMessage/index.js.

So I had a quick test which will save the users' addresses into an address list in server memory as a "customize channel", and trigger a key work to send message to these addresses in list as a broadcast in this "customize channel":

let channel_address = [];
bot.dialog('joinChannel',(session)=>{
    channel_address.push(session.message.address);
}).triggerAction({
    matches:/join/i
})

bot.dialog('broadcast',(session)=>{
    channel_address.forEach((address)=>{
        bot.send(
            new builder.Message(session).address(address).text(session.message.text)
        )
    })
}).triggerAction({
    matches:/^broadcast: .*/
})

Test Step:

Open two emulators connect to your local bot

in both emulators, type "join"

in either emulator, type text like broadcast: hi there


问:
Struggling with a warning I am receiving when trying to run my MATLAB function.. The error that comes up is "
Struggling with a warning I am receiving when trying to run my MATLAB function.. The error that comes up is

"Warning: Failure at t=3.107182e-03.  Unable to meet integration tolerances without reducing the
  step size below the smallest value allowed (6.938894e-18) at time t. In ode15s (line 730)"

I know I have to find the singularity in the function, but I am not sure how to enable myself to view the ode values that were able to compile prior to the error.
Anyone know how to view the values? My code is the following:

```<code>function EMatlabModel()
 % Define constants
 H = 0.04; %[m] Height between cathode and anode
 D = 0.000399; %[m^2/s] diffusion
 F = 96485.3329; %[C] Faraday's constant
 z = 1; % charge of gold
 r = 0.02; %[m] radius of space between electrodes
 m = 1; % mobility of gold
 R = 0.008314; %[J/molK] - divded by 1000 to ensure correct units
 T = 360.65; %[K] temperature of cell
 nY = 99; % Number of interior nodes (y direction)
 dY = (H - 0)/(nY + 1); % Node spacing (y direction)
 tspan = [0 H];
 Co = 0.01*ones(nY+1,1);

% Integrate discretized ODEs using ode15s
sol = ode15s(@funcs,tspan,Co)

% Plot the results
x = linspace(0.15,0.95,5);
el = deval(x,sol)
plot(x,el)
colormap hsv
colorbar
xlabel('Length Away from Cathode');
ylabel('Concentration of Gold');

 %------------------------------------------------------------
 % Define functions to be integrated in x.
 %------------------------------------------------------------
function res = funcs(x,y) % where y = C
    res=zeros(nY+1,1);

    %u = 1e-10;
    um = 0.04;
    Cin = 0.01;
    Vin = 5 + 2.037;

     res(1) = D/dY^2*(y(2) - 2*y(1) + Cin)+ ...
         D/z/dY^2*(y(2) - 2*y(1) + Cin) + ...
         y(1)*um*2*(abs(y(1) - r/2)/r^2) + D*y(1)*F*z*m*Vin/(R*T*H);

      for j = 2:nY
         %ux(j) = um*(1 - abs(y(j) - r/2)/r);
         res(j) = D/dY^2*(y(j+1) - 2*y(j) + y(j-1)) +...
             + D/z/dY^2*(y(j+1) - 2*y(j) + y(j-1)) + ...
             y(j)*um*2*(abs(y(j) - r/2)/r^2) + D*y(j)*F*z*m*Vin/(R*T*H);
      end
  end
 end
</code>```

答: I can't comment but to put your solution definitely diverges that's why you are getting that error, you need to play around with tspan and limit it further

Body:
Struggling with a warning I am receiving when trying to run my MATLAB function.. The error that comes up is

"Warning: Failure at t=3.107182e-03.  Unable to meet integration tolerances without reducing the
  step size below the smallest value allowed (6.938894e-18) at time t. In ode15s (line 730)"

I know I have to find the singularity in the function, but I am not sure how to enable myself to view the ode values that were able to compile prior to the error.
Anyone know how to view the values? My code is the following:

function EMatlabModel()
 % Define constants
 H = 0.04; %[m] Height between cathode and anode
 D = 0.000399; %[m^2/s] diffusion
 F = 96485.3329; %[C] Faraday's constant
 z = 1; % charge of gold
 r = 0.02; %[m] radius of space between electrodes
 m = 1; % mobility of gold
 R = 0.008314; %[J/molK] - divded by 1000 to ensure correct units
 T = 360.65; %[K] temperature of cell
 nY = 99; % Number of interior nodes (y direction)
 dY = (H - 0)/(nY + 1); % Node spacing (y direction)
 tspan = [0 H];
 Co = 0.01*ones(nY+1,1);

% Integrate discretized ODEs using ode15s
sol = ode15s(@funcs,tspan,Co)

% Plot the results
x = linspace(0.15,0.95,5);
el = deval(x,sol)
plot(x,el)
colormap hsv
colorbar
xlabel('Length Away from Cathode');
ylabel('Concentration of Gold');

 %------------------------------------------------------------
 % Define functions to be integrated in x.
 %------------------------------------------------------------
function res = funcs(x,y) % where y = C
    res=zeros(nY+1,1);

    %u = 1e-10;
    um = 0.04;
    Cin = 0.01;
    Vin = 5 + 2.037;

     res(1) = D/dY^2*(y(2) - 2*y(1) + Cin)+ ...
         D/z/dY^2*(y(2) - 2*y(1) + Cin) + ...
         y(1)*um*2*(abs(y(1) - r/2)/r^2) + D*y(1)*F*z*m*Vin/(R*T*H);

      for j = 2:nY
         %ux(j) = um*(1 - abs(y(j) - r/2)/r);
         res(j) = D/dY^2*(y(j+1) - 2*y(j) + y(j-1)) +...
             + D/z/dY^2*(y(j+1) - 2*y(j) + y(j-1)) + ...
             y(j)*um*2*(abs(y(j) - r/2)/r^2) + D*y(j)*F*z*m*Vin/(R*T*H);
      end
  end
 end


问:
Using command line arguments in Python: Understanding sys.argv
I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

```<code>from sys import argv

script, first, second, third = argv

print("the script is called:", (script))
print("your first variable is:", (first))
print("your second variable is:", (second))
print("your third variable is:", (third))
</code>```

I'm getting this error:

```<code>Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack
</code>```

Any idea what's wrong?

答: You forgot to pass arguments to the script, e.g. foo.py bar baz quux.

Body:
I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

from sys import argv

script, first, second, third = argv

print("the script is called:", (script))
print("your first variable is:", (first))
print("your second variable is:", (second))
print("your third variable is:", (third))

I'm getting this error:

Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack

Any idea what's wrong?


问:
Reshape from wide to long in big query (standard SQL)
Unfortunately reshaping in BQ it's not as easy as in R and I can't export my data for this project.

Here is input

```<code>date    country A             B         C      D
20170928    CH  3000.3        121       13     3200
20170929    CH  2800.31       137       23     1614.31
</code>```

Expected output

```<code>date    country Metric  Value
20170928    CH  A       3000.3
20170928    CH  B       121
20170928    CH  C       13
20170928    CH  D       3200
20170929    CH  A       2800.31
20170929    CH  B       137
20170929    CH  C       23
20170929    CH  D       1614.31
</code>```

Also my table has many more columns and rows (but I assume a lot of manual will be required)

答:
You need UNION which is denoted using commas in bigquery

```<code>SELECT date, country, Metric, Value
FROM (
  SELECT date, country, 'A' as Metric,  A as Value FROM your_table
), (
  SELECT date, country, 'B' as Metric,  B as Value FROM your_table
), (
  SELECT date, country, 'C' as Metric,  C as Value FROM your_table
) , (
  SELECT date, country, 'D' as Metric,  D as Value FROM your_table
)
</code>```

Body:
Unfortunately reshaping in BQ it's not as easy as in R and I can't export my data for this project.

Here is input

date    country A             B         C      D
20170928    CH  3000.3        121       13     3200
20170929    CH  2800.31       137       23     1614.31

Expected output

date    country Metric  Value
20170928    CH  A       3000.3
20170928    CH  B       121
20170928    CH  C       13
20170928    CH  D       3200
20170929    CH  A       2800.31
20170929    CH  B       137
20170929    CH  C       23
20170929    CH  D       1614.31

Also my table has many more columns and rows (but I assume a lot of manual will be required)

Body:
You need UNION which is denoted using commas in bigquery

SELECT date, country, Metric, Value
FROM (
  SELECT date, country, 'A' as Metric,  A as Value FROM your_table
), (
  SELECT date, country, 'B' as Metric,  B as Value FROM your_table
), (
  SELECT date, country, 'C' as Metric,  C as Value FROM your_table
) , (
  SELECT date, country, 'D' as Metric,  D as Value FROM your_table
)


问:
invalid volume spec ":/io": invalid volume specification: ':/io'
I'm learning docker using book docker in practice.

I am working on technique 44 in chapter 5.

I have downloaded sample deb file from net using below command.

```<code>$ wget http://mirrors.kernel.org/ubuntu/pool/main/libe/libeatmydata/eatmydata_26-2_amd64.deb
</code>```

Then run the below command

```<code>$ docker run -v ${pwd}:/io dockerinpractice/alienate
docker: Error response from daemon: invalid volume spec ":/io": invalid volume specification: ':/io'.
See 'docker run --help'.
</code>```

My docker version is -

Server Version: 17.06.0-ce

My ubuntu version is -

Description:    Ubuntu 16.10

How to solve this issue?

答:
docker -v mounts the source volume to container volume, and these should be absolute folder path

for ex: docker run -v /home/ubuntu/test:/var/html/ {image name}

else if you want to pass it as PWD then use

docker run -v $(pwd):/var/html/ {image name}

note : use () not {} because $(pwd) it will execute the command pwd and replace $(pwd)

Body:
I'm learning docker using book docker in practice.

I am working on technique 44 in chapter 5.

I have downloaded sample deb file from net using below command.

$ wget http://mirrors.kernel.org/ubuntu/pool/main/libe/libeatmydata/eatmydata_26-2_amd64.deb

Then run the below command

$ docker run -v ${pwd}:/io dockerinpractice/alienate
docker: Error response from daemon: invalid volume spec ":/io": invalid volume specification: ':/io'.
See 'docker run --help'.

My docker version is -

Server Version: 17.06.0-ce

My ubuntu version is -

Description:    Ubuntu 16.10

How to solve this issue?