问:
PE: Adding code at the end of .txt section
As I understand in PE file Virtual Size shows how much space it allocates for section during loading and Raw Size shows how big the section is on disk.

I came across to this executable which did the following:

It subtracted the virtual size (offset 0x8) from the raw data size (offset 0x10) and made sure there was some space(for example 100 bytes). At offset 0x14 from the text section header it found the offset in the file for the section itself. It added to this the virtual size, finding right where the section ends in the file. it copied some shellcode(which at the end eventually jumped to the original entry point of an executable to make sure original executable ran) to the end of the text section of the binary.

Now I'm little confused here, if the Virtual Size shows the exact space which will be allocated for executable, would not adding code at the end of .txt section overwrite some other data of executable and make it crash? thanks.

答:
Uhmmm, this hack code seems crafted to hide malicious code between sections.

Going to your question, you are correct VirtualSize is the space really allocated in memory and RawSize is the the space used on disk to hold the section data.
What you missed is (from MS PECOFF spec):

VirtualSize:    The total size of the section when loaded into memory. If this value is greater than SizeOfRawData, the section is zero-padded. This field is valid only for executable images and should be set to zero for object files.

This means that if a the result of SizeOfRawData-VirtualSize is positive we have some space available on disk actually filled with 0's.

If that space is enough to hold the malicious code then adding the start of text section on disk with the VirtualSize you can get the start of 0's padded area that can be used to copy the code.

The rest is story...


来源: stackexchange

问:
Creating an exe for tkinter python 2.7
I have been trying to create a executable for a tkinter gui I have created in python 2.7. So far I have tried using py2exe and pyinstaller but with no luck. When I tried py2exe the cmd would pop up and then immediately close. When I used pyinstaller the executable would "fail to execute script." I'm not sure what I am doing wrong. Here is the script I have written for my gui

```<code>import Tkinter as tk
from tkFileDialog import askopenfilename
from Tkinter import *
import pandas as pd
import ttk
import subprocess

# Import all graph codes.
import graph_1
import graph_2
import graph_3
import graph_4

def import_csv_data():
    global v
    csv_file_path = askopenfilename()
    print(csv_file_path)
    v.set(csv_file_path)
    df = pd.read_csv(csv_file_path)

def openfile():
    subprocess.call(['notepad.exe', 'C:/help.txt'])

# Functions for calling graphs.
def graph_1():
    graph_1.display_graph(v.get())

def graph_2():
    graph_2.display_graph(v.get())

def graph_3():
    graph_3.display_graph(v.get())

def graph_4():
    graph_4.display_graph(v.get())

# Read in data buttons.
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = ttk.Entry(root, textvariable=v).grid(row=0, column=1)
ttk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)

# Title and icon of the GUI.
root.title('Graphs')
root.iconbitmap('C:/icon.ico')
root.geometry("370x118")

#Graph Buttons.
ttk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0)
ttk.Button(root, text='Graph 2', command=graph_2).grid(row=3, column=1)
ttk.Button(root, text='Graph 3', command=graph_3).grid(row=4, column=0)
ttk.Button(root, text='Graph 4', command=graph_4).grid(row=4, column=1)

def new_window():
    # Import all graph codes.
    import graph_1
    import graph_2
    import graph_3
    import graph_4

    def import_csv_data():
        global v
        csv_file_path = askopenfilename()
        print(csv_file_path)
        v.set(csv_file_path)
        df = pd.read_csv(csv_file_path)

    # Define the functions before calling them.
    def doNothing():
        print "nothing"

    # Functions for calling graphs.
    def graph_1():
        graph_1.display_graph(v.get())

    def graph_2():
        graph_2.display_graph(v.get())

    def graph_3():
        graph_3.display_graph(v.get())

    def graph_4():
        graph_4.display_graph(v.get())

    # Read in data buttons.
    root = tk.Tk()
    tk.Label(root, text='File Path').grid(row=0, column=0)
    v = tk.StringVar()
    entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
    ttk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)

    # Title and icon of the GUI.
    root.title('Graphs')
    root.iconbitmap('C:/icon.ico')
    root.geometry("370x118")

    #Graph Buttons.
    ttk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0)
    ttk.Button(root, text='Graph 2', command=graph_2).grid(row=3, column=1)
    ttk.Button(root, text='Graph 3', command=graph_3).grid(row=4, column=0)
    ttk.Button(root, text='Graph 4', command=graph_4).grid(row=4, column=1)

    #Menu setup and buttons for new window.
    menu =  Menu(root)
    root.config(menu=menu)
    subMenu = Menu(menu)
    menu.add_cascade(label="File",menu=subMenu)
    subMenu.add_command(label="New", command=new_window)
    subMenu.add_command(label="Exit", command=root.destroy)
    editMenu = Menu(menu)
    menu.add_cascade(label = "Help", menu=editMenu)
    editMenu.add_command(label="Help", command=openfile)

# Menu setup and buttons.
menu =  Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=new_window)
subMenu.add_command(label="Exit", command=root.destroy)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=openfile)

root.mainloop()
</code>```

答:
It's possible that pyinstaller is not including the icon file.

First of all, with pyinstaller you should get the program working in "one folder" mode before trying "one file" mode.

Try changing 'C:/icon.ico' to just 'icon.ico' and manually putting the icon file in the distribution folder (the folder that contains your .exe).  If this makes the .exe work, you'll need to edit pyinstaller's spec file to tell it to include the icon file.

ContentLicense: CC BY-SA 3.0

Title: Creating an exe for tkinter python 2.7

Body:
I have been trying to create a executable for a tkinter gui I have created in python 2.7. So far I have tried using py2exe and pyinstaller but with no luck. When I tried py2exe the cmd would pop up and then immediately close. When I used pyinstaller the executable would "fail to execute script." I'm not sure what I am doing wrong. Here is the script I have written for my gui

import Tkinter as tk
from tkFileDialog import askopenfilename
from Tkinter import *
import pandas as pd
import ttk
import subprocess

# Import all graph codes.
import graph_1
import graph_2
import graph_3
import graph_4

def import_csv_data():
    global v
    csv_file_path = askopenfilename()
    print(csv_file_path)
    v.set(csv_file_path)
    df = pd.read_csv(csv_file_path)

def openfile():
    subprocess.call(['notepad.exe', 'C:/help.txt'])

# Functions for calling graphs.
def graph_1():
    graph_1.display_graph(v.get())

def graph_2():
    graph_2.display_graph(v.get())

def graph_3():
    graph_3.display_graph(v.get())

def graph_4():
    graph_4.display_graph(v.get())

# Read in data buttons.
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = ttk.Entry(root, textvariable=v).grid(row=0, column=1)
ttk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)

# Title and icon of the GUI.
root.title('Graphs')
root.iconbitmap('C:/icon.ico')
root.geometry("370x118")

#Graph Buttons.
ttk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0)
ttk.Button(root, text='Graph 2', command=graph_2).grid(row=3, column=1)
ttk.Button(root, text='Graph 3', command=graph_3).grid(row=4, column=0)
ttk.Button(root, text='Graph 4', command=graph_4).grid(row=4, column=1)

def new_window():
    # Import all graph codes.
    import graph_1
    import graph_2
    import graph_3
    import graph_4

    def import_csv_data():
        global v
        csv_file_path = askopenfilename()
        print(csv_file_path)
        v.set(csv_file_path)
        df = pd.read_csv(csv_file_path)

    # Define the functions before calling them.
    def doNothing():
        print "nothing"

    # Functions for calling graphs.
    def graph_1():
        graph_1.display_graph(v.get())

    def graph_2():
        graph_2.display_graph(v.get())

    def graph_3():
        graph_3.display_graph(v.get())

    def graph_4():
        graph_4.display_graph(v.get())

    # Read in data buttons.
    root = tk.Tk()
    tk.Label(root, text='File Path').grid(row=0, column=0)
    v = tk.StringVar()
    entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
    ttk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)

    # Title and icon of the GUI.
    root.title('Graphs')
    root.iconbitmap('C:/icon.ico')
    root.geometry("370x118")

    #Graph Buttons.
    ttk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0)
    ttk.Button(root, text='Graph 2', command=graph_2).grid(row=3, column=1)
    ttk.Button(root, text='Graph 3', command=graph_3).grid(row=4, column=0)
    ttk.Button(root, text='Graph 4', command=graph_4).grid(row=4, column=1)

    #Menu setup and buttons for new window.
    menu =  Menu(root)
    root.config(menu=menu)
    subMenu = Menu(menu)
    menu.add_cascade(label="File",menu=subMenu)
    subMenu.add_command(label="New", command=new_window)
    subMenu.add_command(label="Exit", command=root.destroy)
    editMenu = Menu(menu)
    menu.add_cascade(label = "Help", menu=editMenu)
    editMenu.add_command(label="Help", command=openfile)

# Menu setup and buttons.
menu =  Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=new_window)
subMenu.add_command(label="Exit", command=root.destroy)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=openfile)

root.mainloop()


问:
How to prevent a user from entering a value on a selector field for a value not in the selector list [Acumatica]
Is there a property in the ASPX control to prevent the users from typing a value?  Or the property is in the DAC field declaration?  In this case, the user must only select from the list of values, provided by the selector.  I do not want them to enter a value manually.  This is a key field in a custom screen (if this matters?)</p>

答:
The selector attribute by default will validate the value entered by a user  unless you have ValidateValue = false on your selector.

This selector for example will allow users to select/enter any value.

