问:
catching button clicks in javascript without server interaction
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

```<code>    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }
</code>```

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

答: You do not need to do button.value = password; since reading the value does not change it. I'm not sure why it's being cleared, maybe JavaScript does not allow password field values to be modified.

OwnerDisplayName: eviljack

Body:
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

OwnerDisplayName: Rytis


来源: stackexchange

问:
Display problem with Update Panel in ASP.NET
I'll try to explain my problem the best I can, here goes:  I have an update panel on an ASP.NET page and a Panel server control inside it.  I have an rounded corners extender attached to the Panel server control and the extender has a solid background with a solid border.

ok....I haven't found an easy easy to position the update panel itself, so, what I end up doing is trying to position the Panel server control with CSS.  Once I do and I run the project to see the finished product, there is a big gap from where the update panel control starts and where the Panel is positioned.

What I'm wanting to know is:  What's the best way to position an UpdatePanel or regular panel so that gap that I'm talking about doesn't show up??

If anyone needs me to clarify, let me know in the comments and I'll try my best.

答: Not saying that this is the best answer, but I was playing the same game with gaps displaying after asynchronous postbacks in an UpdatePanel earlier this week.  I had some ajax extender controls inside the UpdatePanel and I found that by moving the markup for those controls so that they were before the controls they extended in the aspx file, my gap problems went away.</p>

OwnerDisplayName: Robert Iver

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bert Evans

LastEditorDisplayName: Bert Evans


问:
Google Apps Script TableCell not accepting Attributes
I have some code I am using for a google apps script macro. This uses the DocumentApp TableRow and Table Cell datatype.

```<code>//row is TableRow datatype
function appendRow(row){
    var style = {};
    style[DocumentApp.Attribute.FONT_SIZE] = '8';
    style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
    row.appendTableCell(SOME_TEXT).setAttributes(style);
}
</code>```

So when I run this function the resulting cell in the row is still the default left justified. Am I missing something? They have this example on their website.

https://developers.google.com/apps-script/reference/document/table-cell#setAttributes(Object)

```<code>var body = DocumentApp.getActiveDocument().getBody();

// Define a custom paragraph style.
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
 DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.FONT_SIZE] = 18;
style[DocumentApp.Attribute.BOLD] = true;

// Append a plain paragraph.
var par = body.appendParagraph('A paragraph with custom style.');

// Apply the custom style.
par.setAttributes(style);
</code>```

答:
You may refer with this sample tutorial. Here's a sample code adding a table with cell text in right justified.

```<code>function addTableInDocument() {

  var headerStyle = {};
  headerStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#336600';
  headerStyle[DocumentApp.Attribute.BOLD] = true;
  headerStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFFFFF';

  //Style for the cells other than header row
  var cellStyle = {};
  cellStyle[DocumentApp.Attribute.BOLD] = false;
  cellStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
  cellStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;

  var doc = DocumentApp.getActiveDocument();

  //get the body section of document
  var body = doc.getBody();

  //Add a table in document
  var table = body.appendTable();

  //Create 5 rows and 4 columns
  for(var i=0; i<2; i++){
    var tr = table.appendTableRow();

    //add 4 cells in each row
    for(var j=0; j<2; j++){
      var td = tr.appendTableCell('Cell '+i+j);

      //if it is header cell, apply the header style else cellStyle
      if(i == 0) td.setAttributes(headerStyle);
      else td.setAttributes(cellStyle);

      //Apply the para style to each paragraph in cell
      var paraInCell = td.getChild(0).asParagraph();
      paraInCell.setAttributes(cellStyle);
    }
  }

  doc.saveAndClose();
}
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have some code I am using for a google apps script macro. This uses the DocumentApp TableRow and Table Cell datatype.

//row is TableRow datatype
function appendRow(row){
    var style = {};
    style[DocumentApp.Attribute.FONT_SIZE] = '8';
    style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
    row.appendTableCell(SOME_TEXT).setAttributes(style);
}

So when I run this function the resulting cell in the row is still the default left justified. Am I missing something? They have this example on their website.

https://developers.google.com/apps-script/reference/document/table-cell#setAttributes(Object)

var body = DocumentApp.getActiveDocument().getBody();

// Define a custom paragraph style.
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
 DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.FONT_SIZE] = 18;
style[DocumentApp.Attribute.BOLD] = true;

// Append a plain paragraph.
var par = body.appendParagraph('A paragraph with custom style.');

// Apply the custom style.
par.setAttributes(style);

Body:
You may refer with this sample tutorial. Here's a sample code adding a table with cell text in right justified.

function addTableInDocument() {

  var headerStyle = {};
  headerStyle[DocumentApp.Attribute.BACKGROUND_COLOR] = '#336600';
  headerStyle[DocumentApp.Attribute.BOLD] = true;
  headerStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFFFFF';

  //Style for the cells other than header row
  var cellStyle = {};
  cellStyle[DocumentApp.Attribute.BOLD] = false;
  cellStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
  cellStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;

  var doc = DocumentApp.getActiveDocument();

  //get the body section of document
  var body = doc.getBody();

  //Add a table in document
  var table = body.appendTable();

  //Create 5 rows and 4 columns
  for(var i=0; i<2; i++){
    var tr = table.appendTableRow();

    //add 4 cells in each row
    for(var j=0; j<2; j++){
      var td = tr.appendTableCell('Cell '+i+j);

      //if it is header cell, apply the header style else cellStyle
      if(i == 0) td.setAttributes(headerStyle);
      else td.setAttributes(cellStyle);

      //Apply the para style to each paragraph in cell
      var paraInCell = td.getChild(0).asParagraph();
      paraInCell.setAttributes(cellStyle);
    }
  }

  doc.saveAndClose();
}

Hope this helps.


问:
Application can't scaffold items
I created an MVC 5 application in VS 2013 Professional and then used EF 6.1 code first with an existing DB on SQL Server Express. When I try to create the views I’m using the “New scaffolded item…” then selecting the “MVC 5 controller with views, using Entity Framework.” I select the model and context classes and click OK. Then the following error message appears and no code is created. I’ve uninstalled EF Power Tools with the same error.

Error

There was an error running the selected code generator: ‘Exception has
  been thrown by the target of an invocation.’

I've also tried uninstalling/reinstalling VS 2013 and SQL Server with no changes.

Any other ideas about what might cause this error?

答:
I realize this question is old now, but I thought I'd post what solved my issue in case it helps anyone later on. In my case, it was a combination of several things mentioned in other answers. To secure my connection string I had...

Moved the connection string out of the Web.config file

Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config

Used a SqlConnectionStringBuilder to put the elements together and then pass it to my context class constructor

After doing this, I was unable to create any more controllers. To fix the issue, I had to ...

Put the complete connection string back in Web.config AND remove the reference to the external connection string file

Add a parameterless constructor to my context class and give it the name of my connectionString like this:
public contextClass() : base("name=connectionStringName") { }

Rebuild the solution, and create the controller again, and it worked!

Title: Application can't scaffold items


问:
Symfont/Twig FatalErrorException in Twig Core.php line 1595:
Note: This is my first Symfony project, so obvious mistakes are possible.

I have just pushed my Symfony application from my local environment (where it works nicely) to a live server.  Sadly, after running server:start, if I try and curl one of the local routes in the same way I tested on my local, I get the below error back:

FatalErrorException in Core.php line 1595: Parse Error: syntax error,
  unexpected '.'

Note that the Core.php file is /var/www/symfony_playground/vendor/twig/twig/lib/Twig/Extension/Core.php

I didn't some searching online, and cannot see anyone else getting similar issues, so wonder whether I have a dependency issue (although I checked this).

The line in twig that is causing the issue looks like:

```<code>$ret = $object->$method(...$arguments);
</code>```

Any suggestions much appreciated.

答:
My guess is your server is not very up-to-date when it comes to PHP. Variadic functions (the ...$arguments) were introduced in PHP 5.6 so my guess is your server is running an older version than that.

Give it a debug with by echoing phpversion() or even the more detailed phpinfo().

If this is the case the only solution would be to update PHP as downgrading symfony doesn't really work.

Body:
Note: This is my first Symfony project, so obvious mistakes are possible.

I have just pushed my Symfony application from my local environment (where it works nicely) to a live server.  Sadly, after running server:start, if I try and curl one of the local routes in the same way I tested on my local, I get the below error back:

FatalErrorException in Core.php line 1595: Parse Error: syntax error,
  unexpected '.'

Note that the Core.php file is /var/www/symfony_playground/vendor/twig/twig/lib/Twig/Extension/Core.php

I didn't some searching online, and cannot see anyone else getting similar issues, so wonder whether I have a dependency issue (although I checked this).

The line in twig that is causing the issue looks like:

$ret = $object->$method(...$arguments);

Any suggestions much appreciated.


问:
C - a NON INT function example?
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

```<code>int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);
</code>```

I want a STRING example. I attempted to modify the above .. but I FAILED.

```<code>char cube(char n){
return n;
}

