问:
How to inherit class attributes in Python 3.6.1
I'm trying to figure out how to inherit all of the attributes/methods from one class into another class.  I'm basing it off of How to inherit a python base class? but I can't figure out how to get it to work for my simple example.  In this example, I just want to make a new class that has all the functionality of RandomForestClassifier but with a new attribute (called new_attribute).  In this method, I can't use the arguments of the original RandomForestClassifier but I can add my new attribute.

How can I set it up so I can use all of the parameters from the original RandomForestClassifier along with adding this new_attribute?

```<code>from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute):
        Super(RandomForestClassifier, self).__init__()
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)
</code>```

Error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-221-686839873f88> in <module>()
      5         Super(RandomForestClassifier, self).__init__()
      6         self.new_attribute = new_attribute
----> 7 A = NewClassifier(n_estimators=1, new_attribute=0)

TypeError: __init__() got an unexpected keyword argument 'n_estimators'
</code>```

Hindsight:
This was a poorly constructed question.  I got the above to work with the code below. However, @Mseifert has a better representation in the answers:

```<code>class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None):
        RandomForestClassifier.__init__(self, n_estimators, criterion, max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_features, max_leaf_nodes, min_impurity_split, bootstrap, oob_score, n_jobs, random_state, verbose, warm_start, class_weight)
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)
</code>```

答:
The easiest way would be to accept new_attribute as first and must-have argument:

```<code>from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, *args, **kwargs):  # just accept any argument
        # Find out what the value of "new_argument is" and remove it either from
        # the positional arguments (args) or keyword arguments (kwargs) so that
        # the remaining arguments can simply be passed to the super-class.
        if args:  # if there are positional arguments
            new_attribute = args[0]
            args = args[1:]
        else:     # no positional arguments
            new_attribute = kwargs.pop('new_attribute')

        super().__init__(*args, **kwargs)
        self.new_attribute = new_attribute
</code>```

Note that it's super not Super and you don't need the arguments in python-3.x

Body:
I'm trying to figure out how to inherit all of the attributes/methods from one class into another class.  I'm basing it off of How to inherit a python base class? but I can't figure out how to get it to work for my simple example.  In this example, I just want to make a new class that has all the functionality of RandomForestClassifier but with a new attribute (called new_attribute).  In this method, I can't use the arguments of the original RandomForestClassifier but I can add my new attribute.

How can I set it up so I can use all of the parameters from the original RandomForestClassifier along with adding this new_attribute?

from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute):
        Super(RandomForestClassifier, self).__init__()
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-221-686839873f88> in <module>()
      5         Super(RandomForestClassifier, self).__init__()
      6         self.new_attribute = new_attribute
----> 7 A = NewClassifier(n_estimators=1, new_attribute=0)

TypeError: __init__() got an unexpected keyword argument 'n_estimators'

Hindsight:
This was a poorly constructed question.  I got the above to work with the code below. However, @Mseifert has a better representation in the answers:

class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None):
        RandomForestClassifier.__init__(self, n_estimators, criterion, max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_features, max_leaf_nodes, min_impurity_split, bootstrap, oob_score, n_jobs, random_state, verbose, warm_start, class_weight)
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)

Body:
The easiest way would be to accept new_attribute as first and must-have argument:

from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, *args, **kwargs):  # just accept any argument
        # Find out what the value of "new_argument is" and remove it either from
        # the positional arguments (args) or keyword arguments (kwargs) so that
        # the remaining arguments can simply be passed to the super-class.
        if args:  # if there are positional arguments
            new_attribute = args[0]
            args = args[1:]
        else:     # no positional arguments
            new_attribute = kwargs.pop('new_attribute')

        super().__init__(*args, **kwargs)
        self.new_attribute = new_attribute

Note that it's super not Super and you don't need the arguments in python-3.x


来源: stackexchange

问:
How can I count occurrences with groupBy?
I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.

```<code>List<String> list = Arrays.asList("Hello", "Hello", "World");
Map<String, Long> wordToFrequency = // what goes here?
</code>```

So in this case, I would like the map to consist of these entries:

```<code>Hello -> 2
World -> 1
</code>```

How can I do that?

答:
Here is the simple solution by StreamEx:

StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());
```

This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.

ContentLicense: CC BY-SA 4.0

Body:
I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.

List<String> list = Arrays.asList("Hello", "Hello", "World");
Map<String, Long> wordToFrequency = // what goes here?

So in this case, I would like the map to consist of these entries:

Hello -> 2
World -> 1

How can I do that?

Body:
Here is the simple solution by StreamEx:

StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());

This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.


问:
Help getting all queues in a glassfish server
I am developing a monitoring tool for a server runing glassfish, to do that, I have to get all the queues in this server.
I was able to do that connecting using tcp when it was running ActiveMQ, there was a DestinationSource.GetQueues() method.

I wanted to do that in OpenMQ, but after 4 days of research I couldn't find any sign that someone like that exists, so I gave up. My next try is doing that using JMX protocol. I could just connect, I am taking a look at all these MBeans, but I can't find any DestinationAttribute that may return the information I want.

I would like to know if anybody knows if it is possible to the all the queues.

Thanks in advance,
Oscar

答: To do that you have to use JMX and the MBeanServerConnection.invoke method</p>

ContentLicense: CC BY-SA 2.5


问:
DataTables Binding with MVC in multiple View
I using MVC with Datables.js to display the data. It's working fine, my issue is on click of row i am passing the EmployeeID in to different EmployeeWorkDetails Action and this consist different  EmployeeWorkDetails view.

Now I need to bind EmployeeWorkDetails in Datatables in different view, how can I achieve this?

Index View

```<code><table id="EmployeeTable" style="display:none">
    <thead>
        <tr>
            <th>Select</th>
            <th>EmployeeID</th>
            <th>EmployeeName</th>

</table>

function LoadData() {
    $.ajax({
        "url": "@Url.Action("Home", "EmployeeList")",
        method: 'post',
        dataType: 'json',
        success: function (data) {
            $('#EmployeeTable').DataTable(
            {
                data: data,select: true,
                columns: [
                    // using anchor tag
                    { "data": "EmployeeID", "render": function (data) {
                        return '<a class="btn btn-primary" href="/Home/EmployeeWorkDetails/' + data + '"></a>';}, "autoWidth": true,},
                    { "data": "EmployeeID", "autoWidth": true,},
                    { "data": "EmployeeName", "autoWidth": true, visible: false },},
                ]
            ,});}}) }
</code>```

Controller

```<code>public class HomeController : Controller
{
    public ActionResult index(int id)
    {
        return View();
    }
    [HttpGet]
    public JsonResult EmployeeList()
    {
        var data = EmployeeList.GetEmployeeData();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    [HttpGet]
    public ActionResult EmployeeWorkDetails(int id)
    {
        var workDetails= emp.EmployeeWorkDetails(int id)
        return View(workDetails);
    }
}
     This is View of EmployeeWorkDetails
   @model IEnumerable<WorkEmployee.Models.workDetails>
      // Is it possible to pass  workDetails in datatables Data
    $(document).ready(function () {
        oTable = $('#EmployeTable').DataTable(
               {
                   searching: true,
                   ordering: true,
                   select: true,
                   data: @workDetails,
                   columns: [
                            { "data": "EmployeeId", "autoWidth": true, },
                            { "data": "EmployeeName", "autoWidth": true, },
                   ],
               });
    });
</code>```

答:
This is how you pass the employee id to the controller:

Controller:

```<code>//Create an edmx to your table
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult EmployeeWorkDetails(int id)
    {
       //var workDetails= emp.EmployeeWorkDetails(int id)

       //put a breakpoint here to see id passed

       return View("Index2001");
    }

    public ActionResult Index2001()
    {
        IList<EmployeeList> empList;
        using (BreazEntities24 entity = new BreazEntities24())
        {
            empList = entity.EmployeeLists.ToList();
        }
        return View(empList);
    }
</code>```

View:

```<code>@model IEnumerable<Testy20161006.Models.EmployeeList>
@using Testy20161006.Models
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2001</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />

    <script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#EmployeeTable").DataTable({
                "order": [[1, "desc"]],
                "pagingType": "full",
                "deferRender": true,
                "columns": [
                {
                    "data": "EmployeeID", "render": function (data, type, row) {
                        return '<a class="btn btn-primary" href="/Home/EmployeeWorkDetails/' + data + '">click</a>'
                    }, "autoWidth": true,
                },
                { "data": "EmployeeID", "autoWidth": true, },
                { "data": "EmployeeName", "autoWidth": true, visible: true }
                ]
            });
        })
    </script>
</head>
<body>
    <div>
        <table id="EmployeeTable" class="display table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Select</th>
                    <th>EmployeeID</th>
                    <th>EmployeeName</th>
            </thead>
            <tbody>
                @foreach (EmployeeList emp in Model)
                {
                    <tr>
                        <td>@emp.EmployeeID</td>
                        <td>@emp.EmployeeID</td>
                        <td>@emp.EmployeeName</td>
                    </tr>
                }
            </tbody>

        </table>
    </div>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I using MVC with Datables.js to display the data. It's working fine, my issue is on click of row i am passing the EmployeeID in to different EmployeeWorkDetails Action and this consist different  EmployeeWorkDetails view.

Now I need to bind EmployeeWorkDetails in Datatables in different view, how can I achieve this?

Index View

            Select
            EmployeeID
            EmployeeName

function LoadData() {
    $.ajax({
        "url": "@Url.Action("Home", "EmployeeList")",
        method: 'post',
        dataType: 'json',
        success: function (data) {
            $('#EmployeeTable').DataTable(
            {
                data: data,select: true,
                columns: [
                    // using anchor tag
                    { "data": "EmployeeID", "render": function (data) {
                        return '';}, "autoWidth": true,},
                    { "data": "EmployeeID", "autoWidth": true,},
                    { "data": "EmployeeName", "autoWidth": true, visible: false },},
                ]
            ,});}}) }

Controller

public class HomeController : Controller
{
    public ActionResult index(int id)
    {
        return View();
    }
    [HttpGet]
    public JsonResult EmployeeList()
    {
        var data = EmployeeList.GetEmployeeData();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    [HttpGet]
    public ActionResult EmployeeWorkDetails(int id)
    {
        var workDetails= emp.EmployeeWorkDetails(int id)
        return View(workDetails);
    }
}
     This is View of EmployeeWorkDetails
   @model IEnumerable<WorkEmployee.Models.workDetails>
      // Is it possible to pass  workDetails in datatables Data
    $(document).ready(function () {
        oTable = $('#EmployeTable').DataTable(
               {
                   searching: true,
                   ordering: true,
                   select: true,
                   data: @workDetails,
                   columns: [
                            { "data": "EmployeeId", "autoWidth": true, },
                            { "data": "EmployeeName", "autoWidth": true, },
                   ],
               });
    });

Body:
This is how you pass the employee id to the controller:

Controller:

//Create an edmx to your table
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult EmployeeWorkDetails(int id)
    {
       //var workDetails= emp.EmployeeWorkDetails(int id)

       //put a breakpoint here to see id passed

       return View("Index2001");
    }

    public ActionResult Index2001()
    {
        IList<EmployeeList> empList;
        using (BreazEntities24 entity = new BreazEntities24())
        {
            empList = entity.EmployeeLists.ToList();
        }
        return View(empList);
    }

View:

@model IEnumerable<Testy20161006.Models.EmployeeList>
@using Testy20161006.Models
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2001</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />

    <script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#EmployeeTable").DataTable({
                "order": [[1, "desc"]],
                "pagingType": "full",
                "deferRender": true,
                "columns": [
                {
                    "data": "EmployeeID", "render": function (data, type, row) {
                        return '<a class="btn btn-primary" href="/Home/EmployeeWorkDetails/' + data + '">click</a>'
                    }, "autoWidth": true,
                },
                { "data": "EmployeeID", "autoWidth": true, },
                { "data": "EmployeeName", "autoWidth": true, visible: true }
                ]
            });
        })
    </script>
</head>
<body>
    <div>
        <table id="EmployeeTable" class="display table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Select</th>
                    <th>EmployeeID</th>
                    <th>EmployeeName</th>
            </thead>
            <tbody>
                @foreach (EmployeeList emp in Model)
                {
                    <tr>
                        <td>@emp.EmployeeID</td>
                        <td>@emp.EmployeeID</td>
                        <td>@emp.EmployeeName</td>
                    </tr>
                }
            </tbody>

        </table>
    </div>
</body>
</html>


问:
BIC is over-fitting the number of components in an image segmentation model using GaussianMixture from scikit-learn
I am using a GMM to segment/cluster hyper-spectral image data which is 800x800 pixels and 4 bands.

I took a picture and applied a GMM to cluster pixels.

Now, in my current situation, it is easy enough for me to manually determine how many components are in an image. (Grass,water,rocks... etc)

I have manually run the GMM on my data from n_components=3..8 and have determined that 5 components is probably the best n_components to model reality.

In future applications, I will need the ability to automatically identify n_components I should be using in my GMM, because manual determination will not be possible.

So, I decided to use the BIC as a cost function to determine the proper n_components to use in the model.

I ran the BIC on the test data where I manually determined that n_components=5 best models reality and found that the BIC horribly over-fits my data.

It is suggesting that I use as many components as I possibly can.

```<code>newdata=img_data.reshape(800*800,4)
n_components = np.arange(1, 15)
BIC = np.zeros(n_components.shape)

for i, n in enumerate(n_components):
    gmm = GaussianMixture(n_components=n,
          covariance_type='tied')
    gmm.fit(newdata)

BIC[i] = gmm.bic(newdata)
plt.plot(BIC)
</code>```

Now ideally, I would like to see my BIC score minimized at 5, but as you can see above it looks like it is continually decreasing with n_components.

Does anyone have any idea what might be going on here? Maybe I need to smooth the data in someway to reduce noise before using the BIC? Or am I improperly using the BIC function?

答:
So after a little bit of googling, I decided to apply a simple Gaussian smoothing filter to my array and it seemed to produce a local min in my BIC score list which was the n_components which I expected. I wrote a small script to pick out the first local min and use it as a parameter for my gmm model.

```<code>newdata=img_data.reshape(800*800,4)
#Apply a Gaussian smoothing filter over a pixel neighborhood
newdata=sy.ndimage.filters.gaussian_filter(newdata,(1.5,1.5))
#Create the vector of n_components you wish to test using the BIC alogrithm
n_components = np.arange(1, 10)
#Create an empty vector in which to store BIC scores
BIC = np.zeros(n_components.shape)

for i, n in enumerate(n_components):
    #Fit gmm to data for each value in n_components vector
    gmm = GaussianMixture(n_components=n,
          covariance_type='tied')
    gmm.fit(newdata)
    #Store BIC scores in a list
    BIC[i] = gmm.bic(newdata)

#Plot resulting BIC list (Scores(n_components))
plt.plot(BIC)
plt.show()
</code>```

BIC Scores With Smoothing

Body:
I am using a GMM to segment/cluster hyper-spectral image data which is 800x800 pixels and 4 bands.

I took a picture and applied a GMM to cluster pixels.

Now, in my current situation, it is easy enough for me to manually determine how many components are in an image. (Grass,water,rocks... etc)

I have manually run the GMM on my data from n_components=3..8 and have determined that 5 components is probably the best n_components to model reality.

In future applications, I will need the ability to automatically identify n_components I should be using in my GMM, because manual determination will not be possible.

So, I decided to use the BIC as a cost function to determine the proper n_components to use in the model.

I ran the BIC on the test data where I manually determined that n_components=5 best models reality and found that the BIC horribly over-fits my data.

It is suggesting that I use as many components as I possibly can.

newdata=img_data.reshape(800*800,4)
n_components = np.arange(1, 15)
BIC = np.zeros(n_components.shape)

for i, n in enumerate(n_components):
    gmm = GaussianMixture(n_components=n,
          covariance_type='tied')
    gmm.fit(newdata)

BIC[i] = gmm.bic(newdata)
plt.plot(BIC)

Now ideally, I would like to see my BIC score minimized at 5, but as you can see above it looks like it is continually decreasing with n_components.

Does anyone have any idea what might be going on here? Maybe I need to smooth the data in someway to reduce noise before using the BIC? Or am I improperly using the BIC function?

Body:
So after a little bit of googling, I decided to apply a simple Gaussian smoothing filter to my array and it seemed to produce a local min in my BIC score list which was the n_components which I expected. I wrote a small script to pick out the first local min and use it as a parameter for my gmm model.

newdata=img_data.reshape(800*800,4)
#Apply a Gaussian smoothing filter over a pixel neighborhood
newdata=sy.ndimage.filters.gaussian_filter(newdata,(1.5,1.5))
#Create the vector of n_components you wish to test using the BIC alogrithm
n_components = np.arange(1, 10)
#Create an empty vector in which to store BIC scores
BIC = np.zeros(n_components.shape)

for i, n in enumerate(n_components):
    #Fit gmm to data for each value in n_components vector
    gmm = GaussianMixture(n_components=n,
          covariance_type='tied')
    gmm.fit(newdata)
    #Store BIC scores in a list
    BIC[i] = gmm.bic(newdata)

#Plot resulting BIC list (Scores(n_components))
plt.plot(BIC)
plt.show()

BIC Scores With Smoothing


问:
Use View from a Query across multiple SELECTS
I've got a query in similar structure to below

```<code>SELECT blah
FROM   A, B, C
WHERE  $SOME_COMMON_IF_AND
AND    $SPECIFIC_1

UNION

SELECT blah
FROM   A, B, C, D
WHERE  $SOME_COMMON_IF_AND
AND    $SPECIFIC_2

UNION

...
</code>```

In am attempt to reduce query time, I'm trying to strip out the $SOME_COMMON_IF_AND parts and project it as a view, and have the SELECT clauses use this view as a baseline.

I can't seem to figure out the correct syntax to do this, any suggestions?

Thanks in advance!

--- EDITED FOR MORE INFO---

For example:

```<code>(SELECT blah
FROM   A, B, C
WHERE  $SOME_COMMON_IF_AND)
AS WORK_TABLE_1

%$@#%$@# -- the missing link

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_1

UNION

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_2

UNION

....
</code>```

This is on DB2 but I'm look for a general SQL solution, the original query is a beast (1000 line +), hence me abstracting the WHERE clause. Please let me know if more clarification is needed.

答:
What you're looking for is called a common table expression.  It's just like having an in-line view:</p>

```<code>with
work_table_1 as (
   SELECT blah
   FROM   A, B, C
   WHERE  $SOME_COMMON_IF_AND
)
SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_1

