问:
how to delete or add column in grid panel
grid.getcolumnModel().setHidden(0,true) will be effected for column menu
 and not grid panel. In column menu u can enable or disable the column. How do we add or remove the column in grid panel dynamically?</p>

答:
The reconfigure function might not work well with plugins. Especially if you have something like FilterBar.

If you only need to do this once, based on some global settings that use can use initComponent and change your initial config. Be sure to make all changes to the config before calling this.callParent();

Tested with ExtJS 6.2 (but should also work for ExtJS 4 and 5)

```<code>initComponent: function() {
    // less columns for this setting
    if (!app.Settings.dontUseFruits()) {
        var newColumns = [];
        for(var i=0; i<this.columns.items.length; i++) {
            var column = this.columns.items[i];
            // remove (don't add) columns for which `dataIndex` starts with "fruit"
            if (column.dataIndex.search(/^fruit/) < 0) {
                newColumns.push(column);
            }
        }
        this.columns.items = newColumns;
    }

    this.callParent();
</code>```

Body:
The reconfigure function might not work well with plugins. Especially if you have something like FilterBar.

If you only need to do this once, based on some global settings that use can use initComponent and change your initial config. Be sure to make all changes to the config before calling this.callParent();

Tested with ExtJS 6.2 (but should also work for ExtJS 4 and 5)

initComponent: function() {
    // less columns for this setting
    if (!app.Settings.dontUseFruits()) {
        var newColumns = [];
        for(var i=0; i<this.columns.items.length; i++) {
            var column = this.columns.items[i];
            // remove (don't add) columns for which `dataIndex` starts with "fruit"
            if (column.dataIndex.search(/^fruit/) < 0) {
                newColumns.push(column);
            }
        }
        this.columns.items = newColumns;
    }

    this.callParent();


来源: stackexchange

问:
Using an updated array of objects inside a directive
Within a view I'm using ng-repeat inside a directive to loop over an array of objects from my controller. During this phase the objects inside the array suffer value changes. When I change the view and create a new instance of the same directive, I want to loop over the array of objects yet again but this time loop over the updated array of objects.

If I modify the objects in the first view and pass the same array of objects in the second view, the directive uses the initial array, not the updated one. What I tried is watching the array for changes, it sees the changes but still during the second instance of the directive it uses the initial array.

Can someone explain whats going on and how could I solve this ?

答:
You can have a simple parent child relationship directive, in which directive have access to scope of controller o the view in which it's added. so you can have ng-repeat in directive & array in scope variable of controller. Then automatically the values will be sync by two way data binding. You can follow following plunk I've created.

It depends upon how are you sharing data between controller & directive. Two data binding helps make it sync else you've to handle it over event or using $watch in directive (if you're using jquery code inside directive).

https://plnkr.co/edit/m47TPgcX7lY8nL1LswCv?p=preview

```<code>app.directive('helloWorld', function ($compile, CarCompany) {
  return {
    restrict: 'E',
    template: '<div>\
                  <h2>HelloWorld directive</h2>\
                  <p ng-repeat="car in carc">{{car.name}}</p>\
                  <h3>Liste des marques:</h3>\
              </div>',
    link: function (scope, elem, attrs) {

      var ul = document.createElement('ul');
      var lis = '';
      angular.forEach(CarCompany, function(item) {
        lis += '<li>' + item.name + '</li>';
      });
      ul.innerHTML = lis;

      elem.append(ul);

      $compile(ul)(scope);
    },

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

This's simple directive showing shared scope between controller & directive.
https://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/11/understanding-scopes-in-angularjs-custom-directives.aspx

ContentLicense: CC BY-SA 3.0

Body:
You can have a simple parent child relationship directive, in which directive have access to scope of controller o the view in which it's added. so you can have ng-repeat in directive & array in scope variable of controller. Then automatically the values will be sync by two way data binding. You can follow following plunk I've created.

It depends upon how are you sharing data between controller & directive. Two data binding helps make it sync else you've to handle it over event or using $watch in directive (if you're using jquery code inside directive).

https://plnkr.co/edit/m47TPgcX7lY8nL1LswCv?p=preview

app.directive('helloWorld', function ($compile, CarCompany) {
  return {
    restrict: 'E',
    template: '<div>\
                  <h2>HelloWorld directive</h2>\
                  <p ng-repeat="car in carc">{{car.name}}</p>\
                  <h3>Liste des marques:</h3>\
              </div>',
    link: function (scope, elem, attrs) {

      var ul = document.createElement('ul');
      var lis = '';
      angular.forEach(CarCompany, function(item) {
        lis += '<li>' + item.name + '</li>';
      });
      ul.innerHTML = lis;

      elem.append(ul);

      $compile(ul)(scope);
    },

  };
});

This's simple directive showing shared scope between controller & directive.
https://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/11/understanding-scopes-in-angularjs-custom-directives.aspx


问:
Find the next word after matching a word in Javascript
Want to get the first word after the number from the string "Apply for 2 insurances".

```<code>var Number = 2;
var text = "Apply for 2 insurances or more";
</code>```

In this case i want to get the string after the Number, So my expected result is "insurances"

答:
A solution with findIndex that gets only the word after the number:

var number = 2;
var text = "Apply for 2 insurances or more";
var words = text.split(' ');

var numberIndex = words.findIndex((word) => word == number);
var nextWord = words[numberIndex + 1];

console.log(nextWord);```

ContentLicense: CC BY-SA 4.0

Body:
Want to get the first word after the number from the string "Apply for 2 insurances".

var Number = 2;
var text = "Apply for 2 insurances or more";

In this case i want to get the string after the Number, So my expected result is "insurances"


问:
no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>)’
```<code>void show_image(){
   // Create a Mat to store images
Mat cam_image;
ERROR_CODE err;

// Loop until 'e' is pressed
char key = '';
while (key != 'e') {

    // Grab images
    err = cam.grab();

    // Check if successful
    if (err == SUCCESS) {
        // Retrieve left image and show with OpenCV
        cam.retrieveImage(zed_image, VIEW_LEFT);
        cv::imshow("VIEW", cv::Mat(cam_image.getHeight(), cam_image.getWidth(), CV_8UC4, cam_image.getPtr<sl::uchar1>(sl::MEM_CPU)));
        key = cv::waitKey(5);
    } else
        key = cv::waitKey(5);
}
}
</code>```

the above function is being called -threaded- by this function:

```<code>void startCAM()
{

    if(show_left){
     cam_call = std::thread(show_image);
    }
    //Wait for data to be grabbed
    while(!has_data)
      sleep_ms(1);
}
</code>```

and I get the error:

```<code>     error: no matching function for call to ‘std::thread::thread(<unresolved     overloaded function type>)’
      cam_call = std::thread(show_image);
</code>```

It should be noted I use no classes or objects, so show_image is not a member function

答:
The error says std::thread::thread(<unresolved overloaded function type>), which means there are multiple functions named show_image.

You need to choose one of those overloads. E.g.:

```<code>std::thread(static_cast<void(*)()>(show_image));
</code>```

Body:
void show_image(){
   // Create a Mat to store images
Mat cam_image;
ERROR_CODE err;

// Loop until 'e' is pressed
char key = '';
while (key != 'e') {

    // Grab images
    err = cam.grab();

    // Check if successful
    if (err == SUCCESS) {
        // Retrieve left image and show with OpenCV
        cam.retrieveImage(zed_image, VIEW_LEFT);
        cv::imshow("VIEW", cv::Mat(cam_image.getHeight(), cam_image.getWidth(), CV_8UC4, cam_image.getPtr<sl::uchar1>(sl::MEM_CPU)));
        key = cv::waitKey(5);
    } else
        key = cv::waitKey(5);
}
}

the above function is being called -threaded- by this function:

void startCAM()
{

    if(show_left){
     cam_call = std::thread(show_image);
    }
    //Wait for data to be grabbed
    while(!has_data)
      sleep_ms(1);
}

and I get the error:

     error: no matching function for call to ‘std::thread::thread(<unresolved     overloaded function type>)’
      cam_call = std::thread(show_image);

It should be noted I use no classes or objects, so show_image is not a member function

Body:
The error says std::thread::thread(<unresolved overloaded function type>), which means there are multiple functions named show_image.

You need to choose one of those overloads. E.g.:

std::thread(static_cast<void(*)()>(show_image));