char *o;
o = cube("string");
</code>```

答:
A string in C is a char* (it's a bit more complex but at this point in your learning let's just call it a char*).

That means your function must have a return type of char* if it needs to return a string.

```<code># <include stdio.h> // for print statement in second part of the code
char* iReturnAString() {
    char* str = 'this is a sample string'
    return str;
}
</code>```

The above would return a string in C.
You can also print the result:

```<code>printf('%s', iReturnAString());
// %s gets replaced with the second argument, assuming it is a string
</code>```

Title: C - a NON INT function example?

Body:
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);

I want a STRING example. I attempted to modify the above .. but I FAILED.

char cube(char n){
return n;
}

char *o;
o = cube("string");

Body:
A string in C is a char* (it's a bit more complex but at this point in your learning let's just call it a char*).

That means your function must have a return type of char* if it needs to return a string.

# <include stdio.h> // for print statement in second part of the code
char* iReturnAString() {
    char* str = 'this is a sample string'
    return str;
}

The above would return a string in C.
You can also print the result:

printf('%s', iReturnAString());
// %s gets replaced with the second argument, assuming it is a string


问:
Does HTML5 audio tag support serving mp3s from another domain?
So I am having a web application with domian "www.example.com" that needs to serve audio from "www.example2.com", but for some reason this is not working (the audio just does not stream)

<audio src="http://www.example2.com/song.mp3" controls preload></audio>

Given that if I put the sound source url directly into the browser the audio will be available

Anyone tried this? thanks

Wa'el

答:
You would need to do some tests but I reckon that it does work, but you may have difficulties with certain actions and queries

Example, you may be able to start/pause/stop but not check the title or the length since that could be a form of XSS


问:
Cast to ObjectId failed for value "0" at path "_id"
I am starting to build my REST Api using Node.js for my web app. So far I tested it in postman and it works. For example I insert this link http://localhost:3000/news and works by giving me back a json response.

```<code>            [
          {
            "_id": "593978f7995e071df49b08d8",
            "updatedAt": "2017-06-08T16:19:03.551Z",
            "createdAt": "2017-06-08T16:19:03.551Z",
            "title": "Camping in the City and this year.",
            "image": "img/news1.jpg",
            "description": "From the Municipality of Larissa, and in particular the Social Policy Advocacy and the Department of Sports and Culture and Social Policy, it is announced that following the absolutely successful 'Camping in the City' program, organized last summer, the Municipality of Larissa in collaboration with the citys stakeholders, the program Will be implemented this year as well.",
            "__v": 0,
            "comments": [
              {
                "updatedAt": "2017-06-08T16:19:03.547Z",
                "createdAt": "2017-06-08T16:19:03.547Z",
                "rating": 5,
                "comment": "Λατρεύω το camping!!!",
                "author": "Theo",
                "_id": "593978f7995e071df49b08db"
              },
              {
                "updatedAt": "2017-06-08T16:19:03.550Z",
                "createdAt": "2017-06-08T16:19:03.550Z",
                "rating": 5,
                "comment": "Καλά μιλάμε τέλειο!!!",
                "author": "Chris",
                "_id": "593978f7995e071df49b08da"
              },
              {
                "updatedAt": "2017-06-08T16:19:03.550Z",
                "createdAt": "2017-06-08T16:19:03.550Z",
                "rating": 2,
                "comment": "Βαρετό.",
                "author": "Σοφία.",
                "_id": "593978f7995e071df49b08d9"
              }
            ]
          }
        ]
</code>```

My routes are written as shown

```<code>                    var express = require('express');
                var bodyParser = require('body-parser');
                var mongooser = require('mongoose');

                var News = require('../models/news')

                var newsRouter = express.Router();

                newsRouter.use(bodyParser.json());

                newsRouter.route('/')
                .get(function(req,res,next){
                    News.find({},function(err,news){
                       if(err) throw err;
                       res.json(news);
                    });
                })

                .post(function(req,res,next){
                   News.create(req.body,function(err,news){
                      if(err) throw err;

                      console.log('News created')
                      var id = news._id;

                      res.writeHead(200,{
                         'Content-Type':'text/plain'
                      });
                       res.end('Added the article with id: ' + id);
                   })
                })
                .delete(function (req, res, next) {
                        News.remove({}, function (err, resp) {
                            if (err) throw err;
                            res.json(resp);
                        });
                });

                newsRouter.route('/:newsId')
                .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news);
                        });
                    })

                .put(function (req, res, next) {
                        News.findByIdAndUpdate(req.params.newsId, {
                            $set: req.body
                        }, {
                            new: true
                        }, function (err, news) {
                            if (err) throw err;
                            res.json(news);
                    });
                })

                .delete(function (req, res, next) {
                        News.findByIdAndRemove(req.params.newsId, function (err, resp) {
                            if (err) throw err;
                            res.json(resp);
                    });
                });

                newsRouter.route('/:newsId/comments')
                    .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news.comments);
                        });
                    })

                    .post(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            news.comments.push(req.body);
                            news.save(function (err, news) {
                                if (err) throw err;
                                console.log('Updated Comments!');
                                res.json(news);
                            });
                        });
                    })

                    .delete(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            for (var i = (news.comments.length - 1); i >= 0; i--) {
                                news.comments.id(news.comments[i]._id).remove();
                            }
                            news.save(function (err, result) {
                                if (err) throw err;
                                res.writeHead(200, {
                                    'Content-Type': 'text/plain'
                                });
                                res.end('Deleted all comments!');
                            });
                        });
                    });

                newsRouter.route('/:newsId/comments/:commentId')
                    .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news.comments.id(req.params.commentId));
                        });
                    })

                    .put(function (req, res, next) {
                        // We delete the existing commment and insert the updated
                        // comment as a new comment
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            news.comments.id(req.params.commentId).remove();
                            news.comments.push(req.body);
                            news.save(function (err, news) {
                                if (err) throw err;
                                console.log('Updated Comments!');
                                res.json(news);
                            });
                        });
                    })

                    .delete(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            news.comments.id(req.params.commentId).remove();
                            news.save(function (err, resp) {
                                if (err) throw err;
                                res.json(resp);
                            });
                        });
                    });

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

Since this is ready,I want to read this json from the client side using Angular.js. So I created a factory.

```<code>angular.module('larissaApp')
               .constant('baseURL', 'http://localhost:3000/')
               .factory('newsFactory',['$resource', 'baseURL', function($resource,baseURL) {

               var newsfac = {};

               newsfac.getNews = function(){
                    return $resource(baseURL+"news/:id",null,  {'update':{method:'PUT' }});
               };

               return newsfac;

        }])
</code>```

and a controller.

