问:
content is missing from HTTP Get and Post requests in Express/Mongoose project
I have the following files. I have a recipe.js file which outlines the Mongoose Schema for a recipe and the comments for a recipe. The code for it goes as follows:

```<code>const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');

let Schema = mongoose.Schema;

let commentSchema = Schema({

  rating: {
    type: Number,
    // required: true,
    min: 1,
    max: 5,
  },

  recipeItem: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Recipe'
  },

  comment: {
    type: String,
     // required: true
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

  likedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

 favouredBy: {
    type: mongoose.Schema.Types.ObjectId
 }
});

let Comment = mongoose.model('Comment', commentSchema);

let recipeSchema = Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: {
    type: Array,
    required: true
  },

  comments: [commentSchema],

  category: {
    type: String,
    required: true,
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }

});

/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).

let Recipe = mongoose.model('Recipe', recipeSchema);

module.exports = Recipe;
module.exports = Comment;

/// refactor this so that these are in the router, not in the models file

/*

module.exports.getRecipeByName = (name, callback) => {
  let nameQuery = {name: name};
  Recipe.findOne(nameQuery, callback);
};

module.exports.getRecipesByCategory = (category, callback) => {
  Recipe.find({'category': category});
};

*/
</code>```

I also have a user.js file where I outline a a User model and the relation it has to the other models/schemas. The code in the file is as follows:

```<code>const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
const passport = require('passport');

let Schema = mongoose.Schema;

let User = Schema({

  name: {
    type: String
  },

  // The passport plugin already inputs username and password into our Schema

  username: {
    type: String,
    unique: true,
    required: true
  },

   password: {
   type: String,
   required: true,
   },

  profilePic: {
    type: String
  },

  email: {
    type: String,
    unique: true,
    required: true
  },

  admin: {
    type: Boolean,
      defualt: false
  },

  usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],

  userComments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],

  usersFavouriteRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}],

  usersLikedRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]

});

let options = ({missingPasswordError: "Incorrect password, try again"});

User.plugin(passportLocalMongoose, options);

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

And here is recipeRouter.js, the file where I define all the HTTP requests and routes:

```<code>const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const verification = require('../verification');
const Comment = require('../models/recipe');

// I temporarily removed verification.checkIfUserExists to see if all this database stuff works

router = express.Router();

router.use(bodyParser.json());

router.get('/', (req, res) => {
  res.json('Here are the recipes!')
});

router.get('/showrecipes', (req, res) => {
  Recipe.find({}).populate('Comment').exec((err, recipes) => {
      if (err) throw err;
      res.json(recipes);
  })
});

router.get("/showrecipes/:recipeId", (req, res) => {
    let nameQuery = {_id: req.params.recipeId};

    Recipe.findOne(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    })
        //// Don't know if this is correct
        .populate('comment.recipeItem');
});

router.get('/showrecipes/category/:categoryname', (req, res) => {

    let nameQuery = {category: req.params.categoryname};

    Recipe.find(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    });
});

router.post('/addrecipe', (req, res, next) => {

  Recipe.create({
      name: req.body.name,
      description: req.body.description,
      steps: req.body.steps,
      ingredients: req.body.ingredients,
      category: req.body.category
  }, (err, recipes) => {
    if (err) throw err;

    res.json(recipes);
  });
});

// See if this works

router.put("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};

    Recipe.findByIdAndUpdate(query, {
        $set: req.body
    }, {
        new: true
    }, (err, recipe) => {
        if (err) throw err;
        res.json(recipe)
    })
});

    router.delete("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};

        Recipe.findByIdAndRemove(query, (err, recipe) => {
            if (err) throw err;

            res.send('Recipe was succesfully deleted');
        })

    });

    router.get("/showrecipes/:recipeId", (req, res) => {
        let nameQuery = {_id: req.params.recipeId};

        Recipe.findOne(nameQuery, (err, recipes) => {
            if (err) throw err;

            res.json(recipes);
        })

            .populate('comments')

            .exec((err) => {
                if (err) throw err;
            })
    });

    router.post("/showrecipes:/:recipeId/addcomment", (req, res, next) => {

        Comment.create({
            rating: req.body.rating,
            comment: req.body.comment,
            postedBy: postedBy,
            date: Date.now(),
            recipeItem: recipeId
        })

    });

router.get('/showrecipes/byuser/:username', (req, res) => {

    let query = {postedBy: req.params.username};

    Recipe.find(query, (err, recipes) => {
        if (err) throw err;
        res.json(recipes)
    })

});

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

Now, at some point I was able to create recipes and store them in my database without a problem. But now this weird thing happens.

Here, I make my post request as you can see in the screenshot below:

But for some strange reason, everytime I make a get request, none of the key/value pairs I specified in my json body request are there. Each recipe object now only as the _id in it.

Can anyone help me? This just seems so weird.

答:
Looks like you're simply missing the application/json Content-Type header.

In Postman, just set the header, as shown in this gif.

Body:
I have the following files. I have a recipe.js file which outlines the Mongoose Schema for a recipe and the comments for a recipe. The code for it goes as follows:

const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');

let Schema = mongoose.Schema;

let commentSchema = Schema({

  rating: {
    type: Number,
    // required: true,
    min: 1,
    max: 5,
  },

  recipeItem: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Recipe'
  },

  comment: {
    type: String,
     // required: true
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

  likedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

 favouredBy: {
    type: mongoose.Schema.Types.ObjectId
 }
});

let Comment = mongoose.model('Comment', commentSchema);

let recipeSchema = Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: {
    type: Array,
    required: true
  },

  comments: [commentSchema],

  category: {
    type: String,
    required: true,
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }

});

/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).

let Recipe = mongoose.model('Recipe', recipeSchema);

module.exports = Recipe;
module.exports = Comment;

/// refactor this so that these are in the router, not in the models file

/*

module.exports.getRecipeByName = (name, callback) => {
  let nameQuery = {name: name};
  Recipe.findOne(nameQuery, callback);
};

module.exports.getRecipesByCategory = (category, callback) => {
  Recipe.find({'category': category});
};

*/

I also have a user.js file where I outline a a User model and the relation it has to the other models/schemas. The code in the file is as follows:

const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
const passport = require('passport');

let Schema = mongoose.Schema;

let User = Schema({

  name: {
    type: String
  },

  // The passport plugin already inputs username and password into our Schema

  username: {
    type: String,
    unique: true,
    required: true
  },

   password: {
   type: String,
   required: true,
   },

  profilePic: {
    type: String
  },

  email: {
    type: String,
    unique: true,
    required: true
  },

  admin: {
    type: Boolean,
      defualt: false
  },

  usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],

  userComments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],

  usersFavouriteRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}],

  usersLikedRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]

});

let options = ({missingPasswordError: "Incorrect password, try again"});

User.plugin(passportLocalMongoose, options);

module.exports = mongoose.model('User', User);

And here is recipeRouter.js, the file where I define all the HTTP requests and routes:

const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const verification = require('../verification');
const Comment = require('../models/recipe');

// I temporarily removed verification.checkIfUserExists to see if all this database stuff works

router = express.Router();

router.use(bodyParser.json());

router.get('/', (req, res) => {
  res.json('Here are the recipes!')
});

router.get('/showrecipes', (req, res) => {
  Recipe.find({}).populate('Comment').exec((err, recipes) => {
      if (err) throw err;
      res.json(recipes);
  })
});

router.get("/showrecipes/:recipeId", (req, res) => {
    let nameQuery = {_id: req.params.recipeId};

    Recipe.findOne(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    })
        //// Don't know if this is correct
        .populate('comment.recipeItem');
});

router.get('/showrecipes/category/:categoryname', (req, res) => {

    let nameQuery = {category: req.params.categoryname};

    Recipe.find(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    });
});

router.post('/addrecipe', (req, res, next) => {

  Recipe.create({
      name: req.body.name,
      description: req.body.description,
      steps: req.body.steps,
      ingredients: req.body.ingredients,
      category: req.body.category
  }, (err, recipes) => {
    if (err) throw err;

    res.json(recipes);
  });
});

// See if this works

