问:
What is the overhead of creating a new HttpClient per call in a WebAPI client?
What should be the HttpClient lifetime of a WebAPI client?

 Is it better to have one instance of the HttpClient for multiple calls?

What's the overhead of creating and disposing a HttpClient per request, like in example below (taken from http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client):

```<code>using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync<Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}
</code>```

答:
As the other answers state, HttpClient is meant for reuse. However, reusing a single HttpClient instance across a multi-threaded application means you can't change the values of its stateful properties, like BaseAddress and DefaultRequestHeaders (so you can only use them if they are constant across your application).

One approach for getting around this limitation is wrapping HttpClient with a class that duplicates all the HttpClient methods you need (GetAsync, PostAsync etc) and delegates them to a singleton HttpClient. However that's pretty tedious (you will need to wrap the extension methods too), and fortunately there is another way - keep creating new HttpClient instances, but reuse the underlying HttpClientHandler. Just make sure you don't dispose the handler:

```<code>HttpClientHandler _sharedHandler = new HttpClientHandler(); //never dispose this
HttpClient GetClient(string token)
{
    //client code can dispose these HttpClient instances
    return new HttpClient(_sharedHandler, disposeHandler: false)
    {
       DefaultRequestHeaders =
       {
            Authorization = new AuthenticationHeaderValue("Bearer", token)
       }
    };
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What should be the HttpClient lifetime of a WebAPI client?

 Is it better to have one instance of the HttpClient for multiple calls?

What's the overhead of creating and disposing a HttpClient per request, like in example below (taken from http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client):

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync<Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}

Body:
As the other answers state, HttpClient is meant for reuse. However, reusing a single HttpClient instance across a multi-threaded application means you can't change the values of its stateful properties, like BaseAddress and DefaultRequestHeaders (so you can only use them if they are constant across your application).

One approach for getting around this limitation is wrapping HttpClient with a class that duplicates all the HttpClient methods you need (GetAsync, PostAsync etc) and delegates them to a singleton HttpClient. However that's pretty tedious (you will need to wrap the extension methods too), and fortunately there is another way - keep creating new HttpClient instances, but reuse the underlying HttpClientHandler. Just make sure you don't dispose the handler:

HttpClientHandler _sharedHandler = new HttpClientHandler(); //never dispose this
HttpClient GetClient(string token)
{
    //client code can dispose these HttpClient instances
    return new HttpClient(_sharedHandler, disposeHandler: false)
    {
       DefaultRequestHeaders =
       {
            Authorization = new AuthenticationHeaderValue("Bearer", token)
       }
    };
}


来源: stackexchange

问:
@PropertySource cannot be opened because it does not exist
I have the problem with configuration file that is located in other directory than my jar file.

I use @PropertySource for loading properties.

```<code>@PropertySource(ignoreResourceNotFound = true, value = "${ext.properties.dir:classpath:}/properties.properties")
</code>```

I try to run jar using following command:

```<code>java -jar import-0.0.1-SNAPSHOT.jar -Dext.properties.dir=file:/C:\Users\Admin\Desktop\
</code>```

The following error pring in logs: Properties location

Properties location
  [${ext.properties.dir:classpath:}/properties.properties] not resolvable:
  class path resource [properties.properties] cannot be opened because it
  does not exist

How can I fix this error?

答:
I saw that you are using spring boot application, according to the spring documentation you can try to use this environment property:

```<code>--spring.config.location=file:/path/location/file-name.properties
</code>```

The final instruction would be:

```<code>java -jar import-0.0.1-SNAPSHOT.jar --spring.config.location=file:C:\Users\Admin\Desktop\import.properties
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the problem with configuration file that is located in other directory than my jar file.

I use @PropertySource for loading properties.

@PropertySource(ignoreResourceNotFound = true, value = "${ext.properties.dir:classpath:}/properties.properties")

I try to run jar using following command:

java -jar import-0.0.1-SNAPSHOT.jar -Dext.properties.dir=file:/C:\Users\Admin\Desktop\

The following error pring in logs: Properties location

Properties location
  [${ext.properties.dir:classpath:}/properties.properties] not resolvable:
  class path resource [properties.properties] cannot be opened because it
  does not exist

How can I fix this error?

Body:
I saw that you are using spring boot application, according to the spring documentation you can try to use this environment property:

--spring.config.location=file:/path/location/file-name.properties

The final instruction would be:

java -jar import-0.0.1-SNAPSHOT.jar --spring.config.location=file:C:\Users\Admin\Desktop\import.properties


问:
How to show maximum same adjacent elements in an array in Java
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

```<code>int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);
</code>```

```<code> Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )
</code>```

My output is (directly from console)

1