```<code>[PXSelector(typeof(ARContact.contactID), ValidateValue = false)]
</code>```

If you make the selector like so, then only the values from the list are allowed to be selected/entered.

```<code>[PXSelector(typeof(ARContact.contactID))]
</code>```

Body:
The selector attribute by default will validate the value entered by a user  unless you have ValidateValue = false on your selector.

This selector for example will allow users to select/enter any value.

[PXSelector(typeof(ARContact.contactID), ValidateValue = false)]

If you make the selector like so, then only the values from the list are allowed to be selected/entered.

[PXSelector(typeof(ARContact.contactID))]


问:
How to make a 1s second pause inside a forEach loop reading a firebase file?
I have the follow javascript function that reads data from firebase inside an each loop.

I am using it to plot the data in a google map trough its API.

I would like to know how to make a 1second pause between each round of the loop.

var markers = [];
var mapObject;
var z = 0;
var myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    });
  });
});
```

答:
Push them all, then process them one by one:

var markers = [],
  mapObject, currentMarker = 0,
  myLatLngA = [];

function processMarkers() {
  if (currentMarker >= myLatLngA.length) return; // stop
  var marker = new google.maps.Marker({
    position: myLatLngA[currentMarker],
    map: mapObject
  });
  markers.push(marker);
  marker.setMap(mapObject);
  currentMarker++;
  setTimeout(processMarkers, 1000);
}

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
    });
    processMarkers();
  });
});```


问:
Problems with onContextItemSelected with two fragments
I am using a ViewPager. I have two tabs and, consequently, two fragments that each one have their own Context Menu Options. My problem is when I click in Context Menu options in Fragment B, the method onContextItemSelected() in fragment A is called. How can I solve this?

I do the same as shown in the official Android documentation:
https://developer.android.com/guide/topics/ui/menus.html#context-menu

```<code>@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    PositionClicked = info.position;

    switch (item.getItemId()) {

        case R.id.menu_edit:
            return true;

        case R.id.menu_archive:
            return true;

        case R.id.menu_report:
            return true;

        case R.id.menu_delete:
            Log.i(TAG, "Delete Menu Buttom");

            new AlertDialog.Builder(getActivity()).setTitle("Tem certeza?")
                .setMessage("Você está prestes a deletar sua Postagem!")
                .setPositiveButton("Deletar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //ShowSwipeRefreshin();

                        delete_item(MongodbObjtoDelete);

                        DialogResp = true;
                        feedItems.remove(PositionClicked);
                        listAdapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("Cancelar", null).show();

            return true;

        default:
            return super.onContextItemSelected(item);
    }
}
</code>```

答:
you can fix it like this : </p>

```<code>FragmentManager manager = getFragmentManager();
if (manager.findFragmentByTag("frag1").isVisible()){
    // do fragment 1
}else{

}
</code>```

Body:
I am using a ViewPager. I have two tabs and, consequently, two fragments that each one have their own Context Menu Options. My problem is when I click in Context Menu options in Fragment B, the method onContextItemSelected() in fragment A is called. How can I solve this?

I do the same as shown in the official Android documentation:
https://developer.android.com/guide/topics/ui/menus.html#context-menu

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    PositionClicked = info.position;

    switch (item.getItemId()) {

        case R.id.menu_edit:
            return true;

        case R.id.menu_archive:
            return true;

        case R.id.menu_report:
            return true;

        case R.id.menu_delete:
            Log.i(TAG, "Delete Menu Buttom");

            new AlertDialog.Builder(getActivity()).setTitle("Tem certeza?")
                .setMessage("Você está prestes a deletar sua Postagem!")
                .setPositiveButton("Deletar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //ShowSwipeRefreshin();

                        delete_item(MongodbObjtoDelete);

                        DialogResp = true;
                        feedItems.remove(PositionClicked);
                        listAdapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("Cancelar", null).show();

            return true;

        default:
            return super.onContextItemSelected(item);
    }
}

Body:
you can fix it like this :

FragmentManager manager = getFragmentManager();
if (manager.findFragmentByTag("frag1").isVisible()){
    // do fragment 1
}else{

}


问:
Streaming a file in ASP.NET, C#?
Assume we have the access to sth.avi on www.dl.com with a direct link.

e.g : www.dl.com\sth.avi

Also we have a website => www.dl2.com.

Now, we wanna let some users to download sth.avi from www.dl2.com, but we don't have enough space on www.dl2.com to save sth.avi.

Is it possible in ASP.NET for us to read sth.avi from www.dl.com as streaming file and share it without saving the file on our domain.

P.S:

I don't wanna share this link www.dl.com\sth.avi, actually I wanna share something like this link www.dl2.com\downloads\sth.avi

答: Instead of streaming simply configure the web server on www.dl2.com to redirect requests for /downloads/sth.avi to www.dl.com/sth.avi.

ContentLicense: CC BY-SA 2.5

Title: Streaming a file in ASP.NET, C#?


答:
Example of working ContextMenu

```<code>@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle("");
        menu.setHeaderIcon("");
        String[] menuItems = getResources().getStringArray(R.array.ContextMenu);
        for (int I = 0; I < menuItems.length; I++) {
            menu.add(Menu.NONE, I, I, menuItems[I]);
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int menuItemIndex = item.getItemId();

        if(menuItemIndex == 0){
            //do something
        }

        return true;
    }
</code>```

also check which views registered for Context menu.

```<code>registerForContextMenu(view);
</code>```

Title: Problems with onContextItemSelected with two fragments

Body:
Example of working ContextMenu

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle("");
        menu.setHeaderIcon("");
        String[] menuItems = getResources().getStringArray(R.array.ContextMenu);
        for (int I = 0; I < menuItems.length; I++) {
            menu.add(Menu.NONE, I, I, menuItems[I]);
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int menuItemIndex = item.getItemId();

        if(menuItemIndex == 0){
            //do something
        }

        return true;
    }

also check which views registered for Context menu.

registerForContextMenu(view);


问:
Removing all child node elements from XML in C#?
I have the following XML structure:

XML

```<code><?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
</code>```

At some point, the <Users> gets filled up with different users, but I want to be able to delete them all in a single, simple function.

Attempt

```<code>/// <summary>
/// Removes all nodes from XML creds file on application close
/// </summary>
public static void RemoveXMLData()
{
    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);
    document.RemoveNodes();
}
</code>```

This doesn't seem to be working. I've done the following as well:

Attempt #2

```<code>        string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
        XDocument document = XDocument.Load(xmlPath);

        foreach (var node in document.Descendants("Users"))
        {
            node.Remove();
        }
</code>```

But this yields an exception error.