router.put("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};

    Recipe.findByIdAndUpdate(query, {
        $set: req.body
    }, {
        new: true
    }, (err, recipe) => {
        if (err) throw err;
        res.json(recipe)
    })
});

    router.delete("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};

        Recipe.findByIdAndRemove(query, (err, recipe) => {
            if (err) throw err;

            res.send('Recipe was succesfully deleted');
        })

    });

    router.get("/showrecipes/:recipeId", (req, res) => {
        let nameQuery = {_id: req.params.recipeId};

        Recipe.findOne(nameQuery, (err, recipes) => {
            if (err) throw err;

            res.json(recipes);
        })

            .populate('comments')

            .exec((err) => {
                if (err) throw err;
            })
    });

    router.post("/showrecipes:/:recipeId/addcomment", (req, res, next) => {

        Comment.create({
            rating: req.body.rating,
            comment: req.body.comment,
            postedBy: postedBy,
            date: Date.now(),
            recipeItem: recipeId
        })

    });

router.get('/showrecipes/byuser/:username', (req, res) => {

    let query = {postedBy: req.params.username};

    Recipe.find(query, (err, recipes) => {
        if (err) throw err;
        res.json(recipes)
    })

});

module.exports = router;

Now, at some point I was able to create recipes and store them in my database without a problem. But now this weird thing happens.

Here, I make my post request as you can see in the screenshot below:

But for some strange reason, everytime I make a get request, none of the key/value pairs I specified in my json body request are there. Each recipe object now only as the _id in it.

Can anyone help me? This just seems so weird.


来源: stackexchange

问:
When to use header('Content-Type: application/json') in PHP
I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

OR

if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

thanks

答:
W3 Description For the Content-Type

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

Shortly speaking, just to inform the receiver what kind of data he received and consume it accordingly.

ContentLicense: CC BY-SA 3.0


问:
How do I refresh the columns of a view in SSDT?
I'm getting this error when trying to deploy a SQL Server Data Tools (SSDT) database project:

View or function 'dbo.Employees' has more column names specified than columns defined.

I deleted a column from the underlying table and the view looks like this:

```<code>CREATE VIEW [dbo].[Employees] AS SELECT * FROM [$(ExternalDB)].[dbo].[Employees];
</code>```

Doing a Google search brings back this page which says that SQL Server keeps meta data on views which must be refreshed. They mention this command:

```<code>EXEC sp_refreshview 'Employees';
</code>```

If I put that in the pre-deployment script, it'll run before the column was dropped. If I put it in the post-deployment script, the deployment will throw the error before it gets executed. So my question is where or how can I do that with an SSDT project?

答:
This is interesting as by default ssdt will refresh any views which depend on any table that has changed as part of a deployment.

Was the column dropped as part of a normal ssdt deployment?

In your publish profile or publish options are you setting ScriptRefreshModule to false?

Aside from this select * in a view is bad practice, put the full column list and this problem disappears, you can even right click the "select *" and choose to expand to get the full column list - do that instead :)
Ed

Body:
I'm getting this error when trying to deploy a SQL Server Data Tools (SSDT) database project:

View or function 'dbo.Employees' has more column names specified than columns defined.

I deleted a column from the underlying table and the view looks like this:

CREATE VIEW [dbo].[Employees] AS SELECT * FROM [$(ExternalDB)].[dbo].[Employees];

Doing a Google search brings back this page which says that SQL Server keeps meta data on views which must be refreshed. They mention this command:

EXEC sp_refreshview 'Employees';

If I put that in the pre-deployment script, it'll run before the column was dropped. If I put it in the post-deployment script, the deployment will throw the error before it gets executed. So my question is where or how can I do that with an SSDT project?


问:
Getting a 405 (Method Not Allowed) in AngularJS
So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.

Here is my code.

```<code><div ng-controller="MyCtrl">
  <div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">

    <a class="back" href="#/lawyer">Back</a>

    <button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
      Edit
    </button>

    <button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>

    <button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>

    <div class="people-view">

      <h2 class="name">{{person.firstName}}</h2>

      <h2 class="name">{{person.lastName}}</h2>

      <span class="title">{{person.email}}</span>

      <span class="date">{{person.website}} </span>

    </div>

    <div class="list-view">

      <form>

        <fieldset ng-disabled="inactive">

          <legend>Basic Info</legend>

          <b>First Name:</b>

          <input type="text" ng-model="person.firstName">
          <br>

          <b>Last Name:</b>

          <input type="text" ng-model="person.lastName">
          <br>

          <b>Email:</b>

          <input type="email" ng-model="person.email">

        </fieldset>

      </form>

    </div>
  </div>
</div>
</code>```

Services

```<code>    app.factory('people', function ($http) {
    var service = {};
    service.getUserInfo = function () {
        return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
    };

    service.confirmUser = function (lawyerId) {
        return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');

    };

    return service;

});
</code>```

LawyerController

```<code>    app.controller('LawyerController', ['$scope', 'people', '$routeParams',
    function ($scope, people, $routeParams) {

        $scope.lawyerId = $routeParams.id;
        people.getUserInfo().then(function (response) {
            $scope.userInfo = response.data;
        });

    }]);
</code>```

HomeController

```<code>    var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
    if (!isConfirmed) {
        people.getUserInfo().then(function (response) {

            $scope.userInfo = response.data;

        }, function (error) {
            console.log(error)
        });
    }
});
</code>```

App.js

```<code>    $scope.doDelete = function(lawyer) {
        var index = $scope.userInfo.lawyers.indexOf(lawyer);
        $scope.userInfo.lawyers.splice(index, 1);
        location.href = '#/lawyer';
    };
</code>```

答:
If you changed your HTML, so you passed the person instead.

```<code><button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
</code>```

You can use this to find the index within the lawyers, then remove it.

```<code>$scope.doDelete = function(lawyer) {
    var index = $scope.userInfo.lawyers.indexOf(lawyer);
    $scope.userInfo.lawyers.splice(index, 1)
};
</code>```

The issue is your are using $http.delete which performs an HTTP Delete request.  This doesn't sound like something you intended.

Body:
So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.

Here is my code.

    Back

    <button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
      Edit
    </button>

    <button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>

    <button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>

{{person.firstName}}

{{person.lastName}}

      {{person.email}}

      {{person.website}}

      <form>

        <fieldset ng-disabled="inactive">

          <legend>Basic Info</legend>

          First Name:

          <input type="text" ng-model="person.firstName">

          Last Name:

          <input type="text" ng-model="person.lastName">

          Email:

          <input type="email" ng-model="person.email">

        </fieldset>

      </form>

Services

    app.factory('people', function ($http) {
    var service = {};
    service.getUserInfo = function () {
        return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
    };

    service.confirmUser = function (lawyerId) {
        return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');

    };

    return service;

});

LawyerController

    app.controller('LawyerController', ['$scope', 'people', '$routeParams',
    function ($scope, people, $routeParams) {

        $scope.lawyerId = $routeParams.id;
        people.getUserInfo().then(function (response) {
            $scope.userInfo = response.data;
        });

    }]);

HomeController

    var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
    if (!isConfirmed) {
        people.getUserInfo().then(function (response) {

            $scope.userInfo = response.data;

        }, function (error) {
            console.log(error)
        });
    }
});

App.js

    $scope.doDelete = function(lawyer) {
        var index = $scope.userInfo.lawyers.indexOf(lawyer);
        $scope.userInfo.lawyers.splice(index, 1);
        location.href = '#/lawyer';
    };

Body:
If you changed your HTML, so you passed the person instead.

<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>

You can use this to find the index within the lawyers, then remove it.

$scope.doDelete = function(lawyer) {
    var index = $scope.userInfo.lawyers.indexOf(lawyer);
    $scope.userInfo.lawyers.splice(index, 1)
};

The issue is your are using $http.delete which performs an HTTP Delete request.  This doesn't sound like something you intended.


问:
Laravel update database with concate string is not working
Now I am trying to update Laravel Eloquent Model like this:

```<code>                Res_Reservations::where('time_id', $time['id'])
                    ->where('date',  $bus['date'])
                    ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                    ->update(['time_id' => $time['move'], 'reason' => 'reason' . $notesAdd]);
</code>```

I want to add extra string to the 'reason' field as below.

reason field = reason field + $notesAdd;

But it does not working. It acts as below.

reason field = 'reason' + $notesAdd;

How can I fix it?

答:
The easiest way will need you to load the record first so that it becomes an Laravel object, then update the property, and save the record.</p>