[I@6d06d69c

答:
You are doing two mistakes in your code, first you are using the same index i for both your input array arr and result array resultArr, you should use a different one for resultArr like this

```<code>int resultArrIndex = 0;
for (i=1; i<length; i++)
{
  if (arr[i-1]==arr[i])
  {
    counter++;      // Counter to represent maximal adjacent occurred elem.
    resultArr[resultArrIndex] = arr[i]  //Writing elements in result array
    resultArrIndex++;
  }
}
</code>```

Second this is not the way to print an Array, either you do it in a for loop like this

```<code>for (int i = 0; i < resultArr.length; i++) {
  System.out.println(resultArr[i]);  // will print each in a line
}
</code>```

or like this

```<code>System.out.println(Arrays.toString(resultArr));  // Print all in one line
</code>```

Body:
Im new to Java and i'm doing array sorting problems and i'm having difficulties with this problem. Searched for simmular or duplicate posts, but didn't seem to find any.

The problem is "Find the most same, adjacent elements in an array and write them in to a new array".

My question is.
How can i store most occurued adjacent elements in an array from another array ?

This is what I have comed up so far.

int[] arr= {2, 1, 1, 3, 3, 2, 2, 2, 2, 1 ,1}; //test array

int counter=0;
int i = 0;
int length = arr.length;
int[] resultArr=new int[length];

for (i=1; i<length; i++)

    {
   if (arr[i-1]==arr[i])
    {
     counter++;      // Counter to represent maximal adjacent occurred elem.
     resultArr[i] = arr[i]  //Writing elements in result array
    }

}
 System.out.println(counter);
 System.out.println(resultArr);

 Input: It is the test array "arr"

 Output 1 : Shoud be 4 representing the maximum of same adjacent elements ( i.e the 2's in the array )
 Output 2 : Must be an array that contains the 4 elements of the array ({2, 2, 2 ,2} )

My output is (directly from console)

1

[I@6d06d69c

Body:
You are doing two mistakes in your code, first you are using the same index i for both your input array arr and result array resultArr, you should use a different one for resultArr like this

int resultArrIndex = 0;
for (i=1; i<length; i++)
{
  if (arr[i-1]==arr[i])
  {
    counter++;      // Counter to represent maximal adjacent occurred elem.
    resultArr[resultArrIndex] = arr[i]  //Writing elements in result array
    resultArrIndex++;
  }
}

Second this is not the way to print an Array, either you do it in a for loop like this

for (int i = 0; i < resultArr.length; i++) {
  System.out.println(resultArr[i]);  // will print each in a line
}

or like this

System.out.println(Arrays.toString(resultArr));  // Print all in one line


问:
AngularJS confirm before route change
Is it possible to listen for route changes AND onwindowunload both to confirm page leave without saving changes?

Use cases:

User clicks Back

User presses back button in browser

User types in a different URL

If the user clicks 'cancel' stop the page / route change.

I've seen a few different examples but none worked quite right.

答:
For Angular ES6 Users</p>

```<code>export default class myRouteController {

  constructor($scope, $window) {
    this.$scope = $scope;
    this.$window = $window;

    this.$scope.$on('$stateChangeStart', (evt) => {
      if(this.form.$dirty && !$window.confirm('Are you sure you want to leave this page?')) {
        evt.preventDefault();
      }
    });
  }
}
</code>```

Title: AngularJS confirm before route change

Body:
For Angular ES6 Users

export default class myRouteController {

  constructor($scope, $window) {
    this.$scope = $scope;
    this.$window = $window;

    this.$scope.$on('$stateChangeStart', (evt) => {
      if(this.form.$dirty && !$window.confirm('Are you sure you want to leave this page?')) {
        evt.preventDefault();
      }
    });
  }
}


问:
Recursively scanning for a child propery or state via script in reactjs
I'm trying to write a utility function to get the (first) title propery of the current component (of the route).

I can get the tile property of the route:

```<code>function getPageTitleByRoutes(routes) {
  for (let i = routes.length - 1; i >= 0; i -= 1) {
    if (routes[i].hasOwnProperty('title')) {
      return routes[i].title;
    }
  }

  return null;
}
</code>```

But now I want move the title prop to my components:

```<code>function getPageTitle(props) {
  // ?? Iterate recurively ?? Context ok on render ??
  React.Children.forEach(props.children, (child, i) => {
    console.log(child + ' at index: ' + i);
    // If it has title
    // ??
    // ??
    if(title) return title;
    return getPageTitle(child.props);
  });

  return null;
}
</code>```

I have a component setup like this under react router:

```<code><Router>
  <Route path="/" title="App Title" component={App}>
    <Route path="page1" title="Comp A" component={Comp1} />
    <Route path="page2" title="Comp B" component={Comp2} />
  </Route>
  <Route path="/login" title="Login Comp" component={Login} />
</Router>

var NavBar = React.createClass({
  render() {
    const someTitle = getPageTitleByRoutes(this.props.routes);
    // Line above works but now want to get 'title' (defaultProps)
    // from "active/routed" component:
    const someTitle = getPageTitle(this.props);
    return (
      <div>
        <h2>{someTitle}</h2>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});
</code>```

Then I create my app like this:

```<code>var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        {this.props.children}
      </div>
    )
  }
});
</code>```

Maybe there is another approach? I also have react-redux connected...

答:
You are not passing any props nor any children to your <NavBar /> component.  This is why this.props.routes and this.props.children are empty.

Try giving <NavBar /> a route prop and some children.  You decide what to add there.

For example:

<NavBar routes={[{title: 'First Title'}, {title: 'Second Title'}]} />

Or passing along your <App />'s children like it looked like you may have intended but like so:

<NavBar>
     {this.props.children}
</NavBar>

Body:
I'm trying to write a utility function to get the (first) title propery of the current component (of the route).

I can get the tile property of the route:

function getPageTitleByRoutes(routes) {
  for (let i = routes.length - 1; i >= 0; i -= 1) {
    if (routes[i].hasOwnProperty('title')) {
      return routes[i].title;
    }
  }

  return null;
}

But now I want move the title prop to my components:

function getPageTitle(props) {
  // ?? Iterate recurively ?? Context ok on render ??
  React.Children.forEach(props.children, (child, i) => {
    console.log(child + ' at index: ' + i);
    // If it has title
    // ??
    // ??
    if(title) return title;
    return getPageTitle(child.props);
  });

  return null;
}

I have a component setup like this under react router:

<Router>
  <Route path="/" title="App Title" component={App}>
    <Route path="page1" title="Comp A" component={Comp1} />
    <Route path="page2" title="Comp B" component={Comp2} />
  </Route>
  <Route path="/login" title="Login Comp" component={Login} />
</Router>

var NavBar = React.createClass({
  render() {
    const someTitle = getPageTitleByRoutes(this.props.routes);
    // Line above works but now want to get 'title' (defaultProps)
    // from "active/routed" component:
    const someTitle = getPageTitle(this.props);
    return (

{someTitle}

           history.push('page1') }>Page 1
           history.push('page2') }>Page 2

    )
  }
});

Then I create my app like this:

var App = React.createClass({
  render() {
    return (

        <NavBar />
        {this.props.children}

    )
  }
});

Maybe there is another approach? I also have react-redux connected...


问:
Change user with Firebase Google user authentication
When using Firebase Google user authentication the user is immediately logged in if they have already authorized the application and only logged in to one Google account.

Is there a way to force the "Choose an account" dialog to appear so that the user has the opportunity to login to a different Google account or create a new one?

Currency as far as I know the user has to manually logout of the current Google account (or login to > 1) from Google.com to make the dialog appear.

答:
You can force to choose an account with 'prompt' provider parameter.

```<code>var googleAuthProvider = new firebase.auth.GoogleAuthProvider();
googleAuthProvider.setCustomParameters({
   prompt: 'select_account'
});
firebase.auth().signInWithRedirect(googleAuthProvider)
</code>```

Tested with Firebase JavaScript SDK v4.1.2

Body:
You can force to choose an account with 'prompt' provider parameter.

var googleAuthProvider = new firebase.auth.GoogleAuthProvider();
googleAuthProvider.setCustomParameters({
   prompt: 'select_account'
});
firebase.auth().signInWithRedirect(googleAuthProvider)

Tested with Firebase JavaScript SDK v4.1.2


问:
Will call to static function be overwritten
I have 2 classes called A and B.
Class B contains a static function called calculate which performs an async network call and stores the data of it locally.

I wanted to know if the following code will kill the async task inside the calculate function.

```<code>Class A
{
 B.calculate(); // performs long running async task
 B.calculate(); // the above call to calculate has not finished but this was called
}
</code>```

Will the async task that started from the first call to calculate continue executing or will it be destroyed and a new task created
?

答:
No, executing an AsyncTask again will not kill the original.  Instead it will add a new task to the async task queue (because by default only 1 async task runs at a time) which will eventually be run causing a 2nd network request.

(Note:  the above assumes you create a new instance of the AsycTask subclass.  If you try to execute the same instance again, you will get an exception.)

Body:
I have 2 classes called A and B.
Class B contains a static function called calculate which performs an async network call and stores the data of it locally.

I wanted to know if the following code will kill the async task inside the calculate function.

Class A
{
 B.calculate(); // performs long running async task
 B.calculate(); // the above call to calculate has not finished but this was called
}

Will the async task that started from the first call to calculate continue executing or will it be destroyed and a new task created
?


问:
Best way to stream mp3s from java/c++ server to html5?
I am looking into streaming mp3s from a java (preferably) or c++ server to an html5 browser on another computer.

I know html5 (depending on the browser) supports rtp, so if possible, that would be the best way to proceed.

In terms of the server side however, I am stuck. Are there any Java libraries that would enable mp3 streaming via rtp? I have looked at live555 for c++, but it seems to be a little too heavy for what I am looking for.

Or am I approaching this whole thing wrong. Basically I am looking to create a program where users can point to mp3 files on their computers/other users can open a webpage and stream these mp3 files from there.

Thanks

答:
Check these Java RTP implementations:

java.net.RTP

RTP Java Library

jlibrtp

ContentLicense: CC BY-SA 2.5


问:
Second path fragment must not be a drive or UNC name
How to read all image files in folder by  environment path folder in main folder:

```<code>   string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mainFolder");
</code>```

for example if inner folder for one file path is:

```<code>  Bitmap bmp = new Bitmap(path + "/folder/pic1.bmp");
</code>```

but I want read all files of  mainFolder/folder:

```<code>pic1.bmp
pic2.bmp
pic3.bmp
pic5.bmp
</code>```

Not sure how to do it properly:

```<code>foreach (string imageFileName in Directory.GetFiles(path, "/folder/*.bmp"))
{
    using (Bitmap bmp = new Bitmap(imageFileName))
    {
      // process
    }
}
</code>```

this way I  have: Second path fragment must not be a drive or UNC name

and  this way:

```<code>foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.bmp"))
</code>```

I got: Illegal characters in path.

答:
Directory.GetFiles() does not accept asterisks in its path name. What you can do, is provide the file extension as a searchpattern:

```<code>foreach(string filename in Directory.GetFiles(Path.Combine(path, "folder"), "*.jpg"))
    //Do your stuff here
</code>```

Further reading

Body:
How to read all image files in folder by  environment path folder in main folder:

   string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mainFolder");

for example if inner folder for one file path is:

  Bitmap bmp = new Bitmap(path + "/folder/pic1.bmp");

but I want read all files of  mainFolder/folder:

pic1.bmp
pic2.bmp
pic3.bmp
pic5.bmp

Not sure how to do it properly:

foreach (string imageFileName in Directory.GetFiles(path, "/folder/*.bmp"))
{
    using (Bitmap bmp = new Bitmap(imageFileName))
    {
      // process
    }
}

this way I  have: Second path fragment must not be a drive or UNC name

and  this way:

foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.bmp"))

I got: Illegal characters in path.

Body:
Directory.GetFiles() does not accept asterisks in its path name. What you can do, is provide the file extension as a searchpattern:

foreach(string filename in Directory.GetFiles(Path.Combine(path, "folder"), "*.jpg"))
    //Do your stuff here

Further reading


问:
Visual studio 2015 gives me errors upon creating a simple test console program
Here is the code I am using.

```<code>#include "stdafx.h"
#include <iostream>

int main() {
    std::cout << "hi";

    return 0;
}
</code>```

When I create simple c++ console application and try to build it, this error occurs:

```<code>cannot open include file 'stdio.h': No such file or directory
</code>```

Why? Shouldn't stdio.h be included as a standard library? What can I do to get it back?

edit: I have just looked into C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include directory. There is no stdio.h or stdafx.h . I really am not sure why. How can I get them back?

答:
I had the same problem in Visual Studio Community 2015 after installing the current Windows SDK and as Signa already wrote earlier, this can be fixed for all projects within a "Toolset.props" file (at least for VS2015) and I find this to be the most convenient solution, because this has to be done only once. I've got a few side notes, because there is something to watch out for.

For each build platform there is an own "Toolset.props" file, so both need to be modified if you want to build for 32 and 64 bit targets:

```<code>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\Win32\PlatformToolsets\v140\Toolset.props

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.props
</code>```

The files are write-protected and you need to remove the write protection before you can change those files (remember to put it back on after you're done).

As of now the current SDK version is "10.0.15063.0" and you need to adjust that to the version you want to use (or to the SDK version you have installed).

Look out for the IncludePath and LibraryPath lines in those props files and add the following paths to them:

IncludePath: $(ProgramFiles)\Windows Kits\10\Include\10.0.15063.0\ucrt

LibraryPath: $(ProgramFiles)\Windows Kits\10\Lib\10.0.15063.0\ucrt\$(PlatformTarget)

Here a sample how this looks like for the 32 bit version:

```<code>// ... some XML before that ...
<PropertyGroup>
    // ... executable path .....
    <IncludePath Condition="'$(IncludePath)' == ''">$(VC_IncludePath);$(WindowsSDK_IncludePath);$(ProgramFiles)\Windows Kits\10\Include\10.0.15063.0\ucrt;</IncludePath>
    // ... reference path ...
    <LibraryPath Condition="'$(LibraryPath)' == ''">$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;$(ProgramFiles)\Windows Kits\10\Lib\10.0.15063.0\ucrt\$(PlatformTarget);</LibraryPath>
    // ... more XML ...
</PropertyGroup>
// ... even more XML ....
</code>```

Body:
Here is the code I am using.

#include "stdafx.h"
#include <iostream>

int main() {
    std::cout << "hi";

    return 0;
}

When I create simple c++ console application and try to build it, this error occurs:

cannot open include file 'stdio.h': No such file or directory

Why? Shouldn't stdio.h be included as a standard library? What can I do to get it back?

edit: I have just looked into C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include directory. There is no stdio.h or stdafx.h . I really am not sure why. How can I get them back?

Body:
I had the same problem in Visual Studio Community 2015 after installing the current Windows SDK and as Signa already wrote earlier, this can be fixed for all projects within a "Toolset.props" file (at least for VS2015) and I find this to be the most convenient solution, because this has to be done only once. I've got a few side notes, because there is something to watch out for.

For each build platform there is an own "Toolset.props" file, so both need to be modified if you want to build for 32 and 64 bit targets:

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\Win32\PlatformToolsets\v140\Toolset.props

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Platforms\x64\PlatformToolsets\v140\Toolset.props

The files are write-protected and you need to remove the write protection before you can change those files (remember to put it back on after you're done).

As of now the current SDK version is "10.0.15063.0" and you need to adjust that to the version you want to use (or to the SDK version you have installed).

Look out for the IncludePath and LibraryPath lines in those props files and add the following paths to them:

IncludePath: $(ProgramFiles)\Windows Kits\10\Include\10.0.15063.0\ucrt

LibraryPath: $(ProgramFiles)\Windows Kits\10\Lib\10.0.15063.0\ucrt\$(PlatformTarget)

Here a sample how this looks like for the 32 bit version:

// ... some XML before that ...
<PropertyGroup>
    // ... executable path .....
    <IncludePath Condition="'$(IncludePath)' == ''">$(VC_IncludePath);$(WindowsSDK_IncludePath);$(ProgramFiles)\Windows Kits\10\Include\10.0.15063.0\ucrt;</IncludePath>
    // ... reference path ...
    <LibraryPath Condition="'$(LibraryPath)' == ''">$(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;$(ProgramFiles)\Windows Kits\10\Lib\10.0.15063.0\ucrt\$(PlatformTarget);</LibraryPath>
    // ... more XML ...
</PropertyGroup>
// ... even more XML ....


问:
How can I add a new Layout to the new Form Ext. on TYPO3 8.7?
I want to use a new layout for the new form extension in TYPO3 8.6 LTS. The old way don't work:

```<code>TCEFORM.tt_content {
    layout {
        types {
            form {
                removeItems = 900,910,920,930,940,950,999
                addItems {
                    800 = test
                }
            }
    }
}
</code>```

The items to remove are shown, and the new item test, will don't show in Backend. Why? And how can I bring it to work?
Thank you for any help

答:
Please try with:</p>

```<code>TCEFORM.tt_content.layout.types.form_formframework{
//et cetera
</code>```

Body:
I want to use a new layout for the new form extension in TYPO3 8.6 LTS. The old way don't work:

TCEFORM.tt_content {
    layout {
        types {
            form {
                removeItems = 900,910,920,930,940,950,999
                addItems {
                    800 = test
                }
            }
    }
}

The items to remove are shown, and the new item test, will don't show in Backend. Why? And how can I bring it to work?
Thank you for any help

Body:
Please try with:

TCEFORM.tt_content.layout.types.form_formframework{
//et cetera


问:
Import all modules from a directory at once [NODE]
```<code>MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js
</code>```

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.

答:
You can use manual way to import all modules in a directory

```<code>var allModules = {};
require('fs').readdirSync(__dirname + '/modules/').forEach(function(file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '');
    allModules[name] = require('./modules/' + file);
  }
});
// allModules.a(params)
</code>```

or you can use this library for this case require-dir

```<code>var requireDir = require('require-dir');
var modulesPackage = requireDir('./modules');
// modulesPackage contains
//{
//  a: require("./modules/a"),
//  b: require("./modules/b")
//}
</code>```

The lib has a tip: If you want to require() the same directory in multiple places, you can do this in the directory itself! Just make an index.js file with the following:

```<code>module.exports = require('require-dir')();   // defaults to '.'
</code>```

Where you want to use a package in modules:

```<code>var mds = require('./modules');
// mds.a(params) .....
</code>```

Body:
MyApp
├── main.js
└── modules
    ├── a.js
    ├── b.js
    ├── c.js
    ├── d.js
    ├── e.js

In my NodeJS app, how can I import all my custom modules (a,b,c,d,e) in my main.js file at once?

I have long list of modules and I dont want to import them all separately.

Body:
You can use manual way to import all modules in a directory

var allModules = {};
require('fs').readdirSync(__dirname + '/modules/').forEach(function(file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '');
    allModules[name] = require('./modules/' + file);
  }
});
// allModules.a(params)

or you can use this library for this case require-dir

var requireDir = require('require-dir');
var modulesPackage = requireDir('./modules');
// modulesPackage contains
//{
//  a: require("./modules/a"),
//  b: require("./modules/b")
//}

The lib has a tip: If you want to require() the same directory in multiple places, you can do this in the directory itself! Just make an index.js file with the following:

module.exports = require('require-dir')();   // defaults to '.'

Where you want to use a package in modules:

var mds = require('./modules');
// mds.a(params) .....


问:
How to get listview column lines with dynamically changing column width in MVVM pattern
I have a list view in wpf, with 3 comboboxes and 2 checkbox as columns. I play with checkbox visibility based on some search criteria. I could achieve horizontal line between rows, however i could not achieve vertical line to separate columns. I change the visibility of checkbox & column width from my model.I need to follow MVVM pattern.
Help much appreciated.
Thanks in advance.

Below is my xaml code

```<code><ListView  Grid.ColumnSpan="3" Grid.Column="1" Grid.Row="2"
                           ItemsSource="{Binding NewTransactionSetlist,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                          SelectedItem="{Binding SelectedNewItem,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                           SelectedIndex="{Binding SelectedNewIndex, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                           VerticalAlignment="Top" Height="320"  SelectionMode="Single"
                          HorizontalAlignment="Center" Width="1240">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="Padding" Value="0,2"/>
                            <Setter Property="BorderBrush" Value="LightGray"/>
                            <Setter Property="BorderThickness" Value="0,0,0,1"/>
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                            <!--<EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem" ></EventSetter>
                            <Style.Triggers>
                                    <Trigger Property="IsKeyboardFocusWithin" Value="true">
                                        <Setter Property="IsSelected" Value="true" />
                                    </Trigger>
                                </Style.Triggers>-->
                            <!--<Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Value="True">
                                    <Setter Property="IsSelected" Value="True"  />
                                </DataTrigger>
                            </Style.Triggers>-->

                        </Style>
                    </ListView.ItemContainerStyle>
                    <!--<i:Interaction.Triggers>
                        <i:EventTrigger EventName="PreviewGotKeyboardFocus">
                            <i:InvokeCommandAction Command="{Binding PreviewGotKeyboardFocusCommand}"
                                                  />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>-->
                    <!--<Style TargetType="{x:Type ListViewItem}">
                         <Style.Triggers>
                            <DataTrigger Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Value="True">
                                <Setter Property="IsSelected" Value="True"  />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>-->
                    <ListView.InputBindings>
                        <KeyBinding
                         Key="Delete"
                         Command="{Binding NewTransactionDataGridRowDeleteCommand}"/>
                    </ListView.InputBindings>
                    <ListView.View>
                        <GridView ColumnHeaderContainerStyle="{StaticResource GridViewHeaderStyle}">
                            <GridViewColumn Header="Transaction" Width="{Binding NewTransactionHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"   >
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxParamList" HorizontalAlignment="Left" Width="{Binding TransactionHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              Text="{Binding ParamGroup, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              SelectedValue ="{Binding ParamGroup, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              ItemsSource="{Binding ParamGroupList}" >
                                            <i:Interaction.Triggers>
                                                <i:EventTrigger EventName="SelectionChanged">
                                                    <i:InvokeCommandAction Command="{Binding DataContext.ParameterNewSelectionChangedCommand,
                                                    RelativeSource={RelativeSource AncestorType=ListView}}"/>
                                                </i:EventTrigger>
                                            </i:Interaction.Triggers>
                                        </ComboBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="System" Width="{Binding NewSystemHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxSystemList"  HorizontalAlignment="Left" Width="{Binding SystemHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              Text="{Binding SystemName, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              SelectedValue ="{Binding SystemName, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              ItemsSource="{Binding SystemNameList}"   />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="HandAdd" Width="{Binding NewHandAddHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <CheckBox Name="CheckBoxNewHandAdd" Width="{Binding HandAddHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Visibility="{Binding HandAddVisibility,Converter={StaticResource BoolToVisConverter}}"
                                                  IsChecked="{Binding HandAdd, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Margin="90,0,0,0" ></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="Downstream" Width="{Binding NewDownstreamHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <CheckBox Width="{Binding DownstreamHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Visibility="{Binding DownstreamVisibility,Converter={StaticResource BoolToVisConverter}}"
                                                  IsChecked="{Binding Downstream, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center"  Margin="90,0,0,0"></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="Node" Width="{Binding NewNodeHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxNodeList" Width="{Binding NodeHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Text="{Binding Node, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left"
                                                  SelectedValue ="{Binding Node, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}"  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              ItemsSource="{Binding NodeList}" />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>
</code>```

答:
http://blog.bulatgafurov.name/2010/06/listview-horizontal-and-vertical.html

this blog solved my problem...!

Body:
I have a list view in wpf, with 3 comboboxes and 2 checkbox as columns. I play with checkbox visibility based on some search criteria. I could achieve horizontal line between rows, however i could not achieve vertical line to separate columns. I change the visibility of checkbox & column width from my model.I need to follow MVVM pattern.
Help much appreciated.
Thanks in advance.

Below is my xaml code

<ListView  Grid.ColumnSpan="3" Grid.Column="1" Grid.Row="2"
                           ItemsSource="{Binding NewTransactionSetlist,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                          SelectedItem="{Binding SelectedNewItem,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                           SelectedIndex="{Binding SelectedNewIndex, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                           VerticalAlignment="Top" Height="320"  SelectionMode="Single"
                          HorizontalAlignment="Center" Width="1240">
                    <ListView.ItemContainerStyle>
                        -->

                        </Style>
                    </ListView.ItemContainerStyle>

                    <ListView.InputBindings>
                        <KeyBinding
                         Key="Delete"
                         Command="{Binding NewTransactionDataGridRowDeleteCommand}"/>
                    </ListView.InputBindings>
                    <ListView.View>
                        <GridView ColumnHeaderContainerStyle="{StaticResource GridViewHeaderStyle}">
                            <GridViewColumn Header="Transaction" Width="{Binding NewTransactionHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"   >
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxParamList" HorizontalAlignment="Left" Width="{Binding TransactionHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              Text="{Binding ParamGroup, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              SelectedValue ="{Binding ParamGroup, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              ItemsSource="{Binding ParamGroupList}" >

                                        </ComboBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="System" Width="{Binding NewSystemHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxSystemList"  HorizontalAlignment="Left" Width="{Binding SystemHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              Text="{Binding SystemName, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              SelectedValue ="{Binding SystemName, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                                              ItemsSource="{Binding SystemNameList}"   />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="HandAdd" Width="{Binding NewHandAddHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <CheckBox Name="CheckBoxNewHandAdd" Width="{Binding HandAddHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Visibility="{Binding HandAddVisibility,Converter={StaticResource BoolToVisConverter}}"
                                                  IsChecked="{Binding HandAdd, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Margin="90,0,0,0" ></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="Downstream" Width="{Binding NewDownstreamHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <CheckBox Width="{Binding DownstreamHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Visibility="{Binding DownstreamVisibility,Converter={StaticResource BoolToVisConverter}}"
                                                  IsChecked="{Binding Downstream, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center"  Margin="90,0,0,0"></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="Node" Width="{Binding NewNodeHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                            <ComboBox x:Name="ComboBoxNodeList" Width="{Binding NodeHeaderLength,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                                                  Text="{Binding Node, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left"
                                                  SelectedValue ="{Binding Node, Mode=TwoWay, NotifyOnSourceUpdated=True,
                                        UpdateSourceTrigger=PropertyChanged}"  IsEditable="False" Style="{DynamicResource DatagridComboboxFontstyle}"
                                              ItemsSource="{Binding NodeList}" />
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>


问:
Regex to split a hashtag into words
I am trying to come up with a regex which will correctly split a hashtag into its words. For example:

XP => XP

ACar => A Car

GoodCar => Good Car

OnceUponATime => Once Upon A Time

LoveXP => Love XP

AppleVsXP => Apple Vs XP

JamesBond007 => James Bond 007

Edit:
I have tried

```<code>expanded = ' '.join(re.findall(r"[A-Z][^A-Z]*", self.text))
</code>```

What is a a more robust way which will address all the use cases above?

答:
you can simply do this by this expression, it's totally sufficient:

```<code>expanded = " ".join([a for a in re.split('([A-Z][a-z]+)', i) if a])
</code>```

it gives the following results:

```<code>XP
A Car
Good Car
Once Upon A Time
Love XP
Apple Vs XP
James Bond 007
</code>```

Hope this was helpful.

Title: Regex to split a hashtag into words

Body:
I am trying to come up with a regex which will correctly split a hashtag into its words. For example:

XP => XP

ACar => A Car

GoodCar => Good Car

OnceUponATime => Once Upon A Time

LoveXP => Love XP

AppleVsXP => Apple Vs XP

JamesBond007 => James Bond 007

Edit:
I have tried

expanded = ' '.join(re.findall(r"[A-Z][^A-Z]*", self.text))

What is a a more robust way which will address all the use cases above?

Body:
you can simply do this by this expression, it's totally sufficient:

expanded = " ".join([a for a in re.split('([A-Z][a-z]+)', i) if a])

it gives the following results:

XP
A Car
Good Car
Once Upon A Time
Love XP
Apple Vs XP
James Bond 007

Hope this was helpful.


问:
How can I make a nil compatible completion handler?
I created a function with a completion handler. Sometimes I need to use the completion block,  sometimes not.

Here is the function:

```<code>func numberCheck(number: String , completion : @escaping (Bool)->()){
     //some task do here
    completion(true)
}
</code>```

use:

```<code>numberCheck(number: "77" , completion: {_ in
    //some task do here
})
</code>```

But I want to leave it completion block nil:

```<code>numberCheck(number: "77" ,  completion: nil)
</code>```

but it is gives me an error:

Nil is not compatible with expected argument type '(Bool) -> ()'

答:
Make the closure optional

```<code>func numberCheck(number: String , completion : @escaping ((Bool)->())?){
</code>```

or for better readability

```<code>typealias CheckResult = (Bool)->()

func numberCheck(number: String , completion : @escaping CheckResult? ){
</code>```

But then you have to write in the body of the function

```<code>completion?(true)
</code>```

Body:
I created a function with a completion handler. Sometimes I need to use the completion block,  sometimes not.

Here is the function:

func numberCheck(number: String , completion : @escaping (Bool)->()){
     //some task do here
    completion(true)
}

use:

numberCheck(number: "77" , completion: {_ in
    //some task do here
})

But I want to leave it completion block nil:

numberCheck(number: "77" ,  completion: nil)

but it is gives me an error:

Nil is not compatible with expected argument type '(Bool) -> ()'

Body:
Make the closure optional

func numberCheck(number: String , completion : @escaping ((Bool)->())?){

or for better readability

typealias CheckResult = (Bool)->()

func numberCheck(number: String , completion : @escaping CheckResult? ){

But then you have to write in the body of the function

completion?(true)


问:
How can one use regex to capture the text occurring between lines beginning with a single semicolon?
I want to capture the text between lines which begin with single semicolons:

sample input:

```<code>s = '''
;

the color blue

;

the color green

;

the color red

;
'''
</code>```

this is the desired output:

```<code>['the color blue', 'the color green', 'the color red']
</code>```

this attempted solution doesn't work:

```<code>import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)
</code>```

this is the wrong output:

```<code>['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']
</code>```

答:
You can use ;\s*(.*?)\s*(?=;). Usage:

```<code>print( re.findall(r'(?s);\s*(.*?)\s*(?=;)', s) )
# output: ['the color blue', 'the color green', 'the color red']
</code>```

Explanation:

```<code>(?s)   # dot-all modifier (. matches newlines)
;      # consume a semicolon
\s*    # skip whitespace
(.*?)  # capture the following text, as little as possible, such that...
\s*    # ... it is followed only by (optional) whitespace, and...
(?=;)  # ... a semicolon
</code>```

Body:
I want to capture the text between lines which begin with single semicolons:

sample input:

s = '''
;

the color blue

;

the color green

;

the color red

;
'''

this is the desired output:

['the color blue', 'the color green', 'the color red']

this attempted solution doesn't work:

import re
pat = r'^;(.*)^;'
r = re.findall(pat, s, re.S|re.M)
print(r)

this is the wrong output:

['\n\nthe color blue\n\n;\n\nthe color green\n\n;\n\nthe color red\n\n']

Body:
You can use ;\s*(.*?)\s*(?=;). Usage:

print( re.findall(r'(?s);\s*(.*?)\s*(?=;)', s) )
# output: ['the color blue', 'the color green', 'the color red']

Explanation:

(?s)   # dot-all modifier (. matches newlines)
;      # consume a semicolon
\s*    # skip whitespace
(.*?)  # capture the following text, as little as possible, such that...
\s*    # ... it is followed only by (optional) whitespace, and...
(?=;)  # ... a semicolon


问:
Call server side method from JavaScript in C#
I want to call a C# server method from JavaScript. In JavaScript function alert is coming but not calling the server method.

Here is my code. This is the server side method:

```<code>public void ReloadData()
{
     //here is the code
}
</code>```

Here is the client side function:

```<code>function GetData() {
alert("Function called");
PageMethods.ReloadData();
}
</code>```

Now, here the getdata function is called and alert is also coming but in server side method is not called. [I have seen by doing in debug mode.]

答:
I believe you will have to use AJAX for this.  Have a look here: https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

ReloadData will be a webmethod in your code behind and will look something like this:

```<code>[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}
</code>```

Then from the client side you will do something like this:

```<code>function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
</code>```

}

CS.aspx is the name of your webpage.

Following on from your comment below; if you did not want to use JQuery then your Javascript code would look something like this:

```<code>var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();
</code>```

Body:
I want to call a C# server method from JavaScript. In JavaScript function alert is coming but not calling the server method.

Here is my code. This is the server side method:

public void ReloadData()
{
     //here is the code
}

Here is the client side function:

function GetData() {
alert("Function called");
PageMethods.ReloadData();
}

Now, here the getdata function is called and alert is also coming but in server side method is not called. [I have seen by doing in debug mode.]

Body:
I believe you will have to use AJAX for this.  Have a look here: https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

ReloadData will be a webmethod in your code behind and will look something like this:

[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}

Then from the client side you will do something like this:

function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });

}

CS.aspx is the name of your webpage.

Following on from your comment below; if you did not want to use JQuery then your Javascript code would look something like this:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();


问:
xmltask (ANT) :: replace withtext not working for null value of xml element
I am trying to replace xml field value using xmltask ( ANT script ) . But it is not replacing the value if the xml element is empty.

for example :

```<code>   <Mydoc>
      <doc>
      <docname>abc.txt</docname>
      <doclocation>xyz</doclocation>
      </doc>
      <doc>
      <docname>mmm.txt</docname>
      <doclocation></doclocation>
      </doc>
    </Mydoc>

in the above example i want to update the "doclocation" element if "docname" element is "mmm.txt"
</code>```

Script used to achieve it.

```<code>        <xmltask dest="sample.xml">
         <fileset file="sample.xml"/>

            <replace
            path="/Mydoc/doc[docname="mmm.txt"]/doclocation/text()"
            withText="newURL"/>

          </xmltask>
</code>```

the above piece of code is not working if 'doclocation' element has null/no value.

what needs to be done here to handle the null values and replace it with the new value ?

答:
You can replace the doclocation element entirely for all cases, using a CDATA section, e.g.:</p>

```<code>     <property name="newURL" value="https://www.stackoverflow.com"/>
     <xmltask source="sample.xml" dest="result.xml">
        <replace path="/Mydoc/doc[docname='mmm.txt']/doclocation">
           <![CDATA[ <doclocation>${newURL}</doclocation> ]]>
        </replace>
     </xmltask>
</code>```

Body:
I am trying to replace xml field value using xmltask ( ANT script ) . But it is not replacing the value if the xml element is empty.

for example :

   <Mydoc>
      <doc>
      <docname>abc.txt</docname>
      <doclocation>xyz</doclocation>
      </doc>
      <doc>
      <docname>mmm.txt</docname>
      <doclocation></doclocation>
      </doc>
    </Mydoc>

in the above example i want to update the "doclocation" element if "docname" element is "mmm.txt"

Script used to achieve it.

        <xmltask dest="sample.xml">
         <fileset file="sample.xml"/>

            <replace
            path="/Mydoc/doc[docname="mmm.txt"]/doclocation/text()"
            withText="newURL"/>

          </xmltask>

the above piece of code is not working if 'doclocation' element has null/no value.

what needs to be done here to handle the null values and replace it with the new value ?

Body:
You can replace the doclocation element entirely for all cases, using a CDATA section, e.g.:

     <property name="newURL" value="https://www.stackoverflow.com"/>
     <xmltask source="sample.xml" dest="result.xml">
        <replace path="/Mydoc/doc[docname='mmm.txt']/doclocation">
           <![CDATA[ <doclocation>${newURL}</doclocation> ]]>
        </replace>
     </xmltask>


问:
filtering out elements from an array based on second array in javascript
I have two following arrays

```<code>1) ['data/proxies/AuthDecoder/1/AuthDecoder.zip',
  'data/proxies/JSONP/1/JSONP.zip',
  'data/proxies/XMLP/1/XMLP.zip',
  'data/proxies/accessControl/1/accessControl.zip']

2) ['AuthDecoder', 'JSONP', 'XMLP',]
</code>```

how do I filter out the first array so that the first array only contains those elements that also have a match in second array.
The name of the proxy (with .zip extension) should match in both arrays.

So after the filtering, first array should look like

```<code>['data/proxies/AuthDecoder/1/AuthDecoder.zip',
  'data/proxies/JSONP/1/JSONP.zip',
  'data/proxies/XMLP/1/XMLP.zip',
]
</code>```

答:
Use Regex for the same

```<code>var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/Spain/i);
document.getElementById("demo").innerHTML = res;
</code>```

write string to be matched between '/' and then followed by modifier

i is case insensitive

g is global search

m is used in multi-line search

Body:
I have two following arrays

1) ['data/proxies/AuthDecoder/1/AuthDecoder.zip',
  'data/proxies/JSONP/1/JSONP.zip',
  'data/proxies/XMLP/1/XMLP.zip',
  'data/proxies/accessControl/1/accessControl.zip']

2) ['AuthDecoder', 'JSONP', 'XMLP',]

how do I filter out the first array so that the first array only contains those elements that also have a match in second array.
The name of the proxy (with .zip extension) should match in both arrays.

So after the filtering, first array should look like

['data/proxies/AuthDecoder/1/AuthDecoder.zip',
  'data/proxies/JSONP/1/JSONP.zip',
  'data/proxies/XMLP/1/XMLP.zip',
]

Body:
Use Regex for the same

var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/Spain/i);
document.getElementById("demo").innerHTML = res;

write string to be matched between '/' and then followed by modifier

i is case insensitive

g is global search

m is used in multi-line search


问:
Help with SQL Stored procedure
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

```<code>Select Name from Lookup_Country where Code = @Code
</code>```

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

```<code>if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code
</code>```

Is this possible?

thx

Thx for the help everyone, I used this:

```<code>DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE
</code>```

答:
Does it help you?</p>

```<code> Select Name from Lookup_Country where (Code = @Code OR Id = @Code)
</code>```

Title: Help with SQL Stored procedure

Body:
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

Select Name from Lookup_Country where Code = @Code

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code

Is this possible?

thx

Thx for the help everyone, I used this:

DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE

Body:
Does it help you?

 Select Name from Lookup_Country where (Code = @Code OR Id = @Code)


问:
run for-loop for large numbers in python
```<code> for i in range(1000000000):
 print(i)
</code>```

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

```<code>>>>MemoryError
</code>```

UPDATE:
Actually I was trying something like this:

```<code>arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))
</code>```

I don't know how to deal with such large numbers.

答:
The range usually returns an list of values  which can be iterated. But, however if you are trying to generate a very large number of values then python Generators are best option as they yield a single value at a time and are being memory efficient to handle large scalable data.</p>

```<code>def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

generatorObject = firstn(1000000000)

for i in generatorObject:
    print(i)
</code>```

Body:
 for i in range(1000000000):
 print(i)

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

>>>MemoryError

UPDATE:
Actually I was trying something like this:

arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))

I don't know how to deal with such large numbers.

Body:
The range usually returns an list of values  which can be iterated. But, however if you are trying to generate a very large number of values then python Generators are best option as they yield a single value at a time and are being memory efficient to handle large scalable data.

def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

generatorObject = firstn(1000000000)

for i in generatorObject:
    print(i)


答:
This code fails because you must provide file name's pattern as a second parameter:

```<code>foreach (string imgFileName in Directory.GetFiles(path, "/folder/*.jpg"))
</code>```

The second one fails because '*' is a special symbol and UNC paths don't accept that.

```<code>foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.jpg"))
</code>```

So you can try to do the following:

```<code>foreach (string imgFileName in Directory.GetFiles(path + "/folder/","*.jpg"))
</code>```

MSDN Directory.GetFiles

Body:
How to read all image files in folder by  environment path folder in main folder:

   string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mainFolder");

for example if inner folder for one file path is:

  Bitmap bmp = new Bitmap(path + "/folder/pic1.bmp");

but I want read all files of  mainFolder/folder:

pic1.bmp
pic2.bmp
pic3.bmp
pic5.bmp

Not sure how to do it properly:

foreach (string imageFileName in Directory.GetFiles(path, "/folder/*.bmp"))
{
    using (Bitmap bmp = new Bitmap(imageFileName))
    {
      // process
    }
}

this way I  have: Second path fragment must not be a drive or UNC name

and  this way:

foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.bmp"))

I got: Illegal characters in path.

Body:
This code fails because you must provide file name's pattern as a second parameter:

foreach (string imgFileName in Directory.GetFiles(path, "/folder/*.jpg"))

The second one fails because '*' is a special symbol and UNC paths don't accept that.

foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.jpg"))

So you can try to do the following:

foreach (string imgFileName in Directory.GetFiles(path + "/folder/","*.jpg"))

MSDN Directory.GetFiles


问:
PHP: $_FILES - Why should i restrict specific file types?
Today I was surfing around in the internet about how to upload files onto my webserver with a php formular, and somehow everybody only allows specific file typs (and restricts all others). For somebody who wants to upload a picture, it is not nice to see that the webpage does not except that file type. What´s the problem with other file types (for example, directly from w3schools.com: only JPG, JPEG, PNG & GIF are allowed).

Thankx in advance,

VicStudio

答:
It is mainly for security reasons. Everything in $_FILES is coming from the user's browser, so if you do not have strict validation on what you accept, malicious users could upload files that are

too large — what if someone uploads a 10 GB image?

have a dangerous file type — what if someone uploads a .php file to your server? Game over.

have an invalid name — what if someone sets the file name to ../../../file.txt? When you save the file, it could end up in a different directory due to the ../.. in the path. This is called a Path Traversal vulnerability.

When processing file uploads, you should validate all three of these against a whitelist. That is, have a list or range of values that you accept, and discard anything that does not fit those critera.


问:
Gap between contents
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

```<code>.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}
</code>```

Thanks in advance

答:
well, this problem seems to be quite tough. I would suggest to fill the content vertically first and then horizontally. You should add equal number of blocks to each column. I mean like this:

```<code>1 4 7
2 5 8
3 6 9
</code>```

So, no horizontal space. However, there will be always some free space vertically since the blocks are not equal. This issue can be solved to certain degree by flexbox justify-content property. Finally, we will get something like this (the wider the screen is, the better):

* {
  box-sizing: border-box;
}

.container {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: row wrap;
      flex-flow: row wrap;
  -webkit-box-pack: justify;
      -ms-flex-pack: justify;
          justify-content: space-between;
  -webkit-box-align: stretch;
      -ms-flex-align: stretch;
          align-items: stretch;
  width: 100%;
}

.subcontainer {
  -webkit-box-flex: 3;
      -ms-flex: 3 1 33.3%;
          flex: 3 1 33.3%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
  -ms-flex-pack: distribute;
      justify-content: space-around;
  padding: 0em 0.5em;
}

.item {
  padding: 0.5em 0em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
    <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
    <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
</div></code>```

It should look quite ok on real monitors and not inside this small sandbox space. For mobile viewports you can always implement corresponding styles.

An alternative to flexboxes can be CSS Grid - check it out. Also I would suggest making the height of blocks equal although in this case the problem is gone naturally :) As far as I know, that's all without resorting to super hacky, messy, JS-involving approaches. Maybe others will come up with better solutions though.

PS check out this css grid example. Seems to be similar to what you want to achieve, although the support for css grid is not full yet.

Title: Gap between contents

Body:
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}

Thanks in advance

Body:
well, this problem seems to be quite tough. I would suggest to fill the content vertically first and then horizontally. You should add equal number of blocks to each column. I mean like this:

1 4 7
2 5 8
3 6 9

So, no horizontal space. However, there will be always some free space vertically since the blocks are not equal. This issue can be solved to certain degree by flexbox justify-content property. Finally, we will get something like this (the wider the screen is, the better):

* {
  box-sizing: border-box;
}

.container {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: row wrap;
      flex-flow: row wrap;
  -webkit-box-pack: justify;
      -ms-flex-pack: justify;
          justify-content: space-between;
  -webkit-box-align: stretch;
      -ms-flex-align: stretch;
          align-items: stretch;
  width: 100%;
}

.subcontainer {
  -webkit-box-flex: 3;
      -ms-flex: 3 1 33.3%;
          flex: 3 1 33.3%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
  -ms-flex-pack: distribute;
      justify-content: space-around;
  padding: 0em 0.5em;
}

.item {
  padding: 0.5em 0em;
}

<div class="container">
  <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
    <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
    <div class="subcontainer">
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
    <div class="item">Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit</div>
  </div>
</div>

It should look quite ok on real monitors and not inside this small sandbox space. For mobile viewports you can always implement corresponding styles.

An alternative to flexboxes can be CSS Grid - check it out. Also I would suggest making the height of blocks equal although in this case the problem is gone naturally :) As far as I know, that's all without resorting to super hacky, messy, JS-involving approaches. Maybe others will come up with better solutions though.

PS check out this css grid example. Seems to be similar to what you want to achieve, although the support for css grid is not full yet.


问:
Boost::Regex Segfault (I think)
I'm having an issue with some C++ code that I'm running. Basically, it works fine with most inputs, but with certain inputs it segfaults after my main function returns. This has been... puzzling. I stopped the run at the segfault to get the stack trace, and it returned this:

#0 malloc_consolidate() at /build/eglibc-oGUzwX/eglibc-2.19/malloc/malloc.c:4151
#1 _int_free() at /build/eglibc-oGUzwX/eglibc-2.19/malloc/malloc.c:4057
#2 boost::re_detail::mem_block_cache::~mem_block_cache()() at /usr/lib/x86_64-linux-gnu/libboost_regex.so.1.54.0
#3 __cxa_finalize() at /build/eglibc-oGUzwX/eglibc-2.19/stdlib/cxa_finalize.c:56
#4 ??() at /usr/lib/x86_64-linux-gnu/libboost_regex.so.1.54.0
#5 ??() at
#6 _dl_fini() at /build/eglibc-oGUzwX/eglibc-2.19/elf/dl-fini.c:252
```

<p>This made me think that I must be doing something wrong with boost regex, but I can't for the life of me figure it out. The way I'm using regex is that users can input a bunch of strings. Those strings could just be normal text, or they could be regular expressions. Because of this, I basically interact with all the inputs as regular expressions. But what if a user gave a string that was intended as plain text but had a character that could be interpreted differently as a regular expression? What I do is go through all plain text input strings and escape all those characters. </p>

<p>Here's the code that I'm working with. This is my main:</p>

```int
main(int argc, char * argv[])
{

    // Process input arguments
    // The desired input is numVertices (int), graph density (double between 0 and 1), halfLoss (double), total loss (double),
    // position expanse (double, m), velocity expanse (double, m/s)
    int num_vertices;
    double graph_density ;
    double half_loss;
    double total_loss;
    double position_expanse;
    double velocity_expanse;

    if (argc == 1)
    {
        num_vertices = 48;
        graph_density = 1;
        half_loss = 200000;
        total_loss = 400000;
        position_expanse = 400000;
        velocity_expanse = 10000;
    }
    else
    {
        if (argc != 7)
        {
            std::cerr << "Need 6 input arguments" << std::endl;
            return 1;
        }

        std::istringstream ss(argv[1]);
        num_vertices;
        if (!(ss >> num_vertices))
            std::cerr << "First input must be an integer" << std::endl;

        graph_density = read_double_input(argv[2]);
        half_loss = read_double_input(argv[3]);
        total_loss = read_double_input(argv[4]);
        position_expanse = read_double_input(argv[5]);
        velocity_expanse = read_double_input(argv[6]);
    }

    // Determine how many edges to create
    int num_edges = (int) ( (graph_density * num_vertices * (num_vertices - 1)) + 0.5 );

    // Create the edges
    int edges_created = 0;
    std::set<std::pair<int, int> > edge_set;
    while (edge_set.size() < num_edges)
    {

        // Pick a random start vertex and end vertex
        int start_vertex = rand() % num_vertices;
        int end_vertex = rand() % num_vertices;

        // Make sure the start and end vertices are not equal
        while (start_vertex == end_vertex)
        {
            end_vertex = rand() % num_vertices;
        }

        // Insert the new edge into our set of edges
        edge_set.insert(std::pair<int, int>(start_vertex, end_vertex));

    }

    // Create connection handler
    ConnectionHandler conn_handler;

    // Create lists for from and to vertices
    std::vector<std::string> from_list;
    std::vector<std::string> to_list;

    // Add connections to from and to lists
    for (std::set<std::pair<int, int> >::const_iterator edge_it = edge_set.begin(), end_it = edge_set.end(); edge_it != end_it; ++edge_it)
    {
        int start_vertex = edge_it->first;
        int end_vertex = edge_it->second;
        from_list.push_back("Radio" + int_to_string(start_vertex));
        to_list.push_back("Radio" + int_to_string(end_vertex));
    }

    // Read the list into the connection handler
    conn_handler.read_connection_list(true, from_list, to_list);
    return 0;

}
```

<p>This code has this ConnectionHandler object that I created. Here's the header for that:</p>

```#ifndef CLCSIM_CONNECTIONHANDLER_HPP_
#define CLCSIM_CONNECTIONHANDLER_HPP_

#include <models/network/NetworkTypes.hpp>
#include <generated/xsd/NetworkModelInterfaceConfig.hpp>

namespace clcsim
{

typedef std::map<std::string, std::set<std::string> > ConnectionFilter;

class ConnectionHandler
{

public:

    ConnectionHandler();
    ~ConnectionHandler();

    void read_connection_list(const bool is_white_list, const std::vector<std::string> &from_radios, const std::vector<std::string> &to_radios);

private:

    ConnectionFilter filter_;
    std::set<std::string> from_list_;
    std::set<std::string> to_list_;
    bool is_white_list_;

};

} // namespace clcsim

#endif // CLCSIM_CONNECTIONHANDLER_HPP_
```

<p>And here's the source:</p>

```#include <models/network/ConnectionHandler.hpp>
#include <oasis/framework/exceptions/ConfigurationException.h>
#include <boost/regex.hpp>

namespace clcsim
{

ConnectionHandler::
ConnectionHandler()
{
}

ConnectionHandler::
~ConnectionHandler()
{
    std::cout << "Destructing conn handler" << std::endl;
}

void
ConnectionHandler::
read_connection_list(
    const bool is_white_list,
    const std::vector<std::string> &from_radios,
    const std::vector<std::string> &to_radios)
{

    std::cout << "Reading the connection list" << std::endl;

    // Make sure the size of both the input vectors are the same
    std::size_t from_radio_size = from_radios.size();
    std::size_t to_radio_size = to_radios.size();
    if (from_radio_size != to_radio_size)
    {
        throw ofs::ConfigurationException("Error while initializing the "
                                          "Network model: "
                                          "Connections in from/to lists don't align"
                                         );
    }

    // Create a regular expression/replacement to find all characters in a non-regular expression
    // that would be interpreted as special characters in a regular expression. Replace them with
    // escape characters
    const boost::regex esc("[.$|()\\[\\]{}*+?\\\\]");
    const std::string rep("\\\\&");

    // Iterate through the specified connections
    for (int i = 0; i < from_radio_size; ++i)
    {

        std::string from_string = boost::regex_replace(from_radios[i], esc, rep, boost::match_default | boost::format_sed);
        std::string to_string = boost::regex_replace(to_radios[i], esc, rep, boost::match_default | boost::format_sed);
        //std::cout << "From " << from_string << " to " << to_string << std::endl;
        filter_[from_string].insert(to_string);
        //filter_[from_radios.at(i)].insert(to_radios.at(i));
    }

    std::cout << "Got here" << std::endl;

}

} // namespace clcsim
```

Sorry for so much code.

I saw some similar threads related to segfaults with boost::regex. In those examples, the users had really simple code that just created a regex and matched it and ran into an error. It turned out the issue was related to the Boost versioning. I tried to see if I could replicate those sorts of errors, but those simple examples worked just fine for me. So... I'm pretty stumped. I'd really appreciate any help!

答: For the sake of removing this from the "Unanswered" list, I'm going to post the answer that was provided in the comments instead of here. The OP determined that the suggestion that Boost linked against eglibc was indeed conflicting with the rest of the code linked against glibc. As such, the OP found that upgrading his OS so that eglibc linked libraries were no longer in use fixed the problem.</p>

Title: Boost::Regex Segfault (I think)

Body:
I'm having an issue with some C++ code that I'm running. Basically, it works fine with most inputs, but with certain inputs it segfaults after my main function returns. This has been... puzzling. I stopped the run at the segfault to get the stack trace, and it returned this:

#0 malloc_consolidate() at /build/eglibc-oGUzwX/eglibc-2.19/malloc/malloc.c:4151
#1 _int_free() at /build/eglibc-oGUzwX/eglibc-2.19/malloc/malloc.c:4057
#2 boost::re_detail::mem_block_cache::~mem_block_cache()() at /usr/lib/x86_64-linux-gnu/libboost_regex.so.1.54.0
#3 __cxa_finalize() at /build/eglibc-oGUzwX/eglibc-2.19/stdlib/cxa_finalize.c:56
#4 ??() at /usr/lib/x86_64-linux-gnu/libboost_regex.so.1.54.0
#5 ??() at
#6 _dl_fini() at /build/eglibc-oGUzwX/eglibc-2.19/elf/dl-fini.c:252

This made me think that I must be doing something wrong with boost regex, but I can't for the life of me figure it out. The way I'm using regex is that users can input a bunch of strings. Those strings could just be normal text, or they could be regular expressions. Because of this, I basically interact with all the inputs as regular expressions. But what if a user gave a string that was intended as plain text but had a character that could be interpreted differently as a regular expression? What I do is go through all plain text input strings and escape all those characters.

Here's the code that I'm working with. This is my main:

int
main(int argc, char * argv[])
{

    // Process input arguments
    // The desired input is numVertices (int), graph density (double between 0 and 1), halfLoss (double), total loss (double),
    // position expanse (double, m), velocity expanse (double, m/s)
    int num_vertices;
    double graph_density ;
    double half_loss;
    double total_loss;
    double position_expanse;
    double velocity_expanse;

    if (argc == 1)
    {
        num_vertices = 48;
        graph_density = 1;
        half_loss = 200000;
        total_loss = 400000;
        position_expanse = 400000;
        velocity_expanse = 10000;
    }
    else
    {
        if (argc != 7)
        {
            std::cerr << "Need 6 input arguments" << std::endl;
            return 1;
        }

        std::istringstream ss(argv[1]);
        num_vertices;
        if (!(ss >> num_vertices))
            std::cerr << "First input must be an integer" << std::endl;

        graph_density = read_double_input(argv[2]);
        half_loss = read_double_input(argv[3]);
        total_loss = read_double_input(argv[4]);
        position_expanse = read_double_input(argv[5]);
        velocity_expanse = read_double_input(argv[6]);
    }

    // Determine how many edges to create
    int num_edges = (int) ( (graph_density * num_vertices * (num_vertices - 1)) + 0.5 );

    // Create the edges
    int edges_created = 0;
    std::set<std::pair<int, int> > edge_set;
    while (edge_set.size() < num_edges)
    {

        // Pick a random start vertex and end vertex
        int start_vertex = rand() % num_vertices;
        int end_vertex = rand() % num_vertices;

        // Make sure the start and end vertices are not equal
        while (start_vertex == end_vertex)
        {
            end_vertex = rand() % num_vertices;
        }

        // Insert the new edge into our set of edges
        edge_set.insert(std::pair<int, int>(start_vertex, end_vertex));

    }

    // Create connection handler
    ConnectionHandler conn_handler;

    // Create lists for from and to vertices
    std::vector<std::string> from_list;
    std::vector<std::string> to_list;

    // Add connections to from and to lists
    for (std::set<std::pair<int, int> >::const_iterator edge_it = edge_set.begin(), end_it = edge_set.end(); edge_it != end_it; ++edge_it)
    {
        int start_vertex = edge_it->first;
        int end_vertex = edge_it->second;
        from_list.push_back("Radio" + int_to_string(start_vertex));
        to_list.push_back("Radio" + int_to_string(end_vertex));
    }

    // Read the list into the connection handler
    conn_handler.read_connection_list(true, from_list, to_list);
    return 0;

}

This code has this ConnectionHandler object that I created. Here's the header for that:

#ifndef CLCSIM_CONNECTIONHANDLER_HPP_
#define CLCSIM_CONNECTIONHANDLER_HPP_

#include <models/network/NetworkTypes.hpp>
#include <generated/xsd/NetworkModelInterfaceConfig.hpp>

namespace clcsim
{

typedef std::map<std::string, std::set<std::string> > ConnectionFilter;

class ConnectionHandler
{

public:

    ConnectionHandler();
    ~ConnectionHandler();

    void read_connection_list(const bool is_white_list, const std::vector<std::string> &from_radios, const std::vector<std::string> &to_radios);

private:

    ConnectionFilter filter_;
    std::set<std::string> from_list_;
    std::set<std::string> to_list_;
    bool is_white_list_;

};

} // namespace clcsim

#endif // CLCSIM_CONNECTIONHANDLER_HPP_

And here's the source:

#include <models/network/ConnectionHandler.hpp>
#include <oasis/framework/exceptions/ConfigurationException.h>
#include <boost/regex.hpp>

namespace clcsim
{

ConnectionHandler::
ConnectionHandler()
{
}

ConnectionHandler::
~ConnectionHandler()
{
    std::cout << "Destructing conn handler" << std::endl;
}

void
ConnectionHandler::
read_connection_list(
    const bool is_white_list,
    const std::vector<std::string> &from_radios,
    const std::vector<std::string> &to_radios)
{

    std::cout << "Reading the connection list" << std::endl;

    // Make sure the size of both the input vectors are the same
    std::size_t from_radio_size = from_radios.size();
    std::size_t to_radio_size = to_radios.size();
    if (from_radio_size != to_radio_size)
    {
        throw ofs::ConfigurationException("Error while initializing the "
                                          "Network model: "
                                          "Connections in from/to lists don't align"
                                         );
    }

    // Create a regular expression/replacement to find all characters in a non-regular expression
    // that would be interpreted as special characters in a regular expression. Replace them with
    // escape characters
    const boost::regex esc("[.$|()\\[\\]{}*+?\\\\]");
    const std::string rep("\\\\&");

    // Iterate through the specified connections
    for (int i = 0; i < from_radio_size; ++i)
    {

        std::string from_string = boost::regex_replace(from_radios[i], esc, rep, boost::match_default | boost::format_sed);
        std::string to_string = boost::regex_replace(to_radios[i], esc, rep, boost::match_default | boost::format_sed);
        //std::cout << "From " << from_string << " to " << to_string << std::endl;
        filter_[from_string].insert(to_string);
        //filter_[from_radios.at(i)].insert(to_radios.at(i));
    }

    std::cout << "Got here" << std::endl;

}

} // namespace clcsim

Sorry for so much code.

I saw some similar threads related to segfaults with boost::regex. In those examples, the users had really simple code that just created a regex and matched it and ran into an error. It turned out the issue was related to the Boost versioning. I tried to see if I could replicate those sorts of errors, but those simple examples worked just fine for me. So... I'm pretty stumped. I'd really appreciate any help!