问:
Unit Testing Doctrine 2 Models
Whats the way to unit test Doctrine 2 models? I am using it with Zend Framework 1.11. It has Zend_Test which uses PHPUnit. I think the right thing to use is PHPUnit_Extensions_Database_TestCase. In Zend Framework, I can use Zend_Test_PHPUnit_Db. How can I modify the code to unit test Doctrine Models instead of Zend_Db classes.

1st, I think instead of using Zend_Db stuff, I have to use Doctrine's stuff instead

```<code>class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    private $_connectionMock;

    protected function getConnection()
    {
        if($this->_connectionMock == null) {
            $connection = Zend_Db::factory(...);
            $this->_connectionMock = $this->createZendDbConnection(
                $connection, 'zfunittests'
            );
            Zend_Db_Table_Abstract::setDefaultAdapter($connection);
        }
        return $this->_connectionMock;
    }
    ...
}
</code>```

答: What exactly do you want to test? If its just the model per se - thats not too difficult. Doctrine 2 models are just plain PHP objects with annotations containing the mapping information. Thats the good thing about Doctrine 2 being "persinstance ignorant": you can test the models just like any regular class.</p>

ContentLicense: CC BY-SA 2.5

Title: Unit Testing Doctrine 2 Models

Body:
Whats the way to unit test Doctrine 2 models? I am using it with Zend Framework 1.11. It has Zend_Test which uses PHPUnit. I think the right thing to use is PHPUnit_Extensions_Database_TestCase. In Zend Framework, I can use Zend_Test_PHPUnit_Db. How can I modify the code to unit test Doctrine Models instead of Zend_Db classes.

1st, I think instead of using Zend_Db stuff, I have to use Doctrine's stuff instead

class BugsTest extends Zend_Test_PHPUnit_DatabaseTestCase
{
    private $_connectionMock;

    protected function getConnection()
    {
        if($this->_connectionMock == null) {
            $connection = Zend_Db::factory(...);
            $this->_connectionMock = $this->createZendDbConnection(
                $connection, 'zfunittests'
            );
            Zend_Db_Table_Abstract::setDefaultAdapter($connection);
        }
        return $this->_connectionMock;
    }
    ...
}


问:
Is it possible to disable floating headers in UITableView with UITableViewStylePlain?
I'm using a UITableView to layout content 'pages'. I'm using the headers of the table view to layout certain images etc. and I'd prefer it if they didn't float but stayed static as they do when the style is set to UITableViewStyleGrouped.

Other then using UITableViewStyleGrouped, is there a way to do this? I'd like to avoid using grouped as it adds a margin down all my cells and requires disabling of the background view for each of the cells. I'd like full control of my layout. Ideally they'd be a "UITableViewStyleBareBones", but I didn't see that option in the docs...

Many thanks,

答:
Maybe you could use scrollViewDidScroll on the tableView
and change the contentInset based on the current visible header.

It seems to work for my use case!

```<code>extension ViewController : UIScrollViewDelegate{

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard   let tableView = scrollView as? UITableView,
            let visible = tableView.indexPathsForVisibleRows,
            let first = visible.first else {
            return
        }

        let headerHeight = tableView.rectForHeader(inSection: first.section).size.height
        let offset =  max(min(0, -tableView.contentOffset.y), -headerHeight)
        self.tableView.contentInset = UIEdgeInsetsMake(offset, 0, -offset, 0)
   }
}
</code>```

Body:
Maybe you could use scrollViewDidScroll on the tableView
and change the contentInset based on the current visible header.

It seems to work for my use case!

extension ViewController : UIScrollViewDelegate{

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard   let tableView = scrollView as? UITableView,
            let visible = tableView.indexPathsForVisibleRows,
            let first = visible.first else {
            return
        }

        let headerHeight = tableView.rectForHeader(inSection: first.section).size.height
        let offset =  max(min(0, -tableView.contentOffset.y), -headerHeight)
        self.tableView.contentInset = UIEdgeInsetsMake(offset, 0, -offset, 0)
   }
}


答:
First of all you need to get your list into a 2D numpy array. As you know how many columns you have this is easy:

```<code>x = np.array(bestof10)
x = x.reshape(-1, 7)
</code>```

So now you have a 2D array of 10 rows and 7 columns (shape = (10, 7)). So now you can easily plot your histogram with matplotlib.

```<code>fig, ax = plt.subplots()
_ = ax.hist([x[:, 1], x[:, 2], x[:, 5]],
            stacked=True, normed=False)
</code>```

Title: Python : Creating stacked histogram with number of different values in numpy array

Body:
I have the followin problem. I have an array with 7 columns. I want a stacked histogram for column 1,2 and 5, so that there are 3 bars that are stacked with the number of different elements in each column. So for column 1 i have 9 values with 4 and 1 value with 3. In column 2 I have 3 values of 3 and 7 vlaues of 4. In column 5 i have different number of values. I have a appoach but its very dirty and i could only plot the column 1 and 2. Furthermore i want to plot a label to the different bars to show what number they are displaying.

bestof10=    [4.041970802919708228e-01  4.000000000000000000e+00    4.000000000000000000e+00    6.710000000000000853e+01    5.500000000000000444e-01    4.000000000000000000e+00    6.000000000000000000e+01
    3.730468750000000000e-01    4.000000000000000000e+00    4.000000000000000000e+00    1.932000000000000171e+02    7.000000000000000666e-01    6.000000000000000000e+00    6.200000000000000000e+01
    3.626570915619389823e-01    4.000000000000000000e+00    3.000000000000000000e+00    3.900000000000000000e+01    5.000000000000000000e-01    4.000000000000000000e+00    5.300000000000000000e+01
    3.568320278503046006e-01    4.000000000000000000e+00    4.000000000000000000e+00    8.640000000000000568e+01    6.000000000000000888e-01    7.000000000000000000e+00    6.300000000000000000e+01
    3.527336860670193808e-01    4.000000000000000000e+00    4.000000000000000000e+00    6.780000000000001137e+01    6.000000000000000888e-01    3.000000000000000000e+00    5.900000000000000000e+01
    3.521825396825397081e-01    4.000000000000000000e+00    4.000000000000000000e+00    1.568000000000000114e+02    7.000000000000000666e-01    1.000000000000000000e+00    5.700000000000000000e+01
    3.432835820895522305e-01    3.000000000000000000e+00    4.000000000000000000e+00    8.904999999999999716e+01    6.500000000000000222e-01    7.000000000000000000e+00    4.200000000000000000e+01
    3.374888691006233121e-01    4.000000000000000000e+00    3.000000000000000000e+00    3.194999999999999929e+01    4.500000000000000111e-01    7.000000000000000000e+00    5.600000000000000000e+01
    3.364879074658254643e-01    4.000000000000000000e+00    4.000000000000000000e+00    2.430000000000000000e+02    7.500000000000000000e-01    5.000000000000000000e+00    6.100000000000000000e+01
    3.244781783681214282e-01    4.000000000000000000e+00    3.000000000000000000e+00    8.100000000000001421e+01    6.000000000000000888e-01    6.000000000000000000e+00    5.500000000000000000e+01]

a  = np.bincount(bestof10[:,1].astype(int))
ab = np.nonzero(a)[0]
a = a[ab]
a = tuple(a)

b  = np.bincount(bestof10[:,2].astype(int))
bb = np.nonzero(b)[0]
b  = b[bb]
b = tuple(b)

histogramParas=np.column_stack((a,b))

N = 2

ind = np.arange(N)
width = 0.35

p1 = plt.bar(ind, histogramParas[0], width, color='r')
p2 = plt.bar(ind, histogramParas[1], width, color='y',bottom=histogramParas[0])

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind+width/2., ('Radius', 'FRC') )

plt.show()

EDIT
Should look like:

Body:
First of all you need to get your list into a 2D numpy array. As you know how many columns you have this is easy:

x = np.array(bestof10)
x = x.reshape(-1, 7)

So now you have a 2D array of 10 rows and 7 columns (shape = (10, 7)). So now you can easily plot your histogram with matplotlib.

fig, ax = plt.subplots()
_ = ax.hist([x[:, 1], x[:, 2], x[:, 5]],
            stacked=True, normed=False)


问:
requireNamespaceQuietStop causing errors in custom summaryFunction caret
I 'updated' the twoClassSummary function in caret to include both the negative and positive predictive values using caret functions:

```<code>testfun <- function (data, lev = NULL, model = NULL)
{
  lvls <- levels(data$obs)
  if (length(lvls) > 2)
    stop(paste("Your outcome has", length(lvls), "levels. The
twoClassSummary() function isn't appropriate."))
  requireNamespaceQuietStop("ModelMetrics")
  if (!all(levels(data[, "pred"]) == lvls))
    stop("levels of observed and predicted data do not match")
  data$y = as.numeric(data$obs == lvls[2])
  rocAUC <- ModelMetrics::auc(ifelse(data$obs == lev[2], 0,
                                     1), data[, lvls[1]])
  out <- c(rocAUC, sensitivity(data[, "pred"], data[, "obs"], lev[1]),
                   specificity(data[, "pred"], data[, "obs"], lev[2]),
                   # next 3 lines are my additions and modifications
                   negPredValue(data[, "obs"], data[, "pred"], lev[2]),
                   posPredValue(data[, "obs"], data[, "pred"], lev[1]))
  names(out) <- c("ROC", "Sens", "Spec", "NPV", "PPV")
  out
}
</code>```

And then my trainControl function:

```<code>train_control <- trainControl(method = 'repeatedcv',
                              number = 10, repeats = 3,
                              summaryFunction = testfun,
                              classProbs = T,
                              savePredictions = T)
</code>```

and then my model function:

```<code>modelSvm <- train(target ~ ., data = twoClassData, trControl = train_control, method = 'svmRadial')
</code>```

The problem is when I run this function, I get the error
Error in ctrl$summaryFunction(testOutput, lev, method) :
  could not find function "requireNamespaceQuietStop"

even though I haven't change that part of the function.

if I type

```<code>twoClassSummary
</code>```

in the console,

environment: namespace:caret

appears (between < > signs) at the end after the function definition and I believe this is the source of my problems.

1) How do I direct R to this environment in the function? and
2) accuracy is not a predefined caret function, any suggestions on how to work accuracy into this code?

Thanks in advance....

答: That function is not exported by caret, so use caret::: requireNamespaceQuietStop instead (or use used library).

Body:
I 'updated' the twoClassSummary function in caret to include both the negative and positive predictive values using caret functions:

testfun <- function (data, lev = NULL, model = NULL)
{
  lvls <- levels(data$obs)
  if (length(lvls) > 2)
    stop(paste("Your outcome has", length(lvls), "levels. The
twoClassSummary() function isn't appropriate."))
  requireNamespaceQuietStop("ModelMetrics")
  if (!all(levels(data[, "pred"]) == lvls))
    stop("levels of observed and predicted data do not match")
  data$y = as.numeric(data$obs == lvls[2])
  rocAUC <- ModelMetrics::auc(ifelse(data$obs == lev[2], 0,
                                     1), data[, lvls[1]])
  out <- c(rocAUC, sensitivity(data[, "pred"], data[, "obs"], lev[1]),
                   specificity(data[, "pred"], data[, "obs"], lev[2]),
                   # next 3 lines are my additions and modifications
                   negPredValue(data[, "obs"], data[, "pred"], lev[2]),
                   posPredValue(data[, "obs"], data[, "pred"], lev[1]))
  names(out) <- c("ROC", "Sens", "Spec", "NPV", "PPV")
  out
}

And then my trainControl function:

train_control <- trainControl(method = 'repeatedcv',
                              number = 10, repeats = 3,
                              summaryFunction = testfun,
                              classProbs = T,
                              savePredictions = T)

and then my model function:

modelSvm <- train(target ~ ., data = twoClassData, trControl = train_control, method = 'svmRadial')

The problem is when I run this function, I get the error
Error in ctrl$summaryFunction(testOutput, lev, method) :
  could not find function "requireNamespaceQuietStop"

even though I haven't change that part of the function.

if I type

twoClassSummary

in the console,

environment: namespace:caret

appears (between < > signs) at the end after the function definition and I believe this is the source of my problems.

1) How do I direct R to this environment in the function? and
2) accuracy is not a predefined caret function, any suggestions on how to work accuracy into this code?

Thanks in advance....


问:
spookyjs hello.js can't recognize module tiny-jsonrpc
I have copied example code from spookyjs npm web-page:

try {
    var Spooky = require('spooky');
} catch (e) {
    Spooky = require('node_modules/spooky');
}

var spooky = new Spooky({
    child: {
        transport: 'http'
    },
    casper: {
        logLevel: 'debug',
        verbose: true
    }
}, function (err) {
    if (err) {
        e = new Error('Failed to initialize SpookyJS');
        e.details = err;
        throw e;
    }

    spooky.start(
        'http://en.wikipedia.org/wiki/Spooky_the_Tuff_Little_Ghost');
    spooky.then(function () {
        this.emit('hello', 'Hello, from ' + this.evaluate(function () {
                return document.title;
            }));
    });
    spooky.run();
});

spooky.on('error', function (e, stack) {
    console.error(e);

    if (stack) {
        console.log(stack);
    }
});

// Uncomment this block to see all of the things Casper has to say.
// There are a lot.
// He has opinions.
spooky.on('console', function (line) {
    console.log(line);
});

spooky.on('hello', function (greeting) {
    console.log(greeting);
});

spooky.on('log', function (log) {
    if (log.space === 'remote') {
        console.log(log.message.replace(/ \- .*/, ''));
    }
});```
</div>
</div>

But it throws an error:</p>

```Error: Cannot find module

'/home/svet/WebstormProjects/nodejsStudy/studyFiles/node_modules/spooky/lib/../node_modules/tiny-jsonrpc/lib/tiny-jsonrpc'

[ { file: 'phantomjs://platform/bootstrap.js',
    line: 299,
    function: 'require' },
  { file: 'phantomjs://platform/bootstrap.js',
    line: 263,
    function: 'require' },
  { file: 'phantomjs://platform/http-server.js',
    line: 6,
    function: '' } ]
{ Error: Child terminated with non-zero exit code 1
    at Spooky.<anonymous>
(/home/svet/WebstormProjects/nodejsStudy/studyFiles/node_modules/spooky/lib/spooky.js:210:17)

    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:194:7)
    at Process.ChildProcess._handle.onexit
(internal/child_process.js:215:12) details: { code: 1, signal: null } }
```

The tiny-jsonrpc module is already installed

答:
You should install phantomjs before executing that script.

You can install phantomjs using npm:
npm install phantomjs

Body:
I have copied example code from spookyjs npm web-page:

try {
    var Spooky = require('spooky');
} catch (e) {
    Spooky = require('node_modules/spooky');
}

var spooky = new Spooky({
    child: {
        transport: 'http'
    },
    casper: {
        logLevel: 'debug',
        verbose: true
    }
}, function (err) {
    if (err) {
        e = new Error('Failed to initialize SpookyJS');
        e.details = err;
        throw e;
    }

    spooky.start(
        'http://en.wikipedia.org/wiki/Spooky_the_Tuff_Little_Ghost');
    spooky.then(function () {
        this.emit('hello', 'Hello, from ' + this.evaluate(function () {
                return document.title;
            }));
    });
    spooky.run();
});

spooky.on('error', function (e, stack) {
    console.error(e);

    if (stack) {
        console.log(stack);
    }
});

// Uncomment this block to see all of the things Casper has to say.
// There are a lot.
// He has opinions.
spooky.on('console', function (line) {
    console.log(line);
});

spooky.on('hello', function (greeting) {
    console.log(greeting);
});

spooky.on('log', function (log) {
    if (log.space === 'remote') {
        console.log(log.message.replace(/ \- .*/, ''));
    }
});

But it throws an error:

Error: Cannot find module

'/home/svet/WebstormProjects/nodejsStudy/studyFiles/node_modules/spooky/lib/../node_modules/tiny-jsonrpc/lib/tiny-jsonrpc'

[ { file: 'phantomjs://platform/bootstrap.js',
    line: 299,
    function: 'require' },
  { file: 'phantomjs://platform/bootstrap.js',
    line: 263,
    function: 'require' },
  { file: 'phantomjs://platform/http-server.js',
    line: 6,
    function: '' } ]
{ Error: Child terminated with non-zero exit code 1
    at Spooky.<anonymous>
(/home/svet/WebstormProjects/nodejsStudy/studyFiles/node_modules/spooky/lib/spooky.js:210:17)

    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:194:7)
    at Process.ChildProcess._handle.onexit
(internal/child_process.js:215:12) details: { code: 1, signal: null } }

The tiny-jsonrpc module is already installed


问:
Install pycharm Ubuntu
I recently had to wipe my computer and reinstall everything.  I remember being able to install pycharm (community edition) with a single sudo apt-get install command and that was all.  I can't find it? I am using Ubuntu 16.04 LTS.

答: You can just easily launch Ubuntu software app, type pycharm on the search bar and install it.

Title: Install pycharm Ubuntu


问:
functions in functions nodejs
I want to get the klout score using a screen name (twitter).

I did this. I know it doesn't work like that, but I don't know how it should work.

```<code>function get_klout(screenName){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    klout.getUserScore(klout_user.id, function(error, klout_response) {
       return Math.round(klout_response.score);
    });
  });
}
</code>```

I want my function to return this number Math.round(klout_response.score);

答:
function get_klout(screenName) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

       return Math.round(klout_response.score);
    });
  });
}
```