```<code>.controller('IndexController',['$scope','newsFactory','AnnouncementsFactory','EventsFactory',function($scope,newsFactory,AnnouncementsFactory,EventsFactory){

                 $scope.message="Loading ...";

                 $scope.newsOne = newsFactory.getNews().get({id:0})
                    .$promise.then(
                        function(response){
                            $scope.newsOne = response;

                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.newsTwo = newsFactory.getNews().get({id:1})
                    .$promise.then(
                        function(response){
                            $scope.newsTwo = response;
                            $scope.showDish = true;
                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.newsThree = newsFactory.getNews().get({id:2})
                    .$promise.then(
                        function(response){
                            $scope.newsTwo = response;

                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.eventOne = EventsFactory.getEvents(0);

                 $scope.eventTwo = EventsFactory.getEvents(1);

                 $scope.eventThree = EventsFactory.getEvents(2);

                 $scope.announcementOne = AnnouncementsFactory.getAnnouncement(0);
                 $scope.announcementTwo = AnnouncementsFactory.getAnnouncement(1);
                 $scope.announcementThree = AnnouncementsFactory.getAnnouncement(2);

    }])
</code>```

As you can for now,I only read dynamically the news. However I get this error in console.

```<code>                events.js:160
                  throw er; // Unhandled 'error' event
                  ^
            CastError: Cast to ObjectId failed for value "0" at path "_id" for model "News"
                at MongooseError.CastError (C:\Users\Theodosios\Desktop\larissa-node\larissa
            App\rest-server\node_modules\mongoose\lib\error\cast.js:26:11)
                at ObjectId.cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-s
            erver\node_modules\mongoose\lib\schema\objectid.js:149:13)
                at ObjectId.SchemaType._castForQuery (C:\Users\Theodosios\Desktop\larissa-no
            de\larissaApp\rest-server\node_modules\mongoose\lib\schematype.js:1023:15)
                at ObjectId.castForQuery (C:\Users\Theodosios\Desktop\larissa-node\larissaAp
            p\rest-server\node_modules\mongoose\lib\schema\objectid.js:189:15)
                at cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\nod
            e_modules\mongoose\lib\cast.js:232:32)
                at Query.cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-serv
            er\node_modules\mongoose\lib\query.js:2933:12)
                at Query.findOne (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-s
            erver\node_modules\mongoose\lib\query.js:1394:10)
                at Function.findOne (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\res
            t-server\node_modules\mongoose\lib\model.js:1360:13)
                at Function.findById (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\re
            st-server\node_modules\mongoose\lib\model.js:1288:15)
                at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\routes\ne
            wsRouter.js:41:14
                at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-nod
            e\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
                at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\nod
            e_modules\express\lib\router\route.js:137:13)
                at Route.dispatch (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-
            server\node_modules\express\lib\router\route.js:112:3)
                at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-nod
            e\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
                at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modu
            les\express\lib\router\index.js:281:22
                at param (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\no
            de_modules\express\lib\router\index.js:354:14)
            npm ERR! code ELIFECYCLE
            npm ERR! errno 1
            npm ERR! rest-server@0.0.0 start: `node ./bin/www`
            npm ERR! Exit status 1
            npm ERR!
            npm ERR! Failed at the rest-server@0.0.0 start script 'node ./bin/www'.
            npm ERR! Make sure you have the latest version of node.js and npm installed.
            npm ERR! If you do, this is most likely a problem with the rest-server package,
            npm ERR! not with npm itself.
            npm ERR! Tell the author that this fails on your system:
            npm ERR!     node ./bin/www
            npm ERR! You can get information on how to open an issue for this project with:
            npm ERR!     npm bugs rest-server
            npm ERR! Or if that isn't available, you can get their info via:
            npm ERR!     npm owner ls rest-server
            npm ERR! There is likely additional logging output above.

            npm ERR! A complete log of this run can be found in:
            npm ERR!     C:\Users\Theodosios\AppData\Roaming\npm-cache\_logs\2017-06-08T16_1
            9_28_708Z-debug.log
</code>```

How can I fix this error? As I said everything works fine with postman.

Thanks,

Theo.

Update

I did a small change in my :/newsId route. Basically I converted req.params.newsId to a mongoose Type.

```<code>newsRouter.route('/:newsId')
                .get(function (req, res, next) {

                        News.findById(req.params.newsId = mongoose.Types.ObjectId(req.params.newsId), function (err, news) {
                            if (err) throw err;
                            res.json(news);
                            console.log(req.body._id);
                        });
                    })
</code>```

But now I get this error.

```<code>2angular.js:12587 GET http://localhost:3000/news/0 500 (Internal Server
Error)

index.html#!/:1 XMLHttpRequest cannot load http://localhost:3000/news/0. No
'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:61612' is therefore not allowed access. The
response had HTTP
</code>```

答:
I've had the same error a couples days ago, so here is my suggestion :

"0" is a string, so not an ObjectId, so you can try to turn it into one. Find the variable containing your id "0" and convert it into an ObjectId like that :

```<code>req.body._id = mongoose.Types.ObjectId(req.body._id);
</code>```

or

```<code>req.params.newsId = mongoose.Types.ObjectId(req.params.newsId);
</code>```

But you have another problem : 0 cannot be an ObjectId because an ObjectId must be a single String of 12 bytes or a string of 24 hex characters. So the above methods won't work.
You may have not recieved a correct ID.

Hope it helps,

Best regards,

 UPDATE

You'r getting an error 500 because your update is wrong, you can't assign a value to req.body._id inside your method News.findById. You should do the following :

```<code>newsRouter.route('/:newsId')
  .get(function (req, res, next) {
    req.params.newsId = mongoose.Types.ObjectId(req.params.newsId);
    News.findById(req.params.newsId, function (err, news) {
      if (err) throw err;
      console.log(req.body._id);
      res.json(news);
    });
  });
</code>```

Body:
I am starting to build my REST Api using Node.js for my web app. So far I tested it in postman and it works. For example I insert this link http://localhost:3000/news and works by giving me back a json response.

            [
          {
            "_id": "593978f7995e071df49b08d8",
            "updatedAt": "2017-06-08T16:19:03.551Z",
            "createdAt": "2017-06-08T16:19:03.551Z",
            "title": "Camping in the City and this year.",
            "image": "img/news1.jpg",
            "description": "From the Municipality of Larissa, and in particular the Social Policy Advocacy and the Department of Sports and Culture and Social Policy, it is announced that following the absolutely successful 'Camping in the City' program, organized last summer, the Municipality of Larissa in collaboration with the citys stakeholders, the program Will be implemented this year as well.",
            "__v": 0,
            "comments": [
              {
                "updatedAt": "2017-06-08T16:19:03.547Z",
                "createdAt": "2017-06-08T16:19:03.547Z",
                "rating": 5,
                "comment": "Λατρεύω το camping!!!",
                "author": "Theo",
                "_id": "593978f7995e071df49b08db"
              },
              {
                "updatedAt": "2017-06-08T16:19:03.550Z",
                "createdAt": "2017-06-08T16:19:03.550Z",
                "rating": 5,
                "comment": "Καλά μιλάμε τέλειο!!!",
                "author": "Chris",
                "_id": "593978f7995e071df49b08da"
              },
              {
                "updatedAt": "2017-06-08T16:19:03.550Z",
                "createdAt": "2017-06-08T16:19:03.550Z",
                "rating": 2,
                "comment": "Βαρετό.",
                "author": "Σοφία.",
                "_id": "593978f7995e071df49b08d9"
              }
            ]
          }
        ]