At the end of the day, I just want to get back to square one with the following file data:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
</code>```

答:
This should work fine:

```<code>XDocument document = XDocument.Load(xmlPath);
document.Descendants("Users").Elements().Remove();
</code>```

As suggested by @Cory, Alternative and faster approach would be:

```<code>document.Root.Elements().Remove();
</code>```

Body:
I have the following XML structure:

XML

<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>

At some point, the <Users> gets filled up with different users, but I want to be able to delete them all in a single, simple function.

Attempt

///
/// Removes all nodes from XML creds file on application close
///
public static void RemoveXMLData()
{
    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);
    document.RemoveNodes();
}

This doesn't seem to be working. I've done the following as well:

Attempt #2

        string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
        XDocument document = XDocument.Load(xmlPath);

        foreach (var node in document.Descendants("Users"))
        {
            node.Remove();
        }

But this yields an exception error.

At the end of the day, I just want to get back to square one with the following file data:

<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>

Body:
This should work fine:

XDocument document = XDocument.Load(xmlPath);
document.Descendants("Users").Elements().Remove();

As suggested by @Cory, Alternative and faster approach would be:

document.Root.Elements().Remove();


问:
Install Font Awesome in Laravel Using Composer
I install Twitter Bootstrap using composer and can easily include the CSS like this:

```<code><link href="{{ URL::asset('css/app.css') }}" rel="stylesheet">
</code>```

However, when I install Font Awesome using composer in the same way, I don't see any CSS files added to that folder. The one CSS file created by Font Awesome is in /app/vendor/components/font-awesome.

How do I include the downloaded Font Awesome CSS into HTML?

Thank you.

答:
Just put the downloaded css file inside public/css/ directory and add following line in your view file.

```<code><link rel="stylesheet" href="{{ asset('css/font-awesome.min.css') }}">
</code>```

And, Make sure your directory structure should like this:

```<code>public/css/font-awesome.min.css
public/fonts/
</code>```

So that, icon will be displayed properly.

ContentLicense: CC BY-SA 4.0

Body:
I install Twitter Bootstrap using composer and can easily include the CSS like this:

<link href="{{ URL::asset('css/app.css') }}" rel="stylesheet">

However, when I install Font Awesome using composer in the same way, I don't see any CSS files added to that folder. The one CSS file created by Font Awesome is in /app/vendor/components/font-awesome.

How do I include the downloaded Font Awesome CSS into HTML?

Thank you.

Body:
Just put the downloaded css file inside public/css/ directory and add following line in your view file.

<link rel="stylesheet" href="{{ asset('css/font-awesome.min.css') }}">

And, Make sure your directory structure should like this:

public/css/font-awesome.min.css
public/fonts/

So that, icon will be displayed properly.


问:
Node ECS Task Not Crashing
Node ECS Task Not Crashing

I have an ECS worker running Node:Boron (v6.9.0).

Every now and then I get a uncaught exception.

For Example:

```<code>{
  "date": "Mon Jul 03 2017 09:09:29 GMT+0000 (UTC)",
  "process": {
  "pid": 28,
  "uid": 0,
  "gid": 0,
  "cwd": "/usr/src/app",
  "execPath": "/usr/local/bin/node",
  "version": "v6.11.0",
  "argv": [
    "/usr/local/bin/node",
    "/usr/src/app/src/poll.js"
  ],
  "memoryUsage": {
    "rss": 67502080,
    "heapTotal": 33660928,
    "heapUsed": 25145608,
    "external": 8981275
  }
},
{
  "os": {
    "loadavg": [
      0.65869140625,
      0.44921875,
      0.4541015625
    ],
    "uptime": 218908
  },
  "trace": [
    {
      "column": null,
      "file": null,
      "function": "Error",
      "line": null,
      "method": null,
      "native": true
    }
  ],
  "stack": [
    "Error: ENOENT: no such file or directory, open 'FILE.EXE'",
    " at Error (native)"
  ],
  "level": "error",
  "message": "uncaughtException: ENOENT: no such file or directory, open 'FILE.EXE'",
  "message": "uncaughtException: ENOENT: no such file or directory, open 'FILE.EXE'",
  "timestamp": "2017-07-03T09:09:29.645Z"
}
</code>```

What I expect to happen is for the app to crash, restart and try again later. And if it can't process it x times, it goes in the dead letter queue.

The problem is, it just hangs and when I look at the task in ECS, it says "RUNNING".

So, it never restarts as it doesn't crash.

Is there any sort of configuration I need to do to get a Node Docker App to crash on an uncaught exception?

答:
Put this in your script:</p>

```<code>process.on('uncaughtException', function (err) {
    process.exit(1)
})
</code>```

Title: Node ECS Task Not Crashing

Body:
Node ECS Task Not Crashing

I have an ECS worker running Node:Boron (v6.9.0).

Every now and then I get a uncaught exception.

For Example:

{
  "date": "Mon Jul 03 2017 09:09:29 GMT+0000 (UTC)",
  "process": {
  "pid": 28,
  "uid": 0,
  "gid": 0,
  "cwd": "/usr/src/app",
  "execPath": "/usr/local/bin/node",
  "version": "v6.11.0",
  "argv": [
    "/usr/local/bin/node",
    "/usr/src/app/src/poll.js"
  ],
  "memoryUsage": {
    "rss": 67502080,
    "heapTotal": 33660928,
    "heapUsed": 25145608,
    "external": 8981275
  }
},
{
  "os": {
    "loadavg": [
      0.65869140625,
      0.44921875,
      0.4541015625
    ],
    "uptime": 218908
  },
  "trace": [
    {
      "column": null,
      "file": null,
      "function": "Error",
      "line": null,
      "method": null,
      "native": true
    }
  ],
  "stack": [
    "Error: ENOENT: no such file or directory, open 'FILE.EXE'",
    " at Error (native)"
  ],
  "level": "error",
  "message": "uncaughtException: ENOENT: no such file or directory, open 'FILE.EXE'",
  "message": "uncaughtException: ENOENT: no such file or directory, open 'FILE.EXE'",
  "timestamp": "2017-07-03T09:09:29.645Z"
}

What I expect to happen is for the app to crash, restart and try again later. And if it can't process it x times, it goes in the dead letter queue.

The problem is, it just hangs and when I look at the task in ECS, it says "RUNNING".

So, it never restarts as it doesn't crash.

Is there any sort of configuration I need to do to get a Node Docker App to crash on an uncaught exception?

Body:
Put this in your script:

process.on('uncaughtException', function (err) {
    process.exit(1)
})


问:
in bash, sed, how can I search/replace this: var = ["blabla, doodoo"]; by var blabla = [blabla, doodoo"];
In bash, sed, how can I search/replace this line :

```<code>var = ["bla bla, doodoo"];
</code>```

with

```<code>var blabla = ["bla bla, doodoo"];
</code>```

blabla and doodoo can be anything (one or more words each) -

I want to copy the section between [" and , and paste it after = .

And more, I need to remove any spaces in the copied part...

Any help would be appreciated!

答:
Give this awk one-liner a try:

```<code>awk -F'[",]' '{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' file
</code>```

With your example:

```<code>kent$  awk -F'[",]' '{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7'<<< 'var = ["bla bla, doodoo"]; '
var blabla = ["bla bla, doodoo"];
</code>```

If you want to do the replacement only on var = .... lines, which means, lines missing the variable name, you can do:

```<code>awk -F'[",]' '/^\s*var\s*=/{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' file
</code>```

Example:

```<code>kent$  head f
var = ["bla bla, doodoo"];
var dontTouchMe = ["a b c, doodoo"];
var  = ["chan g e M e, doodoo"];

kent$  awk -F'[",]' '/^\s*var\s*=/{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' f
var blabla = ["bla bla, doodoo"];
var dontTouchMe = ["a b c, doodoo"];
var  changeMe = ["chan g e M e, doodoo"];
</code>```

Body:
In bash, sed, how can I search/replace this line :

var = ["bla bla, doodoo"];

with

var blabla = ["bla bla, doodoo"];

blabla and doodoo can be anything (one or more words each) -

I want to copy the section between [" and , and paste it after = .

And more, I need to remove any spaces in the copied part...

Any help would be appreciated!

Body:
Give this awk one-liner a try:

awk -F'[",]' '{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' file

With your example:

kent$  awk -F'[",]' '{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7'<<< 'var = ["bla bla, doodoo"]; '
var blabla = ["bla bla, doodoo"];

If you want to do the replacement only on var = .... lines, which means, lines missing the variable name, you can do:

awk -F'[",]' '/^\s*var\s*=/{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' file

Example:

kent$  head f
var = ["bla bla, doodoo"];
var dontTouchMe = ["a b c, doodoo"];
var  = ["chan g e M e, doodoo"];

kent$  awk -F'[",]' '/^\s*var\s*=/{x=$2;gsub(/ /,"",x);sub(/=/,x" =")}7' f
var blabla = ["bla bla, doodoo"];
var dontTouchMe = ["a b c, doodoo"];
var  changeMe = ["chan g e M e, doodoo"];


问:
Using a dynamic IP address for the service provider in a WSDL file
We're running a soap server using PHP, and currently the IP address is hard coded in the WSDL file for providing operations etc. However, there are plans to have the server on larger networks where it may not be able to dictate it's own IP address, and so it needs to allow a dynamic address.

Here's a couple of examples of places with this static IP address.

```<code><wsdl:definitions name="itl_ukmachines" targetNamespace="http://10.10.8.89/InPrServerSys/sp/service.php" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://10.10.8.89/InPrServerSys/sp/service.php" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</code>```

and

```<code><wsdl:operation name="MachineHostPowerUpRegistration">

    <soap:operation
    soapAction="http://10.10.8.89/InPrServerSys/sp/service.php/MachineHostPowerUpRegistration" />
    <wsdl:input>

        <soap:body use="literal" />
    </wsdl:input>
    <wsdl:output>

        <soap:body use="literal" />
    </wsdl:output>
</wsdl:operation>
</code>```

Is there a way to have the php server replace these IP addresses up with it's current IP address on startup, or simply a special value that can go in there so this will work?

答:
Another clean solution is to override the location of our web service from client side, for example:</p>

```<code>$soapClient->__setLocation('http://www.example.com/soapservice');
</code>```

Body:
We're running a soap server using PHP, and currently the IP address is hard coded in the WSDL file for providing operations etc. However, there are plans to have the server on larger networks where it may not be able to dictate it's own IP address, and so it needs to allow a dynamic address.

Here's a couple of examples of places with this static IP address.

<wsdl:definitions name="itl_ukmachines" targetNamespace="http://10.10.8.89/InPrServerSys/sp/service.php" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://10.10.8.89/InPrServerSys/sp/service.php" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

and

<wsdl:operation name="MachineHostPowerUpRegistration">

    <soap:operation
    soapAction="http://10.10.8.89/InPrServerSys/sp/service.php/MachineHostPowerUpRegistration" />
    <wsdl:input>

        <soap:body use="literal" />
    </wsdl:input>
    <wsdl:output>

        <soap:body use="literal" />
    </wsdl:output>
</wsdl:operation>

Is there a way to have the php server replace these IP addresses up with it's current IP address on startup, or simply a special value that can go in there so this will work?

Body:
Another clean solution is to override the location of our web service from client side, for example:

$soapClient->__setLocation('http://www.example.com/soapservice');


问:
Insert data to MySql with loop instead of one by one
My Html code is below:

```<code><form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">
    <tr>
        <td><input type="text" name="finanIns1" id="finanIns1" value=""></td>

        <td id="balance"><input type="number" name="balance1" id="balance1" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns2" id="finanIns2" value=""></td>

        <td id="balance"><input type="number" name="balance2" id="balance2" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0"></td>
    </tr>
    <tr>
        <td><input type="text" name="finanIns3" id="finanIns3" value=""></td>

        <td id="balance"><input type="number" name="balance3" id="balance3" value="" min="0"></td>
        <td id="MonthyComm"><input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0"></td>
    </tr>
    <tr>

</form>
</code>```

My post.php code is below:

```<code>    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);
</code>```

my dbCreditAssessment.php code is below:

```<code>function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}
</code>```

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

答:
If you know the number of fields you have (1,2,3) what you can do is a for loop in php:

```<code>// make a loop to go according to the number of fields you have
for($i=1;$i<=3;$i++){
    // assign the fields value to the variables
    $finanIns = $_post['finanIns'.$i];
    $balance = $_post['balance'.$i];
    $monthlyComm = $_post['monthlyComm'.$i];
    //check if fields are empty, if not, insert to mysql
    if($finanIns != "" && $balance != "" && $monthlyComm != ""){
        addemployementdetails($con,$finanIns,$balance,$monthlyComm);
    }
}
</code>```

Please let me know if it's working :)

Body:
My Html code is below:

<form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">

        <input type="text" name="finanIns1" id="finanIns1" value="">

        <input type="number" name="balance1" id="balance1" value="" min="0">
        <input type="number" name="monthlyComm1" id="monthlyComm1" value="" min="0">

        <input type="text" name="finanIns2" id="finanIns2" value="">

        <input type="number" name="balance2" id="balance2" value="" min="0">
        <input type="number" name="monthlyComm2" id="monthlyComm2" value="" min="0">

        <input type="text" name="finanIns3" id="finanIns3" value="">

        <input type="number" name="balance3" id="balance3" value="" min="0">
        <input type="number" name="monthlyComm3" id="monthlyComm3" value="" min="0">

</form>

My post.php code is below:

    require_once 'db/dbfunction.php';
    require_once 'db/dbCreditAssessment.php';

    session_start();
    $con = open_connection();
$finanIns1 = $_POST['finanIns1'];
$balance1 = $_POST['balance1'];
$monthlyComm1 = $_POST['monthlyComm1'];

$finanIns2 = $_POST['finanIns2'];
$balance2 = $_POST['balance2'];
$monthlyComm2 = $_POST['monthlyComm2'];

$finanIns3 = $_POST['finanIns3'];
$balance3 = $_POST['balance3'];
$monthlyComm3 = $_POST['monthlyComm3'];

addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1);
addemployementdetails($con,$finanIns2,$balance2,$monthlyComm2);
addemployementdetails($con,$finanIns3,$balance3,$monthlyComm3);