UNION

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_2
</code>```

Body:
I've got a query in similar structure to below

SELECT blah
FROM   A, B, C
WHERE  $SOME_COMMON_IF_AND
AND    $SPECIFIC_1

UNION

SELECT blah
FROM   A, B, C, D
WHERE  $SOME_COMMON_IF_AND
AND    $SPECIFIC_2

UNION

...

In am attempt to reduce query time, I'm trying to strip out the $SOME_COMMON_IF_AND parts and project it as a view, and have the SELECT clauses use this view as a baseline.

I can't seem to figure out the correct syntax to do this, any suggestions?

Thanks in advance!

--- EDITED FOR MORE INFO---

For example:

(SELECT blah
FROM   A, B, C
WHERE  $SOME_COMMON_IF_AND)
AS WORK_TABLE_1

%$@#%$@# -- the missing link

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_1

UNION

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_2

UNION

....

This is on DB2 but I'm look for a general SQL solution, the original query is a beast (1000 line +), hence me abstracting the WHERE clause. Please let me know if more clarification is needed.

Body:
What you're looking for is called a common table expression.  It's just like having an in-line view:

with
work_table_1 as (
   SELECT blah
   FROM   A, B, C
   WHERE  $SOME_COMMON_IF_AND
)
SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_1

UNION

SELECT blah
FROM   WORK_TABLE_1
WHERE  $SPECIFIC_2


问:
How to run a search that returns after a certain amount of time?
I have a function that runs an iterative deepening search and would like to return the value from the deepest search after a certain amount of time has passed. The code skeleton would look something like

```<code>import time

answers = []
START = time.clock()
current_depth = 1

while time.clock() - START < DESIRED_RUN_TIME:
    answers.append(IDS(depth=current_depth))
    current_depth += 1

return answers[-1]
</code>```

The problem with this code is it will not return until after the time limit has passed. What is the best way to solve this? If I should just add time checks in the IDS function, how can I make sure to return the last value found? Any help would be greatly appreciated.

答:
Your code should work unless IDS is blocking and takes a very long time. Then you have to wait until IDS is finished and the time limit may not be all that precise.

I'm not sure exactly what you mean by

would like to return the value from the deepest search after a certain amount of time has passed.

and

The problem with this code is it will not return until after the time limit has passed.

If you have time limits and you have update times then you can use this code as a generator.

```<code>import time

answers = []
START = time.clock()
current_depth = 1

def get_ids(update_time, limit_time):
    last_update = time.clock()
    while time.clock() - START < DESIRED_RUN_TIME:
        answers.append(IDS(depth=current_depth))
        current_depth += 1
        if time.clock() - last_update < update_time:
            last_update = time.clock()
            yield answers[-1]

    yield answers[-1]

for i in get_ids(1, 10):  # get an ids every second and stop after 10 seconds
    print(i)
</code>```

Body:
I have a function that runs an iterative deepening search and would like to return the value from the deepest search after a certain amount of time has passed. The code skeleton would look something like

import time

answers = []
START = time.clock()
current_depth = 1

while time.clock() - START < DESIRED_RUN_TIME:
    answers.append(IDS(depth=current_depth))
    current_depth += 1

return answers[-1]

The problem with this code is it will not return until after the time limit has passed. What is the best way to solve this? If I should just add time checks in the IDS function, how can I make sure to return the last value found? Any help would be greatly appreciated.

Body:
Your code should work unless IDS is blocking and takes a very long time. Then you have to wait until IDS is finished and the time limit may not be all that precise.

I'm not sure exactly what you mean by

would like to return the value from the deepest search after a certain amount of time has passed.

and

The problem with this code is it will not return until after the time limit has passed.

If you have time limits and you have update times then you can use this code as a generator.

import time

answers = []
START = time.clock()
current_depth = 1

def get_ids(update_time, limit_time):
    last_update = time.clock()
    while time.clock() - START < DESIRED_RUN_TIME:
        answers.append(IDS(depth=current_depth))
        current_depth += 1
        if time.clock() - last_update < update_time:
            last_update = time.clock()
            yield answers[-1]

    yield answers[-1]

for i in get_ids(1, 10):  # get an ids every second and stop after 10 seconds
    print(i)


问:
Cannot get node server to proxy to nginx on RedHat Ec2 Instance
I have a redhat Ec2 instance. And I have a simple Express App running on port 3000. I installed nginx and it is running correctly because I am able to proxy s3 buckets static sites to other subdomains I am using. However, when I try and proxy my Express app to one of my subdomains I keep getting the nginx failure page. Here is my nginx config block I am using:

```<code>server {
    listen       80;
    listen      api.subdoamin.com:80;
    server_name  api.grouve.tech;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_pass http://00.000.00.000:3000;
            expires 1y;
            log_not_found off;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
     error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}
</code>```

答: Thanks to @DusanBajic the answer is sudo setenforce 0

Body:
I have a redhat Ec2 instance. And I have a simple Express App running on port 3000. I installed nginx and it is running correctly because I am able to proxy s3 buckets static sites to other subdomains I am using. However, when I try and proxy my Express app to one of my subdomains I keep getting the nginx failure page. Here is my nginx config block I am using:

server {
    listen       80;
    listen      api.subdoamin.com:80;
    server_name  api.grouve.tech;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_pass http://00.000.00.000:3000;
            expires 1y;
            log_not_found off;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
     error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}


问:
Repeat state until it doesn't change / is stable
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

```<code>Eq s => State s () -> State s ()
</code>```

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

答:
You can do this in State, but there's no particular benefit. Why not:

```<code>idempotently :: Eq a => (a -> a) -> a -> a
idempotently f a = if a' == a then a else idempotently f a' where a' = f a

idempotentlyM :: Eq s => (s -> s) -> State s ()
idempotentlyM f = modify (idempotently f)
</code>```

If you start with a State s (), you can execState it to get your s -> s out.

Of course, there's no guarantee that f doesn't diverge, so idempotently f may never terminate.

Body:
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

Eq s => State s () -> State s ()

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

Body:
You can do this in State, but there's no particular benefit. Why not:

idempotently :: Eq a => (a -> a) -> a -> a
idempotently f a = if a' == a then a else idempotently f a' where a' = f a

idempotentlyM :: Eq s => (s -> s) -> State s ()
idempotentlyM f = modify (idempotently f)

If you start with a State s (), you can execState it to get your s -> s out.

Of course, there's no guarantee that f doesn't diverge, so idempotently f may never terminate.


问:
Caching policies and techniques for matrices
as explained before, I'm currently working on a small linear algebra library to use in a personal project. Matrices are implemented as C++ vectors and element assignment ( a(i,j) = v; ) is delegated to the assignment to the vector's elements. For my project I'll need to solve tons of square equation systems and, in order to do that, I implemented the LU factorization (Gaussian Elimination) for square matrices. In the current implementation I'm avoiding to recalculate each time the LU factorization by caching the L and U matrices, the problem is that since I'm delegating the element assignment to vector, I can't find a way to say if the matrix is being changed and whether to recalculate the factorization. Any ideas on how to solve this?

Thank you

答: What about keeping a complete hidden copy of the Matrix used with the last LU factorization and check it in O(n*m) time before re-doing it? Ugly but could work.</p>

OwnerDisplayName: Tunnuz

LastEditorDisplayName: Tunnuz


问:
PayPal Adaptive Payments Service 550001 Error
I have implemented a functionality into the admin panel where the admin can release the fund to seller (I am not sure but think this is what we called Adaptive Payments).

A buyer is paying some amount to the admin of application now the admin can release the funds to seller from the admin panel.

All this is working perfect on sandbox, but when I have updated the credentials to the live its showing me the error.

Here is my code.

```<code>$payRequest = new PayRequest();
/*
$receiver is
array:1 [▼
  0 => Receiver {#278 ▼
    +amount: 35.0
    +email: "me****p4@gmail.com"
    +phone: null
    +primary: null
    +invoiceId: null
    +paymentType: null
    +paymentSubType: null
    +accountId: null
  }
]
*/
$receiverList = new ReceiverList($receiver);
$payRequest->receiverList = $receiverList;
$payRequest->senderEmail = "sender@email.com";

$requestEnvelope = new RequestEnvelope("en_US");
$payRequest->requestEnvelope = $requestEnvelope;
$payRequest->actionType = "PAY";
$payRequest->currencyCode = $payment->currency_code;
$payRequest->ipnNotificationUrl = "http://replaceIpnUrl.com";