<p>Your function is async, so you can't just assign what it returns to a variable because you will just assign undefined:
<code>var result = get_klout('foo'); // undefined</code></p>

<p>what you can do is:</p>

<ol>
<li>using <code>async functions</code> in <code>node 8+</code></li>
<li>using <code>Promises</code> </li>
<li>using <code>callbacks</code>:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>function get_klout(screenName, done) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

        done(Math.round(klout_response.score));
    });
  });
}

get_klout('foo', function(response) {
  console.log(response);
});
</code>```

just a note:
In node is a common pattern implementing the error first callback and you should have a look on it because it's the traditional and more used way to handle errors:
http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

Title: functions in functions nodejs

Body:
I want to get the klout score using a screen name (twitter).

I did this. I know it doesn't work like that, but I don't know how it should work.

function get_klout(screenName){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    klout.getUserScore(klout_user.id, function(error, klout_response) {
       return Math.round(klout_response.score);
    });
  });
}

I want my function to return this number Math.round(klout_response.score);

Body:
function get_klout(screenName) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

       return Math.round(klout_response.score);
    });
  });
}

Your function is async, so you can't just assign what it returns to a variable because you will just assign undefined:
var result = get_klout('foo'); // undefined

what you can do is:

using async functions in node 8+

using Promises

using callbacks:

function get_klout(screenName, done) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

        done(Math.round(klout_response.score));
    });
  });
}

get_klout('foo', function(response) {
  console.log(response);
});

just a note:
In node is a common pattern implementing the error first callback and you should have a look on it because it's the traditional and more used way to handle errors:
http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/


问:
Native XML Web Services for SQL Server 2008
I want to share a few small tables from my SQL Server 2008 database. Client is html/javascript based. I started with Native XML Web Services for SQL Server, but it's deprecated in SQL Server 2008.

Is there any other quick and cheap solution, rather then building data service from scratch?

答:
I don't know about built in functionality of SqlServer, but you could do it very quickly using OData interface, as described here (there it explains how to build it from scratch using stackoverflow database).

It's using Entity Framework, and it's actually very nice to have, quick to build, doesn't require much knowledge about it, and it's easy to tweak further.


答:
You can simply use Regular Expression to get the first word after a number, like so ...

var number = 2;
var text = "Apply for 2 insurances test";
var result = text.match(new RegExp(number + '\\s(\\w+)'))[1];

console.log(result);```

Title: Find the next word after matching a word in Javascript


问:
"SyntaxError: Unexpected token < in JSON at position 0"
In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.

Feed.js:

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

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '',
            text: '',
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author,
                                text: text,
                                included: included,
                                victim: victim
                              })
    this.setState({author: '',
                  text: '',
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox
</code>```

In Chrome developer tools, the error seems to be coming from this function:

```<code> loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
</code>```

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

答:
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues.  So, it was returning the HTML from the redirected page instead of the API JSON.  I added an exclusion in a web.config file for the API path.

I was not getting this error when developing locally, because the site and API were on different ports.  There is probably a better way to do this, but it worked.

```<code><?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

2022 UPDATE: having written this several years ago.  I'd call this suggestion more of a workaround - a direct fix.  The better hosting pattern is to simply not try to host these api paths under your website path; rather, host them on separate base URLs entirely.  For my use case example, the API and Web path would be entirely separate Azure Web Services and would get different URL endpoints.

Body:
In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '',
            text: '',
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author,
                                text: text,
                                included: included,
                                victim: victim
                              })
    this.setState({author: '',
                  text: '',
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (

Feed

        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />

    )
  }
})

module.exports = ThreadsBox

In Chrome developer tools, the error seems to be coming from this function:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

Body:
In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues.  So, it was returning the HTML from the redirected page instead of the API JSON.  I added an exclusion in a web.config file for the API path.

I was not getting this error when developing locally, because the site and API were on different ports.  There is probably a better way to do this, but it worked.

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>

2022 UPDATE: having written this several years ago.  I'd call this suggestion more of a workaround - a direct fix.  The better hosting pattern is to simply not try to host these api paths under your website path; rather, host them on separate base URLs entirely.  For my use case example, the API and Web path would be entirely separate Azure Web Services and would get different URL endpoints.


问:
Format Removable media with c# programming
I want to format (FAT32) removable drive with c# programming. In the internet I found a way, but the problem is that it opens the generic windows format program. But I want to do it with C# only and no built in windows support.

My method is:

```<code>// FAT32 Format Button click event
[DllImport("shell32.dll")]
static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID, uint options);
</code>```

答:
Works pretty good via WMI:</p>

```<code>var query = String.Format("SELECT * FROM Win32_Volume WHERE Name = '{0}'", "E:\\\\");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", query);
var queryCollection = from ManagementObject x in searcher.Get() select x;
var volume = queryCollection.FirstOrDefault();

var resultCode = volume.InvokeMethod("Format", new object[] { "FAT32", true, 4096, "Volume Name", false });
</code>```

Body:
I want to format (FAT32) removable drive with c# programming. In the internet I found a way, but the problem is that it opens the generic windows format program. But I want to do it with C# only and no built in windows support.

My method is:

// FAT32 Format Button click event
[DllImport("shell32.dll")]
static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID, uint options);

Body:
Works pretty good via WMI:

var query = String.Format("SELECT * FROM Win32_Volume WHERE Name = '{0}'", "E:\\\\");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", query);
var queryCollection = from ManagementObject x in searcher.Get() select x;
var volume = queryCollection.FirstOrDefault();

var resultCode = volume.InvokeMethod("Format", new object[] { "FAT32", true, 4096, "Volume Name", false });


问:
Which one is called first? constructor or componentDidMount or Render
As i've read online and official documentation. Order is
Constructor-> ComponentWillMount -> Render -> ComponentDidMount and others.

```<code>class Navigation extends Component {
    constructor(props) {
        super(props);
        console.log('constructor', this);
        this.state = { items: [ ] };
    }

componentDidMount() {
    console.log('componentDidMount');

    if ( toDisplay( ) ) {
        api.bringCats()
        .then( categories => {
            const tot_cat = categories.map( cat => { return {name: cat.name, link: cat.link}; })
            this.setState({items: tot_cat,})
        })
    }
}

render() {
    console.log("render")
    //some stuff
}
}
</code>```

im expecting the the log to be in this order
  1. constructor
  2. ComponentDidMount
  3. render

im logging this with constructor inside constructor method. im able to get value for items which is getting its value in componentDidMount why this is happening? and its logging in the correct order (constructor->didmount->render) but why im getting value of items even before calling componentDidMount.

im using <Navigation/> component inside

```<code>Header extends Component{
render(){
  return (<div> <Navigation/> </div>);
}
}
</code>```

答:
i was trying something and found out that this is working fine.

window.cnj = require('circular-json') /*   i added this in starting point first line so i will have access to this inside all imports. */

window.props = JSON.parse(window.cnj.stringify(simple));

I can access window.props from the devtools and its working as expected.

sample can be string, arrays, normal object or circular object.

Body:
As i've read online and official documentation. Order is
Constructor-> ComponentWillMount -> Render -> ComponentDidMount and others.

class Navigation extends Component {
    constructor(props) {
        super(props);
        console.log('constructor', this);
        this.state = { items: [ ] };
    }

componentDidMount() {
    console.log('componentDidMount');

    if ( toDisplay( ) ) {
        api.bringCats()
        .then( categories => {
            const tot_cat = categories.map( cat => { return {name: cat.name, link: cat.link}; })
            this.setState({items: tot_cat,})
        })
    }
}

render() {
    console.log("render")
    //some stuff
}
}

im expecting the the log to be in this order
  1. constructor
  2. ComponentDidMount
  3. render

im logging this with constructor inside constructor method. im able to get value for items which is getting its value in componentDidMount why this is happening? and its logging in the correct order (constructor->didmount->render) but why im getting value of items even before calling componentDidMount.

im using <Navigation/> component inside