My routes are written as shown

                    var express = require('express');
                var bodyParser = require('body-parser');
                var mongooser = require('mongoose');

                var News = require('../models/news')

                var newsRouter = express.Router();

                newsRouter.use(bodyParser.json());

                newsRouter.route('/')
                .get(function(req,res,next){
                    News.find({},function(err,news){
                       if(err) throw err;
                       res.json(news);
                    });
                })

                .post(function(req,res,next){
                   News.create(req.body,function(err,news){
                      if(err) throw err;

                      console.log('News created')
                      var id = news._id;

                      res.writeHead(200,{
                         'Content-Type':'text/plain'
                      });
                       res.end('Added the article with id: ' + id);
                   })
                })
                .delete(function (req, res, next) {
                        News.remove({}, function (err, resp) {
                            if (err) throw err;
                            res.json(resp);
                        });
                });

                newsRouter.route('/:newsId')
                .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news);
                        });
                    })

                .put(function (req, res, next) {
                        News.findByIdAndUpdate(req.params.newsId, {
                            $set: req.body
                        }, {
                            new: true
                        }, function (err, news) {
                            if (err) throw err;
                            res.json(news);
                    });
                })

                .delete(function (req, res, next) {
                        News.findByIdAndRemove(req.params.newsId, function (err, resp) {
                            if (err) throw err;
                            res.json(resp);
                    });
                });

                newsRouter.route('/:newsId/comments')
                    .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news.comments);
                        });
                    })

                    .post(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            news.comments.push(req.body);
                            news.save(function (err, news) {
                                if (err) throw err;
                                console.log('Updated Comments!');
                                res.json(news);
                            });
                        });
                    })

                    .delete(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            for (var i = (news.comments.length - 1); i >= 0; i--) {
                                news.comments.id(news.comments[i]._id).remove();
                            }
                            news.save(function (err, result) {
                                if (err) throw err;
                                res.writeHead(200, {
                                    'Content-Type': 'text/plain'
                                });
                                res.end('Deleted all comments!');
                            });
                        });
                    });

                newsRouter.route('/:newsId/comments/:commentId')
                    .get(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            res.json(news.comments.id(req.params.commentId));
                        });
                    })

                    .put(function (req, res, next) {
                        // We delete the existing commment and insert the updated
                        // comment as a new comment
                        News.findById(req.params.newsId, function (err, news) {
                            if (err) throw err;
                            news.comments.id(req.params.commentId).remove();
                            news.comments.push(req.body);
                            news.save(function (err, news) {
                                if (err) throw err;
                                console.log('Updated Comments!');
                                res.json(news);
                            });
                        });
                    })

                    .delete(function (req, res, next) {
                        News.findById(req.params.newsId, function (err, news) {
                            news.comments.id(req.params.commentId).remove();
                            news.save(function (err, resp) {
                                if (err) throw err;
                                res.json(resp);
                            });
                        });
                    });

                module.exports = newsRouter;

Since this is ready,I want to read this json from the client side using Angular.js. So I created a factory.

angular.module('larissaApp')
               .constant('baseURL', 'http://localhost:3000/')
               .factory('newsFactory',['$resource', 'baseURL', function($resource,baseURL) {

               var newsfac = {};

               newsfac.getNews = function(){
                    return $resource(baseURL+"news/:id",null,  {'update':{method:'PUT' }});
               };

               return newsfac;

        }])

and a controller.

.controller('IndexController',['$scope','newsFactory','AnnouncementsFactory','EventsFactory',function($scope,newsFactory,AnnouncementsFactory,EventsFactory){

                 $scope.message="Loading ...";

                 $scope.newsOne = newsFactory.getNews().get({id:0})
                    .$promise.then(
                        function(response){
                            $scope.newsOne = response;

                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.newsTwo = newsFactory.getNews().get({id:1})
                    .$promise.then(
                        function(response){
                            $scope.newsTwo = response;
                            $scope.showDish = true;
                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.newsThree = newsFactory.getNews().get({id:2})
                    .$promise.then(
                        function(response){
                            $scope.newsTwo = response;

                        },
                        function(response) {
                            $scope.message = "Error: "+response.status + " " + response.statusText;
                        }
                 );

                 $scope.eventOne = EventsFactory.getEvents(0);

                 $scope.eventTwo = EventsFactory.getEvents(1);

                 $scope.eventThree = EventsFactory.getEvents(2);

                 $scope.announcementOne = AnnouncementsFactory.getAnnouncement(0);
                 $scope.announcementTwo = AnnouncementsFactory.getAnnouncement(1);
                 $scope.announcementThree = AnnouncementsFactory.getAnnouncement(2);

    }])

As you can for now,I only read dynamically the news. However I get this error in console.

                events.js:160
                  throw er; // Unhandled 'error' event
                  ^
            CastError: Cast to ObjectId failed for value "0" at path "_id" for model "News"
                at MongooseError.CastError (C:\Users\Theodosios\Desktop\larissa-node\larissa
            App\rest-server\node_modules\mongoose\lib\error\cast.js:26:11)
                at ObjectId.cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-s
            erver\node_modules\mongoose\lib\schema\objectid.js:149:13)
                at ObjectId.SchemaType._castForQuery (C:\Users\Theodosios\Desktop\larissa-no
            de\larissaApp\rest-server\node_modules\mongoose\lib\schematype.js:1023:15)
                at ObjectId.castForQuery (C:\Users\Theodosios\Desktop\larissa-node\larissaAp
            p\rest-server\node_modules\mongoose\lib\schema\objectid.js:189:15)
                at cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\nod
            e_modules\mongoose\lib\cast.js:232:32)
                at Query.cast (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-serv
            er\node_modules\mongoose\lib\query.js:2933:12)
                at Query.findOne (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-s
            erver\node_modules\mongoose\lib\query.js:1394:10)
                at Function.findOne (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\res
            t-server\node_modules\mongoose\lib\model.js:1360:13)
                at Function.findById (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\re
            st-server\node_modules\mongoose\lib\model.js:1288:15)
                at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\routes\ne
            wsRouter.js:41:14
                at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-nod
            e\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
                at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\nod
            e_modules\express\lib\router\route.js:137:13)
                at Route.dispatch (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-
            server\node_modules\express\lib\router\route.js:112:3)
                at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-nod
            e\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
                at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modu
            les\express\lib\router\index.js:281:22
                at param (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\no
            de_modules\express\lib\router\index.js:354:14)
            npm ERR! code ELIFECYCLE
            npm ERR! errno 1
            npm ERR! rest-server@0.0.0 start: `node ./bin/www`
            npm ERR! Exit status 1
            npm ERR!
            npm ERR! Failed at the rest-server@0.0.0 start script 'node ./bin/www'.
            npm ERR! Make sure you have the latest version of node.js and npm installed.
            npm ERR! If you do, this is most likely a problem with the rest-server package,
            npm ERR! not with npm itself.
            npm ERR! Tell the author that this fails on your system:
            npm ERR!     node ./bin/www
            npm ERR! You can get information on how to open an issue for this project with:
            npm ERR!     npm bugs rest-server
            npm ERR! Or if that isn't available, you can get their info via:
            npm ERR!     npm owner ls rest-server
            npm ERR! There is likely additional logging output above.

            npm ERR! A complete log of this run can be found in:
            npm ERR!     C:\Users\Theodosios\AppData\Roaming\npm-cache\_logs\2017-06-08T16_1
            9_28_708Z-debug.log

How can I fix this error? As I said everything works fine with postman.

Thanks,

Theo.

Update

I did a small change in my :/newsId route. Basically I converted req.params.newsId to a mongoose Type.

newsRouter.route('/:newsId')
                .get(function (req, res, next) {

                        News.findById(req.params.newsId = mongoose.Types.ObjectId(req.params.newsId), function (err, news) {
                            if (err) throw err;
                            res.json(news);
                            console.log(req.body._id);
                        });
                    })

But now I get this error.

2angular.js:12587 GET http://localhost:3000/news/0 500 (Internal Server
Error)

index.html#!/:1 XMLHttpRequest cannot load http://localhost:3000/news/0. No
'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:61612' is therefore not allowed access. The
response had HTTP