```<code>$record = Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))->first();

$record->update(['time_id' => $time['move'], 'reason' => $record->reason . $notesAdd]);
</code>```

Body:
Now I am trying to update Laravel Eloquent Model like this:

                Res_Reservations::where('time_id', $time['id'])
                    ->where('date',  $bus['date'])
                    ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                    ->update(['time_id' => $time['move'], 'reason' => 'reason' . $notesAdd]);

I want to add extra string to the 'reason' field as below.

reason field = reason field + $notesAdd;

But it does not working. It acts as below.

reason field = 'reason' + $notesAdd;

How can I fix it?

Body:
The easiest way will need you to load the record first so that it becomes an Laravel object, then update the property, and save the record.

$record = Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))->first();

$record->update(['time_id' => $time['move'], 'reason' => $record->reason . $notesAdd]);


问:
SQL Server Linked Server to MS Access - DSN Architecture Mismatch Error
I am using SQL Server 2016 Express, trying to connect to an Access Database on another server on the network, via an ODBC Data Source. I have looked up a number of tutorials and tried a variety of different methods, but cannot get the connection to work. Ultimately I seem to be stuck on this error:

[Microsoft][ODBC Driver Manager] The specified DSN contains an architecture mismatch between the Driver and Application (Microsoft SQL Server, Error: 7303)

To rule out permissions and networking issues, I have copied the database to the local machine to try to create a test connection. I have verified that the security settings for Microsoft Access are OFF (meaning there is no username / password to log in). I am making sure to use the 32-bit version of the ODBC Data Source Administrator (in Windows\SysWOW64\), have tried a variety of settings in SQL Server, and have even tried creating the linked server directly via T-SQL code, like this:

```<code>EXEC sp_addlinkedserver
     @server = N'TESTLINK',
     @provider = N'MSDASQL',
     @srvproduct = N'',
     @datasrc = N'TEST';
</code>```

Here are the current settings I am using to try to create this connection, where I keep getting this error:

Note that I have also tried each of the settings on the Security tab of the New Linked Server dialog, but have received errors each time.

If anyone has an idea to what I might be missing here, please let me know.

EDIT: There is a similar question here, but it is an old thread, and the highly rated answers were unsuccessful for me (I had already tried):

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

The key to resolving my issue was that I needed to specifically download the 64-bit version of the Access ODBC driver, which can be downloaded here:

https://www.microsoft.com/en-US/download/details.aspx?id=13255

答: If the SQL Server process is running as 64-bit (which seems extremely likely these days) then it needs to have the 64-bit version of the Access Database Engine components installed. They are available for download here.</p>

Body:
I am using SQL Server 2016 Express, trying to connect to an Access Database on another server on the network, via an ODBC Data Source. I have looked up a number of tutorials and tried a variety of different methods, but cannot get the connection to work. Ultimately I seem to be stuck on this error:

[Microsoft][ODBC Driver Manager] The specified DSN contains an architecture mismatch between the Driver and Application (Microsoft SQL Server, Error: 7303)

To rule out permissions and networking issues, I have copied the database to the local machine to try to create a test connection. I have verified that the security settings for Microsoft Access are OFF (meaning there is no username / password to log in). I am making sure to use the 32-bit version of the ODBC Data Source Administrator (in Windows\SysWOW64\), have tried a variety of settings in SQL Server, and have even tried creating the linked server directly via T-SQL code, like this:

EXEC sp_addlinkedserver
     @server = N'TESTLINK',
     @provider = N'MSDASQL',
     @srvproduct = N'',
     @datasrc = N'TEST';

Here are the current settings I am using to try to create this connection, where I keep getting this error:

Note that I have also tried each of the settings on the Security tab of the New Linked Server dialog, but have received errors each time.

If anyone has an idea to what I might be missing here, please let me know.

EDIT: There is a similar question here, but it is an old thread, and the highly rated answers were unsuccessful for me (I had already tried):

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

The key to resolving my issue was that I needed to specifically download the 64-bit version of the Access ODBC driver, which can be downloaded here:

https://www.microsoft.com/en-US/download/details.aspx?id=13255


问:
Trouble with MKMapView zoom to annotation on load
I'm having trouble zooming in on an annotation/pin when the MapView is loaded.

When loading the MapView, I want it to start zoomed out, and then zoom in toward the annotation/pin. The "animated" is set to "true". I'm not sure what it going wrong here.

When the map gets loaded, it briefly displays a gray screen with the pin and then the satellite map around it loads.

Thanks!

Using Swift 3

Map code:

```<code>   @IBOutlet weak var mapView: MKMapView!

   }

   override func viewDidLoad() {
       super.viewDidLoad()

       let distanceSpan:CLLocationDegrees = 300
       let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)
       let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
       mapView.addAnnotation(redRocksPin)

       mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)
</code>```

Pin Class:

```<code>import MapKit

class RedRocksPin: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D

init(title:String, subtitle:String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.subtitle = subtitle
    self.coordinate = coordinate
}
</code>```

答:
In your class declaration make these your class variables:

```<code>    let distanceSpan:CLLocationDegrees = 300
    let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)
</code>```

In ViewWillAppear, do this:

```<code>    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animted)
       view.layoutIfNeeded()

       let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
       mapView.addAnnotation(redRocksPin)
    }
</code>```

And then this:

```<code>    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)
    }
</code>```

So what this does is in your viewwillAppear, it will draw the mapView, so you are able to add the annotation without causing a crash, then in the viewdidappear, it will just zoom in on the annotation you added.

Not sure if this is the best way, but something to try.

Body:
I'm having trouble zooming in on an annotation/pin when the MapView is loaded.

When loading the MapView, I want it to start zoomed out, and then zoom in toward the annotation/pin. The "animated" is set to "true". I'm not sure what it going wrong here.

When the map gets loaded, it briefly displays a gray screen with the pin and then the satellite map around it loads.

Thanks!

Using Swift 3

Map code:

   @IBOutlet weak var mapView: MKMapView!

   }

   override func viewDidLoad() {
       super.viewDidLoad()

       let distanceSpan:CLLocationDegrees = 300
       let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)
       let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
       mapView.addAnnotation(redRocksPin)

       mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)

Pin Class:

import MapKit

class RedRocksPin: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D

init(title:String, subtitle:String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.subtitle = subtitle
    self.coordinate = coordinate
}

Body:
In your class declaration make these your class variables:

    let distanceSpan:CLLocationDegrees = 300
    let redRocks:CLLocationCoordinate2D = CLLocationCoordinate2DMake(39.665496, -105.205438)

In ViewWillAppear, do this:

    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animted)
       view.layoutIfNeeded()

       let redRocksPin = RedRocksPin(title: "Jerry Garcia 1/2/72", subtitle: "Red Rocks Amphitheatre", coordinate: redRocks)
       mapView.addAnnotation(redRocksPin)
    }

And then this:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        mapView.setRegion(MKCoordinateRegionMakeWithDistance(redRocks, distanceSpan, distanceSpan), animated: true)
    }

So what this does is in your viewwillAppear, it will draw the mapView, so you are able to add the annotation without causing a crash, then in the viewdidappear, it will just zoom in on the annotation you added.

Not sure if this is the best way, but something to try.


问:
C - Macro contradiction
I just started learning C and I am not sure about how everything works. Some of examples simply looks weird to me and I cannot predict what would it print. I am programming in GCC, I mean it is my compiler, so every code I test is in GCC.

I understood pointers etc how that all stuff work, but also as you know there are macros. Macros are very weird, and I discovered one example I have no explanation about. For example look at this code particular code:

```<code>#include <stdio.h>

int main(void){

  #define A 1

  if(A == 0){
    #define B 1
  }

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

  printf("Value of A is %d\n", A);

  return 0;
}
</code>```

What should it print? Well, I though it is easy to guess, but now I see that it is not very easy. The result is not what i thought is.

This was my reasoning: we firstly define A to be 1 and then if A is 0 then define B to be 1. So, if B is defined it means that A == 0 and otherwise A == 1. But, surprisingly it prints:

B is defined, which means that A == 0.

  Value of A is 1

What? It just printed a contradiction. I am not sure if this is some weird thing in GCC (because I have no visual studio or other compiler to test it). However, I am 99% sure I somehow misunderstood macros. I tried using variables instead of macros and it works properly.