$sdkConfig = $this->config();
$adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
$payResponse = $adaptivePaymentsService->Pay($payRequest);
</code>```

I am getting error 550001, here is the complete error:

```<code>PayPal\Types\AP\PayResponse Object
(
    [responseEnvelope] => PayPal\Types\Common\ResponseEnvelope Object
        (
            [timestamp] => 2017-06-05T05:16:36.032-07:00
            [ack] => Failure
            [correlationId] => b828f2378a7e
            [build] => 32250686
        )

    [payKey] =>
    [paymentExecStatus] =>
    [payErrorList] =>
    [paymentInfoList] =>
    [sender] =>
    [defaultFundingPlan] =>
    [warningDataList] =>
    [error] => Array
        (
            [0] => PayPal\Types\Common\ErrorData Object
                (
                    [errorId] => 550001
                    [domain] => PLATFORM
                    [subdomain] => Application
                    [severity] => Error
                    [category] => Application
                    [message] => You do not have permission to execute this payment implicitly
                    [exceptionId] =>
                    [parameter] =>
                )
        )
)
</code>```

I have searched a lot about this but did not get any clue. Can someone help me on this.

答: It may be due to your application does not include the implicit payment. As far as I knew, PayPal does not supported for the implicit payment for the new application. Check you App ID again to confirm which application has been granted to your account.</p>

Body:
I have implemented a functionality into the admin panel where the admin can release the fund to seller (I am not sure but think this is what we called Adaptive Payments).

A buyer is paying some amount to the admin of application now the admin can release the funds to seller from the admin panel.

All this is working perfect on sandbox, but when I have updated the credentials to the live its showing me the error.

Here is my code.

$payRequest = new PayRequest();
/*
$receiver is
array:1 [▼
  0 => Receiver {#278 ▼
    +amount: 35.0
    +email: "me****p4@gmail.com"
    +phone: null
    +primary: null
    +invoiceId: null
    +paymentType: null
    +paymentSubType: null
    +accountId: null
  }
]
*/
$receiverList = new ReceiverList($receiver);
$payRequest->receiverList = $receiverList;
$payRequest->senderEmail = "sender@email.com";

$requestEnvelope = new RequestEnvelope("en_US");
$payRequest->requestEnvelope = $requestEnvelope;
$payRequest->actionType = "PAY";
$payRequest->currencyCode = $payment->currency_code;
$payRequest->ipnNotificationUrl = "http://replaceIpnUrl.com";

$sdkConfig = $this->config();
$adaptivePaymentsService = new AdaptivePaymentsService($sdkConfig);
$payResponse = $adaptivePaymentsService->Pay($payRequest);

I am getting error 550001, here is the complete error:

PayPal\Types\AP\PayResponse Object
(
    [responseEnvelope] => PayPal\Types\Common\ResponseEnvelope Object
        (
            [timestamp] => 2017-06-05T05:16:36.032-07:00
            [ack] => Failure
            [correlationId] => b828f2378a7e
            [build] => 32250686
        )

    [payKey] =>
    [paymentExecStatus] =>
    [payErrorList] =>
    [paymentInfoList] =>
    [sender] =>
    [defaultFundingPlan] =>
    [warningDataList] =>
    [error] => Array
        (
            [0] => PayPal\Types\Common\ErrorData Object
                (
                    [errorId] => 550001
                    [domain] => PLATFORM
                    [subdomain] => Application
                    [severity] => Error
                    [category] => Application
                    [message] => You do not have permission to execute this payment implicitly
                    [exceptionId] =>
                    [parameter] =>
                )
        )
)

I have searched a lot about this but did not get any clue. Can someone help me on this.


问:
How to comment SQL statements in Notepad++?
How can I "block comment" SQL statements in Notepad++?

For example:

```<code>CREATE TABLE gmr_virtuemart_calc_categories (
  id int(1) UNSIGNED NOT NULL,
  virtuemart_calc_id int(1) UNSIGNED NOT NULL DEFAULT '0',
  virtuemart_category_id int(1) UNSIGNED NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

It should be wrapped with /* at the start and */ at the end using regex in Notepad++ to produce:

```<code>/*CREATE TABLE ... (...) ENGINE=MyISAM DEFAULT CHARSET=utf8;*/
</code>```

答:
You could use a recursive regex.

I think NP uses boost or PCRE.

This works with both.

https://regex101.com/r/P75bXC/1

Find (?s)(CREATE\s+TABLE[^(]*(\((?:[^()']++|'.*?'|(?2))*\))(?:[^;']|'.*?')*;)

Replace /*$1*/

Explained

```<code> (?s)                           # Dot-all modifier
 (                              # (1 start) The whole match
      CREATE \s+ TABLE [^(]*    # Create statement
      (                              # (2 start), Recursion code group
           \(
           (?:                            # Cluster group
                [^()']++                       # Possesive, not parenth's or quotes
             |                               # or,
                ' .*? '                        # Quotes (can wrap in atomic group if need be)
             |                               # or,
                (?2)                           # Recurse to group 2
           )*                             # End cluster, do 0 to many times
           \)
      )                              # (2 end)
                                     # Trailer before colon statement end
      (?:                            # Cluster group, can be atomic (?> ) if need be
           [^;']                          # Not quote or colon
        |                               # or,
           ' .*? '                        # Quotes
      )*                             # End cluster, do 0 to many times
      ;                              # Colon at the end
 )                              # (1 end)
</code>```

Body:
How can I "block comment" SQL statements in Notepad++?

For example:

CREATE TABLE gmr_virtuemart_calc_categories (
  id int(1) UNSIGNED NOT NULL,
  virtuemart_calc_id int(1) UNSIGNED NOT NULL DEFAULT '0',
  virtuemart_category_id int(1) UNSIGNED NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

It should be wrapped with /* at the start and */ at the end using regex in Notepad++ to produce:

/*CREATE TABLE ... (...) ENGINE=MyISAM DEFAULT CHARSET=utf8;*/

Body:
You could use a recursive regex.

I think NP uses boost or PCRE.

This works with both.

https://regex101.com/r/P75bXC/1

Find (?s)(CREATE\s+TABLE[^(]*(\((?:[^()']++|'.*?'|(?2))*\))(?:[^;']|'.*?')*;)

Replace /*$1*/

Explained

 (?s)                           # Dot-all modifier
 (                              # (1 start) The whole match
      CREATE \s+ TABLE [^(]*    # Create statement
      (                              # (2 start), Recursion code group
           \(
           (?:                            # Cluster group
                [^()']++                       # Possesive, not parenth's or quotes
             |                               # or,
                ' .*? '                        # Quotes (can wrap in atomic group if need be)
             |                               # or,
                (?2)                           # Recurse to group 2
           )*                             # End cluster, do 0 to many times
           \)
      )                              # (2 end)
                                     # Trailer before colon statement end
      (?:                            # Cluster group, can be atomic (?> ) if need be
           [^;']                          # Not quote or colon
        |                               # or,
           ' .*? '                        # Quotes
      )*                             # End cluster, do 0 to many times
      ;                              # Colon at the end
 )                              # (1 end)


问:
How to check the type of multiple variables in SASS
I have created a large number of SASS variables which I need to check that they are in the correct format after a user has changed them.

For example, I have the following variables:

```<code>$varible1: true;
$variable2: false;
$variable3: true;
$variable4: "400, 500, 600";
$variable5: true;
$variable6: "foo bar buzz";
$variable7: 4;
$variable8: 9;
etc...
</code>```

As you can see, not all my variables are booleans, some are numbers or strings too. However, each variable will always be expected to be a certain type ($variable5 should always be a boolean etc). What I want to do is check each variables type and give out an error message if it is incorrect. I have written the following @if statement to check the first variable:

```<code>@if type-of($variable1) != bool {
    @error "'#{$variable1}' is not a valid value for $variable1, you must use a boolean.";
}
</code>```

The problem is, I'm going to end up with a list of 30+ @if statements to check each variable. Is there a way that I can check $variable1, $variable2, $variable3 and $variable5 in one @if statement, and pass the variable name and value into the error message?

My only idea so far has to create another variable that is a list of all the variables I expect to be a boolean and then do an @each loop over it, something like:

```<code>$boolean-variables: $variable1, $variable2, $variable3...
@each $var in $boolean-variables {
    @if type-of($var) != bool {
        @error "'#{$var}' is not a valid value for $var, you must use a boolean.";
    }
}
</code>```

Is this a good way of doing it, or are there other suggestions? Thanks

答:
For those interested, I ended up using a map of the variable names and types and then looped over then, injecting the name and type into an error message.

I did however run into a couple of issues setting up the map. Firstly, the key cannot be a variable, as this returns the variable value rather than the name. I got round this by using the name of the variable, minus the $. This allowed me to see which variable I was looking at whilst still working as a key. Secondly, I needed to have the value of the variables, as well as the type. I set up the value for each pair to be another map, with the variable as the key and the type as the value. This meant I could then run another loop over this data to check these values. Below is an example of how my map was structured:

```<code>$setting-types: (
    variable-name1: ($variable-name1: bool),
    variable-name2: ($variable-name2: bool),
    variable-name3: ($variable-name3: list)
}
</code>```

This effectively returns:

```<code>$setting-types: (
    variable-name1: (true: bool),
    variable-name2: (false: bool),
    variable-name3: (foo, bar, buzz: list)
}
</code>```

I was then able to run an @each function over the map like so:

```<code>@each $setting, $data in $setting-types {
    $setting-name: $setting;
    @each $variable, $type in $data {
        @if type-of($variable) != $type {
            @error "'#{$variable}' is not a valid value for $#{$setting-name}, you must use a #{$type}.";
        }
    }
}
</code>```

The first loop splits each variable in the map, and then the second loop goes over the variable value and expected data type. I then use type-of() to check what the data type for the variable is and if does not match what is written in the map, then the error is shown. I also set another variable after the first loop, which is just the key from the first loop, but can then be accessed in the second loop to help provide some clarity in the error message.

I hope this is clear enough for others to understand, should they need to do something similar.

Body:
I have created a large number of SASS variables which I need to check that they are in the correct format after a user has changed them.

For example, I have the following variables:

$varible1: true;
$variable2: false;
$variable3: true;
$variable4: "400, 500, 600";
$variable5: true;
$variable6: "foo bar buzz";
$variable7: 4;
$variable8: 9;
etc...

As you can see, not all my variables are booleans, some are numbers or strings too. However, each variable will always be expected to be a certain type ($variable5 should always be a boolean etc). What I want to do is check each variables type and give out an error message if it is incorrect. I have written the following @if statement to check the first variable:

@if type-of($variable1) != bool {
    @error "'#{$variable1}' is not a valid value for $variable1, you must use a boolean.";
}

The problem is, I'm going to end up with a list of 30+ @if statements to check each variable. Is there a way that I can check $variable1, $variable2, $variable3 and $variable5 in one @if statement, and pass the variable name and value into the error message?

My only idea so far has to create another variable that is a list of all the variables I expect to be a boolean and then do an @each loop over it, something like:

$boolean-variables: $variable1, $variable2, $variable3...
@each $var in $boolean-variables {
    @if type-of($var) != bool {
        @error "'#{$var}' is not a valid value for $var, you must use a boolean.";
    }
}

Is this a good way of doing it, or are there other suggestions? Thanks

Body:
For those interested, I ended up using a map of the variable names and types and then looped over then, injecting the name and type into an error message.

I did however run into a couple of issues setting up the map. Firstly, the key cannot be a variable, as this returns the variable value rather than the name. I got round this by using the name of the variable, minus the $. This allowed me to see which variable I was looking at whilst still working as a key. Secondly, I needed to have the value of the variables, as well as the type. I set up the value for each pair to be another map, with the variable as the key and the type as the value. This meant I could then run another loop over this data to check these values. Below is an example of how my map was structured:

$setting-types: (
    variable-name1: ($variable-name1: bool),
    variable-name2: ($variable-name2: bool),
    variable-name3: ($variable-name3: list)
}

This effectively returns:

$setting-types: (
    variable-name1: (true: bool),
    variable-name2: (false: bool),
    variable-name3: (foo, bar, buzz: list)
}

I was then able to run an @each function over the map like so:

@each $setting, $data in $setting-types {
    $setting-name: $setting;
    @each $variable, $type in $data {
        @if type-of($variable) != $type {
            @error "'#{$variable}' is not a valid value for $#{$setting-name}, you must use a #{$type}.";
        }
    }
}

The first loop splits each variable in the map, and then the second loop goes over the variable value and expected data type. I then use type-of() to check what the data type for the variable is and if does not match what is written in the map, then the error is shown. I also set another variable after the first loop, which is just the key from the first loop, but can then be accessed in the second loop to help provide some clarity in the error message.

I hope this is clear enough for others to understand, should they need to do something similar.


问:
OpenCL oil painting
I want to implement oil painting filter in OpenCL,but the output image is always black and I cannot figure out why.
Here's the kernel code:</p>

```<code>__kernel void oil_painting(__global const char* R,__global const char* G,__global const char* B,
                 __global char* r,__global char* g,__global char* b)
{
    int i=get_global_id(0);
    int j=get_global_id(1);
    int i1,j1,k;

    int avgR[256],avgG[256],avgB[256],intensity_count[256];
    int max_pixels=0,max_intensity=0,current_intensity;

    for (i1=0;i1<4;i1++) {
        for (j1=0;j1<4;j1++) {
            current_intensity=(((R[(i+i1)*512+j+j1]+
                                 G[(i+i1)*512+j+j1]+
                                 B[(i+i1)*512+j+j1])/3)*70)/255;
            intensity_count[current_intensity]++;

            if (intensity_count[current_intensity]>max_pixels) {
                max_pixels=intensity_count[current_intensity];
                max_intensity=current_intensity;
            }

            avgR[current_intensity]+=R[(i+i1)*512+j+j1];
            avgG[current_intensity]+=G[(i+i1)*512+j+j1];
            avgB[current_intensity]+=B[(i+i1)*512+j+j1];
        }
    }

    r[i*512+j]=min(255,max(0,avgR[max_intensity]/max_pixels));
    g[i*512+j]=min(255,max(0,avgG[max_intensity]/max_pixels));
    b[i*512+j]=min(255,max(0,avgB[max_intensity]/max_pixels));
}
</code>```

答:
Code snippets like the following are going to get you into a lot of trouble:

```<code>current_intensity=(((R[(i+i1)*512+j+j1]+
                     G[(i+i1)*512+j+j1]+
                     B[(i+i1)*512+j+j1])/3)*70)/255;
</code>```

Consider what happens for a pixel of <127,127,127>:

```<code>127 + 127 + 127 = 125 (truncated because `char` is only 8 bytes...)
125 / 3 = 41
41 * 70 = 54 (truncated because `char` is only 8 bytes...)
54 / 255 = 0 (this will always equal 0!)
</code>```

So intensity_count will only ever have its 0-th index incremented, and nothing else.

Casting everything to int might fix this problem.

```<code>current_intensity=((((int)R[(i+i1)*512+j+j1]+
                     (int)G[(i+i1)*512+j+j1]+
                     (int)B[(i+i1)*512+j+j1])/3)*70)/255;
</code>```

New output:

```<code>127 + 127 + 127 = 381
381 / 3 = 127
127 * 70 = 8890
8890 / 255 = 34
</code>```

But you've now got a new problem: what if the values are any higher than 127? Suppose we change this to use <200, 200, 200> instead?

```<code>-56 + -56 + -56 = -168 (`char` only has a range in [-128, 127]! You're overflowing!)
-168 / 3 = -56
-56 * 70 = -3920
-3920 / 255 = -15
</code>```

And now you've crashed your program because either you're going to attempt to access index -15, which is illegal, or you're going to attempt to access index 2^64 - 15 - 1, which is going to still be illegal. Either way, you're going to get bad results.

The simplest solution is to change your kernel arguments to global uchar * instead of global char *, and then make sure that any and all arithmetic is casted upwards to int or long to ensure that overflow doesn't take place.

Title: OpenCL oil painting

Body:
I want to implement oil painting filter in OpenCL,but the output image is always black and I cannot figure out why.
Here's the kernel code:

__kernel void oil_painting(__global const char* R,__global const char* G,__global const char* B,
                 __global char* r,__global char* g,__global char* b)
{
    int i=get_global_id(0);
    int j=get_global_id(1);
    int i1,j1,k;

    int avgR[256],avgG[256],avgB[256],intensity_count[256];
    int max_pixels=0,max_intensity=0,current_intensity;

    for (i1=0;i1<4;i1++) {
        for (j1=0;j1<4;j1++) {
            current_intensity=(((R[(i+i1)*512+j+j1]+
                                 G[(i+i1)*512+j+j1]+
                                 B[(i+i1)*512+j+j1])/3)*70)/255;
            intensity_count[current_intensity]++;

            if (intensity_count[current_intensity]>max_pixels) {
                max_pixels=intensity_count[current_intensity];
                max_intensity=current_intensity;
            }

            avgR[current_intensity]+=R[(i+i1)*512+j+j1];
            avgG[current_intensity]+=G[(i+i1)*512+j+j1];
            avgB[current_intensity]+=B[(i+i1)*512+j+j1];
        }
    }

    r[i*512+j]=min(255,max(0,avgR[max_intensity]/max_pixels));
    g[i*512+j]=min(255,max(0,avgG[max_intensity]/max_pixels));
    b[i*512+j]=min(255,max(0,avgB[max_intensity]/max_pixels));
}

Body:
Code snippets like the following are going to get you into a lot of trouble:

current_intensity=(((R[(i+i1)*512+j+j1]+
                     G[(i+i1)*512+j+j1]+
                     B[(i+i1)*512+j+j1])/3)*70)/255;

Consider what happens for a pixel of <127,127,127>:

127 + 127 + 127 = 125 (truncated because `char` is only 8 bytes...)
125 / 3 = 41
41 * 70 = 54 (truncated because `char` is only 8 bytes...)
54 / 255 = 0 (this will always equal 0!)

So intensity_count will only ever have its 0-th index incremented, and nothing else.

Casting everything to int might fix this problem.

current_intensity=((((int)R[(i+i1)*512+j+j1]+
                     (int)G[(i+i1)*512+j+j1]+
                     (int)B[(i+i1)*512+j+j1])/3)*70)/255;

New output:

127 + 127 + 127 = 381
381 / 3 = 127
127 * 70 = 8890
8890 / 255 = 34

But you've now got a new problem: what if the values are any higher than 127? Suppose we change this to use <200, 200, 200> instead?

-56 + -56 + -56 = -168 (`char` only has a range in [-128, 127]! You're overflowing!)
-168 / 3 = -56
-56 * 70 = -3920
-3920 / 255 = -15

And now you've crashed your program because either you're going to attempt to access index -15, which is illegal, or you're going to attempt to access index 2^64 - 15 - 1, which is going to still be illegal. Either way, you're going to get bad results.

The simplest solution is to change your kernel arguments to global uchar * instead of global char *, and then make sure that any and all arithmetic is casted upwards to int or long to ensure that overflow doesn't take place.


问:
Passwordless sudo login into a server using Ansible
I have an Ansible script using which I would like to run some installation related commands on the remote server. But for installation to go through it is required to be a root user or sudo. I am trying to add the user to the sudoers but it is not working.

```<code>---
- hosts: webservers
  gather_facts: no
  become: yes
  tasks:
        - name: Make sure we have a 'wheel' group
          group:
            name: wheel
            state: present

        - name: Allow 'wheel' group to have passwordless sudo
          lineinfile:
            dest: /etc/sudoers
            state: present
            regexp: '^%wheel'
            line: '%wheel ALL=(ALL) NOPASSWD: ALL'

        - name: Add sudoers users to abkari group
          user: name=abkari groups=wheel append=yes state=present createhome=no
</code>```

On CentOS wheel group is the default group for sudo access. When I run this command it doesn't allow to execute the 1st task. What is the problem here?

答:
You can add "become: yes", under the "name" of your task (at the same level).
It allows to perform the task as sudo.</p>

Body:
I have an Ansible script using which I would like to run some installation related commands on the remote server. But for installation to go through it is required to be a root user or sudo. I am trying to add the user to the sudoers but it is not working.

---
- hosts: webservers
  gather_facts: no
  become: yes
  tasks:
        - name: Make sure we have a 'wheel' group
          group:
            name: wheel
            state: present

        - name: Allow 'wheel' group to have passwordless sudo
          lineinfile:
            dest: /etc/sudoers
            state: present
            regexp: '^%wheel'
            line: '%wheel ALL=(ALL) NOPASSWD: ALL'

        - name: Add sudoers users to abkari group
          user: name=abkari groups=wheel append=yes state=present createhome=no

On CentOS wheel group is the default group for sudo access. When I run this command it doesn't allow to execute the 1st task. What is the problem here?


问:
How to get OneSignal player Ids in Ionic 2
I am using onesignal plugin for an app that I am developing in Ionic 2, the plugin is working. The messages sent from OneSignal are showing in the app but I have a problem when I try to get the player unique id:

This is the code that I use for showing messages, this code works:

```<code> let notificationOpenedCallback = function(jsonData) {
        let alert =alertCtrl.create({
          title: jsonData.notification.payload.title,
          subTitle: jsonData.notification.payload.body,
          buttons: ['OK']
        });
        alert.present();
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window["plugins"].OneSignal
        .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();
</code>```

and this code is for get Ids:

```<code>window["plugins"].OneSignal
             .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
             .endInit();
            window["plugins"].OneSignal.getIds(function(ids){
              firebase.database().ref('usuarios/'+ this.usuarioId).update({
                idOnesignal: ids.userId
              })
</code>```

this code just does not run

答:
I fixed using ionic native onesignal:</p>

```<code>import { OneSignal } from '@ionic-native/onesignal';

constructor(public one: OneSignal) {
   this.bs = firebase.database().ref('/usuarios');
   this.usuarioid = firebase.auth().currentUser.uid;
   this.one.getIds().then((ids) => {this.one_id = ids.userId,
                                    this.bs.child(this.usuarioid).update({idOneSignal: this.one_id})});
  }
</code>```

Body:
I am using onesignal plugin for an app that I am developing in Ionic 2, the plugin is working. The messages sent from OneSignal are showing in the app but I have a problem when I try to get the player unique id:

This is the code that I use for showing messages, this code works:

 let notificationOpenedCallback = function(jsonData) {
        let alert =alertCtrl.create({
          title: jsonData.notification.payload.title,
          subTitle: jsonData.notification.payload.body,
          buttons: ['OK']
        });
        alert.present();
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
      };

      window["plugins"].OneSignal
        .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();

and this code is for get Ids:

window["plugins"].OneSignal
             .startInit("05d411f4-45da-4101-92a5-4a60e5c9fd03", "49543248748")
             .endInit();
            window["plugins"].OneSignal.getIds(function(ids){
              firebase.database().ref('usuarios/'+ this.usuarioId).update({
                idOnesignal: ids.userId
              })

this code just does not run

Body:
I fixed using ionic native onesignal:

import { OneSignal } from '@ionic-native/onesignal';

constructor(public one: OneSignal) {
   this.bs = firebase.database().ref('/usuarios');
   this.usuarioid = firebase.auth().currentUser.uid;
   this.one.getIds().then((ids) => {this.one_id = ids.userId,
                                    this.bs.child(this.usuarioid).update({idOneSignal: this.one_id})});
  }


问:
How can I loop through and pare down an object?
If i have the following:

```<code>{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}
</code>```

How can I morph that into a new object that would look something like this?

```<code>{
    prop: "X",
    apple: 2
},
{
    prop: "Y",
    banana: 2
}
</code>```

答:
You could use a single loop approach with a closure ocer a hash table for collecting the objects with the same prop key.

var data = [{ prop: "X", something: "Apple" }, { prop: "X", something: "Apple" }, { prop: "Y", something: "Banana" }, { prop: "Y", something: "Banana" }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var k2 = a.something.toLowerCase();
            if (!hash[a.prop]) {
                hash[a.prop] = { prop: a.prop };
                hash[a.prop][k2] = 0;
                r.push(hash[a.prop]);
            }
            hash[a.prop][k2]++;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

With more properties to count

var data = [{ prop: "X", something: "Apple", somethingElse: "Orange" }, { prop: "X", something: "Apple" }, { prop: "Y", something: "Banana" }, { prop: "Y", something: "Banana" }],
    result = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.prop]) {
                hash[o.prop] = { prop: o.prop };
                r.push(hash[o.prop]);
            }
            Object.keys(o).forEach(function (k) {
                var k2 = o[k].toLowerCase();
                if (k !== 'prop') {
                    hash[o.prop][k2] = (hash[o.prop][k2] || 0) + 1;
                }
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
If i have the following:

{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}

How can I morph that into a new object that would look something like this?

{
    prop: "X",
    apple: 2
},
{
    prop: "Y",
    banana: 2
}

Body:
You could use a single loop approach with a closure ocer a hash table for collecting the objects with the same prop key.

var data = [{ prop: "X", something: "Apple" }, { prop: "X", something: "Apple" }, { prop: "Y", something: "Banana" }, { prop: "Y", something: "Banana" }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var k2 = a.something.toLowerCase();
            if (!hash[a.prop]) {
                hash[a.prop] = { prop: a.prop };
                hash[a.prop][k2] = 0;
                r.push(hash[a.prop]);
            }
            hash[a.prop][k2]++;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

With more properties to count

var data = [{ prop: "X", something: "Apple", somethingElse: "Orange" }, { prop: "X", something: "Apple" }, { prop: "Y", something: "Banana" }, { prop: "Y", something: "Banana" }],
    result = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.prop]) {
                hash[o.prop] = { prop: o.prop };
                r.push(hash[o.prop]);
            }
            Object.keys(o).forEach(function (k) {
                var k2 = o[k].toLowerCase();
                if (k !== 'prop') {
                    hash[o.prop][k2] = (hash[o.prop][k2] || 0) + 1;
                }
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How return list object to show in view
I have controller where I use service. That service do some querys and return List like this:

Controller:

```<code> public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }
</code>```

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

```<code><div id="event_box" class="margin-bottom-10"></div>
</code>```

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

```<code> return Json(consulta, JsonRequestBehavior.AllowGet);
</code>```

but How can I receive specific object into view?

答:
As  Mike McCaughan mentioned you should go throught some tutorials.

You have multiple options based on this

ViewBag

The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view

@model Keyword

Strongly typed class.
example

```<code>public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}
</code>```

then accessing model in view:

Title: How return list object to show in view

Body:
I have controller where I use service. That service do some querys and return List like this:

Controller:

 public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

 return Json(consulta, JsonRequestBehavior.AllowGet);

but How can I receive specific object into view?

Body:
As  Mike McCaughan mentioned you should go throught some tutorials.

You have multiple options based on this

ViewBag

The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view

@model Keyword

Strongly typed class.
example

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

then accessing model in view:


问:
How to ssr to replace all string in kdb?
table dd

```<code>dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)
</code>```

result:

```<code>"account=abcde;cash=123"    1
"account=abc;cash=345"      2
</code>```

I want to replace everything in account:
so the result should be

```<code>"replace;cash=123"  1
"replace;cash=345"  2
</code>```

I tried this

```<code>update ssr[;"account=* ;";""] each a from dd
</code>```

but it didn't work.

答:
Try the following:</p>

```<code>q)update {";"sv @[s;where (s:";"vs x) like "account=*";:;enlist"newVal=123"]}each a from dd
</code>```

Body:
table dd

dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)

result:

"account=abcde;cash=123"    1
"account=abc;cash=345"      2

I want to replace everything in account:
so the result should be

"replace;cash=123"  1
"replace;cash=345"  2

I tried this

update ssr[;"account=* ;";""] each a from dd

but it didn't work.

Body:
Try the following:

q)update {";"sv @[s;where (s:";"vs x) like "account=*";:;enlist"newVal=123"]}each a from dd


问:
Can radio buttons be bound to an attached behavior in XAML?
In XAML, I have a set of radio buttons as:

```<code><RadioButton Width="25"
             Height="25"
             Foreground="Blue"
             IsChecked="{Binding ??????, Converter={StaticResource StrokeTypeConverter}, ConverterParameter="Ellipse}"
             GroupName="StrokeTypeGroup" />
</code>```

The purpose of each radio button of the "StylusTypeGroup" is to allow selection of either an "Ellipse" , "Line" , or "Rectangle" custom stroke, etc...

Further down in the XAML, I have a behavior tied to an InkCanvas like:

```<code>  <InkCanvas x:Name="MainInkCanvas"
             Grid.Column="1"
             Grid.Row="1"
             Background="Transparent"
             DefaultDrawingAttributes="{Binding CurrentPen.Pen}"
             EditingMode="{Binding EditingMode}">
          <i:Interaction.Behaviors>
                 <b:MainInkCanvasBehavior CustomStrokeType = "{Binding???????}" />
           </i:Interaction.Behaviors>
</code>```

Is there any way using just the XAML code, to bind the result of checking any one (of multiple) radio buttons directly to the CustomStrokeType dependency property of the MainInkCanvasBehavior behavior?  Or am I forced to bind to a property on the viewmodel (as kind of a holding property)?

TIA

答:
The least amount of effort is to create a new property, CheckedRadioButtonID, bind that to your CustomStrokeType and use an IValueConverter to take an int and return a Stroke.  The key is that when the radio button is clicked, you also want to raise an INotifyPropertyEvent for the CheckedRadioButtonID.

```<code>   public int CheckedRadioButtonID
    {
get
{
  if(IsAChecked) return 1;
/// ...
}
     // returns 1,2,3... (number of radio buttons you have)
    //  Implements INotifyPropertyChanged
    }

    public bool IsAChecked
    {
     set
    {
     // when this is set... also raise CheckedRadioButtonID  property changed
    }
    }
</code>```

In XAML bind to CheckedRadioButtonID and have a IValueConverter take an int and return a Stroke.

If you really want to use a MultiValueConverter it would like like this

```<code>                     <b:MainInkCanvasBehavior >
    <b:MainInkCanvasBehavior.CustomStrokeType>
    <MultiBinding Converter="{StaticResource MultiValueConverterThatReturnsStroke}">
                        <Binding ElementName="RadioButton1" Path="IsChecked"></Binding>
                        <Binding ElementName="RadioButton2" Path="IsChecked"></Binding>
                    </MultiBinding>
    </b:MainInkCanvasBehavior.CustomStrokeType>
</b:MainInkCanvasBehavior>
</code>```

Body:
In XAML, I have a set of radio buttons as:

<RadioButton Width="25"
             Height="25"
             Foreground="Blue"
             IsChecked="{Binding ??????, Converter={StaticResource StrokeTypeConverter}, ConverterParameter="Ellipse}"
             GroupName="StrokeTypeGroup" />

The purpose of each radio button of the "StylusTypeGroup" is to allow selection of either an "Ellipse" , "Line" , or "Rectangle" custom stroke, etc...

Further down in the XAML, I have a behavior tied to an InkCanvas like:

  <InkCanvas x:Name="MainInkCanvas"
             Grid.Column="1"
             Grid.Row="1"
             Background="Transparent"
             DefaultDrawingAttributes="{Binding CurrentPen.Pen}"
             EditingMode="{Binding EditingMode}">

Is there any way using just the XAML code, to bind the result of checking any one (of multiple) radio buttons directly to the CustomStrokeType dependency property of the MainInkCanvasBehavior behavior?  Or am I forced to bind to a property on the viewmodel (as kind of a holding property)?

TIA

Body:
The least amount of effort is to create a new property, CheckedRadioButtonID, bind that to your CustomStrokeType and use an IValueConverter to take an int and return a Stroke.  The key is that when the radio button is clicked, you also want to raise an INotifyPropertyEvent for the CheckedRadioButtonID.

   public int CheckedRadioButtonID
    {
get
{
  if(IsAChecked) return 1;
/// ...
}
     // returns 1,2,3... (number of radio buttons you have)
    //  Implements INotifyPropertyChanged
    }

    public bool IsAChecked
    {
     set
    {
     // when this is set... also raise CheckedRadioButtonID  property changed
    }
    }

In XAML bind to CheckedRadioButtonID and have a IValueConverter take an int and return a Stroke.

If you really want to use a MultiValueConverter it would like like this

                     <b:MainInkCanvasBehavior >
    <b:MainInkCanvasBehavior.CustomStrokeType>
    <MultiBinding Converter="{StaticResource MultiValueConverterThatReturnsStroke}">
                        <Binding ElementName="RadioButton1" Path="IsChecked"></Binding>
                        <Binding ElementName="RadioButton2" Path="IsChecked"></Binding>
                    </MultiBinding>
    </b:MainInkCanvasBehavior.CustomStrokeType>
</b:MainInkCanvasBehavior>


问:
Assign key and variable without need to assign in Schema
I have the following mongodb / mongoose Schema

```<code>var forumReplySchema   = new Schema({
    userid : String,
    username: String,
    forumid: {type: String, default: '1'},
    message: {type: String, default: ''},
    time: Number,
});

module.exports = mongoose.model('forum_replies', forumReplySchema);
</code>```

with following query:

```<code>     forum_replies.findOne({forumid: forumid}).then(function (reply) {
    currentReply.username = user.username;
currentReply.rank = result.rank;

});
</code>```

Currently username is assigned cause i have username property in the Schema.
Rank is not assigned cause its not in the Schema.

But is there a way for me to assign rank, without having it defined in the Schema?

Edit: aka, assign rank to the forum replies object without the need to save in Db.

答:
you cannot add properties to mongoose document. If you want to do so, you will need to convert it into plain object first. There are couple of ways you could go about it. Following is one of them.

```<code>reply.toObject();
</code>```

Then you can add properties to it.

```<code>//you have currentReply in your code, I just want to show general idea here
reply.rank = result.rank;
</code>```

Is this what you are looking for?

Update:

Thanks for accepting answer :). Also look into lean() option, this returns you plain JS objects without you having to do the conversion manually. lean() also has performance benefit.

Body:
I have the following mongodb / mongoose Schema

var forumReplySchema   = new Schema({
    userid : String,
    username: String,
    forumid: {type: String, default: '1'},
    message: {type: String, default: ''},
    time: Number,
});

module.exports = mongoose.model('forum_replies', forumReplySchema);

with following query:

     forum_replies.findOne({forumid: forumid}).then(function (reply) {
    currentReply.username = user.username;
currentReply.rank = result.rank;

});

Currently username is assigned cause i have username property in the Schema.
Rank is not assigned cause its not in the Schema.

But is there a way for me to assign rank, without having it defined in the Schema?

Edit: aka, assign rank to the forum replies object without the need to save in Db.

Body:
you cannot add properties to mongoose document. If you want to do so, you will need to convert it into plain object first. There are couple of ways you could go about it. Following is one of them.

reply.toObject();

Then you can add properties to it.

//you have currentReply in your code, I just want to show general idea here
reply.rank = result.rank;

Is this what you are looking for?

Update:

Thanks for accepting answer :). Also look into lean() option, this returns you plain JS objects without you having to do the conversion manually. lean() also has performance benefit.


问:
Lucene: Norwegian Analyser - java.lang.NoSuchMethodError: org.apache.lucene.analysis.WordlistLoader.getSnowballWordSet
I am getting exception while deployment of project having newly implemented Norwegian Analyser

```<code>@Fields({ @Field(index = Index.YES, store = Store.YES, analyzer = @Analyzer(impl=NorwegianAnalyzer.class))
</code>```

Detailed Stack trace of error is :

```<code>Caused by: org.hibernate.search.SearchException: Failed to instantiate lucene analyzer with type org.apache.lucene.analysis.no.NorwegianAnalyzer
        at org.hibernate.search.engine.impl.AnnotationProcessingHelper.getAnalyzer(AnnotationProcessingHelper.java:170)
        at org.hibernate.search.engine.impl.FieldMetadata.<init>(FieldMetadata.java:94)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.bindFieldAnnotation(AbstractDocumentBuilder.java:1085)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.checkForFields(AbstractDocumentBuilder.java:552)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeMemberLevelAnnotations(AbstractDocumentBuilder.java:485)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeClass(AbstractDocumentBuilder.java:392)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.<init>(AbstractDocumentBuilder.java:174)
        at org.hibernate.search.engine.spi.DocumentBuilderContainedEntity.<init>(DocumentBuilderContainedEntity.java:60)
        at org.hibernate.search.spi.SearchFactoryBuilder.initDocumentBuilders(SearchFactoryBuilder.java:396)
        at org.hibernate.search.spi.SearchFactoryBuilder.buildNewSearchFactory(SearchFactoryBuilder.java:222)
        at org.hibernate.search.spi.SearchFactoryBuilder.buildSearchFactory(SearchFactoryBuilder.java:146)
        at org.hibernate.search.event.impl.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:130)
        at org.hibernate.search.hcore.impl.HibernateSearchIntegrator.integrate(HibernateSearchIntegrator.java:83)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1797)
        at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
        at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
        ... 42 more
Caused by: org.hibernate.search.SearchException: Unable to instantiate analyzer class: org.apache.lucene.analysis.no.NorwegianAnalyzer. Verify it has a no-args public constructor and is not abstract. Also Analyzer implementation classes or their tokenStream() and reusableTokenStream() implementations must be final.
        at org.hibernate.search.util.impl.ClassLoaderHelper.analyzerInstanceFromClass(ClassLoaderHelper.java:234)
        at org.hibernate.search.engine.impl.AnnotationProcessingHelper.getAnalyzer(AnnotationProcessingHelper.java:161)
        ... 64 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.hibernate.search.util.impl.ClassLoaderHelper.analyzerInstanceFromClass(ClassLoaderHelper.java:215)
        ... 65 more
Caused by: java.lang.NoSuchMethodError: org.apache.lucene.analysis.WordlistLoader.getSnowballWordSet(Ljava/lang/Class;Ljava/lang/String;)Ljava/util/Set;
        at org.apache.lucene.analysis.no.NorwegianAnalyzer$DefaultSetHolder.<clinit>(NorwegianAnalyzer.java:65)
        at org.apache.lucene.analysis.no.NorwegianAnalyzer.<init>(NorwegianAnalyzer.java:79)
</code>```

Any idea how to resolve the same?

答:
The org.apache.lucene.analysis.no.NorwegianAnalyzer mentioned in the stacktrace seems to not match the expected version of org.apache.lucene.analysis.WordlistLoader.

Since in recent versions of Apache Lucene both classes are included in the same jar, it seems likely that you have some duplicate versions of Lucene jars in your classpath.

Make sure to use only jars from the Apache Lucene version matching the version expected by Hibernate Search.

Body:
I am getting exception while deployment of project having newly implemented Norwegian Analyser

@Fields({ @Field(index = Index.YES, store = Store.YES, analyzer = @Analyzer(impl=NorwegianAnalyzer.class))

Detailed Stack trace of error is :

Caused by: org.hibernate.search.SearchException: Failed to instantiate lucene analyzer with type org.apache.lucene.analysis.no.NorwegianAnalyzer
        at org.hibernate.search.engine.impl.AnnotationProcessingHelper.getAnalyzer(AnnotationProcessingHelper.java:170)
        at org.hibernate.search.engine.impl.FieldMetadata.<init>(FieldMetadata.java:94)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.bindFieldAnnotation(AbstractDocumentBuilder.java:1085)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.checkForFields(AbstractDocumentBuilder.java:552)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeMemberLevelAnnotations(AbstractDocumentBuilder.java:485)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeClass(AbstractDocumentBuilder.java:392)
        at org.hibernate.search.engine.spi.AbstractDocumentBuilder.<init>(AbstractDocumentBuilder.java:174)
        at org.hibernate.search.engine.spi.DocumentBuilderContainedEntity.<init>(DocumentBuilderContainedEntity.java:60)
        at org.hibernate.search.spi.SearchFactoryBuilder.initDocumentBuilders(SearchFactoryBuilder.java:396)
        at org.hibernate.search.spi.SearchFactoryBuilder.buildNewSearchFactory(SearchFactoryBuilder.java:222)
        at org.hibernate.search.spi.SearchFactoryBuilder.buildSearchFactory(SearchFactoryBuilder.java:146)
        at org.hibernate.search.event.impl.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:130)
        at org.hibernate.search.hcore.impl.HibernateSearchIntegrator.integrate(HibernateSearchIntegrator.java:83)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1797)
        at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
        at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
        ... 42 more
Caused by: org.hibernate.search.SearchException: Unable to instantiate analyzer class: org.apache.lucene.analysis.no.NorwegianAnalyzer. Verify it has a no-args public constructor and is not abstract. Also Analyzer implementation classes or their tokenStream() and reusableTokenStream() implementations must be final.
        at org.hibernate.search.util.impl.ClassLoaderHelper.analyzerInstanceFromClass(ClassLoaderHelper.java:234)
        at org.hibernate.search.engine.impl.AnnotationProcessingHelper.getAnalyzer(AnnotationProcessingHelper.java:161)
        ... 64 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.hibernate.search.util.impl.ClassLoaderHelper.analyzerInstanceFromClass(ClassLoaderHelper.java:215)
        ... 65 more
Caused by: java.lang.NoSuchMethodError: org.apache.lucene.analysis.WordlistLoader.getSnowballWordSet(Ljava/lang/Class;Ljava/lang/String;)Ljava/util/Set;
        at org.apache.lucene.analysis.no.NorwegianAnalyzer$DefaultSetHolder.<clinit>(NorwegianAnalyzer.java:65)
        at org.apache.lucene.analysis.no.NorwegianAnalyzer.<init>(NorwegianAnalyzer.java:79)

Any idea how to resolve the same?


问:
Put cursor inside input box onChange in React
I have a component of basic editable list items that operates as such:

My problem is that the cursor does not move into the input box onChange, making a hassle for the user to always click twice. I tried https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js but it did not work. Component looks like:

```<code>import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = ['renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd'];
        super(props, custom_methods);
        this.state = {editing: null};
    }

    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                />
            );
        } else {
            return (
                <li
                  onClick={this.toggleEditing.bind(null, item.id)}
                  key={item.id}
                  className="list-group-item">
                    {item.name}
                </li>
            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }<li key={item.id}>
                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //   </li> */}

              );
          });
        }

        return (
          <div>
            <h4>{this.props.title}:</h4>
                <ul className="list-group">
                    {li_elements}
                </ul>
          </div>
        );
    }
}
</code>```

The items I'm working with now only have a name and ID (type denotes a 'role' or 'task')

How can I make the cursor start at the end of the input box text on change?

答:
I ended up setting focus as in the callback that causes the input box to show:

```<code>toggleEditing(item_id) {
        // this syntax runs the function after this.setState is finished
        this.setState({editing: item_id}, function() {
            this.textInput.focus();
        });
    }
</code>```

Then the original solution given worked:

```<code>   // https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js
    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }
</code>```

and

```<code> <input
      onKeyDown={ this.handleEditField }
      type="text"
      className="form-control"
      ref={(input) => { this.textInput = input; }}
      name="title"
      autofocus
      onFocus={this.moveCaretAtEnd}
      defaultValue={ item.name }
      onChange={(event) => this.editItem(event)}
      style={ {maxWidth: 500} }
    />
</code>```

Body:
I have a component of basic editable list items that operates as such:

My problem is that the cursor does not move into the input box onChange, making a hassle for the user to always click twice. I tried https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js but it did not work. Component looks like:

import React from 'react';

import MyComponent from '../utils/MyComponent';

export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = ['renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd'];
        super(props, custom_methods);
        this.state = {editing: null};
    }

    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField }
                  type="text"
                  className="form-control"
                  ref={ `${item.type}_name_${ item.id }` }
                  name="title"
                  autofocus
                  onFocus={this.moveCaretAtEnd}
                  defaultValue={ item.name }
                />
            );
        } else {
            return (

                    {item.name}

            );
        }
    }

    toggleEditing(item_id) {
        this.setState({editing: item_id});
    }

    render() {
        let li_elements = null;
        let items = this.props.items;

        if (items.length > 0) {
          li_elements = items.map((item) => {
              return (
                  this.renderItemOrEditField(item)
                //   {/* }

                //       {item.name} -
                //       <button onClick={() => {this.props.deleteCallback(this.props.item_type, item.id, item.name)} }>
                //         Delete
                //       </button>
                //
 */}

              );
          });
        }

        return (

{this.props.title}:

                    {li_elements}

        );
    }
}

The items I'm working with now only have a name and ID (type denotes a 'role' or 'task')

How can I make the cursor start at the end of the input box text on change?

Body:
I ended up setting focus as in the callback that causes the input box to show:

toggleEditing(item_id) {
        // this syntax runs the function after this.setState is finished
        this.setState({editing: item_id}, function() {
            this.textInput.focus();
        });
    }

Then the original solution given worked:

   // https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js
    moveCaretAtEnd(e) {
        var temp_value = e.target.value
        e.target.value = ''
        e.target.value = temp_value
    }

and

 <input
      onKeyDown={ this.handleEditField }
      type="text"
      className="form-control"
      ref={(input) => { this.textInput = input; }}
      name="title"
      autofocus
      onFocus={this.moveCaretAtEnd}
      defaultValue={ item.name }
      onChange={(event) => this.editItem(event)}
      style={ {maxWidth: 500} }
    />


问:
Optimize MIN & MAX query
My database table consists of more than 10 million records. I am writing a query containing MIN and MAX functions on the created_date column which I already indexed. But when I am running my select statement it takes too much time and some times execution time get over and do not receive any output.

Is there any way to optimize my query. The query I am trying is below.

```<code>SELECT MIN(created_date) AS Min, MAX(created_date) as Max FROM network ORDER
BY id DESC LIMIT 1000000
</code>```

The above query will give you MIN AND MAX,created_date from the last latest 1 000 000 rows.

答:
```<code>SELECT MIN(created_date) AS Min,
       MAX(created_date) AS Max   -- Get min and max from the 1M rows
    FROM (
        SELECT created_date
            FROM network
            ORDER BY created_date desc
            LIMIT 1000000
         ) AS recent          -- Collect the latest 1M rows
</code>```

This index would help some:

```<code>INDEX(created_date)
</code>```

Rereading question

The latest date is simply MAX(created_date).  The millionth date is `( SELECT created_date FROM network ORDER BY created_date DESC LIMIT 1000000, 1 )

So, this is the first choice:

```<code>SELECT ( SELECT created_date FROM network
            ORDER BY created_date DESC LIMIT 1000000, 1 ) AS Min,
       MAX(created_date) AS Max
    FROM network;
</code>```

Summary Table

```<code>CREATE TABLE Dates (
    create_date DATETIME NOT NULL,
    ct INT UNSIGNED NOT NULL,
    PRIMARY KEY(ct)
) ENGINE=InnoDB;
</code>```

Then, every hour (or other unit of time), count the number of records and store it there.

To find MIN(created_date) is a bit messy; it means summing through that table to find when the count adds up to about 1M, and declaring the hour (or whatever) is when it happened.

Alternatively (and probably better) is to capture the exact DATETIME of each 1000th row.  This means probing network frequently, and storing just the created_date (drop the ct column).  Then this finds the approximate time of the 1M ago:

```<code>SELECT created_date
    FROM Dates
    ORDER BY created_date DESC
    LIMIT 1000, 1
</code>```

(And use that as the subquery for Min.)

Title: Optimize MIN & MAX query

Body:
My database table consists of more than 10 million records. I am writing a query containing MIN and MAX functions on the created_date column which I already indexed. But when I am running my select statement it takes too much time and some times execution time get over and do not receive any output.

Is there any way to optimize my query. The query I am trying is below.

SELECT MIN(created_date) AS Min, MAX(created_date) as Max FROM network ORDER
BY id DESC LIMIT 1000000

The above query will give you MIN AND MAX,created_date from the last latest 1 000 000 rows.

Body:
SELECT MIN(created_date) AS Min,
       MAX(created_date) AS Max   -- Get min and max from the 1M rows
    FROM (
        SELECT created_date
            FROM network
            ORDER BY created_date desc
            LIMIT 1000000
         ) AS recent          -- Collect the latest 1M rows

This index would help some:

INDEX(created_date)

Rereading question

The latest date is simply MAX(created_date).  The millionth date is `( SELECT created_date FROM network ORDER BY created_date DESC LIMIT 1000000, 1 )

So, this is the first choice:

SELECT ( SELECT created_date FROM network
            ORDER BY created_date DESC LIMIT 1000000, 1 ) AS Min,
       MAX(created_date) AS Max
    FROM network;

Summary Table

CREATE TABLE Dates (
    create_date DATETIME NOT NULL,
    ct INT UNSIGNED NOT NULL,
    PRIMARY KEY(ct)
) ENGINE=InnoDB;

Then, every hour (or other unit of time), count the number of records and store it there.

To find MIN(created_date) is a bit messy; it means summing through that table to find when the count adds up to about 1M, and declaring the hour (or whatever) is when it happened.

Alternatively (and probably better) is to capture the exact DATETIME of each 1000th row.  This means probing network frequently, and storing just the created_date (drop the ct column).  Then this finds the approximate time of the 1M ago:

SELECT created_date
    FROM Dates
    ORDER BY created_date DESC
    LIMIT 1000, 1

(And use that as the subquery for Min.)


问:
How can i get a callback for a long press event performed on button
I am trying to get some way to get callback on long press event. I don't know if there is any support provided by the IPHONE sdk  for this.

Do i have to design this functionality by my own or is there anything i am missing to do it.

答: iOS 3.2 and later supports UILongPressGestureRecognizer (documentation).