Header extends Component{
render(){
  return (
 <Navigation/>
);
}
}


问:
Fixed width layout with one child spanning full screen width
Can I create a layout like on the picture below, while setting the fixed width only on the parent container?  I also cannot use position: absolute; left: 0; right: 0; on Full screen width child, as I cannot remove it from the flow, because it's size is dynamic.

I can't change the markup.

The only solution I can think of is setting the fixed width on every Fixed-width child separately, but as I have a lot of them, that's not the most comfortable solution - means adding a class for every child that I add into the parent container.

Here is an example markup you can post a solution to.

HTML

```<code><div class="fixed-width-container">
  <div class="regular-child"></div>
  <div class="full-screen-width-child"></div>
  <div class="regular-child"></div>
  <div class="regular-child"></div>
</div>
</code>```

CSS

```<code>.fixed-width-container {
  width: <some-fixed-width>;
}
</code>```

答:
you can give a try to the flex layout : https://css-tricks.com/snippets/css/a-guide-to-flexbox/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-align: center;
}

body {
  margin: 0;
}

div {
  border: 1px solid #333;
}

.fixed-width-container {
  width: 400px;/* any width set */
  margin: auto;
  padding: 10px 10px 0;
  background: yellow;
  display: flex;
  flex-flow: column;
  align-items: center;
}

.fixed-width-container>div {
  height: 3em;
  margin-bottom: 10px;
  background: lightblue;
  min-width: 100%;
}

