问:
How to return a custom object from a Spring Data JPA GROUP BY query
I'm developing a Spring Boot application with Spring Data JPA. I'm using a custom JPQL query to group by some field and get the count. Following is my repository method.

```<code>@Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")
public List<?> findSurveyCount();
</code>```

It's working and result is obtained as follows:

```<code>[
  [1, "a1"],
  [2, "a2"]
]
</code>```

I would like to get something like this:

```<code>[
  { "cnt":1, "answer":"a1" },
  { "cnt":2, "answer":"a2" }
]
</code>```

How can I achieve this?

答:
define a custom pojo class say sureveyQueryAnalytics and store the query returned value in your custom pojo class</p>

```<code>@Query(value = "select new com.xxx.xxx.class.SureveyQueryAnalytics(s.answer, count(sv)) from Survey s group by s.answer")
List<SureveyQueryAnalytics> calculateSurveyCount();
</code>```

Body:
I'm developing a Spring Boot application with Spring Data JPA. I'm using a custom JPQL query to group by some field and get the count. Following is my repository method.

@Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")
public List<?> findSurveyCount();

It's working and result is obtained as follows:

[
  [1, "a1"],
  [2, "a2"]
]

I would like to get something like this:

[
  { "cnt":1, "answer":"a1" },
  { "cnt":2, "answer":"a2" }
]

How can I achieve this?

Body:
define a custom pojo class say sureveyQueryAnalytics and store the query returned value in your custom pojo class

@Query(value = "select new com.xxx.xxx.class.SureveyQueryAnalytics(s.answer, count(sv)) from Survey s group by s.answer")
List<SureveyQueryAnalytics> calculateSurveyCount();


来源: stackexchange

问:
how to group identical instances in r into one and at the same time, generate frequency and average stats?
I'm at the last stage of cleaning/organizing data and would appreciate suggestions for this step. I'm new to R and don't understand fully how dataframes or other data types work. (I'm trying to learn but have a project due so need a quick solution). I've imported the data from a CSV file.

I want to group instances with the same (date, ID1, ID2, ID3). I want the average of all stats in the output and also a new column with the number of instances grouped.

Note: ID3 contains . I'd like to rename these to "na" before grouping
I've tried solutions

```<code>tdata$ID3[is.na(tdata$ID3)] <- "NA"
tdata[["ID3"]][is.na(tdata[["ID3"]])] <- "NA"
</code>```

But get Error:

```<code>In `[<-.factor`(`*tmp*`, is.na(tdata[["ID3"]]), value = c(3L, 3L,  :
  invalid factor level, NA generated
</code>```

The data is:

```<code>      date     ID1     ID2     ID3 stat1 stat2 stat.3
1 12-03-07  abc123  wxy456  pqr123    10    20     30
2 12-03-07  abc123  wxy456  pqr123    20    40     60
3 10-04-07  bcd456  wxy456  hgf356    10    20     40
4 12-03-07  abc123  wxy456  pqr123    30    60     90
5  5-09-07  spa234  int345   <NA>     40    50     70
</code>```

Desired Output

```<code>date      ID1,     ID2,   ID3,   n, stat1, stat2, stat 3
12-03-07 abc123, wxy456, pqr457, 3,   20,   40, 60
10-04-07 bcd456, wxy456, hgf356, 1,   10,   20, 40
05-09-07 spa234, int345, big234, 1 ,  40,   50, 70
</code>```

I tried this solution: How to merge multiple data.frames and sum and average columns at the same time in R

But I was not successful merging the columns which have to be grouped and tested for similarity.

```<code>DF <- merge(tdata$date, tdata$ID1, tdata$ID2, tdata$ID3, by = "Name", all = T)

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
</code>```

Finally, to generate the n column. Perhaps insert a rows of 1s and use the sum of the column while summarizing?

答:
While I find the dplyr solution proposed by akrun very intuitive to use, there is also a nice data.table solution:

Similarly as akrun, I assume that the NA value has been converted to "big234" to get the desired result.

```<code>library(data.table)
# convert data.frame to data.table
data <- data.table(df1)

# return the desired output
data[, c(.N, lapply(.SD, mean)),
     by = list(date, ID1,ID2, ID3)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm at the last stage of cleaning/organizing data and would appreciate suggestions for this step. I'm new to R and don't understand fully how dataframes or other data types work. (I'm trying to learn but have a project due so need a quick solution). I've imported the data from a CSV file.

I want to group instances with the same (date, ID1, ID2, ID3). I want the average of all stats in the output and also a new column with the number of instances grouped.

Note: ID3 contains . I'd like to rename these to "na" before grouping
I've tried solutions

tdata$ID3[is.na(tdata$ID3)] <- "NA"
tdata[["ID3"]][is.na(tdata[["ID3"]])] <- "NA"

But get Error:

In `[<-.factor`(`*tmp*`, is.na(tdata[["ID3"]]), value = c(3L, 3L,  :
  invalid factor level, NA generated

The data is:

      date     ID1     ID2     ID3 stat1 stat2 stat.3
1 12-03-07  abc123  wxy456  pqr123    10    20     30
2 12-03-07  abc123  wxy456  pqr123    20    40     60
3 10-04-07  bcd456  wxy456  hgf356    10    20     40
4 12-03-07  abc123  wxy456  pqr123    30    60     90
5  5-09-07  spa234  int345   <NA>     40    50     70

Desired Output

date      ID1,     ID2,   ID3,   n, stat1, stat2, stat 3
12-03-07 abc123, wxy456, pqr457, 3,   20,   40, 60
10-04-07 bcd456, wxy456, hgf356, 1,   10,   20, 40
05-09-07 spa234, int345, big234, 1 ,  40,   50, 70

I tried this solution: How to merge multiple data.frames and sum and average columns at the same time in R

But I was not successful merging the columns which have to be grouped and tested for similarity.

DF <- merge(tdata$date, tdata$ID1, tdata$ID2, tdata$ID3, by = "Name", all = T)

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns

Finally, to generate the n column. Perhaps insert a rows of 1s and use the sum of the column while summarizing?

Body:
While I find the dplyr solution proposed by akrun very intuitive to use, there is also a nice data.table solution:

Similarly as akrun, I assume that the NA value has been converted to "big234" to get the desired result.

library(data.table)
# convert data.frame to data.table
data <- data.table(df1)

# return the desired output
data[, c(.N, lapply(.SD, mean)),
     by = list(date, ID1,ID2, ID3)]


问:
Vertical Centering a DIV within an unknown height DIV
I currently have this HTML:

```<code><div id:root>
  <div id:contents>
    <h3>I am the one that need to be vertical centered.</h3>
    <p>Lorem300..............</p>
  </div>
  <img scr:"somewhere.jpg"></img>
</div>
</code>```

And the current SASS:

```<code>img
  width: 100%
  height: inherit
</code>```

The problem I want to solve is I want the 'root' DIV to have the exactly same size as the img. In this case the img width is set to 100%, which means it always take 100% width of the viewport. Is there a way that I can vertically center the 'contents' DIV to the 'root' DIV? Thank you very much. I spent the whole day and still nothing found. Even when I use:

```<code>#contents
  top: 50%
  transform: translateY(-50%)
</code>```

The 'contents' div take the height of the body, not the 'root' div. :(

Is there a way that I can solve this? Thank you!

答:
You can use css flexbox to help you center the #contents

Simply set #rootwith these properties

```<code>#root {
  position: relative; /* needed to position img absolutely with div */
  display: flex; /* make this element flexbox */
  justify-content: center; /* horizontally center children */
  align-items: center; /* vertically center children */
}
</code>```

Then give #contents and img these properties

```<code>#contents {
  position: relative; /* needed to set z-index */
  z-index: 2; /* make #contents above img */
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
}
</code>```

See this fiddle for example. And you can read more about css flexbox from the link above.

Hope this helps,

Body:
I currently have this HTML:

I am the one that need to be vertical centered.

Lorem300..............

And the current SASS:

img
  width: 100%
  height: inherit

The problem I want to solve is I want the 'root' DIV to have the exactly same size as the img. In this case the img width is set to 100%, which means it always take 100% width of the viewport. Is there a way that I can vertically center the 'contents' DIV to the 'root' DIV? Thank you very much. I spent the whole day and still nothing found. Even when I use:

#contents
  top: 50%
  transform: translateY(-50%)

The 'contents' div take the height of the body, not the 'root' div. :(

Is there a way that I can solve this? Thank you!

Body:
You can use css flexbox to help you center the #contents

Simply set #rootwith these properties

#root {
  position: relative; /* needed to position img absolutely with div */
  display: flex; /* make this element flexbox */
  justify-content: center; /* horizontally center children */
  align-items: center; /* vertically center children */
}

Then give #contents and img these properties

#contents {
  position: relative; /* needed to set z-index */
  z-index: 2; /* make #contents above img */
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
}

See this fiddle for example. And you can read more about css flexbox from the link above.

Hope this helps,


问:
How to translate this matlab code to python(numpy)
Matlab code :

```<code> Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));
</code>```

The code I translate :

```<code> Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))
</code>```

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.

答: I think the problem is in indexing, cause MATLAB indexing starts from 1 but Python's starts from 0. Try to decrease indx and j by 1 before running the expression. If j is an index in loop, just start loop from 0 not 1.</p>

Body:
Matlab code :

 Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));

The code I translate :

 Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.


问:
Java convert a HEX String to a BigInt
Hi am trying to convert a hex string such as String hexStr = "1b0ee1e3"; to a bigInt,
ideally i'd like to convert hexStr to a bigint in its decimal form,

I can convert a string to a bigInt w/o issues but when the string contains hex values
i run into problems

答:
Have you tried:

```<code>BigInteger bigInt = new BigInteger(hexString, 16);
</code>```

For example:

```<code>import java.math.*;