close_connection($con);

my dbCreditAssessment.php code is below:

function addemployementdetails($con,$finanIns1,$balance1,$monthlyComm1){

    $query = "insert into employementdetails(finance,balance,monthlycomm)
            values('$finanIns1','$balance1','$monthlyComm1')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }
}

this function will repeat 3 times.
Actually, there are a lot more of the same fields to key in. e.g. finanIns1, finanIns2, finanIns3, finanIns4, finanIns5, ect.

Is there any way to use a loop to replace this way of inserting data?
Also, if the fields are empty, the data will not be inserted to Mysql

Body:
If you know the number of fields you have (1,2,3) what you can do is a for loop in php:

// make a loop to go according to the number of fields you have
for($i=1;$i<=3;$i++){
    // assign the fields value to the variables
    $finanIns = $_post['finanIns'.$i];
    $balance = $_post['balance'.$i];
    $monthlyComm = $_post['monthlyComm'.$i];
    //check if fields are empty, if not, insert to mysql
    if($finanIns != "" && $balance != "" && $monthlyComm != ""){
        addemployementdetails($con,$finanIns,$balance,$monthlyComm);
    }
}

Please let me know if it's working :)


问:
How to properly install a SSL for tomcat?
I am in need of having step by step information about installing a wildcard SSL in tomcat server. I tried suggestions in internet, even contacted the SSL provider but all are messing around, I believe my situation is complex. Check below for my setup.

The domain is purchased from www.inmotionhosting.com

The server is an Amazon EC2. I have installed Tomcat there (No Apache)

The SSL is purchased from Comodo. They sent me 2 files, "STAR_xxx_com.crt" and "STAR_xxx_com.ca-bundle". This is a wildcard SSL

Now, this is all I have. Can someone please provide the step by step instruction about what need to be done?

答:
I will try to help because I have been in the same situation where everything is very confusing and you do not know where to go.  First of all, I think Kaushal Kumar Panday answer is correct, I will just try to elaborate a bit more.

To make Tomcat work with your certificate, you normally create a keystore (JKS, Java KeyStore). The keystore will contain your certificate (public) and your key (private), which should have been provided. I will get to this point later.

To configure Tomcat to use the JKS you edit the server.xml file (normally under tomcat_dir/conf/) and add something like this:

```<code>    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               sslProtocol="TLS"
               keystoreFile="path/mykeystore.jks"
               keystorePass="123456"
               keystoreType="JKS"
               keyAlias="tomcat"
    />
</code>```

This is an example, basically Tomcat configuration... You might want to change the port to 443 and some other details.

Now, the only step remaining is how you get to create the .jks file. You will need to use a tool called keytool which is in a Java JDK under the /bin/ dir. I believe the process is the following:

```<code>keytool -import -trustcacerts -alias root -file STAR_xxx_com.ca-bundle -keystore mykeystore.jks

keytool -import -trustcacerts -alias tomcat -file STAR_xxx_com.crt -keystore mykeystore.jks
</code>```

(I think I remember the import commands will create the JKS for you but otherwise check for the command that creates it for you)

Body:
I will try to help because I have been in the same situation where everything is very confusing and you do not know where to go.  First of all, I think Kaushal Kumar Panday answer is correct, I will just try to elaborate a bit more.

To make Tomcat work with your certificate, you normally create a keystore (JKS, Java KeyStore). The keystore will contain your certificate (public) and your key (private), which should have been provided. I will get to this point later.

To configure Tomcat to use the JKS you edit the server.xml file (normally under tomcat_dir/conf/) and add something like this:

    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               sslProtocol="TLS"
               keystoreFile="path/mykeystore.jks"
               keystorePass="123456"
               keystoreType="JKS"
               keyAlias="tomcat"
    />

This is an example, basically Tomcat configuration... You might want to change the port to 443 and some other details.

Now, the only step remaining is how you get to create the .jks file. You will need to use a tool called keytool which is in a Java JDK under the /bin/ dir. I believe the process is the following:

keytool -import -trustcacerts -alias root -file STAR_xxx_com.ca-bundle -keystore mykeystore.jks

keytool -import -trustcacerts -alias tomcat -file STAR_xxx_com.crt -keystore mykeystore.jks

(I think I remember the import commands will create the JKS for you but otherwise check for the command that creates it for you)


问:
Importing python project from github
Im trying to download this project in python from github
and import it to eclipse ubuntu.

The interpreter of python is 3 and I noticed that after the git clone and running the setup.py, the output is in folder python 2.7 instead of python 3

And when I try to import scapy_http.http I get an exeption (probably the interpreter looking for it inside python 2.7 folder).

When I try to replace the interpreter to python 2.7 I get other exeption on import scapy.all

the import scapy suppose to come before import scapy_http

I installed scapy for python 3: pip3 install scapy-python3

So how can I import the scapy-http project to my eclipse project given the interpreter is python 3?

Thanks.

答:
It should be ok if you did pip3 install scary-python3. It's a bit hard to tell exactly what's going on (please provide error messages, etc.) but I would suggest you try:

```<code>sudo python3 setup.py install
</code>```

If you haven't already. The problem might be that you left off the 3 and thus it was stored in python 2 libraries.

Title: Importing python project from github

Body:
It should be ok if you did pip3 install scary-python3. It's a bit hard to tell exactly what's going on (please provide error messages, etc.) but I would suggest you try:

sudo python3 setup.py install

If you haven't already. The problem might be that you left off the 3 and thus it was stored in python 2 libraries.


问:
Delete command is deleting data rather than just the columns
I am currently trying to reformat some sheets that receive their input from other macros. The input to the sheets is fine, but once I try to delete the columns that I need to get rid of (A:H) it only happens on one sheet and all of the data disappears on that sheet.

Here is my code:

```<code>Dim wsSheet As Worksheet
Dim current_flt_date, dept_time As Date
Dim dept_station, arrv_station, subfleet_type, route, red_eye As String
Dim current_flt_number As Integer

For Each wsSheet In ThisWorkbook.Worksheets

    If Not wsSheet.Name = "Sheet3" Then
        wsSheet.Rows(1).Value = Worksheets("Sheet3").Rows(1).Value
        lCol = Cells(1, Columns.Count).End(xlToLeft).Column
        wsSheet.Cells(1, lCol + 1) = "Qty Loaded"
        wsSheet.Rows(1).Font.Bold = True
        wsSheet.Rows(1).Font.Underline = True
        current_flt_date = wsSheet.Cells(2, 1)
        Debug.Print current_flt_date
        dept_station = wsSheet.Cells(2, 2)
        current_flt_number = wsSheet.Cells(2, 3)
        dept_time = wsSheet.Cells(2, 4)
        arrv_station = wsSheet.Cells(2, 5)
        subfleet_type = wsSheet.Cells(2, 6)
        Debug.Print subfleet_type
        route = wsSheet.Cells(2, 7)
        red_eye = wsSheet.Cells(2, 8)
        Range("A:H").Delete

    End If

Next wsSheet
</code>```

I added some screens as well. The first one shows what happens without the delete and the second is with the delete.

Without delete

答:
To have the columns deleted on all the desired worksheets I think you should write:

```<code>wsSheet.Range("A:H").Delete
</code>```

Also do you mean that columns that should not  have be deleted were deleted with your code?

Body:
I am currently trying to reformat some sheets that receive their input from other macros. The input to the sheets is fine, but once I try to delete the columns that I need to get rid of (A:H) it only happens on one sheet and all of the data disappears on that sheet.

Here is my code:

Dim wsSheet As Worksheet
Dim current_flt_date, dept_time As Date
Dim dept_station, arrv_station, subfleet_type, route, red_eye As String
Dim current_flt_number As Integer

For Each wsSheet In ThisWorkbook.Worksheets

    If Not wsSheet.Name = "Sheet3" Then
        wsSheet.Rows(1).Value = Worksheets("Sheet3").Rows(1).Value
        lCol = Cells(1, Columns.Count).End(xlToLeft).Column
        wsSheet.Cells(1, lCol + 1) = "Qty Loaded"
        wsSheet.Rows(1).Font.Bold = True
        wsSheet.Rows(1).Font.Underline = True
        current_flt_date = wsSheet.Cells(2, 1)
        Debug.Print current_flt_date
        dept_station = wsSheet.Cells(2, 2)
        current_flt_number = wsSheet.Cells(2, 3)
        dept_time = wsSheet.Cells(2, 4)
        arrv_station = wsSheet.Cells(2, 5)
        subfleet_type = wsSheet.Cells(2, 6)
        Debug.Print subfleet_type
        route = wsSheet.Cells(2, 7)
        red_eye = wsSheet.Cells(2, 8)
        Range("A:H").Delete

    End If

Next wsSheet

I added some screens as well. The first one shows what happens without the delete and the second is with the delete.

Without delete

Body:
To have the columns deleted on all the desired worksheets I think you should write:

wsSheet.Range("A:H").Delete

Also do you mean that columns that should not  have be deleted were deleted with your code?


问:
Hiding a private overloaded virtual function?
I have a class hierarchy that works approximately like this:

```<code>class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA : A
{
private:
    virtual void f(int) override {}
};

class DB : public DA, B
{
private:
    virtual void f(char*) override {}
};
</code>```

When I try to compile with clang (or gcc, for that matter), it gives me the warning

```<code><source>:22:18: warning: 'DB::f' hides overloaded virtual function [-Woverloaded-virtual]
    virtual void f(char*) override {}
                 ^
<source>:16:18: note: hidden overloaded virtual function 'DA::f' declared here: type mismatch at 1st parameter ('int' vs 'char *')
    virtual void f(int) override {}
                 ^
</code>```

Which I understand, but should it really give that warning? After all, DB cannot even see the hidden function (which might even be named the same by coincidence).

If it wasn't private, I could use

```<code>using DA::f;
</code>```

to clarify, of course, but the function is private, DB doesn't even know about it, and certainly shouldn't expose it.

Is there a way to fix this without deactivating that warning, i.e. telling the compiler that everything is designed as is intended?

答:
What I ended up doing (for now) is using composition instead of private inheritance. So my code currently looks like

```<code>class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA
{
    class D : A
    {
    private:
        virtual void f(int) override {}
    } d;
};

class DB : public DA
{
    class D : B
    {
    private:
        virtual void f(char*) override {}
    } d;
};
</code>```

I'm not 100% happy with this, as the d members cause additional syntactial overhead, but at least it works without changing the public interface.

Body:
I have a class hierarchy that works approximately like this:

class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA : A
{
private:
    virtual void f(int) override {}
};

class DB : public DA, B
{
private:
    virtual void f(char*) override {}
};

When I try to compile with clang (or gcc, for that matter), it gives me the warning

<source>:22:18: warning: 'DB::f' hides overloaded virtual function [-Woverloaded-virtual]
    virtual void f(char*) override {}
                 ^
<source>:16:18: note: hidden overloaded virtual function 'DA::f' declared here: type mismatch at 1st parameter ('int' vs 'char *')
    virtual void f(int) override {}
                 ^

Which I understand, but should it really give that warning? After all, DB cannot even see the hidden function (which might even be named the same by coincidence).

If it wasn't private, I could use

using DA::f;

to clarify, of course, but the function is private, DB doesn't even know about it, and certainly shouldn't expose it.

Is there a way to fix this without deactivating that warning, i.e. telling the compiler that everything is designed as is intended?

Body:
What I ended up doing (for now) is using composition instead of private inheritance. So my code currently looks like

class A
{
protected:
    virtual void f(int) = 0;
};

class B
{
protected:
    virtual void f(char*) = 0;
};

class DA
{
    class D : A
    {
    private:
        virtual void f(int) override {}
    } d;
};

class DB : public DA
{
    class D : B
    {
    private:
        virtual void f(char*) override {}
    } d;
};

I'm not 100% happy with this, as the d members cause additional syntactial overhead, but at least it works without changing the public interface.


问:
Receiving UDP packets at high frequency : packet loss?
I have a C++ application which uses a UDP Server (using Boost.Asio) that receives packets from a gigabit local network device at a high frequency (3500 packets per second). Some users report a few packet losses. So in the end I chose to run in parallel WireShark and my application to check if there are any packets that WireShark is able to receive but not my application.

What I found is that WireShark does not receive every packet, it seems that it misses some. My application misses also a few more frames that Wireshark received correctly.

My questions : Is it possible WireShark gets packets that my application does not ? I thought maybe WireShark has low-level access to the IP stack and packets are discarded by the OS even if they are shown in WireShark ?
Is it possible that the operation in (1) takes too much time such that the next async_receive_from is called too late?
I would like to have opinions on this subject. Thanks.

Here is the code I use (quite basic). udp_server.h :

```<code>#pragma once

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <fstream>

const int MAX_BUFFER_SIZE = 65537;

using boost::asio::ip::udp;

class UDPServer
{
public:
    UDPServer(boost::asio::io_service& ios, udp::endpoint endpoint)
        :m_io_service(ios),
        m_udp_socket(m_io_service, endpoint)
    {
        // Resize the buffer to max size in the component property
        m_recv_buffer.resize(MAX_BUFFER_SIZE);

        m_output_file.open("out.bin", std::ios::out | std::ios::binary);

        StartReceive();
    }

public:
    void StartReceive()
    {
        m_udp_socket.async_receive_from(
            boost::asio::buffer(m_recv_buffer), m_remote_endpoint,
            boost::bind(&UDPServer::HandleReceive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

private:
    void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        if (!error || error == boost::asio::error::message_size)
        {
            // Write to output -- (1)
            m_output_file.sputn(&m_recv_buffer[0], bytes_transferred);

            // Start to receive again
            StartReceive();
        }
    }

    boost::asio::io_service&    m_io_service;
    udp::socket                 m_udp_socket;
    udp::endpoint               m_remote_endpoint;
    std::vector<char>           m_recv_buffer;
    std::filebuf                m_output_file;
};
</code>```

main.cpp:

```<code>include <boost/asio.hpp>
#include "udp_server.h"

const unsigned short PORT_NUMBER = 44444;

int main()
{
    boost::asio::io_service ios;
    boost::asio::ip::udp::endpoint endpoint(udp::endpoint(udp::v4(), PORT_NUMBER));
    UDPServer server(ios, endpoint);
    ios.run();

    return 0;
}
</code>```

答:
Is this possible that WireShark get a packet and that my application
  does not ?

Yes.  In particular, each socket has its own fixed-size incoming-data buffer, and if, at the moment the kernel tries to add the new incoming packet to that buffer, the buffer doesn't have enough available space to hold that packet, then the packet will not be added to the buffer, and so the application reading incoming data from that socket will not receive it.

Given that, it's entirely possible that WireShark's buffer had room to accept the incoming packet, but your own app's buffer did not.

Body:
I have a C++ application which uses a UDP Server (using Boost.Asio) that receives packets from a gigabit local network device at a high frequency (3500 packets per second). Some users report a few packet losses. So in the end I chose to run in parallel WireShark and my application to check if there are any packets that WireShark is able to receive but not my application.

What I found is that WireShark does not receive every packet, it seems that it misses some. My application misses also a few more frames that Wireshark received correctly.

My questions : Is it possible WireShark gets packets that my application does not ? I thought maybe WireShark has low-level access to the IP stack and packets are discarded by the OS even if they are shown in WireShark ?
Is it possible that the operation in (1) takes too much time such that the next async_receive_from is called too late?
I would like to have opinions on this subject. Thanks.

Here is the code I use (quite basic). udp_server.h :

#pragma once

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <fstream>

const int MAX_BUFFER_SIZE = 65537;

using boost::asio::ip::udp;