.full-screen-width-child {
  width: 99vw;/* 100vw is fine too */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fixed-width-container">
  <div class="regular-child">Fixed-width child</div>
  <div class="full-screen-width-child">Full screen width child with dynamic contents</div>
  <div class="regular-child">Fixed-width child</div>
  <div class="regular-child">Fixed-width child</div>
</div></code>```

codepen to test and play with

Body:
Can I create a layout like on the picture below, while setting the fixed width only on the parent container?  I also cannot use position: absolute; left: 0; right: 0; on Full screen width child, as I cannot remove it from the flow, because it's size is dynamic.

I can't change the markup.

The only solution I can think of is setting the fixed width on every Fixed-width child separately, but as I have a lot of them, that's not the most comfortable solution - means adding a class for every child that I add into the parent container.

Here is an example markup you can post a solution to.

HTML

CSS

.fixed-width-container {
  width: <some-fixed-width>;
}

Body:
you can give a try to the flex layout : https://css-tricks.com/snippets/css/a-guide-to-flexbox/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-align: center;
}

body {
  margin: 0;
}

div {
  border: 1px solid #333;
}

.fixed-width-container {
  width: 400px;/* any width set */
  margin: auto;
  padding: 10px 10px 0;
  background: yellow;
  display: flex;
  flex-flow: column;
  align-items: center;
}

.fixed-width-container>div {
  height: 3em;
  margin-bottom: 10px;
  background: lightblue;
  min-width: 100%;
}

.full-screen-width-child {
  width: 99vw;/* 100vw is fine too */
}

<div class="fixed-width-container">
  <div class="regular-child">Fixed-width child</div>
  <div class="full-screen-width-child">Full screen width child with dynamic contents</div>
  <div class="regular-child">Fixed-width child</div>
  <div class="regular-child">Fixed-width child</div>
</div>

codepen to test and play with


问:
recover lost C# pages
I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder</p>

答:
http://www.red-gate.com/products/dotnet-development/reflector/ Can decompile .NET assemblies into source code - however it won't be the code you wrote as alot of it will have been changed by the compiler (IE your comments will have gone bye bye)

You can then rebuild your Project in your IDE of choice and you are done.

Title: recover lost C# pages


问:
How to solve Output argument (and maybe others) not assigned during call
I'm trying to write a script that achieves the following:

Loop over each pixel in a dicom image.

If the pixel value exceeds a user-defined threshold (t1) then:
 Overlay a filter kernel/block of user-defined size.
 Find a percentile (t2) of all values in the block/kernel.
 Find the mean of all pixels in the block that are less than t2.
 Replace the original pixel > t1 with the mean of those less than the t2
 percentile.

I've tried using the blockproc function for this as follows:

```<code>function bkgdsub()
clc;

dimX = 5;        %Size of the kernel/block
dimY = dimX;

bfmap = dicomread('IM8');
myfilter = @filter;

subimg = blockproc(bfmap, [dimX dimY], myfilter, 'PadPartialBlocks', false);
imshow(subimg)

end

function subtract = filter(block_struct)

dimX = 5;          %Set the 2D size of the kernel footprint (z, y).
dimY = dimX;
t1 = 100;   %Set threshold 1 (t1)
t2 = 75;     %Set percentile threshold (t2)

avg = [];
singlevalue = ones([dimX dimY]);

for n = 1:dimX
    for m = 1:dimY
        if block_struct.data(n,m) >= t1;

            pc = prctile(blockstruct.data, t2)

                for i = 1:size(blockstruct.data, 1)
                    for j = 1:size(blockstruct.data, 2)
                        if blockstruct.data(i, j) < pc
                            avg = [avg blockstruct.data(i, j)];
                        end
                    end
                end

            avgMn = mean(avg(:))

            singlevalue(n,m) = avgMn
        end
    end
end
end
</code>```

I run into the following errors:

Function BLOCKPROC encountered an error while evaluating the user
  supplied function handle, FUN.

The cause of the error was:

Output argument "subtract" (and maybe others) not assigned during call
  to "C:...\test.m>filter".

Error in blockprocFunDispatcher (line 14)
          output_block = fun(block_struct);

Error in blockprocInMemory (line 81) [ul_output fun_nargout] =
  blockprocFunDispatcher(fun,block_struct,...

Error in blockproc (line 237)
      result_image = blockprocInMemory(source,fun,options);

Error in bfsubtract2 (line 15) subimg = blockproc(bfmap, [dimX dimY],
  myfilter, 'PadPartialBlocks', false);

Any thoughts on how I could tackle this?  Any insight into these errors with using blockproc is also appreciated.

Tx.

答:
So this turned out to be easier to implement with nlfilter.  Code block below if anyone needs it in the future.</p>

```<code>function main()
clc;            %Clear the command window

dimX = 3;       %Set the 2D size of the kernel footprint (z, y).
dimY = dimX;
w = [dimY dimX];

t1 = 100;       %Set threshold 1 (BF)
t2 = 75;        %Set percentile threshold

%kernel1=ones(5, 5)

kernel = xlsread('testgrid.xlsx')   %loads in the test matrix from first sheet of excel file

bfmap = dicomread('IM8');

fun = @windfilt;

Subtract = nlfilter(kernel, w, fun)

end

function y = windfilt(A)

    t1 = 7;
    t2 = 75;
    avg = [];

    [m, n] = size(A);

    if A(2, 2) >= t1             %Set back to t1
        pc = prctile(A(:), t2);

        for i = 1:size(A, 1)
            for j = 1:size(A, 2)
                if ((A(i, j) <= pc) & (A(i, j) ~= 0))
                    avg = [avg A(i, j)];
                end
            end
        end

        y = median(avg(:));
        clear avg

    else
        y = A(2, 2);      %Set y = to the center pixel value if ~> t1
    end

end
</code>```

Body:
I'm trying to write a script that achieves the following:

Loop over each pixel in a dicom image.

If the pixel value exceeds a user-defined threshold (t1) then:
 Overlay a filter kernel/block of user-defined size.
 Find a percentile (t2) of all values in the block/kernel.
 Find the mean of all pixels in the block that are less than t2.
 Replace the original pixel > t1 with the mean of those less than the t2
 percentile.

I've tried using the blockproc function for this as follows:

function bkgdsub()
clc;

dimX = 5;        %Size of the kernel/block
dimY = dimX;

bfmap = dicomread('IM8');
myfilter = @filter;

subimg = blockproc(bfmap, [dimX dimY], myfilter, 'PadPartialBlocks', false);
imshow(subimg)

end

function subtract = filter(block_struct)

dimX = 5;          %Set the 2D size of the kernel footprint (z, y).
dimY = dimX;
t1 = 100;   %Set threshold 1 (t1)
t2 = 75;     %Set percentile threshold (t2)

avg = [];
singlevalue = ones([dimX dimY]);

for n = 1:dimX
    for m = 1:dimY
        if block_struct.data(n,m) >= t1;

            pc = prctile(blockstruct.data, t2)

                for i = 1:size(blockstruct.data, 1)
                    for j = 1:size(blockstruct.data, 2)
                        if blockstruct.data(i, j) < pc
                            avg = [avg blockstruct.data(i, j)];
                        end
                    end
                end

            avgMn = mean(avg(:))

            singlevalue(n,m) = avgMn
        end
    end
end
end

I run into the following errors:

Function BLOCKPROC encountered an error while evaluating the user
  supplied function handle, FUN.

The cause of the error was:

Output argument "subtract" (and maybe others) not assigned during call
  to "C:...\test.m>filter".

Error in blockprocFunDispatcher (line 14)
          output_block = fun(block_struct);

Error in blockprocInMemory (line 81) [ul_output fun_nargout] =
  blockprocFunDispatcher(fun,block_struct,...

Error in blockproc (line 237)
      result_image = blockprocInMemory(source,fun,options);

Error in bfsubtract2 (line 15) subimg = blockproc(bfmap, [dimX dimY],
  myfilter, 'PadPartialBlocks', false);

Any thoughts on how I could tackle this?  Any insight into these errors with using blockproc is also appreciated.

Tx.

Body:
So this turned out to be easier to implement with nlfilter.  Code block below if anyone needs it in the future.

function main()
clc;            %Clear the command window

dimX = 3;       %Set the 2D size of the kernel footprint (z, y).
dimY = dimX;
w = [dimY dimX];

t1 = 100;       %Set threshold 1 (BF)
t2 = 75;        %Set percentile threshold

%kernel1=ones(5, 5)

kernel = xlsread('testgrid.xlsx')   %loads in the test matrix from first sheet of excel file

bfmap = dicomread('IM8');

fun = @windfilt;

Subtract = nlfilter(kernel, w, fun)

end

function y = windfilt(A)

    t1 = 7;
    t2 = 75;
    avg = [];

    [m, n] = size(A);

    if A(2, 2) >= t1             %Set back to t1
        pc = prctile(A(:), t2);

        for i = 1:size(A, 1)
            for j = 1:size(A, 2)
                if ((A(i, j) <= pc) & (A(i, j) ~= 0))
                    avg = [avg A(i, j)];
                end
            end
        end

        y = median(avg(:));
        clear avg

    else
        y = A(2, 2);      %Set y = to the center pixel value if ~> t1
    end

end


问:
Google BigQuery - regex functions for utf-8
```<code>SELECT  REGEXP_EXTRACT('name=北海道新幹線|gauge=1435|layer=2|usage=main|bridge=yes|', r'layer=(-?[0-9]+)|') AS Layer
</code>```

yield null.  while

```<code>select  REGEXP_EXTRACT('layer=2|',r'layer=(-?[0-9]+)|') as layer
</code>```

yield the wanted result : 2

I suspect the first one failed due to utf-8 characters?

How to extract layer info for the first string?

答:
The trailing | is interpreted as OR. You need to escape it with a backslash, e.g.:

```<code>SELECT  REGEXP_EXTRACT('name=北海道新幹線|gauge=1435|layer=2|usage=main|bridge=yes|', r'layer=(-?[0-9]+)\|') AS Layer
</code>```

Without the backslash, the second example that you have works because the regex is interpreted as the pattern OR the empty string.

Body:
SELECT  REGEXP_EXTRACT('name=北海道新幹線|gauge=1435|layer=2|usage=main|bridge=yes|', r'layer=(-?[0-9]+)|') AS Layer

yield null.  while

select  REGEXP_EXTRACT('layer=2|',r'layer=(-?[0-9]+)|') as layer

yield the wanted result : 2

I suspect the first one failed due to utf-8 characters?

How to extract layer info for the first string?

Body:
The trailing | is interpreted as OR. You need to escape it with a backslash, e.g.:

SELECT  REGEXP_EXTRACT('name=北海道新幹線|gauge=1435|layer=2|usage=main|bridge=yes|', r'layer=(-?[0-9]+)\|') AS Layer

Without the backslash, the second example that you have works because the regex is interpreted as the pattern OR the empty string.


问:
Highcharts: Handling ng-click on tooltips
I need some help with a problem I am encountering. I created a chart and a custom tooltip, whenever the user clicks on the tooltip, it should call the $scope function.

```<code>        tooltip: {
            pointFormatter: function() {
              return $compile(angular.element("<p style='color:red' ng-click='handleClick()'>Click here</p>"))(scope);
            }
        }
</code>```

I created a jsfiddle for it.

Thanks!

答:
Compile the tooltip element after the tooltip appears.

In the pointFormatter return string:

```<code>pointFormatter: function() {
  return "<p style='color:red' ng-click='handleClick()'>Click here</p>"
}
</code>```

In the click callback:

```<code>events: {
  click: function(e) {
    tooltip.refresh(e.point, e);
    $compile(tooltip.label.div)(scope)
  }
</code>```

example: http://jsfiddle.net/mj9mj1n5/

Body:
I need some help with a problem I am encountering. I created a chart and a custom tooltip, whenever the user clicks on the tooltip, it should call the $scope function.

        tooltip: {
            pointFormatter: function() {
              return $compile(angular.element("
Click here
"))(scope);
            }
        }

I created a jsfiddle for it.

Thanks!

Body:
Compile the tooltip element after the tooltip appears.

In the pointFormatter return string:

pointFormatter: function() {
  return "<p style='color:red' ng-click='handleClick()'>Click here</p>"
}

In the click callback:

events: {
  click: function(e) {
    tooltip.refresh(e.point, e);
    $compile(tooltip.label.div)(scope)
  }

example: http://jsfiddle.net/mj9mj1n5/


问:
AFHTTPRequestOperation getting NSPOSIXErrorDomain "No such file or directory"
I am using AFHTTPRequestOperation to download a large file to the Documents directory on my device.

```<code>NSURLRequest *request = [NSURLRequest requestWithURL:vectorFile.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSString *path = [self pathForFileName:vectorFile.fileName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    double percentDone = (double)totalBytesRead / (double)totalBytesExpectedToRead;
    progress(percentDone, totalBytesRead, totalBytesExpectedToRead);

}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        NSString *path = [self pathForFileName:vectorFile.fileName];

        extracting();
        [SSZipArchive unzipFileAtPath:path toDestination:[self path] progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {

            NSLog(@"Unzipping");

        } completionHandler:^(NSString *path2, BOOL succeeded, NSError *error) {

            if (!error) {
                NSLog(@"Successfully downloaded file to %@", path);

                dispatch_async(dispatch_get_main_queue(), ^{

                    completion(YES);

                });
            } else {

                NSLog(@"%@", error);
                failure(error);

            }

        }];

    });

} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {

    NSLog(@"%@", error);
    failure(error);

}];
[operation start];
</code>```

For some strange reason, it works on the Simulator to download the files, but on the device (iPhone 6) I get the following error:

```<code>Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"
</code>```

The URL is correct, as it downloads in my browser correctly and in the Simulator. Why would this just be happening on the device? And what could be causing it?

I have tried restarting my device and resetting network settings.

答:
This error (No such file or directory) can also be thrown if you using [NSURLSessionConfiguration backgroundConfiguration]

In iOS 10 at least, if you try to resume such tasks using whatever resumeData is there, your session delegate call will return that error.

Not sure what has changed since iOS 9, since this was working properly in iOS 7-9.

Body:
I am using AFHTTPRequestOperation to download a large file to the Documents directory on my device.

NSURLRequest *request = [NSURLRequest requestWithURL:vectorFile.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSString *path = [self pathForFileName:vectorFile.fileName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    double percentDone = (double)totalBytesRead / (double)totalBytesExpectedToRead;
    progress(percentDone, totalBytesRead, totalBytesExpectedToRead);

}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        NSString *path = [self pathForFileName:vectorFile.fileName];

        extracting();
        [SSZipArchive unzipFileAtPath:path toDestination:[self path] progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {

            NSLog(@"Unzipping");

        } completionHandler:^(NSString *path2, BOOL succeeded, NSError *error) {

            if (!error) {
                NSLog(@"Successfully downloaded file to %@", path);

                dispatch_async(dispatch_get_main_queue(), ^{

                    completion(YES);

                });
            } else {

                NSLog(@"%@", error);
                failure(error);

            }

        }];

    });

} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {

    NSLog(@"%@", error);
    failure(error);

}];
[operation start];

For some strange reason, it works on the Simulator to download the files, but on the device (iPhone 6) I get the following error:

Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"

The URL is correct, as it downloads in my browser correctly and in the Simulator. Why would this just be happening on the device? And what could be causing it?

I have tried restarting my device and resetting network settings.


问:
Can Webhooks be used with a GitHub OAuth App?
So I've been reading GitHub developer docs and about webhooks they have the following statement:

Webhooks allow you to build or set up GitHub Apps which subscribe to certain events on GitHub.com. When one of those events is triggered, we'll send a HTTP POST payload to the webhook's configured URL. Webhooks can be used to update an external issue tracker, trigger CI builds, update a backup mirror, or even deploy to your production server. You're only limited by your imagination.

However, about Apps they've also got this statement:

Apps on GitHub extend and improve existing workflows. People can
  purchase apps from GitHub Marketplace or browse useful tools and
  services that integrate with GitHub in Works with GitHub.

If you're building or adding integrations, this documentation will
  help get you up and running.

For support requests, bug reports, and discussions related to GitHub
  Apps (not OAuth Apps), use the GitHub Platform Forum. The forum allows
  you to collaborate with other integrators as well as engineers and
  product managers from GitHub.

If your request is about OAuth Apps, or if you need to discuss a
  private concern, please contact support directly.

This seems that Webhooks can only be used with GitHub Apps? The difference between GitHub Apps and GitHub OAuth Apps isn't very clear and I fail to see why an OAuth app would not be able to use Webhooks?

答:
Edit

Can Webhooks be used with a GitHub OAuth App?

Yes.

Webhooks allow you to build or set up GitHub Apps which subscribe to certain events on GitHub.com.

This is an incorrect statement. This should be 'an integration with GitHub' rather than 'GitHub Apps'.

This seems that Webhooks can only be used with GitHub Apps?

No. GitHub Apps include implicit support for Webhooks. OAuth Applications request tokens with a scope for write:repo_hook or admin:org_hook to register a Webhook on the Repository or Organization.

There is a guide for creating webhooks that suggests to use the repo hooks or org hooks API endpoints.

The difference between GitHub Apps and GitHub OAuth Apps isn't very clear and I fail to see why an OAuth app would not be able to use Webhooks?

There is documentation that describes some differences between GitHub Apps and OAuth Apps.

TLDR advantages of GitHub Apps:

Granular Permissions

Option to use short-lived Tokens

GitHub Apps do not need to add a Webhook to a Repository or Organization

Avoids having Machine/Service Account users

Original

Webhooks allow your server/application to get notified whenever a specific event happens - regardless of whether you are using OAuth or GitHub App. Your application will then need to process an event and act accordingly.

Separately, your application will need to interact with GitHub's API to create, read, edit, or delete information. GitHub will usually require credentials to access or update specific information. Authentication to GitHub's API can use multiple methods:

None

Basic Authentication (username/password)

OAuth2 Token

Personal Access Token (PAT)

Installation Access Token

There are additional differences between legacy GitHub integrations and GitHub Apps.

Older integrations were based on Oauth2 and use a Token associated with a user's account. Integrations would interact with GitHub's API on behalf of a user - which is why some organizations would set up a machine user. Webhooks also need to be added explicitly.

GitHub Apps will interact with GitHub's API on it's own behalf. You must explicitly grant a GitHub App access to an Organization or Repository which enables both Webhook and API access.


问:
Installing angular bootstrap toggle
I'm learning Angular 2 so still not familiar with how it implements plugins.
I'm trying to implement angular bootstrap toggle:
http://ziscloud.github.io/angular-bootstrap-toggle/

Instructions say:
As soon as you've got all the files downloaded and included in your page you just need to declare a dependency on the ui.toggle module:
angular.module('myModule', ['ui.toggle']);

I'm not sure what that means. I just got used to declaring them in package.json and app.module.ts.

I don't see anywhere in these files where I might add that line.

package.json looks like this:

```<code>{
  "name": "arv2",
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
...
    "mydatepicker": "^2.0.21",
    "ng2-validation": "^4.2.0",
  },
  "devDependencies": {
    "@angular/cli": "1.0.2",
    "@angular/compiler-cli": "^4.0.0",
...
    "webpack-dev-server": "~2.4.2",
    "webpack-hot-middleware": "^2.18.0"
  }
}
</code>```

and app.module.ts looks like this:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
...
import { CustomFormsModule } from 'ng2-validation';

@NgModule({
    declarations: [
        AppComponent,
        SwitchClientComponent,
        SwitchClientPipe,
        ...
    ],
    imports: [
        BrowserModule,
    ...
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

finally, the actual page I'm trying to implement it on looks like this:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
  ...
}
</code>```