public class Test {
    public static void main(String[] args) {
        String hexStr = "1b0ee1e3";
        BigInteger bigInt = new BigInteger(hexStr, 16);
        System.out.println(bigInt); // Prints 453960163
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java convert a HEX String to a BigInt

Body:
Have you tried:

BigInteger bigInt = new BigInteger(hexString, 16);

For example:

import java.math.*;

public class Test {
    public static void main(String[] args) {
        String hexStr = "1b0ee1e3";
        BigInteger bigInt = new BigInteger(hexStr, 16);
        System.out.println(bigInt); // Prints 453960163
    }
}


问:
Using toCharArray to check if String has any non-digits
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

```<code>public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}
</code>```

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

答:
You can use String#matches(String) where the parameter is a regular expression, \D matches any non-digit. Like,

```<code>public void setMobile(String mobile) {
    if (!mobile.matches("\\D")) {
        this.mobile = mobile;
    }
}
</code>```

If you really want to do it with toCharArray() you might use a for-each loop and short circuit return on a non-digit. Like

```<code>public void setMobile(String mobile) {
    for (char ch : mobile.toCharArray()) {
        if (!Character.isDigit(ch)) {
            return;
        }
    }
    this.mobile = mobile;
}
</code>```

Or, using a Pattern and Matcher; and only setting mobile if all the characters are digits. Like,

```<code>public void setMobile(String mobile) {
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(mobile);
    if (m.matches()) {
        this.mobile = mobile;
    }
}
</code>```

Body:
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

Body:
You can use String#matches(String) where the parameter is a regular expression, \D matches any non-digit. Like,

public void setMobile(String mobile) {
    if (!mobile.matches("\\D")) {
        this.mobile = mobile;
    }
}

If you really want to do it with toCharArray() you might use a for-each loop and short circuit return on a non-digit. Like

public void setMobile(String mobile) {
    for (char ch : mobile.toCharArray()) {
        if (!Character.isDigit(ch)) {
            return;
        }
    }
    this.mobile = mobile;
}

Or, using a Pattern and Matcher; and only setting mobile if all the characters are digits. Like,

public void setMobile(String mobile) {
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(mobile);
    if (m.matches()) {
        this.mobile = mobile;
    }
}


问:
React components does not display
```<code>class App extends Component {
constructor(props){
super(props);
this.state={ recipes :{} }
 this.addRecipe=this.addRecipe.bind(this);
}

addRecipe (recipe) {//add new fish to recipes
var timestamp = (new Date()).getTime();
this.state.recipes['recipe'+timestamp] = recipe;
this.setState({ recipes : this.state.recipes });
}
componentWillMount(){
  this.setState({
  recipes : require('./sample-recipes')
});
}
render() {
return (
  <div className="App">
  <h2>Welcome to the Recipe Book</h2>
   <button> {/*onClick, how to call Addrecipe here.*/ }
    Add Recipe
   </button>
   <AddRecipe addRecipe={this.addRecipe}/>
   <div>{this.state.recipes}</div>
  </div>
  );
 }
 }

var AddRecipe = React.createClass({
create : function(event) {
event.preventDefault();
var recipe = {
  name : this.refs.name.value,
  ingredients:this.refs.ingredients.value
}

this.props.addRecipe(recipe);
this.refs.form.reset();
},
render : function() {
return (
  <form className="add" ref="form" onSubmit={this.create}>
  <span> Recipe <input type="text" ref="name" placeholder="Recipe Name"/>

 </span>
   <span>Ingredients <input type="text" ref="ingredients"

 placeholder="ingredients" /></span>
    <button type="submit">Add</button>
    <button type="submit">Cancel</button>
  </form>
  )
  }
  });
  export default App;
</code>```

I am building this recipe book in reactjs (i have started learning react).

1) How do I display all the recipes from file sample-recipes.js on page load. Why it doesn't display all the recipes in the file on writing {this.state.recipes}.

2) How should I call AddRecipe component on click of the button (Add    Recipe).

答:
1) Recipes should be an array which you have to map and return html or another component for every object inside. First you have to change current state structure to something like this:

```<code>componentWillMount(){
  this.setState({
    recipes : [{
      //include timestamp here, I created example recipe to get it to work
      name : 'Tomato',
      ingredients:'Just Tomato'
    }]
  });
}
</code>```

Then in addRecipe function you have to add next recipe to an array and you CAN NOT use this.state.sth outside constructor:

```<code>addRecipe (recipe) {
  this.setState({ recipes: [...this.state.recipes, recipe]});
}
</code>```

Of course, you can map an object as you tried, but it's easier to work with arrays.

Now you can display recipes this way:

```<code><ul>
  {this.state.recipes.map(recipe => {
    return <li>{recipe.name}</li>
  })}
</ul>
</code>```

2) You need another state variable, something like displayAddRecipeForm. Then bind a function which changes the state to the opposite:

```<code><button onClick={() => {this.setState({ displayAddRecipeForm: !this.state.displayAddRecipeForm })}}>Add Recipe</button>
</code>```

Pass the state to AddRecipe component as a property and set the className basing on props:

```<code><form className={this.props.display ? '' : 'hide'}  ref="form" onSubmit={this.create}>
</code>```

Title: React components does not display

Body:
class App extends Component {
constructor(props){
super(props);
this.state={ recipes :{} }
 this.addRecipe=this.addRecipe.bind(this);
}

addRecipe (recipe) {//add new fish to recipes
var timestamp = (new Date()).getTime();
this.state.recipes['recipe'+timestamp] = recipe;
this.setState({ recipes : this.state.recipes });
}
componentWillMount(){
  this.setState({
  recipes : require('./sample-recipes')
});
}
render() {
return (

Welcome to the Recipe Book

   <button> {/*onClick, how to call Addrecipe here.*/ }
    Add Recipe
   </button>
   <AddRecipe addRecipe={this.addRecipe}/>

{this.state.recipes}

  );
 }
 }

var AddRecipe = React.createClass({
create : function(event) {
event.preventDefault();
var recipe = {
  name : this.refs.name.value,
  ingredients:this.refs.ingredients.value
}

this.props.addRecipe(recipe);
this.refs.form.reset();
},
render : function() {
return (
  <form className="add" ref="form" onSubmit={this.create}>
   Recipe <input type="text" ref="name" placeholder="Recipe Name"/>

   Ingredients <input type="text" ref="ingredients"

 placeholder="ingredients" />
    <button type="submit">Add</button>
    <button type="submit">Cancel</button>
  </form>
  )
  }
  });
  export default App;

I am building this recipe book in reactjs (i have started learning react).

1) How do I display all the recipes from file sample-recipes.js on page load. Why it doesn't display all the recipes in the file on writing {this.state.recipes}.

2) How should I call AddRecipe component on click of the button (Add    Recipe).

Body:
1) Recipes should be an array which you have to map and return html or another component for every object inside. First you have to change current state structure to something like this:

componentWillMount(){
  this.setState({
    recipes : [{
      //include timestamp here, I created example recipe to get it to work
      name : 'Tomato',
      ingredients:'Just Tomato'
    }]
  });
}

Then in addRecipe function you have to add next recipe to an array and you CAN NOT use this.state.sth outside constructor:

addRecipe (recipe) {
  this.setState({ recipes: [...this.state.recipes, recipe]});
}

Of course, you can map an object as you tried, but it's easier to work with arrays.

Now you can display recipes this way:

<ul>
  {this.state.recipes.map(recipe => {
    return <li>{recipe.name}</li>
  })}
</ul>

2) You need another state variable, something like displayAddRecipeForm. Then bind a function which changes the state to the opposite:

<button onClick={() => {this.setState({ displayAddRecipeForm: !this.state.displayAddRecipeForm })}}>Add Recipe</button>

Pass the state to AddRecipe component as a property and set the className basing on props:

<form className={this.props.display ? '' : 'hide'}  ref="form" onSubmit={this.create}>


问:
Python - C embedded Segmentation fault
I am facing a problem similar to the Py_initialize / Py_Finalize not working twice with numpy .. The basic coding in C:

```<code>Py_Initialize();
import_array();
//Call a python function which imports numpy as a module
//Py_Finalize()
</code>```

The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module. If I remove numpy, it works fine.

As a temporary work around I tried not to use Py_Finalize(), but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ]. And I tried but did not understand the suggestion in that link I posted. Can someone please suggest the best way to finalize the call while having imports such as numpy.

Thanks
santhosh.

答:
I recently faced a very similar issue and developed a workaround that works for my purposes, so I thought I would write it here in the hope it might help others.

The problem

I work with some postprocessing pipeline for which I can write a own functor to work on some data passing through the pipeline and I wanted to be able to use Python scripts for some of the operations.

The problem is that the only thing I can control is the functor itself, which gets instantiated and destroyed at times beyond my control. I furthermore have the problem that even if I do not call Py_Finalize the pipeline sometimes crashes once I pass another dataset through the pipeline.

The solution in a Nutshell

For those who don't want to read the whole story and get straight to the point, here's the gist of my solution:

The main idea behind my workaround is not to link against the Python library, but instead load it dynamically using dlopen and then get all the addresses of the required Python functions using dlsym. Once that's done, one can call Py_Initialize() followed by whatever you want to do with Python functions followed by a call to Py_Finalize() once you're done. Then, one can simply unload the Python library. The next time you need to use Python functions, simply repeat the steps above and Bob's your uncle.

However, if you are importing NumPy at any point between Py_Initialize and Py_Finalize, you will also need to look for all the currently loaded libraries in your program and manually unload those using dlclose.

Detailed workaround

Loading instead of linking Python

The main idea as I mentioned above is not to link against the Python library. Instead, what we will do is load the Python library dynamically using dlopen():

    #include
    ...
    void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);

The code above loads the Python shared library and returns a handle to it (the return type is an obscure pointer type, thus the void*). The second argument (RTLD_NOW | RTLD_GLOBAL) is there to make sure that the symbols are properly imported into the current application's scope.

Once we have a pointer to the handle of the loaded library, we can search that library for the functions it exports using the dlsym function:

#include <dlfcn.h>
...
// Typedef named 'void_func_t' which holds a pointer to a function with
// no arguments with no return type
typedef void (*void_func_t)(void);
void_func_t MyPy_Initialize = dlsym(pHandle, "Py_Initialize");
```

<p>The <code>dlsym</code> function takes two parameters: a pointer to the handle of the library that we obtained previously and the name of the function we are looking for (in this case, <code>Py_Initialize</code>). Once we have the address of the function we want, we can create a function pointer and initialize it to that address. To actually call the <code>Py_Initialize</code> function, one would then simply write:</p>

<pre class="lang-cpp prettyprint-override"><code>MyPy_Initialize();
</code>```

For all the other functions provided by the Python C-API, one can just add calls to dlsym and initialize function pointers to its return value and then use those function pointers instead of the Python functions. One simply has to know the parameter and return value of the Python function in order to create the correct type of function pointer.

Once we are finished with the Python functions and call Py_Finalize using a procedure similar to the one for Py_Initialize one can unload the Python dynamic library in the following way:

dlclose(pHandle);
pHandle = NULL;
```

<h2>Manually unloading NumPy libraries</h2>

<p>Unfortunately, this does not solve the segmentation fault problems that occur when importing NumPy. The problems comes from the fact that NumPy also loads some libraries using <code>dlopen</code> (or something equivalent) and those do not get unloaded them when you call <code>Py_Finalize</code>. Indeed, if you list all the loaded libraries within your program, you will notice that after closing the Python environment with <code>Py_Finalize</code>, followed by a call to <code>dlclose</code>, some NumPy libraries will remain loaded in memory.</p>

<p>The second part of the solution requires to list all the Python libraries that remain in memory after the call <code>dlclose(pHandle);</code>. Then, for each of those libraries, grab a handle to them and then call <code>dlclose</code>on them. After that, they should get unloaded automatically by the operating system. </p>

<p>Fortunately, there are functions under both Windows and Linux (sorry MacOS, couldn't find anything that would work in your case...):
 - Linux: <code>dl_iterate_phdr</code>
 - Windows: <code>EnumProcessModules</code> in conjunction with <code>OpenProcess</code> and <code>GetModuleFileNameEx</code></p>

<h2>Linux</h2>

<p>This is rather straight forward once you read the documentation about <code>dl_iterate_phdr</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <link.h>
#include <string>
#include <vector>

// global variables are evil!!! but this is just for demonstration purposes...
std::vector<std::string> loaded_libraries;

// callback function that gets called for every loaded libraries that
// dl_iterate_phdr finds
int dl_list_callback(struct dl_phdr_info *info, size_t, void *)
{
    loaded_libraries.push_back(info->dlpi_name);
    return 0;
}

int main()
{
    ...
    loaded_libraries.clear();
    dl_iterate_phdr(dl_list_callback, NULL);
    // loaded_libraries now contains a list of all dynamic libraries loaded
    // in your program
    ....
}
</code>```

Basically, the function dl_iterate_phdr cycles through all the loaded libraries (in the reverse order they were loaded) until either the callback returns something other than 0 or it reaches the end of the list. To save the list, the callback simply adds each element to a global std::vector (one should obviously avoid global variables and use a class for example).

Windows

Under Windows, things get a little more complicated, but still manageable:

#include <windows.h>
#include <psapi.h>

std::vector<std::string> list_loaded_libraries()
{
     std::vector<std::string> m_asDllList;
     HANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION
                                 | PROCESS_VM_READ,
                                 FALSE, GetCurrentProcessId()));
     if (hProcess) {
         HMODULE hMods[1024];
         DWORD cbNeeded;

         if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
             const DWORD SIZE(cbNeeded / sizeof(HMODULE));
             for (DWORD i(0); i < SIZE; ++i) {
                TCHAR szModName[MAX_PATH];

                // Get the full path to the module file.
                if (GetModuleFileNameEx(hProcess,
                                        hMods[i],
                                        szModName,
                                        sizeof(szModName) / sizeof(TCHAR))) {
#ifdef UNICODE
                    std::wstring wStr(szModName);
                    std::string tModuleName(wStr.begin(), wStr.end());
#else
                    std::string tModuleName(szModName);
#endif /* UNICODE */
                    if (tModuleName.substr(tModuleName.size()-3) == "dll") {
                        m_asDllList.push_back(tModuleName);
                    }
                 }
             }
         }
         CloseHandle(hProcess);
     }
     return m_asDllList;
}
```

<p>The code in this case is slightly longer than for the Linux case, but the main idea is the same: list all the loaded libraries and save them into a <code>std::vector</code>. Don't forget to also link your program to the <code>Psapi.lib</code>!</p>

<h2>Manual unloading</h2>

<p>Now that we can list all the loaded libraries, all you need to do is find among those the ones that come from loading NumPy, grab a handle to them and then call <code>dlclose</code> on that handle. The code below will work on both Windows and Linux, provided that you use the dlfcn-win32 library.</p>

<pre class="lang-cpp prettyprint-override"><code>#ifdef WIN32
#  include <windows.h>
#  include <psapi.h>
#  include "dlfcn_win32.h"
#else
#  include <dlfcn.h>
#  include <link.h> // for dl_iterate_phdr
#endif /* WIN32 */

#include <string>
#include <vector>

// Function that list all loaded libraries (not implemented here)
std::vector<std::string> list_loaded_libraries();

int main()
{
    // do some preprocessing stuff...

    // store the list of loaded libraries now
    // any libraries that get added to the list from now on must be Python
    // libraries
    std::vector<std::string> loaded_libraries(list_loaded_libraries());
    std::size_t start_idx(loaded_libraries.size());

    void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);

    // Not implemented here: get the addresses of the Python function you need

    MyPy_Initialize(); // Needs to be defined somewhere above!

    MyPyRun_SimpleString("import numpy"); // Needs to be defined somewhere above!

    // ...

    MyPyFinalize(); // Needs to be defined somewhere above!

    // Now list the loaded libraries again and start manually unloading them
    // starting from the end
    loaded_libraries = list_loaded_libraries();

    // NB: this below assumes that start_idx != 0, which should always hold true
    for(std::size_t i(loaded_libraries.size()-1) ; i >= start_idx ; --i) {
        void* pHandle = dlopen(loaded_libraries[i].c_str(),
#ifdef WIN32
                               RTLD_NOW // no support for RTLD_NOLOAD
#else
                               RTLD_NOW|RTLD_NOLOAD
#endif /* WIN32 */
                    );
        if (pHandle) {
            const unsigned int Nmax(50); // Avoid getting stuck in an infinite loop
            for (unsigned int j(0) ; j < Nmax && !dlclose(pHandle) ; ++j);
        }
    }
}
</code>```

Final words

The examples shown here capture the basic ideas behind my solution, but can certainly be improved to avoid global variables and facilitate ease of use (for example, I wrote a singleton class that handles the automatic initialization of all the function pointers after loading the Python library).