class UDPServer
{
public:
    UDPServer(boost::asio::io_service& ios, udp::endpoint endpoint)
        :m_io_service(ios),
        m_udp_socket(m_io_service, endpoint)
    {
        // Resize the buffer to max size in the component property
        m_recv_buffer.resize(MAX_BUFFER_SIZE);

        m_output_file.open("out.bin", std::ios::out | std::ios::binary);

        StartReceive();
    }

public:
    void StartReceive()
    {
        m_udp_socket.async_receive_from(
            boost::asio::buffer(m_recv_buffer), m_remote_endpoint,
            boost::bind(&UDPServer::HandleReceive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

private:
    void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        if (!error || error == boost::asio::error::message_size)
        {
            // Write to output -- (1)
            m_output_file.sputn(&m_recv_buffer[0], bytes_transferred);

            // Start to receive again
            StartReceive();
        }
    }

    boost::asio::io_service&    m_io_service;
    udp::socket                 m_udp_socket;
    udp::endpoint               m_remote_endpoint;
    std::vector<char>           m_recv_buffer;
    std::filebuf                m_output_file;
};

main.cpp:

include <boost/asio.hpp>
#include "udp_server.h"

const unsigned short PORT_NUMBER = 44444;

int main()
{
    boost::asio::io_service ios;
    boost::asio::ip::udp::endpoint endpoint(udp::endpoint(udp::v4(), PORT_NUMBER));
    UDPServer server(ios, endpoint);
    ios.run();

    return 0;
}


问:
I'm getting an error [ReflectionException] Class App\Http\Controllers\Frontend\TagsController does not exist when I run php artisan route:list
I'm getting an error [ReflectionException] Class App\Http\Controllers\Frontend\TagsController does not exist when I run php artisan route:list

some one help.

答:
Try namespace like this, in the controller</p>

```<code>namespace App\Http\Controllers\Frontend;
</code>```

Body:
Try namespace like this, in the controller

namespace App\Http\Controllers\Frontend;


问:
Android viewpager actual default offscreen page limit
I have implemented simple ViewPager with its pager adapter.PagerAdapter takes list of views to displaye in ViewPager.I have not called setOffscreenPageLimit for ViewPager to set limit.
So by default 1 limit is selected.(1 page should be retained to either side of the current page in an idle state).But in actual there are 2 pages retained to either side.

```<code>0 | 1 | 2(current visible) | 3 | 4
</code>```

Could you please confirm why it is happening?

答:
I tried to reproduce this behavior, but with the following code I see container.getChildCount() always 3 or lower:

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    SectionsPagerAdapter mSectionsPagerAdapter;

    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        private String TAG = SectionsPagerAdapter.class.getSimpleName();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Log.v(TAG, "container.getChildCount:" + container.getChildCount());
            return super.instantiateItem(container, position);
        }

        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            return String.format(l, "Section %d", position);
        }
    }

    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            ListView listView = (ListView) rootView.findViewById(R.id.listView);
            ArrayAdapter<String> listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
            listAdapter.add("Fragment Body " + getArguments().getInt(ARG_SECTION_NUMBER));
            listAdapter.add("one");
            listAdapter.add("two");
            listAdapter.add("three");
            listView.setAdapter(listAdapter);
            return rootView;
        }
    }

}
</code>```

activity_main.xml

```<code><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>
</code>```

fragment_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            tools:context=".MainActivity$PlaceholderFragment">

<ListView
    android:id="@+id/listView"
    android:layout_height="match_parent"
    android:layout_width="wrap_content" />
</code>```

Body:
I have implemented simple ViewPager with its pager adapter.PagerAdapter takes list of views to displaye in ViewPager.I have not called setOffscreenPageLimit for ViewPager to set limit.
So by default 1 limit is selected.(1 page should be retained to either side of the current page in an idle state).But in actual there are 2 pages retained to either side.

0 | 1 | 2(current visible) | 3 | 4

Could you please confirm why it is happening?

Body:
I tried to reproduce this behavior, but with the following code I see container.getChildCount() always 3 or lower:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    SectionsPagerAdapter mSectionsPagerAdapter;

    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        private String TAG = SectionsPagerAdapter.class.getSimpleName();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Log.v(TAG, "container.getChildCount:" + container.getChildCount());
            return super.instantiateItem(container, position);
        }

        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            return String.format(l, "Section %d", position);
        }
    }

    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            ListView listView = (ListView) rootView.findViewById(R.id.listView);
            ArrayAdapter<String> listAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
            listAdapter.add("Fragment Body " + getArguments().getInt(ARG_SECTION_NUMBER));
            listAdapter.add("one");
            listAdapter.add("two");
            listAdapter.add("three");
            listView.setAdapter(listAdapter);
            return rootView;
        }
    }

}

activity_main.xml

<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>

fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            tools:context=".MainActivity$PlaceholderFragment">

<ListView
    android:id="@+id/listView"
    android:layout_height="match_parent"
    android:layout_width="wrap_content" />


问:
Code to clear all plots in RStudio
I have code to clear the workspace: rm(list=ls()) and code to clear the console: cat("\014")

Is there code to clear all plots from Rstudio?

答:
To prevent error message in case there are no plots to clear:</p>

```<code>if(!is.null(dev.list())) dev.off()
</code>```

Title: Code to clear all plots in RStudio

Body:
To prevent error message in case there are no plots to clear:

if(!is.null(dev.list())) dev.off()


问:
Passing additional parameters in React Router
How can I pass additional parametrs to the component that I am transitioning to.

I have my routes.js as follows. I have declared two paths one for authorList and another for a particluar author's details.

```<code>var routes = (
    <Route path="/" component={require('./components/main')}>
        <Route path="authors" component={require('./components/authors/authorPage')}/>
        <Route path="authors/:authorId" component={require('./components/authors/AuthorDetails')}/>
    </Route>
);

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

And in my authorList Page there is function as follows.

```<code>showAuthorDetails(authorId) {

    var myExtraParams = { key1 : val1, key2 : val2};
    hashHistory.push(`/authors/${authorId});
}
</code>```

Now In my AuthorDetail page I can get authorId by doing

```<code>this.props.params.authorId
</code>```

But I also want to pass myExtraParams as an object but don't want to declare and pass it in the url.
I want to somehow access myExtraParams in the new component, perhaps say like by doing

```<code>this.props.params.myExtraParams
</code>```

should give mt the object.  (Like the way it happens in Angular UI router by using stateParams)

How can I do that?

答:
I am looking at this question. Maybe I am late and you already have got the solution but in case if not then you can simply do this by

router.push({
  pathname: '/some-route',
  search: '?param=123',
  state: {
    additionalParam: 'value',
  },
})}```
</div>
</div>
</p>

<p>And on the receiving component side, you will get it as </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>this.props.location.state.additionalParam</code>```

I hope it helps. In the case of any further help, feel free to let me know.

Thanks

Body:
How can I pass additional parametrs to the component that I am transitioning to.

I have my routes.js as follows. I have declared two paths one for authorList and another for a particluar author's details.

var routes = (
    <Route path="/" component={require('./components/main')}>
        <Route path="authors" component={require('./components/authors/authorPage')}/>
        <Route path="authors/:authorId" component={require('./components/authors/AuthorDetails')}/>
    </Route>
);

module.exports = routes;

And in my authorList Page there is function as follows.

showAuthorDetails(authorId) {

    var myExtraParams = { key1 : val1, key2 : val2};
    hashHistory.push(`/authors/${authorId});
}

Now In my AuthorDetail page I can get authorId by doing

this.props.params.authorId

But I also want to pass myExtraParams as an object but don't want to declare and pass it in the url.
I want to somehow access myExtraParams in the new component, perhaps say like by doing

this.props.params.myExtraParams

should give mt the object.  (Like the way it happens in Angular UI router by using stateParams)

How can I do that?

Body:
I am looking at this question. Maybe I am late and you already have got the solution but in case if not then you can simply do this by

router.push({
  pathname: '/some-route',
  search: '?param=123',
  state: {
    additionalParam: 'value',
  },
})}

And on the receiving component side, you will get it as

this.props.location.state.additionalParam

I hope it helps. In the case of any further help, feel free to let me know.

Thanks


问:
Using Android/Firebase Invite System
I have implemented AppInviteInvitation today with Android and can succesfully send an invite but when the recipient tries to press the install button within the invite they are taken to plus.google.com in their device browser.

Am I doing something wrong?

```<code>  private void onInviteClicked() {
    Intent intent = new AppInviteInvitation.IntentBuilder("Invite")
            .setMessage("Download")
            .setCallToActionText("Install")
            .build();
   final int REQUEST_INVITE = 0;
    startActivityForResult(intent, REQUEST_INVITE);
 }
</code>```

答:
Try setting the deep link property to your app name.

```<code>.setDeepLink(Uri.parse(getString(R.string.app_name)))
</code>```

I was getting a 404 error on the Google Plus link until I added the above statement to the Intent builder. After adding the statement, the invites behaved as expected. I am not using deep links in my application, though they are enabled for the app via the Google Play console.

Title: Using Android/Firebase Invite System

Body:
I have implemented AppInviteInvitation today with Android and can succesfully send an invite but when the recipient tries to press the install button within the invite they are taken to plus.google.com in their device browser.

Am I doing something wrong?

  private void onInviteClicked() {
    Intent intent = new AppInviteInvitation.IntentBuilder("Invite")
            .setMessage("Download")
            .setCallToActionText("Install")
            .build();
   final int REQUEST_INVITE = 0;
    startActivityForResult(intent, REQUEST_INVITE);
 }

Body:
Try setting the deep link property to your app name.

.setDeepLink(Uri.parse(getString(R.string.app_name)))

I was getting a 404 error on the Google Plus link until I added the above statement to the Intent builder. After adding the statement, the invites behaved as expected. I am not using deep links in my application, though they are enabled for the app via the Google Play console.


问:
Find multiple duplicate values in a list in c#
So, lets say I have a list of cars. Each item in the list has a brand and a color property. I would like to find out for each brand how many there are of the same color, and then print that info. The list will be filled by user input. There's no way for me to tell which exact values will be in the list.

Example:

```<code>class Car
    {
        public string brand;
        public string color;
    }

    private void DoSomething()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Toyota", color = "red" });
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "blue" });

        // Find out for each brand how many there are of the same color, and then print that info
        // Example output: Toyota: 2 blue, 1 red
        //                 Audi:   2 red, 1 blue
    }
</code>```

I've spend a long time searching for a way to do this. All I was able to figure out was how to get the number of occurences of a certain item in the list.

If my question is unclear please let me know, I will try to explain a bit more.

答:
Some linq should do this:</p>

```<code>var result = cars.GroupBy(x => new { x.brand, x.color })
    .Select(x => new {
        Brand = x.Key.brand,
        Color = x.Key.color,
        Count = x.Count()
    });