Is it an issue, or did I simply misunderstand how macros work? Please keep in mind that I'm C beginner, so take it easy :).

Thank you in advance.

答:
Preprocessing directives are processed before non-preprocessing tokens are translated. And particularly, preprocessing directives are always evaluated at compile time, and never at runtime (cf. C standard, e.g. this draft).
If a token is a preprocessing token is defined as follows (all others are non-preprocessing tokens):

6.10 Preprocessing directives

(2) A preprocessing directive consists of a sequence of preprocessing
  tokens that begins with a # preprocessing token that (at the start of
  translation phase 4) is either the first character in the source file
  (optionally after white space containing no new-line characters) or
  that follows white space containing at least one new-line character

So if(A == 0) are non-preprocessing tokens (as the respective line does not start with a #, optionally with some space characters before), while #define B 1 is a preprocessing token.
According to the translation phases, preprocessing tokens are evaluated at translation time before the other tokens:

5.1.1.2 Translation phases

(4) Preprocessing directives are executed, macro invocations are
  expanded, and _Pragma unary operator expressions are executed.

(7) ... The resulting tokens are syntactically and semantically
  analyzed and translated as a translation unit.

So B will be defined already before if(A==0) will be translated, and particularly before if(A==0) will be executed. Thus, B will always be defined in your program.

Title: C - Macro contradiction

Body:
I just started learning C and I am not sure about how everything works. Some of examples simply looks weird to me and I cannot predict what would it print. I am programming in GCC, I mean it is my compiler, so every code I test is in GCC.

I understood pointers etc how that all stuff work, but also as you know there are macros. Macros are very weird, and I discovered one example I have no explanation about. For example look at this code particular code:

#include <stdio.h>

int main(void){

  #define A 1

  if(A == 0){
    #define B 1
  }

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

  printf("Value of A is %d\n", A);

  return 0;
}

What should it print? Well, I though it is easy to guess, but now I see that it is not very easy. The result is not what i thought is.

This was my reasoning: we firstly define A to be 1 and then if A is 0 then define B to be 1. So, if B is defined it means that A == 0 and otherwise A == 1. But, surprisingly it prints:

B is defined, which means that A == 0.

  Value of A is 1

What? It just printed a contradiction. I am not sure if this is some weird thing in GCC (because I have no visual studio or other compiler to test it). However, I am 99% sure I somehow misunderstood macros. I tried using variables instead of macros and it works properly.

Is it an issue, or did I simply misunderstand how macros work? Please keep in mind that I'm C beginner, so take it easy :).

Thank you in advance.


问:
What is the scheduler for Apache Mesos's Command Executor?
I'm studying Mesos code, become very confused about the internal working flow of executing a simple docker image,
such as following:

```<code>mesos-execute  --master=XXX \
               --containerizer=docker \
               --name=test \
               --docker_image=XXX \
               --shell=false
</code>```

I believe /src/cli/execute.cpp is the implementation of this "mesos-execute", which is called "Command Executor" in the official document.

I see execute.cpp internally setups a CommandScheduler, which has a void received(queue<Event> events) function that listens for events from the master. If it receives an Event::OFFERS, it will start the procedure of executing the tasks on the offered resources (agents).

However, I cannot find exactly where is the resource offered to the client executable.
I see there is an void Master::offer(…) function in /src/master/master.cpp. But it sends a ResourceOffersMessage, not an event, and no tranforming the event to a message.
I find that only /src/sched/sched.cpp can receive and process this type of message. But I don't see how is sched.cpp used in other code....

So, I cannot find the exact workflow of sending the offered resource (from master), to the Command Executor.  What's the scheduler for this Command Executor?
Could someone help me to understand?

Thanks

答:
I believe /src/cli/execute.cpp is the implementation of this "mesos-execute", which is called "Command Executor" in the official document.

Command Executor is a generic executor that according to documentation has "enough functionality for a wide variety of framework requirements". Executor is responsible for launching a task described in TaskInfo message prepared by scheduler.

Indeed, Master sends a resource offer message but it evolves to full event with proper type.

CLI uses scheduler::Mesos which according to docs is "concrete implementation that connects a scheduler to a Mesos master. Abstracts master detection (connection and disconnection)." received is passed a a callback and called by this lib.

Body:
I'm studying Mesos code, become very confused about the internal working flow of executing a simple docker image,
such as following:

mesos-execute  --master=XXX \
               --containerizer=docker \
               --name=test \
               --docker_image=XXX \
               --shell=false

I believe /src/cli/execute.cpp is the implementation of this "mesos-execute", which is called "Command Executor" in the official document.

I see execute.cpp internally setups a CommandScheduler, which has a void received(queue<Event> events) function that listens for events from the master. If it receives an Event::OFFERS, it will start the procedure of executing the tasks on the offered resources (agents).

However, I cannot find exactly where is the resource offered to the client executable.
I see there is an void Master::offer(…) function in /src/master/master.cpp. But it sends a ResourceOffersMessage, not an event, and no tranforming the event to a message.
I find that only /src/sched/sched.cpp can receive and process this type of message. But I don't see how is sched.cpp used in other code....

So, I cannot find the exact workflow of sending the offered resource (from master), to the Command Executor.  What's the scheduler for this Command Executor?
Could someone help me to understand?

Thanks


问:
Get the real width and height of an image with JavaScript? (in Safari/Chrome)
I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

```<code>var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();
</code>```

But in Webkit browsers like Safari and Google Chrome values are 0.

答:
I checked out the answer of Dio and it works great for me.

$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });

Make sure that you call all your functions aso. that handle with the image size in the recaller function of fadeIn().

Thanks for this.

OwnerDisplayName: Frank Bannister

ContentLicense: CC BY-SA 4.0

Body:
I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();

But in Webkit browsers like Safari and Google Chrome values are 0.

ContentLicense: CC BY-SA 2.5


问:
Hindi to english from pdf
I am not able to copy hindi content from pdf file. When I am trying to copy/paste that content it changes to different hindi characters.

Example-
Original- विधान सभा

After paste- नरधरन सभर

it shows like this.

Can anybody help me to get the exact hindi characters.

答:
What was used to create the PDF?

It was likely been created with an embedded font subset and no toUnicode mapping. Basically the codes of the characters used in the content of the PDF are mapped to glyphs embedded in the PDF which are displayed, but there is no mapping from these codes to regular Unicode codes so copying them produces gibberish. The only way to extract the original contents would be with some form of OCR.

Another possibility is that the application you are pasting it into is not shaping the characters correctly.

Title: Hindi to english from pdf


问:
"No resource found that matches given name" for a resource I'm not using
I have the message:

```<code>Error:(282, 50) No resource found that matches the given name (at 'android:titleTextAppearance' with value '@style/TextAppearance.Widget.ActionBar.Title').
</code>```

however, I'm not trying to access the resource in my styles or anywhere else. I was trying to access it in a style recently but I deleted it already.

答: Somehow Android Studio generated a second values folder called values-v21 with styles.xml under it containing a reference to android:titleTextAppearance. I was able to correct this by correcting the style in the styles.xml file under values-v21.</p>

Body:
I have the message:

Error:(282, 50) No resource found that matches the given name (at 'android:titleTextAppearance' with value '@style/TextAppearance.Widget.ActionBar.Title').

however, I'm not trying to access the resource in my styles or anywhere else. I was trying to access it in a style recently but I deleted it already.


问:
Xamarin form-UWP - black cell showing before data is visible on fast scrolling of list
When i scroll the list fast, each cell appears as black before data is loaded.If i scroll slowly data black cells won't appear. This behavior is happening only for Xamarin UWP project. Please find the below image for reference.

答: This is not a problem with your code. When you scroll too fast the system doesn't have time to render the cells as quickly as you are scrolling, so the black cell appears.</p>


问:
Python 3 tkinter insert file contents into a text box
Okay so I have done about 10 days of searching and I caved in so I'm turning to the community for help.
I am using python 3.6 and tkinter as a user interface.
The basic's of what I'm trying to accomplish is that I have a file that I open and search for a word within the file and insert all the lines that word falls on.
My issue is that its only inserting the first line it finds and I need it to insert all the lines it finds. Sorry for wet coding I'll dry it up once I have functionality later