Body:
I've had the same error a couples days ago, so here is my suggestion :

"0" is a string, so not an ObjectId, so you can try to turn it into one. Find the variable containing your id "0" and convert it into an ObjectId like that :

req.body._id = mongoose.Types.ObjectId(req.body._id);

or

req.params.newsId = mongoose.Types.ObjectId(req.params.newsId);

But you have another problem : 0 cannot be an ObjectId because an ObjectId must be a single String of 12 bytes or a string of 24 hex characters. So the above methods won't work.
You may have not recieved a correct ID.

Hope it helps,

Best regards,

 UPDATE

You'r getting an error 500 because your update is wrong, you can't assign a value to req.body._id inside your method News.findById. You should do the following :

newsRouter.route('/:newsId')
  .get(function (req, res, next) {
    req.params.newsId = mongoose.Types.ObjectId(req.params.newsId);
    News.findById(req.params.newsId, function (err, news) {
      if (err) throw err;
      console.log(req.body._id);
      res.json(news);
    });
  });


问:
how to setup multiple SMTP email servers primary & backup in C#
I am trying to develop a email client. which sends email to the given recipients

```<code>using System.Net;
using System.Net.Mail;

MailMessage msg;
SmtpClient client;
SMTPURL=abc.xyz
SMTPPort=87
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
</code>```

this code is working well, but I have a backup email server with URL 123.xyz

if my abc.xyz is down or I have wrong url I will get a SMTPException

Now my question is how to reroute my message  to 123.xyz backup mail server

My assumption is to catch the SMTPException and change the SMTPURL to 123.xyz and resend, but is this a good way or any other alternates exists to reroute to secondary mail server ?

Thanks in advance

答:
you should be able to use your basic try/catch block:</p>

```<code>public void function sendemail()
{
try{
SendEmailByServer(primaryserverurl);
}
catch(SMTPException se)
{
sendemailbyserver(backupurl);
}
catch(Exception ex)
{
//something else broke
}

}

public void function SendEmailByServer(string server)
{
MailMessage msg;
SmtpClient client;
SMTPURL=server;
SMTPPort=87;
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
}
</code>```

Body:
I am trying to develop a email client. which sends email to the given recipients

using System.Net;
using System.Net.Mail;

MailMessage msg;
SmtpClient client;
SMTPURL=abc.xyz
SMTPPort=87
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);

this code is working well, but I have a backup email server with URL 123.xyz

if my abc.xyz is down or I have wrong url I will get a SMTPException

Now my question is how to reroute my message  to 123.xyz backup mail server

My assumption is to catch the SMTPException and change the SMTPURL to 123.xyz and resend, but is this a good way or any other alternates exists to reroute to secondary mail server ?

Thanks in advance

Body:
you should be able to use your basic try/catch block:

public void function sendemail()
{
try{
SendEmailByServer(primaryserverurl);
}
catch(SMTPException se)
{
sendemailbyserver(backupurl);
}
catch(Exception ex)
{
//something else broke
}

}

public void function SendEmailByServer(string server)
{
MailMessage msg;
SmtpClient client;
SMTPURL=server;
SMTPPort=87;
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
}


问:
How do I read (i.e. understand) this Java array?
```<code>String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};
</code>```

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

```<code>int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };
</code>```

答:
I recommend adding some indentation, which will help you keep track of what's at what level of this nested array:

```<code>String[][][] arr  =  {
    {
        { "a", "b", "c" },
        { "d", "e", null }
    },
    {
        { "x" },
        null
    },
    {
        { "y" }
    },
    {
        { "z", "p" },
        {}
    }
};
</code>```

Does that help? I find this makes it easier to visualize the data structure and to answer questions like "What's the value of arr[1][0][0]?"

You can read the type String[][][] as "an array of arrays of arrays of strings," or perhaps "a three-dimensional array of strings."

Body:
String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };

Body:
I recommend adding some indentation, which will help you keep track of what's at what level of this nested array:

String[][][] arr  =  {
    {
        { "a", "b", "c" },
        { "d", "e", null }
    },
    {
        { "x" },
        null
    },
    {
        { "y" }
    },
    {
        { "z", "p" },
        {}
    }
};

Does that help? I find this makes it easier to visualize the data structure and to answer questions like "What's the value of arr[1][0][0]?"

You can read the type String[][][] as "an array of arrays of arrays of strings," or perhaps "a three-dimensional array of strings."


问:
Initial Questions checkbox default
Could someone please point me to clues to how I can get the Initial Questions of Multiple titles: and Published: (yes, those are turned on in our 5.6 build) to show without the checked attribute by default?

We want <input name="multiple_titles" type="checkbox" value="true"> without checked.

I'm pretty new to DSpace and Mirage2. Cheers! Dave.

答:
I believe that you can override the following code to solve this issue.

```<code>submissionItem.setMultipleFiles(true);
submissionItem.setMultipleTitles(true);
submissionItem.setPublishedBefore(true);
</code>```

in  https://github.com/DSpace/DSpace/blob/dspace-5_x/dspace-api/src/main/java/org/dspace/submit/step/SkipInitialQuestionsStep.java#L52-L55

Since this is in dspace-api, you can create a customized version of the file in your additions module.

Title: Initial Questions checkbox default

Body:
I believe that you can override the following code to solve this issue.

submissionItem.setMultipleFiles(true);
submissionItem.setMultipleTitles(true);
submissionItem.setPublishedBefore(true);

in  https://github.com/DSpace/DSpace/blob/dspace-5_x/dspace-api/src/main/java/org/dspace/submit/step/SkipInitialQuestionsStep.java#L52-L55

Since this is in dspace-api, you can create a customized version of the file in your additions module.


问:
Set focus on UserForm Textbox on tabbing from another Textbox
I have a Userform in Excel. It has 6 Textboxes, they are the only controls on the Userform with TabStop set to True.

I can tab and move through the textboxes. I cannot get SetFocus to work on Events fired when moving between the Textboxes. I can put a CommandButton on the userform with Userform16.Textbox1.Setfocus and it works as expected to move the focus to Textbox1.

I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered. It moves focus to Textbox3 when I tab out of TextBox1.

```<code>Private Sub TextBox2_Enter()
   Cancel = True
   UserForm16.TextBox1.SetFocus
End Sub
</code>```

By putting a Stop in the above, I can see that the event is firing as expected, but it will not allow me to control the focus the next control.

I get the same results with or without the Cancel = True statement in the sub.

答:
I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered, it actually moves focus to Textbox3 when I tab out of TextBox1.

You can't set focus to another control in the _Enter() event. If you try to then the code will move focus to control which has the next TabIndex

For example

Let's say you have 5 textboxes with the following TabIndex

```<code>TextBox1 (TabIndex 0)
TextBox2 (TabIndex 1)
TextBox3 (TabIndex 3)
TextBox4 (TabIndex 4)
TextBox5 (TabIndex 2)
</code>```

Now if you have this code

```<code>Private Sub TextBox2_Enter()
    TextBox3.SetFocus
End Sub
</code>```

The moment you press TAB from TextBox1, the focus will move to TextBox5 (and not TextBox3) as it has the next TabIndex.

Also Cancel = True will not have any effect because it is not an argument of _Enter() like it is of say Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Edit

BTW, the only time the focus will come back to Textbox1 in your scenario is when there are only two TextBoxes in the form.

ContentLicense: CC BY-SA 4.0

Body:
I have a Userform in Excel. It has 6 Textboxes, they are the only controls on the Userform with TabStop set to True.

I can tab and move through the textboxes. I cannot get SetFocus to work on Events fired when moving between the Textboxes. I can put a CommandButton on the userform with Userform16.Textbox1.Setfocus and it works as expected to move the focus to Textbox1.

I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered. It moves focus to Textbox3 when I tab out of TextBox1.

Private Sub TextBox2_Enter()
   Cancel = True
   UserForm16.TextBox1.SetFocus