答:
this angular bootstrap toggle is a concept for AngularJS and not for Angular2.
So you should search for a Plugin, that run on Angular 2.

If you need no text inside, you can look here
https://material.angular.io/components/slide-toggle/overview

And if you want to use the bootstrap switcher, maybe this is one for you
jw-bootstrap-switch-ng2

Title: Installing angular bootstrap toggle

Body:
I'm learning Angular 2 so still not familiar with how it implements plugins.
I'm trying to implement angular bootstrap toggle:
http://ziscloud.github.io/angular-bootstrap-toggle/

Instructions say:
As soon as you've got all the files downloaded and included in your page you just need to declare a dependency on the ui.toggle module:
angular.module('myModule', ['ui.toggle']);

I'm not sure what that means. I just got used to declaring them in package.json and app.module.ts.

I don't see anywhere in these files where I might add that line.

package.json looks like this:

{
  "name": "arv2",
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
...
    "mydatepicker": "^2.0.21",
    "ng2-validation": "^4.2.0",
  },
  "devDependencies": {
    "@angular/cli": "1.0.2",
    "@angular/compiler-cli": "^4.0.0",
...
    "webpack-dev-server": "~2.4.2",
    "webpack-hot-middleware": "^2.18.0"
  }
}

and app.module.ts looks like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER  } from '@angular/core';
...
import { CustomFormsModule } from 'ng2-validation';