here's a sample of my code (it's not the full thing but it should give you more than enough info about what I'm trying to accomplish):

```<code>import tkinter as tk
from tkinter import ttk
# i added all my imports that this class use's in case you guys think they could pose a problem but they shouldn't be a issue

class EXAMPLEapp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default = "dlm64.ico")
        tk.Tk.wm_title(self, "Example.")
        self.FILE_MENU_BAR()
        self.minsize(width = 360, height = 200)
        container = tk.Frame(self)
        container.grid(row=0,column=0, sticky="nsew")
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
        self.frames = {}
        for FRAME in (SearchPage):
            frame = FRAME(container, self)
            self.frames[FRAME] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(SearchPage)
    def FILE_MENU_BAR(self):
        #File
        self.menubar = tk.Menu()
        self.configure(menu = self.menubar)
        File_Menu = tk.Menu(self.menubar, tearoff = False)
        self.menubar.add_cascade(label = "File", menu = File_Menu)
        File_Menu.add_command(label = "EXIT" , command = self.File_EXIT)
        # Edit Menu
        Edit_Menu = tk.Menu(self.menubar, tearoff = False)
        self.menubar.add_cascade(label = "Edit", menu = Edit_Menu)
        Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
        Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
    def File_EXIT(self):
        sys.exit(0)
    def Edit_Cut(self):
        print("CUT")
    def Edit_Copy(self):
        print("COPY")
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class SearchPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
        label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
        button0 = ttk.Button(self, text = "Inventory Search")
        button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button1 = ttk.Button(self, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
        button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button2 = ttk.Button(self, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
        button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button3 = ttk.Button(self, text = "Ship", command = lambda: controller.show_frame(ShipPage))
        button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button4 = ttk.Button(self, text = "Graph", command = lambda: controller.show_frame(PlotPage))
        button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))

        DATE_VAR = tk.StringVar()
        def DATE_SEARCH():
            USER_TEXT = DATE_VAR.get()
            with open('SAMPLE.txt', 'r') as searchfile:
                for line in searchfile:
                    if USER_TEXT == '':
                        LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
                        LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, "PLEASE ENTER A VALUE")
                        LABEL.configure(state = 'disabled')
                        break
                    elif USER_TEXT in line:
                        LABEL = tk.Text(self, width = 100, height = 4, wrap = tk.WORD)
                        LABEL.grid(row = 6, column = 3, sticky = "e", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, line)
                        LABEL.configure(state = 'disabled')
                        ScrollBar = tk.Scrollbar(self)
                        ScrollBar.config(command = LABEL.yview)
                        LABEL.config(yscrollcommand = ScrollBar.set)
                        ScrollBar.grid(row = 6, column = 4, sticky = "e")
                        break
                    else:
                        LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
                        LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, "INVENTORY DOES NOT EXIST")
                        LABEL.configure(state = 'disabled')
        DATE_Search_label = tk.Label(self, text = "Search by DATE", font = ("Helvetica", 9))
        DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
        DATE_Search_Entry = tk.Entry(self, textvariable = DATE_VAR)
        DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
        DATE_SEARCH_BUTTON = ttk.Button(self, text = "Search", command = DATE_SEARCH)
        DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")

app = EXAMPLEapp()
app.mainloop()
</code>```

答:
EDIT:

I have made several changes to your code.

There were way too many emblems with the way you had it set up.

As I am not 100% sure how what you are trying to accomplish I have made progress with your code.

Below is the edited version of your code.
I also created a text file on my end to test with and it seams to have worked so let me know if this is getting close to what you are attempting to do.

A few notes:

1st I moved everything into one class. The way you had it set up was just not going to work without some major changes.

2nd I needed to add self. to many of your variables because they are variables that we need to interact with in the class.

3rd I changed they way you get the data from the entry box. The way you were doing it was just not working so I simplified it by adding .get() function to the entry variable.

4th but probably should have been the 1st thing I mentions. The way you had your main Tk() window starting was odd. I changed how root was created and how we pass it into the class. This seams to make more sense to me.

This is much better to use IMO.

Let me know what parts you still need explanation on and I will make updates to my answer as needed.

Update:

change the while open statement a bit. You do not need to recreate the text box and reconfigure it ever for loop this is not good and will prevent you from seeing multiple items. Also I do not believe you can have a multi line label thought I have never tried. Lets change this to a text box this should do what we need.

```<code>import tkinter as tk
from tkinter import ttk

class EXAMPLEapp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.root.wm_title("TM Duch\'e Nut CO.")
        self.FILE_MENU_BAR()
        self.root.minsize(width = 360, height = 200)
        self.container = tk.Frame(self.root)
        self.container.grid(row=0,column=0, sticky="nsew")
        self.container.grid_rowconfigure(0, weight = 1)
        self.container.grid_rowconfigure(6, weight = 0)
        self.container.grid_columnconfigure(0, weight = 1)
        self.container.grid_columnconfigure(3, weight = 0)

        self.label = tk.Label(self.root, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
        self.label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
        self.button0 = ttk.Button(self.root, text = "Inventory Search")
        self.button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button1 = ttk.Button(self.root, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
        self.button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button2 = ttk.Button(self.root, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
        self.button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button3 = ttk.Button(self.root, text = "Ship", command = lambda: controller.show_frame(ShipPage))
        self.button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button4 = ttk.Button(self.root, text = "Graph", command = lambda: controller.show_frame(PlotPage))
        self.button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.DATE_Search_label = tk.Label(self.root, text = "Search by DATE", font = ("Helvetica", 9))
        self.DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
        self.DATE_Search_Entry = tk.Entry(self.root)
        self.DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
        self.DATE_SEARCH_BUTTON = ttk.Button(self.root, text = "Search", command = lambda: self.DATE_SEARCH())
        self.DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")

    def DATE_SEARCH(self):
        with open('SAMPLE.txt', 'r') as f:
            search_f = f.readlines()
            self.text = tk.Text(self.root, width = 30, height = 2)
            self.text.grid(row = 6, column = 3, sticky = "ew", pady = (0,0), padx = (20,0))
            self.ScrollBar = tk.Scrollbar(self.root)
            self.ScrollBar.config(command = self.text.yview)
            self.text.config(yscrollcommand = self.ScrollBar.set)
            self.ScrollBar.grid(row = 6, column = 4, sticky = "ns")
            self.text.delete(1.0, "end-1c")

            USER_TEXT = self.DATE_Search_Entry.get()
            if USER_TEXT == '':
                self.text.config(foreground = 'red')
                self.text.insert(tk.END, "PLEASE ENTER A VALUE")
            else:
                match_in_file = False
                for line in search_f:
                    if USER_TEXT in line:
                        self.text.config(foreground = 'black')
                        self.text.insert(tk.END, "{}".format(line))
                        match_in_file = True
                if match_in_file == False:
                    self.text.config(foreground = 'red')
                    self.text.insert(tk.END, "INVENTORY DOES NOT EXIST")

    def FILE_MENU_BAR(self):
        #File
        self.menu = tk.Menu(self.root)
        self.root.config(menu = self.menu)
        self.fileMenu = tk.Menu(self.menu, tearoff = 0)
        self.menu.add_cascade(label = "File", menu = self.fileMenu)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label = "Exit", command = lambda: self.root.destroy())
        # Edit Menu
        self.Edit_Menu = tk.Menu(self.menu)
        self.menu.add_cascade(label = "Edit", menu = self.Edit_Menu)
        self.Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
        self.Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)

    def File_EXIT(self):
        sys.exit(0)

    def Edit_Cut(self):
        print("CUT")

    def Edit_Copy(self):
        print("COPY")

root = tk.Tk()
app = EXAMPLEapp(root)
app.mainloop()
</code>```

Body:
Okay so I have done about 10 days of searching and I caved in so I'm turning to the community for help.
I am using python 3.6 and tkinter as a user interface.
The basic's of what I'm trying to accomplish is that I have a file that I open and search for a word within the file and insert all the lines that word falls on.
My issue is that its only inserting the first line it finds and I need it to insert all the lines it finds. Sorry for wet coding I'll dry it up once I have functionality later

here's a sample of my code (it's not the full thing but it should give you more than enough info about what I'm trying to accomplish):

import tkinter as tk
from tkinter import ttk
# i added all my imports that this class use's in case you guys think they could pose a problem but they shouldn't be a issue