I hope this can be useful to someone in the future.

References

dl_iterate_phdr: https://linux.die.net/man/3/dl_iterate_phdr

PsAPI library: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684894(v=vs.85).aspx

OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx

EnumProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx

GetModuleFileNameEx: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683198(v=vs.85).aspx

dlfcn-win32 library: library: https://github.com/dlfcn-win32/dlfcn-win32

Title: Python - C embedded Segmentation fault

Body:
I am facing a problem similar to the Py_initialize / Py_Finalize not working twice with numpy .. The basic coding in C:

Py_Initialize();
import_array();
//Call a python function which imports numpy as a module
//Py_Finalize()

The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module. If I remove numpy, it works fine.

As a temporary work around I tried not to use Py_Finalize(), but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ]. And I tried but did not understand the suggestion in that link I posted. Can someone please suggest the best way to finalize the call while having imports such as numpy.

Thanks
santhosh.

Body:
I recently faced a very similar issue and developed a workaround that works for my purposes, so I thought I would write it here in the hope it might help others.

The problem

I work with some postprocessing pipeline for which I can write a own functor to work on some data passing through the pipeline and I wanted to be able to use Python scripts for some of the operations.

The problem is that the only thing I can control is the functor itself, which gets instantiated and destroyed at times beyond my control. I furthermore have the problem that even if I do not call Py_Finalize the pipeline sometimes crashes once I pass another dataset through the pipeline.

The solution in a Nutshell

For those who don't want to read the whole story and get straight to the point, here's the gist of my solution:

The main idea behind my workaround is not to link against the Python library, but instead load it dynamically using dlopen and then get all the addresses of the required Python functions using dlsym. Once that's done, one can call Py_Initialize() followed by whatever you want to do with Python functions followed by a call to Py_Finalize() once you're done. Then, one can simply unload the Python library. The next time you need to use Python functions, simply repeat the steps above and Bob's your uncle.

However, if you are importing NumPy at any point between Py_Initialize and Py_Finalize, you will also need to look for all the currently loaded libraries in your program and manually unload those using dlclose.

Detailed workaround

Loading instead of linking Python

The main idea as I mentioned above is not to link against the Python library. Instead, what we will do is load the Python library dynamically using dlopen():

    #include
    ...
    void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);

The code above loads the Python shared library and returns a handle to it (the return type is an obscure pointer type, thus the void*). The second argument (RTLD_NOW | RTLD_GLOBAL) is there to make sure that the symbols are properly imported into the current application's scope.

Once we have a pointer to the handle of the loaded library, we can search that library for the functions it exports using the dlsym function:

#include <dlfcn.h>
...
// Typedef named 'void_func_t' which holds a pointer to a function with
// no arguments with no return type
typedef void (*void_func_t)(void);
void_func_t MyPy_Initialize = dlsym(pHandle, "Py_Initialize");

The dlsym function takes two parameters: a pointer to the handle of the library that we obtained previously and the name of the function we are looking for (in this case, Py_Initialize). Once we have the address of the function we want, we can create a function pointer and initialize it to that address. To actually call the Py_Initialize function, one would then simply write:

MyPy_Initialize();

For all the other functions provided by the Python C-API, one can just add calls to dlsym and initialize function pointers to its return value and then use those function pointers instead of the Python functions. One simply has to know the parameter and return value of the Python function in order to create the correct type of function pointer.

Once we are finished with the Python functions and call Py_Finalize using a procedure similar to the one for Py_Initialize one can unload the Python dynamic library in the following way:

dlclose(pHandle);
pHandle = NULL;

Manually unloading NumPy libraries

Unfortunately, this does not solve the segmentation fault problems that occur when importing NumPy. The problems comes from the fact that NumPy also loads some libraries using dlopen (or something equivalent) and those do not get unloaded them when you call Py_Finalize. Indeed, if you list all the loaded libraries within your program, you will notice that after closing the Python environment with Py_Finalize, followed by a call to dlclose, some NumPy libraries will remain loaded in memory.

The second part of the solution requires to list all the Python libraries that remain in memory after the call dlclose(pHandle);. Then, for each of those libraries, grab a handle to them and then call dlcloseon them. After that, they should get unloaded automatically by the operating system.

Fortunately, there are functions under both Windows and Linux (sorry MacOS, couldn't find anything that would work in your case...):
 - Linux: dl_iterate_phdr
 - Windows: EnumProcessModules in conjunction with OpenProcess and GetModuleFileNameEx

Linux

This is rather straight forward once you read the documentation about dl_iterate_phdr:

#include <link.h>
#include <string>
#include <vector>

// global variables are evil!!! but this is just for demonstration purposes...
std::vector<std::string> loaded_libraries;

// callback function that gets called for every loaded libraries that
// dl_iterate_phdr finds
int dl_list_callback(struct dl_phdr_info *info, size_t, void *)
{
    loaded_libraries.push_back(info->dlpi_name);
    return 0;
}

int main()
{
    ...
    loaded_libraries.clear();
    dl_iterate_phdr(dl_list_callback, NULL);
    // loaded_libraries now contains a list of all dynamic libraries loaded
    // in your program
    ....
}

Basically, the function dl_iterate_phdr cycles through all the loaded libraries (in the reverse order they were loaded) until either the callback returns something other than 0 or it reaches the end of the list. To save the list, the callback simply adds each element to a global std::vector (one should obviously avoid global variables and use a class for example).

Windows

Under Windows, things get a little more complicated, but still manageable:

#include <windows.h>
#include <psapi.h>

std::vector<std::string> list_loaded_libraries()
{
     std::vector<std::string> m_asDllList;
     HANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION
                                 | PROCESS_VM_READ,
                                 FALSE, GetCurrentProcessId()));
     if (hProcess) {
         HMODULE hMods[1024];
         DWORD cbNeeded;

         if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
             const DWORD SIZE(cbNeeded / sizeof(HMODULE));
             for (DWORD i(0); i < SIZE; ++i) {
                TCHAR szModName[MAX_PATH];

                // Get the full path to the module file.
                if (GetModuleFileNameEx(hProcess,
                                        hMods[i],
                                        szModName,
                                        sizeof(szModName) / sizeof(TCHAR))) {
#ifdef UNICODE
                    std::wstring wStr(szModName);
                    std::string tModuleName(wStr.begin(), wStr.end());
#else
                    std::string tModuleName(szModName);
#endif /* UNICODE */
                    if (tModuleName.substr(tModuleName.size()-3) == "dll") {
                        m_asDllList.push_back(tModuleName);
                    }
                 }
             }
         }
         CloseHandle(hProcess);
     }
     return m_asDllList;
}

The code in this case is slightly longer than for the Linux case, but the main idea is the same: list all the loaded libraries and save them into a std::vector. Don't forget to also link your program to the Psapi.lib!

Manual unloading

Now that we can list all the loaded libraries, all you need to do is find among those the ones that come from loading NumPy, grab a handle to them and then call dlclose on that handle. The code below will work on both Windows and Linux, provided that you use the dlfcn-win32 library.

#ifdef WIN32
#  include <windows.h>
#  include <psapi.h>
#  include "dlfcn_win32.h"
#else
#  include <dlfcn.h>
#  include <link.h> // for dl_iterate_phdr
#endif /* WIN32 */

#include <string>
#include <vector>

// Function that list all loaded libraries (not implemented here)
std::vector<std::string> list_loaded_libraries();

int main()
{
    // do some preprocessing stuff...

    // store the list of loaded libraries now
    // any libraries that get added to the list from now on must be Python
    // libraries
    std::vector<std::string> loaded_libraries(list_loaded_libraries());
    std::size_t start_idx(loaded_libraries.size());

    void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);

    // Not implemented here: get the addresses of the Python function you need

    MyPy_Initialize(); // Needs to be defined somewhere above!

    MyPyRun_SimpleString("import numpy"); // Needs to be defined somewhere above!

    // ...

    MyPyFinalize(); // Needs to be defined somewhere above!

    // Now list the loaded libraries again and start manually unloading them
    // starting from the end
    loaded_libraries = list_loaded_libraries();

    // NB: this below assumes that start_idx != 0, which should always hold true
    for(std::size_t i(loaded_libraries.size()-1) ; i >= start_idx ; --i) {
        void* pHandle = dlopen(loaded_libraries[i].c_str(),
#ifdef WIN32
                               RTLD_NOW // no support for RTLD_NOLOAD
#else
                               RTLD_NOW|RTLD_NOLOAD
#endif /* WIN32 */
                    );
        if (pHandle) {
            const unsigned int Nmax(50); // Avoid getting stuck in an infinite loop
            for (unsigned int j(0) ; j < Nmax && !dlclose(pHandle) ; ++j);
        }
    }
}

Final words

The examples shown here capture the basic ideas behind my solution, but can certainly be improved to avoid global variables and facilitate ease of use (for example, I wrote a singleton class that handles the automatic initialization of all the function pointers after loading the Python library).