</code>```

Body:
So, lets say I have a list of cars. Each item in the list has a brand and a color property. I would like to find out for each brand how many there are of the same color, and then print that info. The list will be filled by user input. There's no way for me to tell which exact values will be in the list.

Example:

class Car
    {
        public string brand;
        public string color;
    }

    private void DoSomething()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Toyota", color = "red" });
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "blue" });

        // Find out for each brand how many there are of the same color, and then print that info
        // Example output: Toyota: 2 blue, 1 red
        //                 Audi:   2 red, 1 blue
    }

I've spend a long time searching for a way to do this. All I was able to figure out was how to get the number of occurences of a certain item in the list.

If my question is unclear please let me know, I will try to explain a bit more.

Body:
Some linq should do this:

var result = cars.GroupBy(x => new { x.brand, x.color })
    .Select(x => new {
        Brand = x.Key.brand,
        Color = x.Key.color,
        Count = x.Count()
    });


问:
How do I access a static map from a seperate class in C++?
I'd like to access a static map that is stored in a seperate class and iterate through and print the contents.

So I have three files:

HasGlobals.cpp which has the global map.

```<code>/* HasGlobals.cpp */

#include <string>
#include <map>
#include <iostream>

class HasGlobals{
    public:
        static std::map<int, std::string> globalData;

        HasGlobals(){
            globalData.insert(std::pair<int, std::string>(0, "data"));
        };

        ~HasGlobals(){
        };
};
</code>```

WantsGlobals.cpp which has a method that needs to use the map from HasGlobals.cpp for one of its methods.

```<code>/* WantsGlobals.cpp */

#include "HasGlobals.cpp"
#include <string>

class WantsGlobals{
    public:
        WantsGlobals(){
        };

        ~WantsGlobals(){
        };

        //THIS IS THE METHOD THAT I CAN'T GET TO WORK
        void printContentsOfGlobal(){
            HasGlobals * globalRetriever = new HasGlobals();
            for(std::map<int, std::string>::iterator it = globalRetriever->globalData.begin(); it != globalRetriever->globalData.end(); ++it){
                std::cout << it->first << " " << it->second << std::endl;
            }
        };
    };
</code>```

Main.cpp which simply tries to call the printContentsOfGlobal() method in WantsGlobals.cpp.

```<code>/* Main.cpp */

#include <iostream>
#include "WantsGlobals.cpp"

int main(){
    WantsGlobals * globalRetriever = new WantsGlobals();
    globalRetriever->printContentsOfGlobal();
}
</code>```

Right now this code doesn't compile and gives me

undefined reference to 'HasGlobals::globalData'

How would I implement printContentsOfGlobal() so that I can retrieve the data in the map[globalData] in the seperate HasGlobals.cpp file?

EDIT:
Thanks for the help everyone.  Below is the code I created with everyone's help.  Yes it's still not perfect but it compiles and performs the desired behavior:

HasGlobals.hpp

```<code>#include <string>
#include <map>
#include <iostream>

class HasGlobals{
    public:
        static std::map<int, std::string> globalData;

        HasGlobals(){};

        ~HasGlobals(){};

        static std::map<int, std::string> createDummyData(){
            std::map<int, std::string> m;
            m[0] = "Help";
            m[1] = "Me";
            m[2] = "Stackoverflow";
            m[3] = "You're my only hope.";
            return m;
         }
};

std::map<int, std::string> HasGlobals::globalData = HasGlobals::createDummyData();
</code>```

WantsGlobals.hpp

```<code>#include "HasGlobals.hpp"
#include <string>
#include <map>

class WantsGlobals{
    public:
        WantsGlobals(){};

        ~WantsGlobals(){};

        void printContentsOfGlobal(){
            for(std::map<int, std::string>::iterator it = HasGlobals::globalData.begin(); it != HasGlobals::globalData.end(); ++it){
                 std::cout << it->first << " " << it->second << std::endl;
             }
         };
};
</code>```

Main.cpp

```<code>#include <iostream>
#include <"WantsGlobals.hpp">

int main(){
    WantsGlobals * globalRetriever = new WantsGlobals();
    globalRetriever->printContentsOfGlobal();
}
</code>```

答:
(CW as this is now just hints & tips on a dupe, left for posterity.)

Why are you #includeing .cpp files? Don't do that. It looks like those two files should be named .hpp instead.

You're close. Since the map is static, you don't need an instance of HasGlobals to access it, so HasGlobals * globalRetriever = new HasGlobals(); is pointless (plus you leaked it).

The map is "called" HasGlobals::globalData.

Though you will need to find some place to add data to it; the HasGlobals constructor is not the proper place, as that is called every time you instantiate the class. Best to use the initialiser when you define the object, which you forgot to do, hence the "undefined reference" linker error you mentioned in comments.

You are using the map correctly from then on, except from a typo here:

```<code>std::map<int, std:;string>
//                ^
</code>```

Body:
I'd like to access a static map that is stored in a seperate class and iterate through and print the contents.

So I have three files:

HasGlobals.cpp which has the global map.

/* HasGlobals.cpp */

#include <string>
#include <map>
#include <iostream>

class HasGlobals{
    public:
        static std::map<int, std::string> globalData;

        HasGlobals(){
            globalData.insert(std::pair<int, std::string>(0, "data"));
        };

        ~HasGlobals(){
        };
};

WantsGlobals.cpp which has a method that needs to use the map from HasGlobals.cpp for one of its methods.

/* WantsGlobals.cpp */

#include "HasGlobals.cpp"
#include <string>

class WantsGlobals{
    public:
        WantsGlobals(){
        };

        ~WantsGlobals(){
        };

        //THIS IS THE METHOD THAT I CAN'T GET TO WORK
        void printContentsOfGlobal(){
            HasGlobals * globalRetriever = new HasGlobals();
            for(std::map<int, std::string>::iterator it = globalRetriever->globalData.begin(); it != globalRetriever->globalData.end(); ++it){
                std::cout << it->first << " " << it->second << std::endl;
            }
        };
    };

Main.cpp which simply tries to call the printContentsOfGlobal() method in WantsGlobals.cpp.

/* Main.cpp */

#include <iostream>
#include "WantsGlobals.cpp"

int main(){
    WantsGlobals * globalRetriever = new WantsGlobals();
    globalRetriever->printContentsOfGlobal();
}

Right now this code doesn't compile and gives me

undefined reference to 'HasGlobals::globalData'

How would I implement printContentsOfGlobal() so that I can retrieve the data in the map[globalData] in the seperate HasGlobals.cpp file?

EDIT:
Thanks for the help everyone.  Below is the code I created with everyone's help.  Yes it's still not perfect but it compiles and performs the desired behavior:

HasGlobals.hpp

#include <string>
#include <map>
#include <iostream>

class HasGlobals{
    public:
        static std::map<int, std::string> globalData;

        HasGlobals(){};

        ~HasGlobals(){};

        static std::map<int, std::string> createDummyData(){
            std::map<int, std::string> m;
            m[0] = "Help";
            m[1] = "Me";
            m[2] = "Stackoverflow";
            m[3] = "You're my only hope.";
            return m;
         }
};

std::map<int, std::string> HasGlobals::globalData = HasGlobals::createDummyData();

WantsGlobals.hpp

#include "HasGlobals.hpp"
#include <string>
#include <map>

class WantsGlobals{
    public:
        WantsGlobals(){};

        ~WantsGlobals(){};

        void printContentsOfGlobal(){
            for(std::map<int, std::string>::iterator it = HasGlobals::globalData.begin(); it != HasGlobals::globalData.end(); ++it){
                 std::cout << it->first << " " << it->second << std::endl;
             }
         };
};

Main.cpp

#include <iostream>
#include <"WantsGlobals.hpp">

int main(){
    WantsGlobals * globalRetriever = new WantsGlobals();
    globalRetriever->printContentsOfGlobal();
}

Body:
(CW as this is now just hints & tips on a dupe, left for posterity.)

Why are you #includeing .cpp files? Don't do that. It looks like those two files should be named .hpp instead.

You're close. Since the map is static, you don't need an instance of HasGlobals to access it, so HasGlobals * globalRetriever = new HasGlobals(); is pointless (plus you leaked it).

The map is "called" HasGlobals::globalData.

Though you will need to find some place to add data to it; the HasGlobals constructor is not the proper place, as that is called every time you instantiate the class. Best to use the initialiser when you define the object, which you forgot to do, hence the "undefined reference" linker error you mentioned in comments.

You are using the map correctly from then on, except from a typo here:

std::map<int, std:;string>
//                ^


问:
Find number of replacements when using a global Regular Expression
I have a sentence (string) containing words. I want to replace all occurrences of a word with another. I use newString = oldString.replace(/w1/gi, w2);, but now I need to report to the user how many words I actually replaced.

Is there a quick way to do it without resorting to:

Replacing one word at a time and counting.

Comparing oldString to newString word-by-word and tallying the differences?
(The easy case is if oldString === newString => 0 replacements, but beyond that, I'll have to run over both and compare).

Is there any RegEx "trickery" I can use here, or should I just avoid using the g flag?

答:
You could split the string with the regex you're using and get the length.

```<code>oldString.split(/w1/gi).length - 1
</code>```

Working example:

```<code>var string = "The is the of the and the";
var newString = string.replace(/the/gi, "hello");