End Sub

By putting a Stop in the above, I can see that the event is firing as expected, but it will not allow me to control the focus the next control.

I get the same results with or without the Cancel = True statement in the sub.

Body:
I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered, it actually moves focus to Textbox3 when I tab out of TextBox1.

You can't set focus to another control in the _Enter() event. If you try to then the code will move focus to control which has the next TabIndex

For example

Let's say you have 5 textboxes with the following TabIndex

TextBox1 (TabIndex 0)
TextBox2 (TabIndex 1)
TextBox3 (TabIndex 3)
TextBox4 (TabIndex 4)
TextBox5 (TabIndex 2)

Now if you have this code

Private Sub TextBox2_Enter()
    TextBox3.SetFocus
End Sub

The moment you press TAB from TextBox1, the focus will move to TextBox5 (and not TextBox3) as it has the next TabIndex.

Also Cancel = True will not have any effect because it is not an argument of _Enter() like it is of say Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Edit

BTW, the only time the focus will come back to Textbox1 in your scenario is when there are only two TextBoxes in the form.


问:
Refresh an UltraWinGrid from a separate form
I've got a form with a list of customers and another form where customers can be added. When I open the fAddCustomer form, from fCustomerList, I'm calling it using this code:

```<code>Dim f As New Form
f = New fAddCustomer(con, False)
f.MdiParent = Me.MdiParent
f.Show()
</code>```

On fCustomerAdd, I've got a ToolStripButton to add the customer. When the form is closed, I need to refresh the UltraWinGrid that I have on fCustomerList to view the new data on the list automatically.

Because I'm using a ToolStripButton and the form uses f.MdiParent = Me.MdiParent, I can't use the same solution that was used in this answer here, as there is no DialogResult on a ToolStripButton, and you can't use ShowDialog when using MdiParents.

Is there any other way I can achieve this at all?

答:
Here's a simple example:</p>

```<code>' ... in fCustomerList ...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim f As New fAddCustomer(con, False)
    f.MdiParent = Me.MdiParent
    AddHandler f.FormClosed, AddressOf f_FormClosed
    f.Show()
End Sub

Private Sub f_FormClosed(sender As Object, e As FormClosedEventArgs)
    ' ... refresh your UltraWinGrid ...
End Sub
</code>```

Body:
I've got a form with a list of customers and another form where customers can be added. When I open the fAddCustomer form, from fCustomerList, I'm calling it using this code:

Dim f As New Form
f = New fAddCustomer(con, False)
f.MdiParent = Me.MdiParent
f.Show()

On fCustomerAdd, I've got a ToolStripButton to add the customer. When the form is closed, I need to refresh the UltraWinGrid that I have on fCustomerList to view the new data on the list automatically.

Because I'm using a ToolStripButton and the form uses f.MdiParent = Me.MdiParent, I can't use the same solution that was used in this answer here, as there is no DialogResult on a ToolStripButton, and you can't use ShowDialog when using MdiParents.

Is there any other way I can achieve this at all?

Body:
Here's a simple example:

' ... in fCustomerList ...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim f As New fAddCustomer(con, False)
    f.MdiParent = Me.MdiParent
    AddHandler f.FormClosed, AddressOf f_FormClosed
    f.Show()
End Sub

Private Sub f_FormClosed(sender As Object, e As FormClosedEventArgs)
    ' ... refresh your UltraWinGrid ...
End Sub


问:
Using jquery to get value of text area in closest table cell
I have the following table

```<code><tr>
<td data-toggle="tooltip" title="Not Started"><img  src="images/small_info_icon.png"></td>
<td>Demo Demo</td>
<td>January</td>
<td class="updaterow"><textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea></td>
<td id="34455"><button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button> </td>
</tr>
</code>```

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

```<code>$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});
</code>```

Is it possible to get the textvalue of the textarea?

答:
This is what you need -

```<code>$(this).closest('tr').find('textarea').val();
</code>```

Here is a fiddle for the same - https://jsfiddle.net/v44rzxLo/1/. On a side note, do not have same ids for multiple elements.

Body:
I have the following table

Demo Demo
January
<textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea>
<button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button>

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});

Is it possible to get the textvalue of the textarea?

Body:
This is what you need -

$(this).closest('tr').find('textarea').val();

Here is a fiddle for the same - https://jsfiddle.net/v44rzxLo/1/. On a side note, do not have same ids for multiple elements.


问:
How to debug "quotes is not defined" error in Chrome Tools?
I keep getting an error in Chrome Tools that "quotes is not defined". I can find the solution. When I click to have Chrome Tools to show me the error it ends up in the Math.floor-Math.random.

Here is my code.

```<code><div class="container-fluid text-center">
<h1>Random quote Generator</h1>

<br>
<button class="btn btn-danger" type="submit">New Quote</button>

<a href="#" id="tweet" class="btn btn-primary">Tweet Out!</a>
<br>
<div class="quotes">
    <span class="quote"></span>
    <span class="author"></span>
</div>

</div>

$(document).ready(function(){

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];
};

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);

  $(".btn").on("click", function(){
  getQuote();
  });

 });
</code>```

答:
I think you ended the getQuote function too early. Your code should be:

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

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
};

  $(".btn").on("click", function(){
  getQuote();
  });

 });