class EXAMPLEapp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default = "dlm64.ico")
        tk.Tk.wm_title(self, "Example.")
        self.FILE_MENU_BAR()
        self.minsize(width = 360, height = 200)
        container = tk.Frame(self)
        container.grid(row=0,column=0, sticky="nsew")
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
        self.frames = {}
        for FRAME in (SearchPage):
            frame = FRAME(container, self)
            self.frames[FRAME] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(SearchPage)
    def FILE_MENU_BAR(self):
        #File
        self.menubar = tk.Menu()
        self.configure(menu = self.menubar)
        File_Menu = tk.Menu(self.menubar, tearoff = False)
        self.menubar.add_cascade(label = "File", menu = File_Menu)
        File_Menu.add_command(label = "EXIT" , command = self.File_EXIT)
        # Edit Menu
        Edit_Menu = tk.Menu(self.menubar, tearoff = False)
        self.menubar.add_cascade(label = "Edit", menu = Edit_Menu)
        Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
        Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
    def File_EXIT(self):
        sys.exit(0)
    def Edit_Cut(self):
        print("CUT")
    def Edit_Copy(self):
        print("COPY")
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class SearchPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
        label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
        button0 = ttk.Button(self, text = "Inventory Search")
        button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button1 = ttk.Button(self, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
        button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button2 = ttk.Button(self, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
        button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button3 = ttk.Button(self, text = "Ship", command = lambda: controller.show_frame(ShipPage))
        button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        button4 = ttk.Button(self, text = "Graph", command = lambda: controller.show_frame(PlotPage))
        button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))

        DATE_VAR = tk.StringVar()
        def DATE_SEARCH():
            USER_TEXT = DATE_VAR.get()
            with open('SAMPLE.txt', 'r') as searchfile:
                for line in searchfile:
                    if USER_TEXT == '':
                        LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
                        LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, "PLEASE ENTER A VALUE")
                        LABEL.configure(state = 'disabled')
                        break
                    elif USER_TEXT in line:
                        LABEL = tk.Text(self, width = 100, height = 4, wrap = tk.WORD)
                        LABEL.grid(row = 6, column = 3, sticky = "e", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, line)
                        LABEL.configure(state = 'disabled')
                        ScrollBar = tk.Scrollbar(self)
                        ScrollBar.config(command = LABEL.yview)
                        LABEL.config(yscrollcommand = ScrollBar.set)
                        ScrollBar.grid(row = 6, column = 4, sticky = "e")
                        break
                    else:
                        LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
                        LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
                        LABEL.insert(1.0, "INVENTORY DOES NOT EXIST")
                        LABEL.configure(state = 'disabled')
        DATE_Search_label = tk.Label(self, text = "Search by DATE", font = ("Helvetica", 9))
        DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
        DATE_Search_Entry = tk.Entry(self, textvariable = DATE_VAR)
        DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
        DATE_SEARCH_BUTTON = ttk.Button(self, text = "Search", command = DATE_SEARCH)
        DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")

app = EXAMPLEapp()
app.mainloop()

Body:
EDIT:

I have made several changes to your code.

There were way too many emblems with the way you had it set up.

As I am not 100% sure how what you are trying to accomplish I have made progress with your code.

Below is the edited version of your code.
I also created a text file on my end to test with and it seams to have worked so let me know if this is getting close to what you are attempting to do.

A few notes:

1st I moved everything into one class. The way you had it set up was just not going to work without some major changes.

2nd I needed to add self. to many of your variables because they are variables that we need to interact with in the class.

3rd I changed they way you get the data from the entry box. The way you were doing it was just not working so I simplified it by adding .get() function to the entry variable.

4th but probably should have been the 1st thing I mentions. The way you had your main Tk() window starting was odd. I changed how root was created and how we pass it into the class. This seams to make more sense to me.

This is much better to use IMO.

Let me know what parts you still need explanation on and I will make updates to my answer as needed.

Update:

change the while open statement a bit. You do not need to recreate the text box and reconfigure it ever for loop this is not good and will prevent you from seeing multiple items. Also I do not believe you can have a multi line label thought I have never tried. Lets change this to a text box this should do what we need.

import tkinter as tk
from tkinter import ttk