I hope this can be useful to someone in the future.

References

dl_iterate_phdr: https://linux.die.net/man/3/dl_iterate_phdr

PsAPI library: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684894(v=vs.85).aspx

OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx

EnumProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx

GetModuleFileNameEx: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683198(v=vs.85).aspx

dlfcn-win32 library: library: https://github.com/dlfcn-win32/dlfcn-win32


问:
How to get rid of horizontal scroll through adding $(window).width() to :before selector in jQuery
Here is my jQuery - I will explain what I want to do:

I've added 100vw to my section:before selector, but the problem is that the horizontal scroll has appeared (because 100vw adds scroll width to 100vw).

I figured that the way to get around the horizontal scroll issue is to apply $(window).width() to my section:before selector, this way my 100vw won't calculate the scrollbar in.

This is how I fiddle it should be done (but I don't know yet how to achieve this):

select :before element in jQuery

set :before width style to $(window).width()

horizontal scroll is gone.

Any ideas how to do it?

CSS:

```<code>section {
  width:500px;
  height:100vh;
  margin:0 auto;
    background: #222226;

}

section:before {
    content: 'this is my before';
    position: absolute;
    width: 100vw;
    z-index:-1;
    background: #ccc;
    top:0;
    bottom:0;
    right:0;
    left: calc(-50vw + 50%);
}
</code>```

jQuery (I know it is wrong because :before is not part of DOM model but his is the idea):

```<code>    $(document).ready(function() {

        var window = $(document).width();

        $('section:before').css("width", window);

        });
</code>```

答:
Not really sure why you're doing what you're doing but... set the overflow-x property to hidden;

```<code>overflow-x: hidden;
</code>```

It also might be worth it to set margin and padding to 0 in your :before element;

Body:
Here is my jQuery - I will explain what I want to do:

I've added 100vw to my section:before selector, but the problem is that the horizontal scroll has appeared (because 100vw adds scroll width to 100vw).

I figured that the way to get around the horizontal scroll issue is to apply $(window).width() to my section:before selector, this way my 100vw won't calculate the scrollbar in.

This is how I fiddle it should be done (but I don't know yet how to achieve this):

select :before element in jQuery

set :before width style to $(window).width()

horizontal scroll is gone.

Any ideas how to do it?

CSS:

section {
  width:500px;
  height:100vh;
  margin:0 auto;
    background: #222226;

}

section:before {
    content: 'this is my before';
    position: absolute;
    width: 100vw;
    z-index:-1;
    background: #ccc;
    top:0;
    bottom:0;
    right:0;
    left: calc(-50vw + 50%);
}

jQuery (I know it is wrong because :before is not part of DOM model but his is the idea):

    $(document).ready(function() {

        var window = $(document).width();

        $('section:before').css("width", window);

        });

Body:
Not really sure why you're doing what you're doing but... set the overflow-x property to hidden;

overflow-x: hidden;

It also might be worth it to set margin and padding to 0 in your :before element;


问:
jQuery insertBefore, insertAfter problem
I want to make my images as links with help of jQuery:

```<code> $("img:gt(0)").each(function () {
            var curr = $(this);
            if (curr.width() >= 500) {
                var m = 500 / curr.width();
                curr.height(curr.height() * m);
                curr.width(curr.width() * m);
            }
            $("<a href='" + curr.attr("src") + "'>").insertBefore(curr);
            $("</a>").insertAfter(curr);
        });
</code>```

But I'm getting:

```<code><a href="/Images/7827-1280x800.jpg"></a>
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">
</code>```

Instead of:

```<code><a href="/Images/7827-1280x800.jpg">
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">
</a>
</code>```

答: It's because $("") will create a common html element. I think, jQuery will ignore missing closing tag and create this html:  and $("") will be ignored at all.

Body:
I want to make my images as links with help of jQuery:

 $("img:gt(0)").each(function () {
            var curr = $(this);
            if (curr.width() >= 500) {
                var m = 500 / curr.width();
                curr.height(curr.height() * m);
                curr.width(curr.width() * m);
            }
            $("").insertBefore(curr);
            $("").insertAfter(curr);
        });

But I'm getting:

Instead of:

Body: It's because $("<a href='" + curr.attr("src") + "'>") will create a common html element. I think, jQuery will ignore missing closing tag and create this html: <a href="/Images/7827-1280x800.jpg"></a> and $("</a>") will be ignored at all.


问:
Matlab loading files in listbox error: Extraneous arguments entered
I am new to matlab and I am trying to load multiple files in a list box. By far i have this code but it shows me this mistake:
Extraneous arguments entered, please check the documentation.
This is what I have as code:</p>

```<code>% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject    handle to load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[flnm, flpth,cCheck]=uigetfile({'*.mp3'},...
                            'File Select',...
                            'Multiset', 'on');
 %fullpathname=strcat(pathname, filename);
 %text=audioread(fullpathname);
 %set(handles.path_song, 'String',fullpathname);%show full path name in the listbox

 assignin('base','flnm',flnm);
 assignin('base','flpth',flpth);
 assignin('base','cCheck',cCheck);

 %If the user did not press the cancell button
if(cCheck==0)
%Reset selection to first entry
set(handles.playlist,'Value',1);
%Show selected filenames
set(handles.playlist,'String',flnm);
end
%LIST------------------------Display Files---------------------------------

function playlist_Callback(hObject, eventdata, handles)
% hObject    handle to playlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns playlist contents    as cell array
%        contents{get(hObject,'Value')} returns selected item from playlist

listStr=get(hObject,'String');
listVal=get(hObject,'Value');

%Display Selected files
if(iscell(listStr))
   fileName=playlistStr(listVal);
   fprintf('Selected file:%s\n',fileName);
else
   fileName=listStr;
   fprintf('Selected file:%s\n',fileName);
end
</code>```

答:
There are some errors in your code:

in the load_Callback cllback

in the call to uigetfile there is a typo: the propery Multiset should be Multiselect

the test if(cCheck==0) should be if(cCheck): if the user presses the Open pushbutton, uigetfile returns 1

in the playlist_Callback

in the if(iscell(listStr))

the name of the list should be listStr instead of playlistStr

if the condition is met (that is if listStr is a cellarray) you have to convert the selected item (listStr(listVal)) from cellarray to a char string by using the char function because fprintf is not defined for cell input

Fixing the above errors, the two callback result:

```<code>% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject    handle to load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% [flnm, flpth,cCheck]=uigetfile({'*.txt'},...
%                             'File Select',...
%                             'Multiset', 'on');
[flnm, flpth,cCheck]=uigetfile({'*.txt'},...
                            'File Select',...
                            'Multiselect', 'on');
%fullpathname=strcat(pathname, filename);
 %text=audioread(fullpathname);
 %set(handles.path_song, 'String',fullpathname);%show full path name in the listbox

assignin('base','flnm',flnm);
assignin('base','flpth',flpth);
assignin('base','cCheck',cCheck);

%If the user did not press the cancell button
%If the user did not press the cancell button
% if(cCheck==0)
if(cCheck)
   %Reset selection to first entry
   set(handles.playlist,'Value',1);
   %Show selected filenames
   set(handles.playlist,'String',flnm);
end

%LIST------------------------Display Files---------------------------------

function playlist_Callback(hObject, eventdata, handles)
% hObject    handle to playlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns playlist contents    as cell array
%        contents{get(hObject,'Value')} returns selected item from playlist

listStr=get(hObject,'String');
listVal=get(hObject,'Value');

%Display Selected files
if(iscell(listStr))
% % %    fileName=playlistStr(listVal);
   fileName=char(listStr(listVal));
   fprintf('Selected file:%s\n',fileName);
else
   fileName=listStr;
   fprintf('Selected file:%s\n',fileName);
end
</code>```

Hope this helps,

Qapla'

Body:
I am new to matlab and I am trying to load multiple files in a list box. By far i have this code but it shows me this mistake:
Extraneous arguments entered, please check the documentation.
This is what I have as code:

% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject    handle to load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[flnm, flpth,cCheck]=uigetfile({'*.mp3'},...
                            'File Select',...
                            'Multiset', 'on');
 %fullpathname=strcat(pathname, filename);
 %text=audioread(fullpathname);
 %set(handles.path_song, 'String',fullpathname);%show full path name in the listbox

 assignin('base','flnm',flnm);
 assignin('base','flpth',flpth);
 assignin('base','cCheck',cCheck);

 %If the user did not press the cancell button
if(cCheck==0)
%Reset selection to first entry
set(handles.playlist,'Value',1);
%Show selected filenames
set(handles.playlist,'String',flnm);
end
%LIST------------------------Display Files---------------------------------

function playlist_Callback(hObject, eventdata, handles)
% hObject    handle to playlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns playlist contents    as cell array
%        contents{get(hObject,'Value')} returns selected item from playlist

listStr=get(hObject,'String');
listVal=get(hObject,'Value');

%Display Selected files
if(iscell(listStr))
   fileName=playlistStr(listVal);
   fprintf('Selected file:%s\n',fileName);
else
   fileName=listStr;
   fprintf('Selected file:%s\n',fileName);
end

Body:
There are some errors in your code:

in the load_Callback cllback

in the call to uigetfile there is a typo: the propery Multiset should be Multiselect

the test if(cCheck==0) should be if(cCheck): if the user presses the Open pushbutton, uigetfile returns 1

in the playlist_Callback

in the if(iscell(listStr))

the name of the list should be listStr instead of playlistStr

if the condition is met (that is if listStr is a cellarray) you have to convert the selected item (listStr(listVal)) from cellarray to a char string by using the char function because fprintf is not defined for cell input

Fixing the above errors, the two callback result:

% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject    handle to load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% [flnm, flpth,cCheck]=uigetfile({'*.txt'},...
%                             'File Select',...
%                             'Multiset', 'on');
[flnm, flpth,cCheck]=uigetfile({'*.txt'},...
                            'File Select',...
                            'Multiselect', 'on');
%fullpathname=strcat(pathname, filename);
 %text=audioread(fullpathname);
 %set(handles.path_song, 'String',fullpathname);%show full path name in the listbox

assignin('base','flnm',flnm);
assignin('base','flpth',flpth);
assignin('base','cCheck',cCheck);

%If the user did not press the cancell button
%If the user did not press the cancell button
% if(cCheck==0)
if(cCheck)
   %Reset selection to first entry
   set(handles.playlist,'Value',1);
   %Show selected filenames
   set(handles.playlist,'String',flnm);
end

%LIST------------------------Display Files---------------------------------

function playlist_Callback(hObject, eventdata, handles)
% hObject    handle to playlist (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns playlist contents    as cell array
%        contents{get(hObject,'Value')} returns selected item from playlist

listStr=get(hObject,'String');
listVal=get(hObject,'Value');

%Display Selected files
if(iscell(listStr))
% % %    fileName=playlistStr(listVal);
   fileName=char(listStr(listVal));
   fprintf('Selected file:%s\n',fileName);
else
   fileName=listStr;
   fprintf('Selected file:%s\n',fileName);
end

Hope this helps,

Qapla'


问:
SQL - Row sum with condition from 2 tables
I have 2 tables and want to get the row sum from 2 tables with conditions.
Here are my tables:

tabale1,
tabale2

i want the row sum from 2 tables, like:

```<code>if sk not null sum sk but if it is null sk = ss
</code>```

For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40

I really need that, please help!

Table1:

Table2:

答:
Use coalesce to pick sk if sk is not null. Otherwise (if sk is null), ss will be used.

UNION ALL the two tables, and GROUP BY its result:

```<code>select name, sum(skss)
from
(
    select name, coalesce(sk, ss) skss
    from table1
    union all
    select name, coalesce(sk, ss) skss
    from table2
) dt
group by name
</code>```

Body:
I have 2 tables and want to get the row sum from 2 tables with conditions.
Here are my tables:

tabale1,
tabale2

i want the row sum from 2 tables, like:

if sk not null sum sk but if it is null sk = ss

For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40

I really need that, please help!

Table1:

Table2:

Body:
Use coalesce to pick sk if sk is not null. Otherwise (if sk is null), ss will be used.

UNION ALL the two tables, and GROUP BY its result:

select name, sum(skss)
from
(
    select name, coalesce(sk, ss) skss
    from table1
    union all
    select name, coalesce(sk, ss) skss
    from table2
) dt
group by name


问:
How to return the error validator laravel in string format
In this example code:

```<code> public function test(Request $request) {
    $rule = [
        'name' => 'required'
    ];
    $validator = Validator::make($request->all(), $rule);
    if ($validator->fails()) {
        return $validator->errors(); // <-- String format, not array
    }
    return $request->name;
}
</code>```

I need that the error be a simple string.

Thanks

答:
Do something like this:</p>

```<code>return $validator->errors()->first('name');
</code>```

Body:
In this example code:

 public function test(Request $request) {
    $rule = [
        'name' => 'required'
    ];
    $validator = Validator::make($request->all(), $rule);
    if ($validator->fails()) {
        return $validator->errors(); // <-- String format, not array
    }
    return $request->name;
}

I need that the error be a simple string.

Thanks

Body:
Do something like this:

return $validator->errors()->first('name');


问:
Using C# Pointers
How does c# makes use of pointers? If C# is a managed language and the garbage collector does a good job at preventing memory leaks and freeing up memory properly, then what is the effect of using pointers in c# and how "unsafe" are they?

答:
To use pointers you have to allow unsafe code, and mark the methods using pointers as unsafe. You then have to fix any pointers in memory to make sure the garbage collector doesn't move them:

```<code>byte[] buffer = new byte[256];

// fixed ensures the buffer won't be moved and so make your pointers invalid
fixed (byte* ptrBuf = buffer) {
    // ...
}
</code>```

It is unsafe because, theoretically, you could take a pointer, walk the entire address space, and corrupt or change the internal CLR data structures to, say, change a method implementation. You can't do that in managed code.

Title: Using C# Pointers

Body:
To use pointers you have to allow unsafe code, and mark the methods using pointers as unsafe. You then have to fix any pointers in memory to make sure the garbage collector doesn't move them:

byte[] buffer = new byte[256];

// fixed ensures the buffer won't be moved and so make your pointers invalid
fixed (byte* ptrBuf = buffer) {
    // ...
}

It is unsafe because, theoretically, you could take a pointer, walk the entire address space, and corrupt or change the internal CLR data structures to, say, change a method implementation. You can't do that in managed code.


问:
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

```<code>// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............
</code>```

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

```<code>https://localhost/signin-facebook?code=<access-token>
</code>```

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

```<code>/Account/ExternalLoginCallback?error=access_denied
</code>```

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

```<code>    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=<code-received-removed-for-obvious-reasons>

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=<code-from-step-1>

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>
</code>```

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.

答: This drove me insane. All was working until I deployed to my staging environment. I was using Microsoft.Owin.Security.Facebook version 3.0.1 from Nuget. Updated it to the prelease version 3.1.0 from Nuget and I no longer got the access denied error...</p>

Body:
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

https://localhost/signin-facebook?code=<access-token>

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

/Account/ExternalLoginCallback?error=access_denied

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.


问:
Why I need to specify permit again in the controller?
I am writing an app which has a comment controller, inside the controller,
it has the strong parameter like

```<code>def comment_params
  params.require(:comment).permit(:text)
end
</code>```

but I found I still need to add permit when I use

@comment = @post.comments.build(params[:comment].permit(:text)) in the create method or I will receive the error.

I would like to know the reason here. I am using Rails5.

答:
why I need to specific permit again in the controller?

Because you didn't use your comment_params.

```<code>@post.comments.build(comment_params)
</code>```

There is no magic, you should use your method.

In this code you didn't use it:

```<code>@post.comments.build(params[:comment].permit(:text))
</code>```

Body:
I am writing an app which has a comment controller, inside the controller,
it has the strong parameter like

def comment_params
  params.require(:comment).permit(:text)
end

but I found I still need to add permit when I use

@comment = @post.comments.build(params[:comment].permit(:text)) in the create method or I will receive the error.

I would like to know the reason here. I am using Rails5.

Body:
why I need to specific permit again in the controller?

Because you didn't use your comment_params.

@post.comments.build(comment_params)

There is no magic, you should use your method.

In this code you didn't use it:

@post.comments.build(params[:comment].permit(:text))


问:
Mocking getActionBar() returns null
I'm testing an activity, and I want to mock getActionBar(). I've tried doing it the usual way, that is

```<code>ActionBar mActionBar;

@Before
public void setup() {
    initMocks(this);
    mActionBar = Mockito.mock(ActionBar.class);
}

@Test
public void someTest(){
    when(activity.getActionBar()).thenReturn(mActionBar);
}
</code>```

But that doesn't seem to do anything, because I still get an NPE, when I try using the action bar in the activity after getActionBar().

答:
You are probably calling other methods on the mocked ActionBar in the code you are testing, like for example:

```<code>Tab tab = actionBar.getSelectedTab()
</code>```

This returns null.  Using tab then will result in a NPE.

This means you will need to mock more, for example:

```<code>when(actionBar.getSelectedTab()).thenReturn(mock(Tab.class));
</code>```

Now the above example will return a mocked Tab.

Title: Mocking getActionBar() returns null

Body:
I'm testing an activity, and I want to mock getActionBar(). I've tried doing it the usual way, that is

ActionBar mActionBar;

@Before
public void setup() {
    initMocks(this);
    mActionBar = Mockito.mock(ActionBar.class);
}

@Test
public void someTest(){
    when(activity.getActionBar()).thenReturn(mActionBar);
}

But that doesn't seem to do anything, because I still get an NPE, when I try using the action bar in the activity after getActionBar().

Body:
You are probably calling other methods on the mocked ActionBar in the code you are testing, like for example:

Tab tab = actionBar.getSelectedTab()

This returns null.  Using tab then will result in a NPE.

This means you will need to mock more, for example:

when(actionBar.getSelectedTab()).thenReturn(mock(Tab.class));

Now the above example will return a mocked Tab.


问:
Webservices in ASP .NET MVC2
I am using ASP .NET MVC2 to create a data driven web site. Part of the feature request is also to create reusable web services to expose some of the data and business logic using which end users can create mashups. There will be a significant amount of users using it within and outside our organization.

So far I have built the application that communicates to the database (using the entity framework ORM), processes and displays the data (using the model view view model pattern). This part has been straightforward for the website part.

As for the webservices part, I am looking into using WCF to create the web services. Should I create WCF data services as a separate project. I am guessing I should be able to reuse some of the code in the controller.

In the website part should I call these web services and use them as the model? Any best practices?

As somoeone new to asp .net, any pointers towards the right direction would be greatly appreciated.

答:
You could use a separate web application for hosting the web services. This will give you the possibility to host your MVC application and WCF service in separate virtual directories in IIS. Once you wrote the web service you could generate a client proxy and then in the client application you could use a repository:

```<code>public interface IProductsRepository
{
    IEnumerable<Person> GetProducts();
}
</code>```

and then have a specific implementation of this repository that will fetch the data from your WCF service:

```<code>public class ProductsRepositoryWcf
{
    public IEnumerable<Person> GetProducts()
    {
        using (var client = new YourWebServiceClient())
        {
            // call the web service method
            return client.GetProducts();
        }
    }
}
</code>```

And finally inject this repository into the constructor of your controller which might look like this:

```<code>public class HomeController: Controller
{
    private readonly IProductsRepository _repository;
    public HomeController(IProductsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var products = _repository.GetProducts();
        // TODO: An intermediary step might be necessary to convert the Product
        // model coming from the web service to a view model which is adapted
        // to the given view
        return View(products);
    }
}
</code>```

As you can see now the controller is completely decoupled by the way data is fetched. All it cares is that it respects the given contract (IProductsRepository interface). Using your favorite DI framework you could easily switch the implementation.

By the way if your code resembles mine, theonly thing that you should change in your current MVC application is to externalize the models and data access layers into a separate WCF service project which you would add service reference to, implement the ProductsRepositoryWcf repository and instruct your DI framework to use this implementation instead of the ProductsRepositorySql which would now go to the web service.

Title: Webservices in ASP .NET MVC2

Body:
You could use a separate web application for hosting the web services. This will give you the possibility to host your MVC application and WCF service in separate virtual directories in IIS. Once you wrote the web service you could generate a client proxy and then in the client application you could use a repository:

public interface IProductsRepository
{
    IEnumerable<Person> GetProducts();
}

and then have a specific implementation of this repository that will fetch the data from your WCF service:

public class ProductsRepositoryWcf
{
    public IEnumerable<Person> GetProducts()
    {
        using (var client = new YourWebServiceClient())
        {
            // call the web service method
            return client.GetProducts();
        }
    }
}

And finally inject this repository into the constructor of your controller which might look like this:

public class HomeController: Controller
{
    private readonly IProductsRepository _repository;
    public HomeController(IProductsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var products = _repository.GetProducts();
        // TODO: An intermediary step might be necessary to convert the Product
        // model coming from the web service to a view model which is adapted
        // to the given view
        return View(products);
    }
}

As you can see now the controller is completely decoupled by the way data is fetched. All it cares is that it respects the given contract (IProductsRepository interface). Using your favorite DI framework you could easily switch the implementation.

By the way if your code resembles mine, theonly thing that you should change in your current MVC application is to externalize the models and data access layers into a separate WCF service project which you would add service reference to, implement the ProductsRepositoryWcf repository and instruct your DI framework to use this implementation instead of the ProductsRepositorySql which would now go to the web service.


问:
Angular Directive: Button Spinner
I have created a directive, its behave like when you click on button it will show spinner or loader, its show user there is something in progress like API call or moving to another page, I am facing following issues:

If more than one directive used on page, its show spinner for both button instead clicked button, i want it should show only for clicked button

In some scenarios, clicked event bind three times, as there are three span used inside button to show spinner, there is some issue with event propagation

Here is directive code:

```<code>(function () {
    'use strict';

    angular
        .module('app.base')
        .directive('buttonSpinner', directiveFunction)
        .controller('btnController', ControllerFunction);

    // ----- directiveFunction -----
    directiveFunction.$inject = [];

    /* @ngInject */
    function directiveFunction() {

        var directive = {
            restrict: 'E',
            scope: {
              label: "@",
              available: "="
            },
            controller: 'btnController',
            controllerAs: 'vm',
            replace: true,
            transclude: true,
            template:
              '<button ng-disabled="vm.isDisabled">'
                + '<span ng-hide="vm.isClicked">{{label}}</span>'
                + '<div class="spinner" ng-show="vm.isClicked">'
                +   '<span class="bounce1"></span>'
                +   '<span class="bounce2"></span>'
                +   '<span class="bounce3"></span>'
                + '</div>' +
              '</button>'
        };

        return directive;
    }

    // ----- ControllerFunction -----
    ControllerFunction.$inject = [ '$scope' ];

    /* @ngInject */
    function ControllerFunction( $scope ) {

        var vm = this;
        vm.isClicked = false;
        $scope.$on('APICALLED', function(event, data){
          vm.isClicked = data.done;
          if( data.elem ) {
            angular.element(document.getElementById(data.elem))[0].disabled = true;
          } else {
            vm.isDisabled = data.disable;
          }
        });
    }

})();
</code>```

How to use:

In View:

```<code><button-spinner class="btn btn-primary btn-block btn-lg" type="submit" ng-click="vm.notifyMe($event)" label="Notify Me" available="vm.notify.is" id="notifyMeBtn"></button-spinner>
</code>```

In Controller:

to show spinner:

```<code>$rootScope.$broadcast('APICALLED', {'done': true, 'disable': true});
</code>```

to hide spinner:

```<code> $rootScope.$broadcast('APICALLED', {'done': false, 'disable': false});
</code>```

答:
Your problem is related to your $broadcast's so its a pattern problem. $rootScope.$broadcast() isnt a good solution at all. e.g.) You need to destroy $rootScope.$broadcast.$on() bindings manually. Just parse a unique scope var into the directive like loading. This scope param could be handled by the controller itself for each loading procedure:

```<code>/* @ngInject */
function directiveFunction() {

    var directive = {
        restrict: 'E',
        scope: {
            label: "@",
            available: "=",
            loading: "="
        },
        controller: 'btnController',
        controllerAs: 'vm',
        replace: true,
        transclude: true,
        template:
        '<button ng-disabled="vm.isDisabled">'
        + '<span ng-hide="vm.isClicked">{{label}}</span>'
        + '<div class="spinner" ng-show="vm.loading">'
        +   '<span class="bounce1"></span>'
        +   '<span class="bounce2"></span>'
        +   '<span class="bounce3"></span>'
        + '</div>' +
        '</button>'
    };

    return directive;
}
</code>```

View

```<code><button-spinner class="btn btn-primary btn-block btn-lg"
                type="submit"
                ng-click="vm.notifyMe($event)"
                loading="vm.isLoading"
                label="Notify Me"
                available="vm.notify.is"
                id="notifyMeBtn"></button-spinner>
</code>```

Title: Angular Directive: Button Spinner

Body:
I have created a directive, its behave like when you click on button it will show spinner or loader, its show user there is something in progress like API call or moving to another page, I am facing following issues:

If more than one directive used on page, its show spinner for both button instead clicked button, i want it should show only for clicked button

In some scenarios, clicked event bind three times, as there are three span used inside button to show spinner, there is some issue with event propagation

Here is directive code:

(function () {
    'use strict';

    angular
        .module('app.base')
        .directive('buttonSpinner', directiveFunction)
        .controller('btnController', ControllerFunction);

    // ----- directiveFunction -----
    directiveFunction.$inject = [];

    /* @ngInject */
    function directiveFunction() {

        var directive = {
            restrict: 'E',
            scope: {
              label: "@",
              available: "="
            },
            controller: 'btnController',
            controllerAs: 'vm',
            replace: true,
            transclude: true,
            template:
              '<button ng-disabled="vm.isDisabled">'
                + '{{label}}'
                + '
'
                +   ''
                +   ''
                +   ''
                + '
' +
              '</button>'
        };

        return directive;
    }

    // ----- ControllerFunction -----
    ControllerFunction.$inject = [ '$scope' ];

    /* @ngInject */
    function ControllerFunction( $scope ) {

        var vm = this;
        vm.isClicked = false;
        $scope.$on('APICALLED', function(event, data){
          vm.isClicked = data.done;
          if( data.elem ) {
            angular.element(document.getElementById(data.elem))[0].disabled = true;
          } else {
            vm.isDisabled = data.disable;
          }
        });
    }

})();

How to use:

In View:

<button-spinner class="btn btn-primary btn-block btn-lg" type="submit" ng-click="vm.notifyMe($event)" label="Notify Me" available="vm.notify.is" id="notifyMeBtn"></button-spinner>

In Controller:

to show spinner:

$rootScope.$broadcast('APICALLED', {'done': true, 'disable': true});

to hide spinner:

 $rootScope.$broadcast('APICALLED', {'done': false, 'disable': false});

Body:
Your problem is related to your $broadcast's so its a pattern problem. $rootScope.$broadcast() isnt a good solution at all. e.g.) You need to destroy $rootScope.$broadcast.$on() bindings manually. Just parse a unique scope var into the directive like loading. This scope param could be handled by the controller itself for each loading procedure:

/* @ngInject */
function directiveFunction() {

    var directive = {
        restrict: 'E',
        scope: {
            label: "@",
            available: "=",
            loading: "="
        },
        controller: 'btnController',
        controllerAs: 'vm',
        replace: true,
        transclude: true,
        template:
        '<button ng-disabled="vm.isDisabled">'
        + '<span ng-hide="vm.isClicked">{{label}}</span>'
        + '<div class="spinner" ng-show="vm.loading">'
        +   '<span class="bounce1"></span>'
        +   '<span class="bounce2"></span>'
        +   '<span class="bounce3"></span>'
        + '</div>' +
        '</button>'
    };

    return directive;
}

View

<button-spinner class="btn btn-primary btn-block btn-lg"
                type="submit"
                ng-click="vm.notifyMe($event)"
                loading="vm.isLoading"
                label="Notify Me"
                available="vm.notify.is"
                id="notifyMeBtn"></button-spinner>


问:
C++: Quicksort words instead of numbers
I am trying to write a code that uses quicksort to sort words by alphabetical order, but when I run my code it gets stuck on inputting the user's words. What's the reason behind this? It works fine when I leave the array as an integer array. Thanks in advance!</p>

```<code>#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

void quicksort(char a[], int size, int left, int right)
{
    int i = left;
    int j = right;
    int pivot = a[(left+right)/2];
    char temp;
    while (i <= j)
    {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }

    if (i < right)
        quicksort(a, size, i, right);
    if (j > left)
        quicksort(a, size, left, j);
}

int main()
{
    char a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
        cin >> a[i];
        quicksort(a, n, 0, n-1);
        cout << endl;
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
        cout << endl;

    return 0;

}
</code>```

答:
You code may work but you're trying to read words in an array of char. You need to use a string (store a whole word) or an array of string (store multiple strings).

Your code may look like this:

```<code>int main()
{
    string a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;

    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        quicksort(a, n, 0, a[i].length -1);
    }

    cout << "The sorted elements are: " << endl;

    for (int i = 0; i < n; i++)
        cout << a[i] << " " << endl;

    return 0;
}
</code>```

Please have in mind the that the code structure in c++ it's different than python. Have a look to this coding and naming conventions
http://www.dofactory.com/reference/csharp-coding-standards

Title: C++: Quicksort words instead of numbers

Body:
I am trying to write a code that uses quicksort to sort words by alphabetical order, but when I run my code it gets stuck on inputting the user's words. What's the reason behind this? It works fine when I leave the array as an integer array. Thanks in advance!

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

void quicksort(char a[], int size, int left, int right)
{
    int i = left;
    int j = right;
    int pivot = a[(left+right)/2];
    char temp;
    while (i <= j)
    {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }

    if (i < right)
        quicksort(a, size, i, right);
    if (j > left)
        quicksort(a, size, left, j);
}

int main()
{
    char a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
        cin >> a[i];
        quicksort(a, n, 0, n-1);
        cout << endl;
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
        cout << endl;

    return 0;

}

Body:
You code may work but you're trying to read words in an array of char. You need to use a string (store a whole word) or an array of string (store multiple strings).

Your code may look like this:

int main()
{
    string a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;

    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        quicksort(a, n, 0, a[i].length -1);
    }

    cout << "The sorted elements are: " << endl;

    for (int i = 0; i < n; i++)
        cout << a[i] << " " << endl;

    return 0;
}

Please have in mind the that the code structure in c++ it's different than python. Have a look to this coding and naming conventions
http://www.dofactory.com/reference/csharp-coding-standards


问:
Can't use delete method on Ruby on rails
I am a beginner of Ruby on rails, I failed when I try to delete the object that I  create. here is the code.
controller

```<code>class PuzzlesController < ApplicationController
  def index
    @puzzles = Puzzle.all
  end
  def show
    @puzzle=Puzzle.find(params[:id])
  end
  def new
    @puzzle = Puzzle.new

  end
  def create
      #render plain: params[:puzzle].inspect
    @puzzle = Puzzle.new(puzzle_params)
    if(@puzzle.save)
      redirect_to @puzzle
    else
      render 'new'
    end
  end
  def edit
    @puzzle=Puzzle.find(params[:id])
  end
  def update
    @puzzle=Puzzle.find(params[:id])
    if(@puzzle.update(puzzle_params))
      redirect_to @puzzle
    else
      render 'edit'
    end
  end
  def destroy
    @puzzle = Puzzle.find(params[:id])
    @puzzle.destroy

    redirect_to puzzle_path
  end
  private def puzzle_params
    params.require(:puzzle).permit(:title,:body,:category,:difficulty)
  end
end
</code>```

show

```<code><h2><%= @puzzle.title %></h2>
    <p><%= @puzzle.body %></p>
    <p><%= @puzzle.category %></p>
    <p><%= @puzzle.difficulty %></p>
<hr>
<%= link_to "Edit", edit_puzzle_path(@puzzle), :class => 'btn btn-default'%>
<%= link_to "Delete", puzzle_path(@puzzle),
            method: :delete,
            data: {confrim: 'are you sure? '},
             :class => 'btn btn-danger'%>
</code>```

when i click on delete, its like re-render the page. i searched a lot on internet and cant find a solution for it.

this is the information on rails server.

```<code>Started GET "/puzzles/1" for ::1 at 2017-04-02 18:51:18 +0930
Processing by PuzzlesController#show as HTML
  Parameters: {"id"=>"1"}
  Puzzle Load (0.5ms)  SELECT  "puzzles".* FROM "puzzles" WHERE "puzzles"."id" = ? LIM             IT ?  [["id", 1], ["LIMIT", 1]]
  Rendering puzzles/show.html.erb within layouts/application
  Rendered puzzles/show.html.erb within layouts/application (1.0ms)
Completed 200 OK in 63ms (Views: 46.2ms | ActiveRecord: 0.5ms)
</code>```

答:
change your redirect path</p>

```<code>redirect_to puzzles_path
</code>```

Body:
I am a beginner of Ruby on rails, I failed when I try to delete the object that I  create. here is the code.
controller

class PuzzlesController < ApplicationController
  def index
    @puzzles = Puzzle.all
  end
  def show
    @puzzle=Puzzle.find(params[:id])
  end
  def new
    @puzzle = Puzzle.new

  end
  def create
      #render plain: params[:puzzle].inspect
    @puzzle = Puzzle.new(puzzle_params)
    if(@puzzle.save)
      redirect_to @puzzle
    else
      render 'new'
    end
  end
  def edit
    @puzzle=Puzzle.find(params[:id])
  end
  def update
    @puzzle=Puzzle.find(params[:id])
    if(@puzzle.update(puzzle_params))
      redirect_to @puzzle
    else
      render 'edit'
    end
  end
  def destroy
    @puzzle = Puzzle.find(params[:id])
    @puzzle.destroy

    redirect_to puzzle_path
  end
  private def puzzle_params
    params.require(:puzzle).permit(:title,:body,:category,:difficulty)
  end
end

show

<%= @puzzle.title %>

<%= @puzzle.body %>

<%= @puzzle.category %>

<%= @puzzle.difficulty %>

<%= link_to "Edit", edit_puzzle_path(@puzzle), :class => 'btn btn-default'%>
<%= link_to "Delete", puzzle_path(@puzzle),
            method: :delete,
            data: {confrim: 'are you sure? '},
             :class => 'btn btn-danger'%>

when i click on delete, its like re-render the page. i searched a lot on internet and cant find a solution for it.

this is the information on rails server.

Started GET "/puzzles/1" for ::1 at 2017-04-02 18:51:18 +0930
Processing by PuzzlesController#show as HTML
  Parameters: {"id"=>"1"}
  Puzzle Load (0.5ms)  SELECT  "puzzles".* FROM "puzzles" WHERE "puzzles"."id" = ? LIM             IT ?  [["id", 1], ["LIMIT", 1]]
  Rendering puzzles/show.html.erb within layouts/application
  Rendered puzzles/show.html.erb within layouts/application (1.0ms)
Completed 200 OK in 63ms (Views: 46.2ms | ActiveRecord: 0.5ms)

Body:
change your redirect path

redirect_to puzzles_path