@NgModule({
    declarations: [
        AppComponent,
        SwitchClientComponent,
        SwitchClientPipe,
        ...
    ],
    imports: [
        BrowserModule,
    ...
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

finally, the actual page I'm trying to implement it on looks like this:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-switch-client',
  templateUrl: './switch-client.component.html',
  styleUrls: ['./switch-client.component.scss']

})
export class SwitchClientComponent implements OnInit {
  ...
}


答:
You need to decompile the C#. It is an advanced user scenario, but it can be done... sort of.

How do I decompile a .NET EXE into readable C# source code?

Title: recover lost C# pages

Body: I had a problem I lost all my source(CS) of web site pages but I had only published pages on server ,so please if there is any way to recover theses published pages to orignal pages with code,bin folder


问:
How can i unhide javascript and html errors hidden by filters in chrome?
I hide the JavaScript and HTML errors from console but it finds difficult job for me unhide them again.

How can unhide them again?

答:
Solved the problem by doing these steps:

Select Console.

Right click.

Move to Filter and

Then select unhide all.


问:
ERROR {org.wso2.carbon.idp.mgt.util.IdPManagementUtil} - Error when accessing the IdentityProviderManager for tenant
Getting this exception in WSO2IS 5.1.0 on signin.</p>

```<code>[2017-01-28 20:12:22,384] ERROR {org.wso2.carbon.idp.mgt.util.IdPManagementUtil} -  Error when accessing the IdentityProviderManager for tenant : xyz.com org.wso2.carbon.idp.mgt.IdentityProviderManagementException: Error retrieving primary certificate for tenant : xyz.com
        at org.wso2.carbon.idp.mgt.IdentityProviderManager.getResidentIdP(IdentityProviderManager.java:214)
        at org.wso2.carbon.idp.mgt.util.IdPManagementUtil.getRememberMeTimeout(IdPManagementUtil.java:98)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.setAuthCookie(DefaultAuthenticationRequestHandler.java:347)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.concludeFlow(DefaultAuthenticationRequestHandler.java:284)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.handle(DefaultAuthenticationRequestHandler.java:120)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultRequestCoordinator.handle(DefaultRequestCoordinator.java:135)
        at org.wso2.carbon.identity.application.authentication.framework.servlet.CommonAuthenticationServlet.doPost(CommonAuthenticationServlet.java:53)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:60)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CSRFPreventionFilter.doFilter(CSRFPreventionFilter.java:88)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CRLFPreventionFilter.doFilter(CRLFPreventionFilter.java:59)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1698)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Issue is with client-truststore.jks

Step 1

replace wso2appm-1.2.1-SNAPSHOT/repository/resources/security/wso2carbon.jks with jks file generated from pfx file (SSL files sent by provider)

Change jks file name, keystore password and alias in carbon.xml

replace client-truststore.jks with one you create in folder wso2appm-1.2.1-SNAPSHOT/repository/resources/security/client-truststore.jks

To create client-truststore.jks file please follow below steps

keytool -export -alias certalias -keystore your_jks.jks -file .pem

This will generate .pem file

If you don't know certalias name please find it by following steps and run abve command with correct alias

on Linux

keytool -list -v -keystore your_jks.jks | grep "Alias name\|Creation date"

on Windows

keytool -list -v -keystore your_jks.jks | findstr "Alias Creation"

step 2

keytool -import -alias certalias -file .pem -keystore client-truststore.jks -storepass wso2carbon

This will generate client-truststore.jks and replace the old (wso2appm-1.2.1-SNAPSHOT/repository/resources/security/client-truststore.jks) with this

Now change keystore alias in carbon.xml (wso2appm-1.2.1-SNAPSHOT/repository/conf/carbon.xml)

Run the application and check.

If still error comes change identityAlias in  below line in "repository/deployment/server/jaggeryapps/publisher/controllers/acs.jag"

var identityAlias = configs.ssoConfiguration.identityAlias;

change to
var identityAlias = "your identity alias name"

Body:
Getting this exception in WSO2IS 5.1.0 on signin.

[2017-01-28 20:12:22,384] ERROR {org.wso2.carbon.idp.mgt.util.IdPManagementUtil} -  Error when accessing the IdentityProviderManager for tenant : xyz.com org.wso2.carbon.idp.mgt.IdentityProviderManagementException: Error retrieving primary certificate for tenant : xyz.com
        at org.wso2.carbon.idp.mgt.IdentityProviderManager.getResidentIdP(IdentityProviderManager.java:214)
        at org.wso2.carbon.idp.mgt.util.IdPManagementUtil.getRememberMeTimeout(IdPManagementUtil.java:98)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.setAuthCookie(DefaultAuthenticationRequestHandler.java:347)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.concludeFlow(DefaultAuthenticationRequestHandler.java:284)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultAuthenticationRequestHandler.handle(DefaultAuthenticationRequestHandler.java:120)
        at org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.DefaultRequestCoordinator.handle(DefaultRequestCoordinator.java:135)
        at org.wso2.carbon.identity.application.authentication.framework.servlet.CommonAuthenticationServlet.doPost(CommonAuthenticationServlet.java:53)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:60)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CSRFPreventionFilter.doFilter(CSRFPreventionFilter.java:88)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CRLFPreventionFilter.doFilter(CRLFPreventionFilter.java:59)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1698)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)


问:
How to install JBoss Developer Studio on Windows
I am trying to install JBoss Developer Studio 9 on Windows using executable JAR file.

I have Java in my machine and set the PATH and JAVA_HOME environment variables.

But while launching the jar, I am facing this error:

Java virtual machine launcher couldn't find the main class program will exit

Could some one please help me in resolving this.

答: Try to use devstudio-10.4.0.GA-installer-eap.jar from here. I tried that.


问:
Building GCC make: *** [all] Error 2
I am trying to set up a cross-compiler for i686-elf on Ubuntu following the OSDev GCC Cross-Compiler Tutuorial. However, the code to set up GCC fails to build every time. I know my sources are not out of date because I sudo apt-get update'd before doing anything.

In order to get the packages I needed, I did:

```<code>sudo apt-get install g++
sudo apt-get install make
sudo apt-get install bison
sudo apt-get install flex
sudo apt-get install libgmp3-dev
sudo apt-get install libmpfr-dev libmpfr-doc libmpfr4 libmpfr4-dbg
sudo apt-get install mpc
sudo apt-get install texinfo
sudo apt-get install libcloog-isl-dev
</code>```

I think there is no problem with that method?

Then, with gcc-5.2.0 and binutils-2.25.1 (in ubuntu, bintuils appears to not work with anything above that old version) I installed binutils just fine. I went to build gcc but when I typed in make, I got the following error:

Unfortunately, I can't copy+paste 30 pages in, but this all the code near the end:

```<code>checking command to parse nm output from gcc  -m32 object... failed
checking how to run the C preprocessor... /lib/cpp
checking for ANSI C header files... no
checking for sys/types.h... no
checking for sys/stat.h... no
checking for stdlib.h... no
checking for string.h... no
checking for memory.h... no
checking for strings.h... no
checking for inttypes.h... no
checking for stdint.h... no
checking for unistd.h... no
checking for dlfcn.h... no
checking for objdir... .libs
checking if gcc  -m32 supports -fno-rtti -fno-exceptions... no
checking for gcc  -m32 option to produce PIC... -fPIC -DPIC
checking if gcc  -m32 PIC flag -fPIC -DPIC works... yes
checking if gcc  -m32 static flag -static works... no
checking if gcc  -m32 supports -c -o file.o... yes
checking if gcc  -m32 supports -c -o file.o... (cached) yes
checking whether the gcc  -m32 linker (ld -m elf_x86_64 -m elf_i386) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... configure: error: Link tests are not allowed after GCC_NO_EXECUTABLES.
Makefile:9590: recipe for target 'configure-zlib' failed
make[1]: *** [configure-zlib] Error 1
make[1]: Leaving directory '/home/david/scr'
Makefile:876: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

And this is the part (right after that) where something really bad happens:

```<code>checking dynamic linker characteristics... configure: error: Link tests are not allowed after GCC_NO_EXECUTABLES.
Makefile:9590: recipe for target 'configure-zlib' failed
make[1]: *** [configure-zlib] Error 1
make[1]: Leaving directory '/home/david/scr'
Makefile:876: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

Can anyone tell me what I am doing wrong and how I would fix it?

Thanks!

答: In addition to --with-system-zlib, it worked for me when I use --disable-multilib option.

Title: Building GCC make: *** [all] Error 2

Body:
I am trying to set up a cross-compiler for i686-elf on Ubuntu following the OSDev GCC Cross-Compiler Tutuorial. However, the code to set up GCC fails to build every time. I know my sources are not out of date because I sudo apt-get update'd before doing anything.

In order to get the packages I needed, I did:

sudo apt-get install g++
sudo apt-get install make
sudo apt-get install bison
sudo apt-get install flex
sudo apt-get install libgmp3-dev
sudo apt-get install libmpfr-dev libmpfr-doc libmpfr4 libmpfr4-dbg
sudo apt-get install mpc
sudo apt-get install texinfo
sudo apt-get install libcloog-isl-dev

I think there is no problem with that method?

Then, with gcc-5.2.0 and binutils-2.25.1 (in ubuntu, bintuils appears to not work with anything above that old version) I installed binutils just fine. I went to build gcc but when I typed in make, I got the following error:

Unfortunately, I can't copy+paste 30 pages in, but this all the code near the end:

checking command to parse nm output from gcc  -m32 object... failed
checking how to run the C preprocessor... /lib/cpp
checking for ANSI C header files... no
checking for sys/types.h... no
checking for sys/stat.h... no
checking for stdlib.h... no
checking for string.h... no
checking for memory.h... no
checking for strings.h... no
checking for inttypes.h... no
checking for stdint.h... no
checking for unistd.h... no
checking for dlfcn.h... no
checking for objdir... .libs
checking if gcc  -m32 supports -fno-rtti -fno-exceptions... no
checking for gcc  -m32 option to produce PIC... -fPIC -DPIC
checking if gcc  -m32 PIC flag -fPIC -DPIC works... yes
checking if gcc  -m32 static flag -static works... no
checking if gcc  -m32 supports -c -o file.o... yes
checking if gcc  -m32 supports -c -o file.o... (cached) yes
checking whether the gcc  -m32 linker (ld -m elf_x86_64 -m elf_i386) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... configure: error: Link tests are not allowed after GCC_NO_EXECUTABLES.
Makefile:9590: recipe for target 'configure-zlib' failed
make[1]: *** [configure-zlib] Error 1
make[1]: Leaving directory '/home/david/scr'
Makefile:876: recipe for target 'all' failed
make: *** [all] Error 2

And this is the part (right after that) where something really bad happens:

checking dynamic linker characteristics... configure: error: Link tests are not allowed after GCC_NO_EXECUTABLES.
Makefile:9590: recipe for target 'configure-zlib' failed
make[1]: *** [configure-zlib] Error 1
make[1]: Leaving directory '/home/david/scr'
Makefile:876: recipe for target 'all' failed
make: *** [all] Error 2

Can anyone tell me what I am doing wrong and how I would fix it?

Thanks!