class EXAMPLEapp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.root.wm_title("TM Duch\'e Nut CO.")
        self.FILE_MENU_BAR()
        self.root.minsize(width = 360, height = 200)
        self.container = tk.Frame(self.root)
        self.container.grid(row=0,column=0, sticky="nsew")
        self.container.grid_rowconfigure(0, weight = 1)
        self.container.grid_rowconfigure(6, weight = 0)
        self.container.grid_columnconfigure(0, weight = 1)
        self.container.grid_columnconfigure(3, weight = 0)

        self.label = tk.Label(self.root, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
        self.label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
        self.button0 = ttk.Button(self.root, text = "Inventory Search")
        self.button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button1 = ttk.Button(self.root, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
        self.button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button2 = ttk.Button(self.root, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
        self.button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button3 = ttk.Button(self.root, text = "Ship", command = lambda: controller.show_frame(ShipPage))
        self.button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.button4 = ttk.Button(self.root, text = "Graph", command = lambda: controller.show_frame(PlotPage))
        self.button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
        self.DATE_Search_label = tk.Label(self.root, text = "Search by DATE", font = ("Helvetica", 9))
        self.DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
        self.DATE_Search_Entry = tk.Entry(self.root)
        self.DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
        self.DATE_SEARCH_BUTTON = ttk.Button(self.root, text = "Search", command = lambda: self.DATE_SEARCH())
        self.DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")

    def DATE_SEARCH(self):
        with open('SAMPLE.txt', 'r') as f:
            search_f = f.readlines()
            self.text = tk.Text(self.root, width = 30, height = 2)
            self.text.grid(row = 6, column = 3, sticky = "ew", pady = (0,0), padx = (20,0))
            self.ScrollBar = tk.Scrollbar(self.root)
            self.ScrollBar.config(command = self.text.yview)
            self.text.config(yscrollcommand = self.ScrollBar.set)
            self.ScrollBar.grid(row = 6, column = 4, sticky = "ns")
            self.text.delete(1.0, "end-1c")

            USER_TEXT = self.DATE_Search_Entry.get()
            if USER_TEXT == '':
                self.text.config(foreground = 'red')
                self.text.insert(tk.END, "PLEASE ENTER A VALUE")
            else:
                match_in_file = False
                for line in search_f:
                    if USER_TEXT in line:
                        self.text.config(foreground = 'black')
                        self.text.insert(tk.END, "{}".format(line))
                        match_in_file = True
                if match_in_file == False:
                    self.text.config(foreground = 'red')
                    self.text.insert(tk.END, "INVENTORY DOES NOT EXIST")

    def FILE_MENU_BAR(self):
        #File
        self.menu = tk.Menu(self.root)
        self.root.config(menu = self.menu)
        self.fileMenu = tk.Menu(self.menu, tearoff = 0)
        self.menu.add_cascade(label = "File", menu = self.fileMenu)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label = "Exit", command = lambda: self.root.destroy())
        # Edit Menu
        self.Edit_Menu = tk.Menu(self.menu)
        self.menu.add_cascade(label = "Edit", menu = self.Edit_Menu)
        self.Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
        self.Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)

    def File_EXIT(self):
        sys.exit(0)

    def Edit_Cut(self):
        print("CUT")

    def Edit_Copy(self):
        print("COPY")

root = tk.Tk()
app = EXAMPLEapp(root)
app.mainloop()


问:
Testing Roaming App Data in Emulator C#
I am using Visual Studio 2017 and trying to program a C# UWP application for Windows phone. When I try to test roaming app data between the host computer and the emulator (Mobile emulator 10.0.15063.0) the data does not sync.  Even after waiting several hours.  The emulator appears to be working as my emails and calendar sync across devices. When I search for the files on the host computer it appears to be created correctly:

```<code>C:\Users\Owner\AppData\Local\Packages\23840StartPoint.StartPointRunning_x6wjmepvaasdr\RoamingState
</code>```

I have checked the package manifest and the package name and version match. I have tried several different options but nothing works.  Am I missing something.

The Application Data sample from GitHub is what I used as a model teaching myself to write/read files. It does not work on my setup either.

```<code>var applicationData = ApplicationData.Current;

ulong storage = applicationData.RoamingStorageQuota;

//Create file client.txt => store data => Roaming folder
ApplicationDataContainer roamingSettings =   ApplicationData.Current.RoamingSettings;

StorageFolder roamingFolder1 = ApplicationData.Current.RoamingFolder;
StorageFile file1 = await roamingFolder1.CreateFileAsync(Filename1, CreationCollisionOption.ReplaceExisting);

SetUpFlag = "true";
String string6 = Views.Colors101.m_BackGroundColor + ";" +  Views.Colors101.m_CalendarColor + ";" + Views.Colors101.m_HeaderColor;

String toWrite = SetUpFlag + ";" + string6;

StorageFile xfile1 = await roamingFolder1.GetFileAsync(Filename1);

await FileIO.WriteTextAsync(xfile1, toWrite);

ApplicationData.Current.SignalDataChanged();
</code>```

答:
Maybe try my version to see if it works better..</p>

```<code>const string _listofStuffFile = "allMyStuff.txt";
public static async Task<bool> SaveMyListData(List<string> saveData)
    {
        try
        {
            var savedStuffFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync(_listofStuffFile, CreationCollisionOption.ReplaceExisting);
            using (Stream ws = await savedStuffFile.OpenStreamForWriteAsync())
            {
                var ss = new DataContractSerializer(typeof(List<string>));
                ss.WriteObject(ws, saveData);
            }
            return true;
        }
        catch { }
        return false;
    }

public static async Task<List<string>> GetMyListData()
    {
        try
        {
            var rs = await ApplicationData.Current.RoamingFolder.OpenStreamForReadAsync(_listofStuffFile);
            if (rs == null)
                return new List<string>();
            var ss = new DataContractSerializer(typeof(List<string>));
            var sr = (List<string>)ss.ReadObject(rs);
            return sr;
        }
        catch { }
        return new List<string>();
    }
</code>```

Title: Testing Roaming App Data in Emulator C#

Body:
I am using Visual Studio 2017 and trying to program a C# UWP application for Windows phone. When I try to test roaming app data between the host computer and the emulator (Mobile emulator 10.0.15063.0) the data does not sync.  Even after waiting several hours.  The emulator appears to be working as my emails and calendar sync across devices. When I search for the files on the host computer it appears to be created correctly:

C:\Users\Owner\AppData\Local\Packages\23840StartPoint.StartPointRunning_x6wjmepvaasdr\RoamingState

I have checked the package manifest and the package name and version match. I have tried several different options but nothing works.  Am I missing something.

The Application Data sample from GitHub is what I used as a model teaching myself to write/read files. It does not work on my setup either.

var applicationData = ApplicationData.Current;

ulong storage = applicationData.RoamingStorageQuota;

//Create file client.txt => store data => Roaming folder
ApplicationDataContainer roamingSettings =   ApplicationData.Current.RoamingSettings;

StorageFolder roamingFolder1 = ApplicationData.Current.RoamingFolder;
StorageFile file1 = await roamingFolder1.CreateFileAsync(Filename1, CreationCollisionOption.ReplaceExisting);

SetUpFlag = "true";
String string6 = Views.Colors101.m_BackGroundColor + ";" +  Views.Colors101.m_CalendarColor + ";" + Views.Colors101.m_HeaderColor;

String toWrite = SetUpFlag + ";" + string6;

StorageFile xfile1 = await roamingFolder1.GetFileAsync(Filename1);

await FileIO.WriteTextAsync(xfile1, toWrite);

ApplicationData.Current.SignalDataChanged();

Body:
Maybe try my version to see if it works better..

const string _listofStuffFile = "allMyStuff.txt";
public static async Task<bool> SaveMyListData(List<string> saveData)
    {
        try
        {
            var savedStuffFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync(_listofStuffFile, CreationCollisionOption.ReplaceExisting);
            using (Stream ws = await savedStuffFile.OpenStreamForWriteAsync())
            {
                var ss = new DataContractSerializer(typeof(List<string>));
                ss.WriteObject(ws, saveData);
            }
            return true;
        }
        catch { }
        return false;
    }

public static async Task<List<string>> GetMyListData()
    {
        try
        {
            var rs = await ApplicationData.Current.RoamingFolder.OpenStreamForReadAsync(_listofStuffFile);
            if (rs == null)
                return new List<string>();
            var ss = new DataContractSerializer(typeof(List<string>));
            var sr = (List<string>)ss.ReadObject(rs);
            return sr;
        }
        catch { }
        return new List<string>();
    }


答:
You can do this without making an extra query by using a raw expression.</p>

```<code>Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => DB::raw("CONCAT(reason, '" . $notesAdd . "')")
                ]);
</code>```

Title: Laravel update database with concate string is not working

Body:
You can do this without making an extra query by using a raw expression.

Res_Reservations::where('time_id', $time['id'])
                ->where('date',  $bus['date'])
                ->where('valid',  config('config.TYPE_SCHEDULE_UNREMOVED'))
                ->update([
                    'time_id' => $time['move'],
                    'reason' => DB::raw("CONCAT(reason, '" . $notesAdd . "')")
                ]);


问:
Custom folder/inbox views in an Outlook Web Add-in
I'm looking for a way to display a custom view of the inbox - one that isn't necessarily constrained to a simple tabular grid.  Basically a calendar view of all past emails (weekly and monthly).

I would also like to make it work as a Web Add-In so I can use it in the Office 365 Web Outlook, along with my Windows Desktop Outlook 2016 app (and Android would be a bonus).

Two main questions:

Is there a way to customize the current folder view for emails using a Web Add-In to support something like this - a calendar layout for all my past emails?

Alternatively, is there a way to link to a custom View using a Web Add-In that is NOT in the context of a selected message?

I've read about module extensions and being able to add an entry point from the navigation pane, but unfortunately those are limited to Office 2016-only in Windows.

From what I can tell the Ribbon support for a web add-in, runs in the context of a message, too (is that correct?) so what (if any) other options are there for running at a more high level, global context, not initiated by viewing a message?

I've proofed out a custom view using the office API via Office.js (still lots of work left, but the only remaining unknown for this route is #2).  Unfortunately I'm loading that view by clicking on any email then clicking the button from there.

答:
Thank you for your questions. The add-in API doesn't support to custom layout for folder view. The add-in runs on single message and cannot run at "higher" level now. If you need such features, please add your request here: https://officespdev.uservoice.com/forums/224641-general/category/131778-outlook-add-ins.

Thanks again for your feedback,
Outlook Engineering Team


问:
python pandas 3 smallest & 3 largest values
How can I find the index of the 3 smallest and 3 largest values in a column in my pandas dataframe? I saw ways to find max and min, but none to get the 3.</p>

答:
```<code>In [55]: import numpy as np

In [56]: import pandas as pd

In [57]: s = pd.Series(np.random.randn(5))

In [58]: s
Out[58]:
0    0.152037
1    0.194204
2    0.296090
3    1.071013
4   -0.324589
dtype: float64

In [59]: s.nsmallest(3) ## s.drop_duplicates().nsmallest(3); if duplicates exists
Out[59]:
4   -0.324589
0    0.152037
1    0.194204
dtype: float64

In [60]: s.nlargest(3) ## s.drop_duplicates().nlargest(3); if duplicates exists
Out[60]:
3    1.071013
2    0.296090
1    0.194204
dtype: float64
</code>```


问:
How to read the JSON String
Kindly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"Dealer ABC"},
{"dealerID":"VARSSTH008","dealerName":"Dealer XYZ"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help...

答:
First, download Google GSON.

Second, create this class:

```<code>class Dealer {
    Dealer() {}
    public void setDealerID(String dealerID) {
        this.dealerID = dealerID;
    }
    public String getDealerID() {
        return dealerID;
    }
    public void setDealerName(String dealerName) {
        this.dealerName = dealerName;
    }
    public String getDealerName() {
        return dealerName;
    }
    private String dealerID;
    private String dealerName;

}
</code>```

Third, use this code:

```<code>String jsonDealer = "[{\"dealerID\":\"VARSSWK103\",\"dealerName\":\"Dealer ABC\"}, {\"dealerID\":\"VARSSTH008\",\"dealerName\":\"Dealer XYZ\"}]";

Gson gson = new Gson();

Type type = new TypeToken<List<Dealer>>(){}.getType();

List<Dealer> fromJson = gson.fromJson(jsonDealer, type);

System.out.println(fromJson.get(0).getDealerName());   // example usage
</code>```

Title: How to read the JSON String

Body:
First, download Google GSON.

Second, create this class:

class Dealer {
    Dealer() {}
    public void setDealerID(String dealerID) {
        this.dealerID = dealerID;
    }
    public String getDealerID() {
        return dealerID;
    }
    public void setDealerName(String dealerName) {
        this.dealerName = dealerName;
    }
    public String getDealerName() {
        return dealerName;
    }
    private String dealerID;
    private String dealerName;

}

Third, use this code:

String jsonDealer = "[{\"dealerID\":\"VARSSWK103\",\"dealerName\":\"Dealer ABC\"}, {\"dealerID\":\"VARSSTH008\",\"dealerName\":\"Dealer XYZ\"}]";

Gson gson = new Gson();

Type type = new TypeToken<List<Dealer>>(){}.getType();

List<Dealer> fromJson = gson.fromJson(jsonDealer, type);

System.out.println(fromJson.get(0).getDealerName());   // example usage


问:
Hibernate search: persist causes sometimes OverlappingFileLockException
I have a WebAppilcation runnig with JPA (Hibernate 5.0.11.Final) and Hibernate Search (5.5.5.Final) in which the user tries to save a new entity. Therefor there will be serveral calls like:

```<code>protected Object saveNewEntity(Object toSave) {
   if (factory == null) {
       factory = Persistence
          .createEntityManagerFactory(DBBase.PERSISTENCE_UNIT);
   }
   EntityManager em = initEntityManager();
   try {
       em.setFlushMode(FlushModeType.COMMIT);
       EntityTransaction transaction = em.getTransaction();
       transaction.begin();
       em.persist(toSave);
       transaction.commit();
   } catch (Exception e) {
       throw e;
   } finally {
       finalizeEntityManager(em);
   }
   return toSave;
}

protected void finalizeEntityManager(EntityManager em) {
   if (em != null && em.isOpen()) {
      em.close();
   }
}
</code>```

The entity which is indexed also saved this way. It has no Cascading and is completly flat (no other tables involved).

Most of the time this will run fine and the index will be updatet.

But sometimes, I don't know why, the follwing exception will occur and therefor the index will not be updated:

```<code>2017-04-04 10:30:48,552 ERROR [LuceneBackendQueueTask:run:54] HSEARCH000073: Error in backend
java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.SharedFileLockTable.checkList(FileLockTable.java:255) ~[?:1.8.0_121]
    at sun.nio.ch.SharedFileLockTable.add(FileLockTable.java:152) ~[?:1.8.0_121]
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1108) ~[?:1.8.0_121]
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1155) ~[?:1.8.0_121]
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:114) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:775) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:123) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:89) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:112) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:198) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:80) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:162) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.run(SyncWorkProcessor.java:148) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
2017-04-04 10:30:48,555 ERROR [LogErrorHandler:handleException:67] HSEARCH000058: Exception occurred java.nio.channels.OverlappingFileLockException
Primary Failure:
    Entity com.rhenus.de.cm.essentials.entities.ContractSearchEntity  Id 96926  Work Type  org.hibernate.search.backend.AddLuceneWork

java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.SharedFileLockTable.checkList(FileLockTable.java:255) ~[?:1.8.0_121]
    at sun.nio.ch.SharedFileLockTable.add(FileLockTable.java:152) ~[?:1.8.0_121]
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1108) ~[?:1.8.0_121]
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1155) ~[?:1.8.0_121]
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:114) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:775) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:123) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:89) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:112) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:198) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:80) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:162) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.run(SyncWorkProcessor.java:148) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
</code>```

I do not manually lock or update the index, nor is the index used by different threads, applications or whatever.
I've read, that this can occur, if the entity has already an id and in the stacktrace the id is stated. But I definetly don't persist an entity with an id. So maybe there is a concurrency effect?

Any tips and help is appreciated. I f you need more information, just ask and I'll provide it. Thank you.

答:
The problem is actually not in Hibernate Search but in the first three lines of code.

You stated that "nor is the index used by different threads, applications or whatever", yet you also suggest this is a Web Application so it most likely needs to react to events out of your control, possibly concurrently even if you didn't expect that.

What is guaranteeing that those initial lines of code are not invoked concurrently? The initialization of the EntityManagerFactory might be triggered multiple times, yet there is no code shutting down the copies which have already been started.

In practice you are having multiple copies of Hibernate Search running and fighting to obtain the exclusive index lock.

Let me recommend to never disable the locking mechanism: it's designed to protect you from similar mistakes. It's enabled by default for very good reasons.

I would also suggest to use some standard approach to initialise Hibernate and/or JPA, any popular JavaEE container (like WildFly) or framework is likely to "do it right", and some of the most advanced ones can automatically enable some insane optimisations.

Body:
I have a WebAppilcation runnig with JPA (Hibernate 5.0.11.Final) and Hibernate Search (5.5.5.Final) in which the user tries to save a new entity. Therefor there will be serveral calls like:

protected Object saveNewEntity(Object toSave) {
   if (factory == null) {
       factory = Persistence
          .createEntityManagerFactory(DBBase.PERSISTENCE_UNIT);
   }
   EntityManager em = initEntityManager();
   try {
       em.setFlushMode(FlushModeType.COMMIT);
       EntityTransaction transaction = em.getTransaction();
       transaction.begin();
       em.persist(toSave);
       transaction.commit();
   } catch (Exception e) {
       throw e;
   } finally {
       finalizeEntityManager(em);
   }
   return toSave;
}

protected void finalizeEntityManager(EntityManager em) {
   if (em != null && em.isOpen()) {
      em.close();
   }
}

The entity which is indexed also saved this way. It has no Cascading and is completly flat (no other tables involved).

Most of the time this will run fine and the index will be updatet.

But sometimes, I don't know why, the follwing exception will occur and therefor the index will not be updated:

2017-04-04 10:30:48,552 ERROR [LuceneBackendQueueTask:run:54] HSEARCH000073: Error in backend
java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.SharedFileLockTable.checkList(FileLockTable.java:255) ~[?:1.8.0_121]
    at sun.nio.ch.SharedFileLockTable.add(FileLockTable.java:152) ~[?:1.8.0_121]
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1108) ~[?:1.8.0_121]
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1155) ~[?:1.8.0_121]
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:114) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:775) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:123) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:89) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:112) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:198) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:80) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:162) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.run(SyncWorkProcessor.java:148) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
2017-04-04 10:30:48,555 ERROR [LogErrorHandler:handleException:67] HSEARCH000058: Exception occurred java.nio.channels.OverlappingFileLockException
Primary Failure:
    Entity com.rhenus.de.cm.essentials.entities.ContractSearchEntity  Id 96926  Work Type  org.hibernate.search.backend.AddLuceneWork