var wordsReplaced = string.split(/the/gi).length - 1;

console.log("Words replaced: ", wordsReplaced);
</code>```

Body:
You could split the string with the regex you're using and get the length.

oldString.split(/w1/gi).length - 1

Working example:

var string = "The is the of the and the";
var newString = string.replace(/the/gi, "hello");

var wordsReplaced = string.split(/the/gi).length - 1;

console.log("Words replaced: ", wordsReplaced);


问:
Angular 2: view does not update when array is updated
I have a component with two array. arrayA and arrayB. arrayB contains filtered elements of arrayA. And in the template:

```<code><div *ngFor="let elem of arrayB">{{elem.something}}</div>
</code>```

I have a button too:

```<code><button (click)="doSomething()">Do Something</button>
</code>```

In the doSomething method I use the filter method on arrayA to update arrayB.

```<code>doSomething() {
    this.arrayB = this.arrayA.filter(elem => { return ***some code***; });
}
</code>```

The problem is that the view doesn't refresh. I tried to use NgZone (ngZone.run(): I wrapped the code in the method.) and ChangeDetectorRef (detectChanges()/markForCheck(): I called this at the end of the method.) too.

What should be the solution for this?

答:
In the doSomething() method I returned with true. Because of this, the method fired twice.
So the solution is to always return with false.

Body:
I have a component with two array. arrayA and arrayB. arrayB contains filtered elements of arrayA. And in the template:

{{elem.something}}

I have a button too:

<button (click)="doSomething()">Do Something</button>

In the doSomething method I use the filter method on arrayA to update arrayB.

doSomething() {
    this.arrayB = this.arrayA.filter(elem => { return ***some code***; });
}

The problem is that the view doesn't refresh. I tried to use NgZone (ngZone.run(): I wrapped the code in the method.) and ChangeDetectorRef (detectChanges()/markForCheck(): I called this at the end of the method.) too.

What should be the solution for this?


问:
Trigger anonymous function inside setInterval immediately
So I have a timer that looks like this

```<code>my_timer = setInterval(function(){
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}, 1000);
</code>```

And I want it to run immediately, and every second after that. I tried appending () to the end of the function, but that caused it to run only once (because it is not returning the function itself to the setInterval?). I then tried to return this; so that it would possibly return the function itself, but that did no good either. That was a random guess.

Is there any way I can get this to work without creating a named function? Thanks!

答:
This doesn't technically create any named functions, but I'm not sure why you'd want to do it:

```<code>(function(func) {
    func();
    setInterval(func, 1000);
})(function() {
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
});
</code>```

Body:
So I have a timer that looks like this

my_timer = setInterval(function(){
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}, 1000);

And I want it to run immediately, and every second after that. I tried appending () to the end of the function, but that caused it to run only once (because it is not returning the function itself to the setInterval?). I then tried to return this; so that it would possibly return the function itself, but that did no good either. That was a random guess.

Is there any way I can get this to work without creating a named function? Thanks!

Body:
This doesn't technically create any named functions, but I'm not sure why you'd want to do it:

(function(func) {
    func();
    setInterval(func, 1000);
})(function() {
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
});


问:
jQuery Alert if paragraph is selected and has specific class
I have html code like below.

```<code><div id='p1' class='thread'>
<p>First Paragraph</p>
<p>Abbot and Costello - Africa Screams</p>
</div>

<div id='p2' class='thread selected'>
<p>Second Paragraph</p>
<p class='flag'>Abbot and Costello - Frank/Meet</p>
</div>

<div id='p3' class='thread'>
<p>Third Paragraph</p>
<p>addin</p>
</div>

<div id='p4' class='thread'>
<p>Forth Paragraph</p>
<p>Begins</p>
</div>
</code>```

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

答:
```<code><script type="text/javascript">
            $(document).ready(function(){
$("p").click(function(){
    if($(this).hasClass("flag")){
        if($(this).parent().hasClass("selected")){
            alert("flag");
        }
            else{}
        }
    else{}
    });
});
        </script>
</code>```

Body:
I have html code like below.

First Paragraph

Abbot and Costello - Africa Screams

Second Paragraph

Abbot and Costello - Frank/Meet

Third Paragraph

addin

Forth Paragraph

Begins

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.


答:
```<code>var carGroups = cars.GroupBy(c => new { c.brand, c.color });
foreach (var carGroup in carGroups)
{
    Console.WriteLine($"{carGroup.Key}, count: {carGroup.Count()}");
}
</code>```

Title: Find multiple duplicate values in a list in c#


问:
addEventListener ('click', ...) By clicking on 'numbers' button text on the display should be equal to that number
I am trying to build a javascript calculator as per freecodecamp requirement on front end track.

Codepen link: https://codepen.io/ekilja01/pen/MoXROe

By pressing any number on calculator the display must be changed to that number. Also the var number has to remember its value, because by clicking the number again it becomes a new number, so after that I can use operators and parseInt to evaluate and display the final value.  I've got an idea how can this be implemented by using jQuery, so something like this:

```<code>   $("#numbers a").not("#clear,#clearall").click(function(){
        number += $(this).text();
        totaldiv.text(number);

    });
    $("#operators a").not("#equals").click(function(){
        operator = $(this).text();
        newnumber = number;
        number = "";
        totaldiv.text("0");
    });
    $("#clear,#clearall").click(function(){
        number = "";
        totaldiv.text("0");
        if ($(this).attr("id") === "clearall") {
            newnumber = "";
        }
    });
    //Add your last .click() here!
    $("#equals").click(function(){
        if (operator === "+"){
            number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
        } else if (operator === "-"){
            number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
        } else if (operator === "÷"){
            number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
        } else if (operator === "×"){
            number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
        }
        totaldiv.text(number);
        number = "";
        newnumber = "";
    });
</code>```

But what can be equivalent to this in vanilla js? I've tried .textContent or .innerHTML, but neither of them work. On calculator's dispay either undefined or 1 ... AC. Also what is the equivalent to .not(). Any help will be much appreciated.

html:

```<code><div id="calculator">
          <p id="cal">CALCULATOR</p>
          <div id="total">
          </div>
          <div id="operators">
              <a>÷</a>
              <a>×</a>
              <a>+</a>
              <a>-</a>
              <a>=</a>
          </div>
          <div id="numbers">
              <a>1</a>
              <a>2</a>
              <a>3</a>
              <a>4</a>
              <a>5</a>
              <a>6</a>
              <a>7</a>
              <a>8</a>
              <a>9</a>
              <a id="clear">C</a>
              <a>0</a>
              <a id="clearall">AC</a>
          </div>
      </div>
</code>```

js:

```<code>document.addEventListener('DOMContentLoaded', function (event) {
    console.log('DOM OK');

    // Declare variables for number, new number and operators

    var number, newNumber, operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    document.getElementById("numbers").addEventListener('click', function(){
        number += this.textContent;
        totalNumber.textContent = number;
    })

})
</code>```

答:
just to display which number is clicked on-</p>

```<code>var totalNumber = document.getElementById("total");
totalNumber.textContent = "";
document.getElementById("numbers").addEventListener('click', function(e){
    totalNumber.textContent += e.target.innerText;
})
</code>```

Body:
I am trying to build a javascript calculator as per freecodecamp requirement on front end track.

Codepen link: https://codepen.io/ekilja01/pen/MoXROe

By pressing any number on calculator the display must be changed to that number. Also the var number has to remember its value, because by clicking the number again it becomes a new number, so after that I can use operators and parseInt to evaluate and display the final value.  I've got an idea how can this be implemented by using jQuery, so something like this:

   $("#numbers a").not("#clear,#clearall").click(function(){
        number += $(this).text();
        totaldiv.text(number);

    });
    $("#operators a").not("#equals").click(function(){
        operator = $(this).text();
        newnumber = number;
        number = "";
        totaldiv.text("0");
    });
    $("#clear,#clearall").click(function(){
        number = "";
        totaldiv.text("0");
        if ($(this).attr("id") === "clearall") {
            newnumber = "";
        }
    });
    //Add your last .click() here!
    $("#equals").click(function(){
        if (operator === "+"){
            number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
        } else if (operator === "-"){
            number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
        } else if (operator === "÷"){
            number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
        } else if (operator === "×"){
            number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
        }
        totaldiv.text(number);
        number = "";
        newnumber = "";
    });

But what can be equivalent to this in vanilla js? I've tried .textContent or .innerHTML, but neither of them work. On calculator's dispay either undefined or 1 ... AC. Also what is the equivalent to .not(). Any help will be much appreciated.

html:

CALCULATOR

              ÷
              ×
              +
              -
              =

              1
              2
              3
              4
              5
              6
              7
              8
              9
              C
              0
              AC

js:

document.addEventListener('DOMContentLoaded', function (event) {
    console.log('DOM OK');

    // Declare variables for number, new number and operators

    var number, newNumber, operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    document.getElementById("numbers").addEventListener('click', function(){
        number += this.textContent;
        totalNumber.textContent = number;
    })

})

Body:
just to display which number is clicked on-

var totalNumber = document.getElementById("total");
totalNumber.textContent = "";
document.getElementById("numbers").addEventListener('click', function(e){
    totalNumber.textContent += e.target.innerText;
})


答:
```<code>  var grp = cars.GroupBy(g => new { g.brand, g.color }).Select(n => new {
                brand = n.Key.brand,
                color = n.Key.color,
                count = n.Count()

            });
</code>```