</code>```

Body:
I keep getting an error in Chrome Tools that "quotes is not defined". I can find the solution. When I click to have Chrome Tools to show me the error it ends up in the Math.floor-Math.random.

Here is my code.

Random quote Generator

<button class="btn btn-danger" type="submit">New Quote</button>

Tweet Out!

$(document).ready(function(){

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];
};

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);

  $(".btn").on("click", function(){
  getQuote();
  });

 });

Body:
I think you ended the getQuote function too early. Your code should be:

$(document).ready(function(){

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
};

  $(".btn").on("click", function(){
  getQuote();
  });

 });


问:
How to pass event from QML signal handler to base class
I have TextField object in which I want to slightly change behaviour of onTabPressed. I'm using Keys attached object for that:

```<code>Keys.onTabPressed: {
  model.item.value = text;
}
</code>```

But then I lose its typical behaviour to switch between TextFields . In QtWidgets I would have done it with something like  return QTextField::onTabPressed(event).

Are there any ways to achieve similar propagation of event to base class' event handler? In other words, is it possible to call base class' function from same function of derived class?

答:
Strange, I thought I've checked that. Solution is prevent an event from being accepted, then it propagates automatically, like shown in https://forum.qt.io/topic/19083/solved-work-around-qml-calling-overriden-functions/6 . In my case:</p>

```<code>Keys.onTabPressed: {
  model.item.value = text;
  event.accepted = false
}
</code>```

Body:
I have TextField object in which I want to slightly change behaviour of onTabPressed. I'm using Keys attached object for that:

Keys.onTabPressed: {
  model.item.value = text;
}

But then I lose its typical behaviour to switch between TextFields . In QtWidgets I would have done it with something like  return QTextField::onTabPressed(event).

Are there any ways to achieve similar propagation of event to base class' event handler? In other words, is it possible to call base class' function from same function of derived class?

Body:
Strange, I thought I've checked that. Solution is prevent an event from being accepted, then it propagates automatically, like shown in https://forum.qt.io/topic/19083/solved-work-around-qml-calling-overriden-functions/6 . In my case:

Keys.onTabPressed: {
  model.item.value = text;
  event.accepted = false
}


问:
How can I sort the result of array_merge() function?
Here is my code:

```<code><?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )
</code>```

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

```<code>/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )
</code>```

答:
```<code>function sort($array){
        $emptyKey ="";
        foreach ($array as $key => $value){
             if(empty($value){
                  $emptyKey = $key;
                   break;
             }
        }
        unset($array[$emptyKey]);
        $array[$emptyKey] = "";
        return $array;
}
</code>```

Body:
Here is my code:

<?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )


问:
XSLT transformation to xml, grouping by key
I have problem with write xsl to transform my xml to raport version.
It looks like that:

```<code><library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>
        <article>
            <authorId>1001</authorId>
            <title>Article1</title>
        </article>
        <article>
            <authorId>1002</authorId>
            <title>Article2</title>
        </article>
        <article>
            <authorId>1001</authorId>
            <title>Article3</title>
        </article>
    </articles>
</library>
</code>```

I want to tranform it to:

```<code><raport>
    <authorArticles>
        <author>John</author>
        <articles>
            <article>Article1</article>
            <article>Article3</article>
        </articles>
    </authorArticles>
    <authorArticles>
        <author>Tom</author>
        <articles>
            <article>Article2</article>
        </articles>
    </authorArticles>
</raport>
</code>```

I have idea to use for each, on for ids in authors and neasted for articles, but I dont know how to do it. Anyone know how to make this transformation ?

答:
This XSLT:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="node() | @*" name="identity">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="library">
    <raport>
        <xsl:apply-templates select="authors/author"/>
    </raport>
</xsl:template>

<xsl:template match="author">
    <authorArticles>
        <xsl:call-template name="identity"/>
        <articles>
            <xsl:apply-templates select="../../articles/article[authorId = current()/@id]"/>
        </articles>
    </authorArticles>
</xsl:template>

<xsl:template match="article">
    <xsl:call-template name="identity"/> <!-- In case of more characteristics -->
</xsl:template>

<xsl:template match="title">
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="author/@id | authorId"/>

</xsl:stylesheet>
</code>```

With this XML input:

```<code><library>
<authors>
    <author id="1001">John</author>
    <author id="1002">Tom</author>
</authors>
<articles>
    <article>
        <authorId>1001</authorId>
        <title>Article1</title>
    </article>
    <article>
        <authorId>1002</authorId>
        <title>Article2</title>
    </article>
    <article>
        <authorId>1001</authorId>
        <title>Article3</title>
    </article>
</articles>
</library>
</code>```

Provides this needed result:

```<code><raport>
    <authorArticles>
       <author>John</author>
       <articles>
          <article>Article1</article>
          <article>Article3</article>
       </articles>
    </authorArticles>
    <authorArticles>
       <author>Tom</author>
       <articles>
           <article>Article2</article>
       </articles>
    </authorArticles>
</raport>
</code>```

The further optimization might be using keys, but it looks premature with your structure.

Body:
I have problem with write xsl to transform my xml to raport version.
It looks like that:

<library>
    <authors>
        <author id="1001">John</author>
        <author id="1002">Tom</author>
    </authors>
    <articles>

            <authorId>1001</authorId>
            <title>Article1</title>

            <authorId>1002</authorId>
            <title>Article2</title>

            <authorId>1001</authorId>
            <title>Article3</title>

    </articles>
</library>

I want to tranform it to:

<raport>
    <authorArticles>
        <author>John</author>
        <articles>

Article1

Article3

        </articles>
    </authorArticles>
    <authorArticles>
        <author>Tom</author>
        <articles>

Article2

        </articles>
    </authorArticles>
</raport>

I have idea to use for each, on for ids in authors and neasted for articles, but I dont know how to do it. Anyone know how to make this transformation ?

Body:
This XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="node() | @*" name="identity">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="library">
    <raport>
        <xsl:apply-templates select="authors/author"/>
    </raport>
</xsl:template>

<xsl:template match="author">
    <authorArticles>
        <xsl:call-template name="identity"/>
        <articles>
            <xsl:apply-templates select="../../articles/article[authorId = current()/@id]"/>
        </articles>
    </authorArticles>
</xsl:template>

<xsl:template match="article">
    <xsl:call-template name="identity"/> <!-- In case of more characteristics -->
</xsl:template>

<xsl:template match="title">
    <xsl:value-of select="."/>
</xsl:template>

<xsl:template match="author/@id | authorId"/>

</xsl:stylesheet>

With this XML input:

<library>
<authors>
    <author id="1001">John</author>
    <author id="1002">Tom</author>
</authors>
<articles>
    <article>
        <authorId>1001</authorId>
        <title>Article1</title>
    </article>
    <article>
        <authorId>1002</authorId>
        <title>Article2</title>
    </article>
    <article>
        <authorId>1001</authorId>
        <title>Article3</title>
    </article>
</articles>
</library>

Provides this needed result:

<raport>
    <authorArticles>
       <author>John</author>
       <articles>
          <article>Article1</article>
          <article>Article3</article>
       </articles>
    </authorArticles>
    <authorArticles>
       <author>Tom</author>
       <articles>
           <article>Article2</article>
       </articles>
    </authorArticles>
</raport>

The further optimization might be using keys, but it looks premature with your structure.


问:
python selenium search query provides multiple results. how choose which is mine search query?
I made a search query with selenium. after that i get multiple results. Now the problem is, only one link is right.how can i select the link from multiple results?  and parse the data from the results.
i have a list and every time a search query is made results may change sometimes its 10 or 15.

the following code will select the first result always, But in this case i am looking for 4 link:

code:

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get("url")
#time.sleep(5)

username = driver.find_element_by_name("p_name")
#time.sleep(1)
username.send_keys("xxxxx)
#username.clear()
driver.find_element_by_xpath("html/body/form/table[6]/tbody/tr/td[2]/input").click()
driver.find_element_by_xpath("html/body/form/table[3]/tbody/tr[2]/td[4]/a").click()

html = driver.page_source

soup =BeautifulSoup(html)

for tag in soup.find_all('table'):
    print tag.text
</code>```

答:
You know the general form of entries in the search results page, that is, they're capitalised and shorn of special characters. Assuming that you have such a search page you can use this knowledge and selenium to search for text containing what you want, in this way, with an xpath expression.

```<code>>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get('http://egov.sos.state.or.us/br/pkg_web_name_srch_inq.do_name_srch?p_name=OREGON%20BUD%20COMPANY%2C%20LLC&p_regist_nbr=&p_srch=PHASE1&p_print=FALSE&p_entity_status=ACTINA')
>>> driver.find_element_by_xpath('.//*[contains(text(),"OREGON BUD COMPANY LLC")]/../..').text
'   4 DLLC ACT 1097010-94   CUR   OREGON BUD COMPANY LLC Search'
</code>```

I've simply dumped the text for the entire row. You'll need to extract the text items you actually want from the parent tr element.

PS: There's a good page of xpath expressions at https://gist.github.com/LeCoupa/8c305ec8c713aad07b14.

Body:
I made a search query with selenium. after that i get multiple results. Now the problem is, only one link is right.how can i select the link from multiple results?  and parse the data from the results.
i have a list and every time a search query is made results may change sometimes its 10 or 15.

the following code will select the first result always, But in this case i am looking for 4 link:

code:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get("url")
#time.sleep(5)

username = driver.find_element_by_name("p_name")
#time.sleep(1)
username.send_keys("xxxxx)
#username.clear()
driver.find_element_by_xpath("html/body/form/table[6]/tbody/tr/td[2]/input").click()
driver.find_element_by_xpath("html/body/form/table[3]/tbody/tr[2]/td[4]/a").click()

html = driver.page_source

soup =BeautifulSoup(html)

for tag in soup.find_all('table'):
    print tag.text

Body:
You know the general form of entries in the search results page, that is, they're capitalised and shorn of special characters. Assuming that you have such a search page you can use this knowledge and selenium to search for text containing what you want, in this way, with an xpath expression.

>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get('http://egov.sos.state.or.us/br/pkg_web_name_srch_inq.do_name_srch?p_name=OREGON%20BUD%20COMPANY%2C%20LLC&p_regist_nbr=&p_srch=PHASE1&p_print=FALSE&p_entity_status=ACTINA')
>>> driver.find_element_by_xpath('.//*[contains(text(),"OREGON BUD COMPANY LLC")]/../..').text
'   4 DLLC ACT 1097010-94   CUR   OREGON BUD COMPANY LLC Search'

I've simply dumped the text for the entire row. You'll need to extract the text items you actually want from the parent tr element.

PS: There's a good page of xpath expressions at https://gist.github.com/LeCoupa/8c305ec8c713aad07b14.


问:
Highcharts exporting hide data labels if number doesn't fit in stacked bar
I am working with highcharts and would like to disable datalabels on the main graph, but show them in the exported graph. However, if the data is smaller than a certain number, I would like to hide the labels in exported graph as well. I have seen this post on how to manage which datalabels are shown according to height: Highcharts stacked bar chart hide data labels not to overlap. However, I am not sure how to show certain datalabels only in the exported graph. This is my graph: https://jsfiddle.net/er1187/nbjh5jz3/
When I export, I want to hide these datalabels that are not showing properly:

I tried using overflow and crop but was unable to fix the appearance so I would like to hide them.

```<code>plotOptions:{
  series: {
    dataLabels: {
      enabled: true,
      inside: true,
      allowOverlap: false,
      crop: true,
      overflow: 'none',
    }
  }
}
</code>```

答:
Fiddle demo with reference of this post. this is one type of hack with dataLabels formatter and load event

Highcharts.setOptions({ // Apply to all charts
  chart: {
    renderTo: 'container',
    defaultSeriesType: 'bar',
    events: {
      load: function() {
        var chart = this;

        $.each(chart.series, function(i, serie) {
          $.each(serie.data, function(j, data) {

            if (data.yBottom - data.plotY < 15) data.dataLabel.hide();
            //
          });
        });
      }
    }
  }
});

Highcharts.chart('container', {
  exporting: {
    chartOptions: {
      legend: {
        enabled: false,
      },
      plotOptions: {
        series: {
          stacking: 'normal',
          dataLabels: {
            inside: true,
            enabled: true,
            style: {
              fontSize: '5px',
              textOutline: 'none'
            },
            formatter: function() {
              return Highcharts.numberFormat(this.y, 1)
            }
          }
        }
      }
    }
  },

  plotOptions: {
    series: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        formatter: function() {
          return ''
        }
      }
    },

  },

  series: [{
    name: 'one',
    data: [5.24957, -1.636452, 5.511623, -5.797109, 6.975687, 4.622862, 2.902466, 3.992426, -0.270407, 3.184849, 12.249839]
  }, {
    name: 'two',
    data: [-1.311533, 2.508312, .97956, -1.725764, 5.177992, 2.1262, 5.41721, 53.811967, 4.060668, -1.317636, 13.763589]
  }]
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div></code>```

Update

Above example work on all formats except PDF when using Client side export

Fix with threads from post  Instead of hiding labels, destroy them when loading

```<code>Highcharts.setOptions({ // Apply to all charts
  chart: {
    renderTo: 'container',
    defaultSeriesType: 'bar',
    events: {
      load: function() {
        var chart = this;

        $.each(chart.series, function(i, serie) {
          $.each(serie.data, function(j, data) {
            if (data.yBottom - data.plotY < 15) data.dataLabel = data.dataLabel.destroy();
            //
          });
        });
      }
    }
  }
});
</code>```

Body:
I am working with highcharts and would like to disable datalabels on the main graph, but show them in the exported graph. However, if the data is smaller than a certain number, I would like to hide the labels in exported graph as well. I have seen this post on how to manage which datalabels are shown according to height: Highcharts stacked bar chart hide data labels not to overlap. However, I am not sure how to show certain datalabels only in the exported graph. This is my graph: https://jsfiddle.net/er1187/nbjh5jz3/
When I export, I want to hide these datalabels that are not showing properly:

I tried using overflow and crop but was unable to fix the appearance so I would like to hide them.

plotOptions:{
  series: {
    dataLabels: {
      enabled: true,
      inside: true,
      allowOverlap: false,
      crop: true,
      overflow: 'none',
    }
  }
}

Body:
Fiddle demo with reference of this post. this is one type of hack with dataLabels formatter and load event

Highcharts.setOptions({ // Apply to all charts
  chart: {
    renderTo: 'container',
    defaultSeriesType: 'bar',
    events: {
      load: function() {
        var chart = this;

        $.each(chart.series, function(i, serie) {
          $.each(serie.data, function(j, data) {

            if (data.yBottom - data.plotY < 15) data.dataLabel.hide();
            //
          });
        });
      }
    }
  }
});

Highcharts.chart('container', {
  exporting: {
    chartOptions: {
      legend: {
        enabled: false,
      },
      plotOptions: {
        series: {
          stacking: 'normal',
          dataLabels: {
            inside: true,
            enabled: true,
            style: {
              fontSize: '5px',
              textOutline: 'none'
            },
            formatter: function() {
              return Highcharts.numberFormat(this.y, 1)
            }
          }
        }
      }
    }
  },

  plotOptions: {
    series: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        formatter: function() {
          return ''
        }
      }
    },

  },

  series: [{
    name: 'one',
    data: [5.24957, -1.636452, 5.511623, -5.797109, 6.975687, 4.622862, 2.902466, 3.992426, -0.270407, 3.184849, 12.249839]
  }, {
    name: 'two',
    data: [-1.311533, 2.508312, .97956, -1.725764, 5.177992, 2.1262, 5.41721, 53.811967, 4.060668, -1.317636, 13.763589]
  }]
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div>

Update

Above example work on all formats except PDF when using Client side export

Fix with threads from post  Instead of hiding labels, destroy them when loading

Highcharts.setOptions({ // Apply to all charts
  chart: {
    renderTo: 'container',
    defaultSeriesType: 'bar',
    events: {
      load: function() {
        var chart = this;

        $.each(chart.series, function(i, serie) {
          $.each(serie.data, function(j, data) {
            if (data.yBottom - data.plotY < 15) data.dataLabel = data.dataLabel.destroy();
            //
          });
        });
      }
    }
  }
});


问:
git checkout branch from outside
Problem: I need somehow to checkout an existing branch of a project that is already cloned locally on my file system without being in that particular folder of this project.

Solution: I'm trying to do the following:

git clone 'github-project-url' 'file-system-folder'

git checkout 'existing-branch' 'file-system-folder'

I do realize that second step is not quite right, but I also am trying to avoid to cd 'file-system-folder'.

答:
Since Git version 1.8.5, you can also use -C <path> option. Be sure to use it before any other command:

git -C ~/my-git-repo checkout master

Note that it doesn't have to be specifically the .git folder. Here is the man documenation:

```<code>-C <path>
       Run as if git was started in <path> instead of the current
       working directory. When multiple -C options are given, each
       subsequent non-absolute -C <path> is interpreted relative to
       the preceding -C <path>.

       This option affects options that expect path name like --git-dir
       and --work-tree in that their interpretations of the path names
       would be made relative to the working directory caused by the -C option.
       For example the following invocations are equivalent:

           git --git-dir=a.git --work-tree=b -C c status
           git --git-dir=c/a.git --work-tree=c/b status
</code>```

Title: git checkout branch from outside

Body:
Since Git version 1.8.5, you can also use -C <path> option. Be sure to use it before any other command:

git -C ~/my-git-repo checkout master

Note that it doesn't have to be specifically the .git folder. Here is the man documenation:

-C <path>
       Run as if git was started in <path> instead of the current
       working directory. When multiple -C options are given, each
       subsequent non-absolute -C <path> is interpreted relative to
       the preceding -C <path>.

       This option affects options that expect path name like --git-dir
       and --work-tree in that their interpretations of the path names
       would be made relative to the working directory caused by the -C option.
       For example the following invocations are equivalent:

           git --git-dir=a.git --work-tree=b -C c status
           git --git-dir=c/a.git --work-tree=c/b status