java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.SharedFileLockTable.checkList(FileLockTable.java:255) ~[?:1.8.0_121]
    at sun.nio.ch.SharedFileLockTable.add(FileLockTable.java:152) ~[?:1.8.0_121]
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:1108) ~[?:1.8.0_121]
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:1155) ~[?:1.8.0_121]
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:114) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:775) ~[lucene-core-5.3.1.jar:5.3.1 1703449 - noble - 2015-09-17 01:38:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:123) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:89) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:112) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:198) ~[hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:80) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:162) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.run(SyncWorkProcessor.java:148) [hibernate-search-engine-5.5.5.Final.jar:5.5.5.Final]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]

I do not manually lock or update the index, nor is the index used by different threads, applications or whatever.
I've read, that this can occur, if the entity has already an id and in the stacktrace the id is stated. But I definetly don't persist an entity with an id. So maybe there is a concurrency effect?

Any tips and help is appreciated. I f you need more information, just ask and I'll provide it. Thank you.


问:
How to pull in remote react components via ECMA6 imports?
We want to separate our components into multiple projects and develop them separately. We do NOT want to pull them in as npm dependencies but rather, pull them in like remote "src" files in html. Is this possible?

import MyCustomReactComponent from "http://foobar";

答: You might want to take a look at this: https://gist.github.com/tonytonyjan/616022dce75f8e6c1603bbeb94ec46a4</p>