问:
In Javascript, how do I automatically move the cursor to the next text box when the current one is full?
Suppose I have two HTML textboxes on my web page:

```<code><input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />
</code>```

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

答:
You could utilize jQuery UI's :focusable selector by replicating the class like this:

```<code>$.extend($.expr[':'], {
    focusable: function(element) {
        var nodeName = element.nodeName.toLowerCase(),
            tabIndex = $.attr(element, 'tabindex');
        return (/input|select|textarea|button|object/.test(nodeName)
            ? !element.disabled
            : 'a' == nodeName || 'area' == nodeName
                ? element.href || !isNaN(tabIndex)
                : !isNaN(tabIndex))
            // the element and all of its ancestors must be visible
            // the browser may report that the area is hidden
            && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
    }
});
</code>```

Then you can handle it like this:

```<code>$(document).ready(function() {
    $('input[type=text]').keydown(function() {
        var $this = $(this),
            $focusables = $(':focusable'),
            current = $focusables.index(this),
            $next;

        if ($this.val().length == $this.attr('maxlength')) {
            $next = $focusables.eq(current+1).length ?$focusables.eq(current+1) : $focusables.eq(0);
                $next.focus();
        }
    });
});
</code>```

See a working example here:

http://jsfiddle.net/kU6ZN/

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

Body:
You could utilize jQuery UI's :focusable selector by replicating the class like this:

$.extend($.expr[':'], {
    focusable: function(element) {
        var nodeName = element.nodeName.toLowerCase(),
            tabIndex = $.attr(element, 'tabindex');
        return (/input|select|textarea|button|object/.test(nodeName)
            ? !element.disabled
            : 'a' == nodeName || 'area' == nodeName
                ? element.href || !isNaN(tabIndex)
                : !isNaN(tabIndex))
            // the element and all of its ancestors must be visible
            // the browser may report that the area is hidden
            && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
    }
});

Then you can handle it like this:

$(document).ready(function() {
    $('input[type=text]').keydown(function() {
        var $this = $(this),
            $focusables = $(':focusable'),
            current = $focusables.index(this),
            $next;

        if ($this.val().length == $this.attr('maxlength')) {
            $next = $focusables.eq(current+1).length ?$focusables.eq(current+1) : $focusables.eq(0);
                $next.focus();
        }
    });
});

See a working example here:

http://jsfiddle.net/kU6ZN/


来源: stackexchange

问:
Web deployment IIS - The Web server is configured to not list the contents of this directory.
I published a web app created in Visual Studio using IIS. My problem starts when I want to share a directory browsing from my folder. Then its working fine until I realized when I published, the files(eg : If I change Label.Text, its not updated) of my web application is not updated.

So I created new web application to test whether my method or publish profile is wrong. Unfortunately, every new project I published I got "HTTP Error 403.14 - Forbidden : The Web server is configured to not list the contents of this directory."

So I think there's something wrong with my IIS, so I reinstall IIS but nothing happens. I also make a lot of work by search existing solution to this problem but nothing works.

I look up at  C:\inetpub\wwwroot\myweb , and only see web.config file, there's no other file like aspx, html, asset folder or etc. I don't want to show directory browsing when open my web, I want to show the design aspx.

答: I repaired my Visual Studio 2017 using Visual Studio Installer, then I uninstall Microsoft.CodeDom.Providers.DotNetCompilerPlatform by go to Manage NuGet Package as I getting Compilation Error during publishing.

ContentLicense: CC BY-SA 3.0


问:
uwsgi with Flask app gives "callable not found or import error"
I want to serve a basic Flask app in a virtualenv using Python 3 and nginx. I'm getting the error

Internal Server Error

when I attempt to browse to the page. I also see errors in /var/log/uwsgi/app/myproj.log that lead me to believe that the error lies within my uwsgi config file. nginx and uwsgi seem to be communicating just fine.

Here's my directory structure:

```<code>/srv/http/myproj/
             |----- setup.py
             |----- env/
             |----- myproj/
                       |----- __init__.py
                       |----- myproj.py
/etc/uwsgi/apps-enabled/
                 |----- myproj.ini
/etc/nginx/sites-enabled/
                 |----- myproj
</code>```

Here's the error I see in /var/log/uwsgi/app/myproj.log:

```<code>Thu Jun  8 00:00:41 2017 - *** Operational MODE: preforking ***
Thu Jun  8 00:00:41 2017 - unable to load app 0 (mountpoint='') (callable not found or import error)
Thu Jun  8 00:00:41 2017 - *** no app loaded. going in full dynamic mode ***
Thu Jun  8 00:00:41 2017 - *** uWSGI is running in multiple interpreter mode ***
Thu Jun  8 00:00:41 2017 - spawned uWSGI master process (pid: 14498)
Thu Jun  8 00:00:41 2017 - spawned uWSGI worker 1 (pid: 14504, cores: 1)
Thu Jun  8 00:00:41 2017 - spawned uWSGI worker 2 (pid: 14505, cores: 1)
Thu Jun  8 00:00:43 2017 - --- no python application found, check your startup logs for errors ---
[pid: 14505|app: -1|req: -1/1] 172.16.72.2 () {46 vars in 726 bytes} [Thu Jun  8 00:00:43 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
</code>```

Here's /etc/uwsgi/apps-enabled/myproj.ini:

```<code>[uwsgi]
plugins = python3
venv = /srv/http/myproj/env
chdir = /srv/http/myproj
module = myproj:myproj
callable = app
</code>```

I also tried with module set to myproj (which made no change in the uwsgi logs) and myproj.myproj (which was less successful because it couldn't find the module myproj.myproj).

Here's /srv/http/myproj/myproj/myproj.py:

```<code>import flask
app = flask.Flask(__name__)
</code>```

Here's /srv/http/myproj/myproj/__init__.py:

```<code>from myproj.myproj import app
</code>```

Here's /etc/nginx/sites-enabled/myproj:

```<code>upstream myproj {
        server unix:///run/uwsgi/app/myproj/socket fail_timeout=0;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name _;

        location / {
                uwsgi_pass myproj;
                include /etc/nginx/uwsgi_params;
        }
}
</code>```

I suppose my question is simple: What am I doing wrong?

Edit: In case it matters:

```<code># lsb_release -d
Description:    Ubuntu 16.04.2 LTS
</code>```

答:
I found the solution after looking at a similarly structured project. Here's the new file that solved the problem:

```<code>[uwsgi]
plugins = python3
venv = /srv/http/myproj/env
chdir = /srv/http/myproj/myproj
pythonpath = ..
module = myproj
callable = app
</code>```

Essentially, I needed my chdir to go one level deeper (and therefore the module one level less deep).

Edit: And finally, to get my imports in my project to work properly, I also needed to add the pythonpath line seen above.

Body:
I want to serve a basic Flask app in a virtualenv using Python 3 and nginx. I'm getting the error

Internal Server Error

when I attempt to browse to the page. I also see errors in /var/log/uwsgi/app/myproj.log that lead me to believe that the error lies within my uwsgi config file. nginx and uwsgi seem to be communicating just fine.

Here's my directory structure:

/srv/http/myproj/
             |----- setup.py
             |----- env/
             |----- myproj/
                       |----- __init__.py
                       |----- myproj.py
/etc/uwsgi/apps-enabled/
                 |----- myproj.ini
/etc/nginx/sites-enabled/
                 |----- myproj

Here's the error I see in /var/log/uwsgi/app/myproj.log:

Thu Jun  8 00:00:41 2017 - *** Operational MODE: preforking ***
Thu Jun  8 00:00:41 2017 - unable to load app 0 (mountpoint='') (callable not found or import error)
Thu Jun  8 00:00:41 2017 - *** no app loaded. going in full dynamic mode ***
Thu Jun  8 00:00:41 2017 - *** uWSGI is running in multiple interpreter mode ***
Thu Jun  8 00:00:41 2017 - spawned uWSGI master process (pid: 14498)
Thu Jun  8 00:00:41 2017 - spawned uWSGI worker 1 (pid: 14504, cores: 1)
Thu Jun  8 00:00:41 2017 - spawned uWSGI worker 2 (pid: 14505, cores: 1)
Thu Jun  8 00:00:43 2017 - --- no python application found, check your startup logs for errors ---
[pid: 14505|app: -1|req: -1/1] 172.16.72.2 () {46 vars in 726 bytes} [Thu Jun  8 00:00:43 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)

Here's /etc/uwsgi/apps-enabled/myproj.ini:

[uwsgi]
plugins = python3
venv = /srv/http/myproj/env
chdir = /srv/http/myproj
module = myproj:myproj
callable = app

I also tried with module set to myproj (which made no change in the uwsgi logs) and myproj.myproj (which was less successful because it couldn't find the module myproj.myproj).

Here's /srv/http/myproj/myproj/myproj.py:

import flask
app = flask.Flask(__name__)

Here's /srv/http/myproj/myproj/__init__.py:

from myproj.myproj import app

Here's /etc/nginx/sites-enabled/myproj:

upstream myproj {
        server unix:///run/uwsgi/app/myproj/socket fail_timeout=0;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name _;

        location / {
                uwsgi_pass myproj;
                include /etc/nginx/uwsgi_params;
        }
}

I suppose my question is simple: What am I doing wrong?

Edit: In case it matters:

# lsb_release -d
Description:    Ubuntu 16.04.2 LTS

Body:
I found the solution after looking at a similarly structured project. Here's the new file that solved the problem:

[uwsgi]
plugins = python3
venv = /srv/http/myproj/env
chdir = /srv/http/myproj/myproj
pythonpath = ..
module = myproj
callable = app

Essentially, I needed my chdir to go one level deeper (and therefore the module one level less deep).

Edit: And finally, to get my imports in my project to work properly, I also needed to add the pythonpath line seen above.


问:
DbContext does not load any entity
I am developing a simple project using Entity Framework, it used to run and load all my database before I reinstall a new copy of windows.

I was using Windows 10; SQL Server 2016; Entity Framework 6.1.3 and target .NET 4.5.2, and Visual Studio 2015.

I re-installed a fresh copy of Windows 10 and everything else.

I made a data connection to my .mdf file and I can read the database in my Visual Studio Server Explorer and verify that my tables are populated with all the rows.

When I run the project I have this error:

"An exception of type 'System.NullReferenceException' occurred in myApp.exe but was not handled in user code"

This is happening because it is reading a list that should be populated from one of my entity attributes

My question is: when I create my DbContext instance, why does it not load any of the entities and their attributes?

Any idea?

EDIT: This is the connection string

" Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="F:\Files\Development\C#\Visual Studio 2015\Projects\NurseOfficeApp\NurseOfficeApp\DB\NurseOfficeApp.NurseOfficeContext.mdf";Integrated Security=True;Connect Timeout=30"

this is where I have the problem

```<code>private void FrmDesignAgency_Load(object sender, EventArgs e)
{
     _context = new NurseOfficeContext();
     var mylist = _context.Set<Agency>().ToList();// mylist.count = 0
     ...
</code>```

mylist.count shouldn't be 0

答:
You can follow the instructions on the following URL:

http://www.entityframeworktutorial.net/

It will help you to setup your first EF application

Title: DbContext does not load any entity

Body:
I am developing a simple project using Entity Framework, it used to run and load all my database before I reinstall a new copy of windows.

I was using Windows 10; SQL Server 2016; Entity Framework 6.1.3 and target .NET 4.5.2, and Visual Studio 2015.

I re-installed a fresh copy of Windows 10 and everything else.

I made a data connection to my .mdf file and I can read the database in my Visual Studio Server Explorer and verify that my tables are populated with all the rows.

When I run the project I have this error:

"An exception of type 'System.NullReferenceException' occurred in myApp.exe but was not handled in user code"

This is happening because it is reading a list that should be populated from one of my entity attributes

My question is: when I create my DbContext instance, why does it not load any of the entities and their attributes?

Any idea?

EDIT: This is the connection string

" Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="F:\Files\Development\C#\Visual Studio 2015\Projects\NurseOfficeApp\NurseOfficeApp\DB\NurseOfficeApp.NurseOfficeContext.mdf";Integrated Security=True;Connect Timeout=30"

this is where I have the problem

private void FrmDesignAgency_Load(object sender, EventArgs e)
{
     _context = new NurseOfficeContext();
     var mylist = _context.Set<Agency>().ToList();// mylist.count = 0
     ...

mylist.count shouldn't be 0


问:
Toggle Checkbox
I have 4 checkboxes and I wish to toggle them (checked or unchecked) and they should all be the same what ever state they are in. I have this so far:

```<code>var toggle_click = false;

function check_them(element){

    if(toggle_click){
        $('#'+element+'_1').attr('checked', true);
        $('#'+element+'_2').attr('checked', true);
        $('#'+element+'_3').attr('checked', true);
        $('#'+element+'_4').attr('checked', true);
    }

    if(!toggle_click){
        $('#'+element+'_1').attr('checked', false);
        $('#'+element+'_2').attr('checked', false);
        $('#'+element+'_3').attr('checked', false);
        $('#'+element+'_4').attr('checked', false);
    }

    if(!toggle_click){ toggle_click = true;   }
    if(toggle_click) { toggle_click = false;  }
}
</code>```

On page load some of the checkboxes may be ticked or not ticked - but once I click a link and run this function, I want these checkboxes to go all to the same state.

When I try the above, it just doesn't seem to tick the boxes and sometimes it ticks them all and running this function again does nothing. What is going on? I am coffee deprived and confused!

Should be making use of a checkbox group or something?

Thanks all for any help

答:
It can also be done using only javascript without troubles, you can use an image or anything that lets you click it too.

```<code><html>
  <body>
    <a href=" javascript:check();"> Toggle </a> <br>
    <input type="checkbox" id="c1" > Un/Check me <br>
    <input type="checkbox" id="c2" > Un/Check me
  </body>
</html>

<script>
function check()
{
  c1.checked = !c1.checked;
  c2.checked = !c2.checked;
}
</script>
</code>```

I hope this helps.

Title: Toggle Checkbox

Body:
I have 4 checkboxes and I wish to toggle them (checked or unchecked) and they should all be the same what ever state they are in. I have this so far:

var toggle_click = false;

function check_them(element){

    if(toggle_click){
        $('#'+element+'_1').attr('checked', true);
        $('#'+element+'_2').attr('checked', true);
        $('#'+element+'_3').attr('checked', true);
        $('#'+element+'_4').attr('checked', true);
    }

    if(!toggle_click){
        $('#'+element+'_1').attr('checked', false);
        $('#'+element+'_2').attr('checked', false);
        $('#'+element+'_3').attr('checked', false);
        $('#'+element+'_4').attr('checked', false);
    }

    if(!toggle_click){ toggle_click = true;   }
    if(toggle_click) { toggle_click = false;  }
}

On page load some of the checkboxes may be ticked or not ticked - but once I click a link and run this function, I want these checkboxes to go all to the same state.

When I try the above, it just doesn't seem to tick the boxes and sometimes it ticks them all and running this function again does nothing. What is going on? I am coffee deprived and confused!

Should be making use of a checkbox group or something?

Thanks all for any help

Body:
It can also be done using only javascript without troubles, you can use an image or anything that lets you click it too.

<html>
  <body>
    <a href=" javascript:check();"> Toggle </a> <br>
    <input type="checkbox" id="c1" > Un/Check me <br>
    <input type="checkbox" id="c2" > Un/Check me
  </body>
</html>

<script>
function check()
{
  c1.checked = !c1.checked;
  c2.checked = !c2.checked;
}
</script>

I hope this helps.


问:
React.js - Cannot read property 'map' of undefined
When the component mounts, I'm making an ajax request that returns an Object with an array of objects.

```<code>getPages() {
  getAllPagesData().then((pages) => {
    let data = pages
    this.setState({ pages });
  });
}
</code>```

Inside this function I can access the data effectively.

console.log(pages.pages[0].description)

Prints the correct page description.

In render I'm setting state to a variable to access in my return:

```<code>render() {

  const pages = this.state.pages.pages
  console.log(pages)

return (
</code>```

That console.log in chrome is:

```<code>(55) [Object, Object, Object, Object,...
</code>```

I'm then trying to iterate through the array using map:

```<code>return (
  <div>
    <Nav />
     { pages.map((post, index) => (
</code>```

It breaks the page and the error is: Cannot read property 'map' of undefined at Pages.render

I've tried many different ways to access this object and the array inside of it, but cannot get individual array items to display inside the render function.

答:
Try using this line in the render method

```<code>const pages = this.state.pages.pages || [ ]
</code>```

It is most likely because the render method is called before the ajax request is complete. So the this.state.pages.pages is undefined initially.

Body:
When the component mounts, I'm making an ajax request that returns an Object with an array of objects.

getPages() {
  getAllPagesData().then((pages) => {
    let data = pages
    this.setState({ pages });
  });
}

Inside this function I can access the data effectively.

console.log(pages.pages[0].description)

Prints the correct page description.

In render I'm setting state to a variable to access in my return:

render() {

  const pages = this.state.pages.pages
  console.log(pages)

return (

That console.log in chrome is:

(55) [Object, Object, Object, Object,...

I'm then trying to iterate through the array using map:

return (

     { pages.map((post, index) => (

It breaks the page and the error is: Cannot read property 'map' of undefined at Pages.render

I've tried many different ways to access this object and the array inside of it, but cannot get individual array items to display inside the render function.

Body:
Try using this line in the render method

const pages = this.state.pages.pages || [ ]

It is most likely because the render method is called before the ajax request is complete. So the this.state.pages.pages is undefined initially.


问:
What is the difference between cropping, resizing and scaling an image?
I am using Perl's
Image::Imlib2
package to generate thumbnails from larger images.

I've done such tasks before with several ImageMagick interfaces (PHP, Ruby, Python) and it was relatively easy. I have no prior experience with Imlib2 and it is a long time since I wrote something in Perl, so I am sorry if this seems naive!

This is what I've tried so far. It is simple, and assumes that scaling an image will keep the aspect ratio, and the generated thumbnail will be an exact miniature copy of the original image.

```<code>use strict;
use warnings;

use Image::Imlib2;

my $dir = 'imgs/*';

my @files = glob ($dir);

foreach my $img ( @files ) {
    my $image = Image::Imlib2->load($img);
    my $cropped_image = $image->create_scaled_image(50, 50);
    $cropped_image->save($img);
}
</code>```

Original image

Generated image

My first look at the image tells me that something is wrong. It may be my ignorance on cropping, resizing and scaling, but the generated image is displaying wrongly on small screens.

I've read What's the difference between cropping and resizing?, and honestly didn't understand anything. Also this one Image scaling.

Could someone explain the differences between those three ideas, and if possible give examples (preferably with Perl) to achieve better results? Or at least describe what I should consider when I want to create thumbnails?

答:
I'm still not certain that you understand the difference between these terms

Your original image is 752 × 500 pixels

Resizing is a vague term that just means making a picture a different size somehow

Scaling is to change the size of an image proportionally. Scaling your picture down by a factor of ten would result in an image 75 × 50 (it should be 75.2 but we can't have 0.2 of a pixel). Scaling it up would make it bigger

You have scaled your picture to 50 × 50 pixels, which is a vertical scale of 10 (500 ÷ 5) but a horizontal scale of 15 (752 ÷ 50), so it appears squashed horizontally (or stretched vertically)

Cropping is to reduce an image by removing parts of it. To crop your image to 50 × 50 you would choose a 50 × 50 rectangle out of the whole picture and remove the rest. It would be a piece about the size of your monkey's nose, but you can pick any region you wish

zdim has shown you how you can call

```<code>$image->create_scaled_image(0, 50)
</code>```

so that the height, or y-dimension, is reduced to 50, while the width, or x-dimension, is scaled by the same factor. That will result in a thumbnail 75 × 50 as above

I hope that helps

As I said in my comment, there is an
Image::Magick
Perl module if you would prefer to be back on familiar ground

Body:
I am using Perl's
Image::Imlib2
package to generate thumbnails from larger images.

I've done such tasks before with several ImageMagick interfaces (PHP, Ruby, Python) and it was relatively easy. I have no prior experience with Imlib2 and it is a long time since I wrote something in Perl, so I am sorry if this seems naive!

This is what I've tried so far. It is simple, and assumes that scaling an image will keep the aspect ratio, and the generated thumbnail will be an exact miniature copy of the original image.

use strict;
use warnings;

use Image::Imlib2;

my $dir = 'imgs/*';

my @files = glob ($dir);

foreach my $img ( @files ) {
    my $image = Image::Imlib2->load($img);
    my $cropped_image = $image->create_scaled_image(50, 50);
    $cropped_image->save($img);
}

Original image

Generated image

My first look at the image tells me that something is wrong. It may be my ignorance on cropping, resizing and scaling, but the generated image is displaying wrongly on small screens.

I've read What's the difference between cropping and resizing?, and honestly didn't understand anything. Also this one Image scaling.

Could someone explain the differences between those three ideas, and if possible give examples (preferably with Perl) to achieve better results? Or at least describe what I should consider when I want to create thumbnails?

Body:
I'm still not certain that you understand the difference between these terms

Your original image is 752 × 500 pixels

Resizing is a vague term that just means making a picture a different size somehow

Scaling is to change the size of an image proportionally. Scaling your picture down by a factor of ten would result in an image 75 × 50 (it should be 75.2 but we can't have 0.2 of a pixel). Scaling it up would make it bigger

You have scaled your picture to 50 × 50 pixels, which is a vertical scale of 10 (500 ÷ 5) but a horizontal scale of 15 (752 ÷ 50), so it appears squashed horizontally (or stretched vertically)

Cropping is to reduce an image by removing parts of it. To crop your image to 50 × 50 you would choose a 50 × 50 rectangle out of the whole picture and remove the rest. It would be a piece about the size of your monkey's nose, but you can pick any region you wish

zdim has shown you how you can call

$image->create_scaled_image(0, 50)

so that the height, or y-dimension, is reduced to 50, while the width, or x-dimension, is scaled by the same factor. That will result in a thumbnail 75 × 50 as above

I hope that helps

As I said in my comment, there is an
Image::Magick
Perl module if you would prefer to be back on familiar ground


问:
Bind Data Model to UI Component - iOS
Is there a way in Objective-C to bind a data model to a UI component?

Imagine a UIViewController which contains several UITextFields, each of which update a property in some object. Each UITextField could have a different object that it is updating.

When the update method for an individual UITextField is called, I'd like to be able to know which object that UITextField should update.

Anyone know how to do this, or if there is a design pattern that accomplishes this? Can you even bind a data model to a UI component in Objective-C?

答:
This binding thing is from Xamarin methodology i think. XCode does not have such thing. You need to use the delegates.

In your case, for multiple textfields created either in storyboard/xib or programatically, you need to apply its delegate and set the textfields "tag" property. Then in the delegate, you can handle each textfields using its unique tags. It is quite simple.

Title: Bind Data Model to UI Component - iOS


问:
Nodejs - Mongoose - callbacks work only once
I am working with callbacks, and it makes the first call (POST), and never work again. I couldn't get any response error in postman.
This is the modal schema:

```<code>var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var ModalitySchema = new mongoose.Schema({
    name: {
    type: String,
    unique: true,
    required: true
  },
  type: {
    type: String,
    required: true
  },
    updated_at: { type: Date, default: Date.now },
  created_at: { type: Date, default: Date.now }
});
</code>```

And this is the call in the controller:

```<code>var mongoose = require('mongoose');
var Modality = require('../models/modality').Modality;

/** create function to create Modality. */
exports.create = function (req, res) {
Modality =new Modality({name:req.body.name,type: req.body.type});
Modality.save( function(err, result) {
        if (!err) {
            return res.json(result);
        } else {
          console.log(err);

            return res.send(err); // 500 error
        }
    });
};
</code>```

and the outers of node:

答:
The server encountered an error. Your model is incorrectly exported, the right way :

var Modality = require('../models/modality').model('Modality').schema

Body:
I am working with callbacks, and it makes the first call (POST), and never work again. I couldn't get any response error in postman.
This is the modal schema:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var ModalitySchema = new mongoose.Schema({
    name: {
    type: String,
    unique: true,
    required: true
  },
  type: {
    type: String,
    required: true
  },
    updated_at: { type: Date, default: Date.now },
  created_at: { type: Date, default: Date.now }
});

And this is the call in the controller:

var mongoose = require('mongoose');
var Modality = require('../models/modality').Modality;

/** create function to create Modality. */
exports.create = function (req, res) {
Modality =new Modality({name:req.body.name,type: req.body.type});
Modality.save( function(err, result) {
        if (!err) {
            return res.json(result);
        } else {
          console.log(err);

            return res.send(err); // 500 error
        }
    });
};

and the outers of node:


问:
mariadb cannot start with error
i'd rebooted server.

and mariadb did not started automatically.

so i'd type service mysqld start. but shows me cannot start with error.

mariadb cannot start with collation error

i wanna start without error

i'm using centos 6.5

```<code>**# mysql --version**
mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Linux (x86_64) using readline 5.1

**# ./mysqld_safe &**
mysqld_safe Logging to '/var/lib/mysql/localhost.localdomain.err'

**localhost.localdomain.err shows me**
mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
[Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
[ERROR] Unknown collation: 'utf8mb4_unicode_ci'
[ERROR] Aborting
[Note] /usr/libexec/mysqld: Shutdown complete

**my.cnf**
[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4
</code>```

答:
Whatever server you have on that machine, it is not MariaDB 10.1. mysql --version only shows the client version, and it is indeed MariaDB 10.1, but the server is not.

MariaDB 10.1 wouldn't have thrown a warning upon skip-locking, it would have been an error, because this option had been removed long before 10.1. It doesn't even exist in 5.5.

What you most likely have is MySQL 5.1, which is still provided on CentOS 6. Maybe you tried to install MariaDB over it and it didn't go well, or something similar happened.

MySQL 5.1 does not have utf8mb4, so the error makes sense, although I would expect it to fail on character-set-server. It is possible that you have another config somewhere else which overrides character-set-server (and adds skip-locking which is not present in your paste, but it must come from somewhere).

Title: mariadb cannot start with error

Body:
i'd rebooted server.

and mariadb did not started automatically.

so i'd type service mysqld start. but shows me cannot start with error.

mariadb cannot start with collation error

i wanna start without error

i'm using centos 6.5

**# mysql --version**
mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Linux (x86_64) using readline 5.1

**# ./mysqld_safe &**
mysqld_safe Logging to '/var/lib/mysql/localhost.localdomain.err'

**localhost.localdomain.err shows me**
mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
[Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
[ERROR] Unknown collation: 'utf8mb4_unicode_ci'
[ERROR] Aborting
[Note] /usr/libexec/mysqld: Shutdown complete

**my.cnf**
[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4


问:
Best Practice to migrate data from MySQL to BigQuery
I tried several csv-formats (different escape characters, quotes and other settings) to export data from MySQL and to import it into BigQuery, but I was not able to find a solution that works in every case.

Google SQL requires the following Code for importing/exporting from/to MySQL. Although, Cloud SQL is not BigQuery, it is a good starting point:

```<code>SELECT * INTO OUTFILE 'filename.csv' CHARACTER SET 'utf8'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' FROM table
</code>```

At the moment I use the following command to import a compressed csv into BigQuery:

```<code>bq --nosync load -F "," --null_marker "NULL" --format=csv PROJECT:DATASET.tableName gs://bucket/data.csv.gz table_schema.json
</code>```

On one hand the bq-command does not allow to set the escape character (" is escaped by another ", which seems to be a well defined CSV-format). On the other hand \" as escape character for MySQL-export would lead to "N as Null-value, which does not work too:

```<code>CSV table references column position 34, but line starting at position:0 contains only 34 columns. (error code: invalid)
</code>```

So my question is: How to write a (table-independent) export command for MySQL in SQL, such that the generated file can be loaded into BigQuery. Which escape character should be used and how to handle/set null values?

答:
I've been running with the same problem, here's my solution:

Exporting data from MySQL

First, export the data from MySQL this way:

```<code>SELECT * INTO OUTFILE 'filename.csv' CHARACTER SET 'utf8'
FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY ''
FROM table <yourtable>
</code>```

This is in reality a tsv file (tab separated values), but you can import them as csv thought.

Import into Big Query

This way you should be able to import it into big query with the following
 parameters:

```<code>bq load --field_delimiter="\t" --null_marker="\N" --quote="" \
PROJECT:DATASET.tableName gs://bucket/data.csv.gz table_schema.json
</code>```

Notes

If any field in you MySQL database contains a tab character (\t), it will break your columns. To prevent that you can add the SQL function REPLACE(<column>, '\t', ' ') on the columns and it will convert from tabs to spaces.

If you set the table schema in big query's web interface you won't need to specify it every time you load a CSV.

I hope this works for you.

Body:
I tried several csv-formats (different escape characters, quotes and other settings) to export data from MySQL and to import it into BigQuery, but I was not able to find a solution that works in every case.

Google SQL requires the following Code for importing/exporting from/to MySQL. Although, Cloud SQL is not BigQuery, it is a good starting point:

SELECT * INTO OUTFILE 'filename.csv' CHARACTER SET 'utf8'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '' FROM table

At the moment I use the following command to import a compressed csv into BigQuery:

bq --nosync load -F "," --null_marker "NULL" --format=csv PROJECT:DATASET.tableName gs://bucket/data.csv.gz table_schema.json

On one hand the bq-command does not allow to set the escape character (" is escaped by another ", which seems to be a well defined CSV-format). On the other hand \" as escape character for MySQL-export would lead to "N as Null-value, which does not work too:

CSV table references column position 34, but line starting at position:0 contains only 34 columns. (error code: invalid)

So my question is: How to write a (table-independent) export command for MySQL in SQL, such that the generated file can be loaded into BigQuery. Which escape character should be used and how to handle/set null values?

Body:
I've been running with the same problem, here's my solution:

Exporting data from MySQL

First, export the data from MySQL this way:

SELECT * INTO OUTFILE 'filename.csv' CHARACTER SET 'utf8'
FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY ''
FROM table <yourtable>

This is in reality a tsv file (tab separated values), but you can import them as csv thought.

Import into Big Query

This way you should be able to import it into big query with the following
 parameters:

bq load --field_delimiter="\t" --null_marker="\N" --quote="" \
PROJECT:DATASET.tableName gs://bucket/data.csv.gz table_schema.json

Notes

If any field in you MySQL database contains a tab character (\t), it will break your columns. To prevent that you can add the SQL function REPLACE(<column>, '\t', ' ') on the columns and it will convert from tabs to spaces.

If you set the table schema in big query's web interface you won't need to specify it every time you load a CSV.

I hope this works for you.


问:
How to match trained image with multiple query images in OpenCV Python
I would like to design an image processing program where it detects and matches hand gestures. What I basically need to do is matching a query image with multiple trained images and returning the best match.
Below code is the implementation of two single hand gestures.</p>

```<code>import cv2 as cv

sift = cv.xfeatures2d.SIFT_create()
bf = cv.BFMatcher()

original_img = cv.imread('./database/bb.jpg', cv.IMREAD_GRAYSCALE)
query_img = cv.imread('./database/b.jpg', cv.IMREAD_GRAYSCALE)

kp1,des1 = sift.detectAndCompute(original_img , None)
kp2, des2 = sift.detectAndCompute(query_img ,None)

matches = bf.knnMatch( des1, des2, k=2 )
good = []

for m,n in matches:
    if m.distance < 0.75 * n.distance:
        good.append ( [m] )

new_img = cv.drawMatchesKnn(original_img, kp1, query_img, kp2, good, None, flags=2)
cv.imshow('matches' , new_img)

k = cv.waitKey(0)
cv.destroyAllWindows()
</code>```

答:
You installed OpenCV3 and the code needs to score for each match. This is the link for
Match each pair of images using opencv3.
Use the above function, you could get the matches for features of each pair of images.
Of course, you need to evaluate the matches and give each match a score, then sort them. I think the link Score for each match could help you.</p>

Body:
I would like to design an image processing program where it detects and matches hand gestures. What I basically need to do is matching a query image with multiple trained images and returning the best match.
Below code is the implementation of two single hand gestures.

import cv2 as cv

sift = cv.xfeatures2d.SIFT_create()
bf = cv.BFMatcher()

original_img = cv.imread('./database/bb.jpg', cv.IMREAD_GRAYSCALE)
query_img = cv.imread('./database/b.jpg', cv.IMREAD_GRAYSCALE)

kp1,des1 = sift.detectAndCompute(original_img , None)
kp2, des2 = sift.detectAndCompute(query_img ,None)

matches = bf.knnMatch( des1, des2, k=2 )
good = []

for m,n in matches:
    if m.distance < 0.75 * n.distance:
        good.append ( [m] )

new_img = cv.drawMatchesKnn(original_img, kp1, query_img, kp2, good, None, flags=2)
cv.imshow('matches' , new_img)

k = cv.waitKey(0)
cv.destroyAllWindows()


问:
GCP Client vs Cloud API Authentication
There seems to have been a divergent path of cloud and api client libraries in for Google Cloud Platform services. In the api client libraries we could use default credentials but I can't find the documentation to use default credentials in the cloud libraries.

Can we still use the default credentials in the cloud libraries? If not is the suggested path to generate a service user with api keys for a project?

答:
For both Cloud Storage and Stackdriver monitoring client libraries, you should be able to use application default credentials by default just like any other Google client libraries.

From the documentation on github:

If no credentials are provided, google-cloud will attempt to detect
  them from the environment using
  GoogleCredentials.getApplicationDefault() which will search for
  Default Application Credentials in the following locations (in order):

The credentials file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable.

Credentials provided by the Google Cloud SDK gcloud auth application-default login command.

Google App Engine built-in credentials.

Google Cloud Shell built-in credentials Google

Compute Engine built-in credentials

Depending on your setup and environment, you can choose the method which works best. Usually the environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to the credentials json file is easiest to set up.

Once you've done the above, you can go ahead and call the respective libraries.

For Cloud Storage (copying the example here):

```<code>// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // The name for the new bucket
    String bucketName = args[0];  // "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.getName());
  }
}
</code>```

For Stackdriver monitoring (copying the example here):

```<code>import com.google.api.Metric;
import com.google.api.MonitoredResource;

// Imports the Google Cloud client library
import com.google.cloud.monitoring.spi.v3.MetricServiceClient;

import com.google.monitoring.v3.CreateTimeSeriesRequest;
import com.google.monitoring.v3.Point;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.monitoring.v3.TimeSeries;
import com.google.monitoring.v3.TypedValue;
import com.google.protobuf.util.Timestamps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Your Google Cloud Platform project ID
    String projectId = System.getProperty("projectId");

    if (projectId == null) {
      System.err.println("Usage: QuickstartSample -DprojectId=YOUR_PROJECT_ID");
      return;
    }

    // Instantiates a client
    MetricServiceClient metricServiceClient = MetricServiceClient.create();

    // Prepares an individual data point
    TimeInterval interval = TimeInterval.newBuilder()
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();
    TypedValue value = TypedValue.newBuilder()
        .setDoubleValue(123.45)
        .build();
    Point point = Point.newBuilder()
        .setInterval(interval)
        .setValue(value)
        .build();

    List<Point> pointList = new ArrayList<>();
    pointList.add(point);

    ProjectName name = ProjectName.create(projectId);

    // Prepares the metric descriptor
    Map<String, String> metricLabels = new HashMap<String, String>();
    metricLabels.put("store_id", "Pittsburg");
    Metric metric = Metric.newBuilder()
        .setType("custom.googleapis.com/stores/daily_sales")
        .putAllLabels(metricLabels)
        .build();

    // Prepares the monitored resource descriptor
    Map<String, String> resourceLabels = new HashMap<String, String>();
    resourceLabels.put("project_id", projectId);
    MonitoredResource resource = MonitoredResource.newBuilder()
        .setType("global")
        .putAllLabels(resourceLabels)
        .build();

    // Prepares the time series request
    TimeSeries timeSeries = TimeSeries.newBuilder()
        .setMetric(metric)
        .setResource(resource)
        .addAllPoints(pointList)
        .build();
    List<TimeSeries> timeSeriesList = new ArrayList<>();
    timeSeriesList.add(timeSeries);

    CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
        .setNameWithProjectName(name)
        .addAllTimeSeries(timeSeriesList)
        .build();

    // Writes time series data
    metricServiceClient.createTimeSeries(request);

    System.out.printf("Done writing time series data.%n");

    metricServiceClient.close();
  }
}
</code>```

BTW, Cloud Monitoring libraries APIs v2 are deprecated in favor of Stackdriver Monitoring libraries and APIs v3.

Title: GCP Client vs Cloud API Authentication

Body:
For both Cloud Storage and Stackdriver monitoring client libraries, you should be able to use application default credentials by default just like any other Google client libraries.

From the documentation on github:

If no credentials are provided, google-cloud will attempt to detect
  them from the environment using
  GoogleCredentials.getApplicationDefault() which will search for
  Default Application Credentials in the following locations (in order):

The credentials file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable.

Credentials provided by the Google Cloud SDK gcloud auth application-default login command.

Google App Engine built-in credentials.

Google Cloud Shell built-in credentials Google

Compute Engine built-in credentials

Depending on your setup and environment, you can choose the method which works best. Usually the environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to the credentials json file is easiest to set up.

Once you've done the above, you can go ahead and call the respective libraries.

For Cloud Storage (copying the example here):

// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // The name for the new bucket
    String bucketName = args[0];  // "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.getName());
  }
}

For Stackdriver monitoring (copying the example here):

import com.google.api.Metric;
import com.google.api.MonitoredResource;

// Imports the Google Cloud client library
import com.google.cloud.monitoring.spi.v3.MetricServiceClient;

import com.google.monitoring.v3.CreateTimeSeriesRequest;
import com.google.monitoring.v3.Point;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.monitoring.v3.TimeSeries;
import com.google.monitoring.v3.TypedValue;
import com.google.protobuf.util.Timestamps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Your Google Cloud Platform project ID
    String projectId = System.getProperty("projectId");

    if (projectId == null) {
      System.err.println("Usage: QuickstartSample -DprojectId=YOUR_PROJECT_ID");
      return;
    }

    // Instantiates a client
    MetricServiceClient metricServiceClient = MetricServiceClient.create();

    // Prepares an individual data point
    TimeInterval interval = TimeInterval.newBuilder()
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();
    TypedValue value = TypedValue.newBuilder()
        .setDoubleValue(123.45)
        .build();
    Point point = Point.newBuilder()
        .setInterval(interval)
        .setValue(value)
        .build();

    List<Point> pointList = new ArrayList<>();
    pointList.add(point);

    ProjectName name = ProjectName.create(projectId);

    // Prepares the metric descriptor
    Map<String, String> metricLabels = new HashMap<String, String>();
    metricLabels.put("store_id", "Pittsburg");
    Metric metric = Metric.newBuilder()
        .setType("custom.googleapis.com/stores/daily_sales")
        .putAllLabels(metricLabels)
        .build();

    // Prepares the monitored resource descriptor
    Map<String, String> resourceLabels = new HashMap<String, String>();
    resourceLabels.put("project_id", projectId);
    MonitoredResource resource = MonitoredResource.newBuilder()
        .setType("global")
        .putAllLabels(resourceLabels)
        .build();

    // Prepares the time series request
    TimeSeries timeSeries = TimeSeries.newBuilder()
        .setMetric(metric)
        .setResource(resource)
        .addAllPoints(pointList)
        .build();
    List<TimeSeries> timeSeriesList = new ArrayList<>();
    timeSeriesList.add(timeSeries);

    CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
        .setNameWithProjectName(name)
        .addAllTimeSeries(timeSeriesList)
        .build();

    // Writes time series data
    metricServiceClient.createTimeSeries(request);

    System.out.printf("Done writing time series data.%n");

    metricServiceClient.close();
  }
}

BTW, Cloud Monitoring libraries APIs v2 are deprecated in favor of Stackdriver Monitoring libraries and APIs v3.


问:
Generating JAXB Classes from XSD Issue
I have a bunch of XSD files and I added them to my project to generate classes from them using JAXB. I am using JDeveloper 11, JDK 1.6 and JAXB 2.0. An XSD file imports other XSD files so I'm generating the content model of the main file, however, I keep getting this error An error was encountered while migrating JAXB. Property "Any" is already defined. Use <jaxb:property> to resolve this conflict.

The rest of the file may contain types of the same name.

I also tried commenting out all the xs:any elements inside the choice and leaving only one, also commenting out their corresponding imports, and was able to generate the jaxb classes. But if I add one more, then I get the error.

I tried the same thing using JDeveloper 12c and using Eclipse but the same thing happened.

What could be the issue here, I also tried looking up the issue, but did not find anything that could work for me.

Below is the main XSD file

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

SWIFT SCRL@2014. All rights reserved.

This schema is a component of MyStandards, the SWIFT collaborative Web application used to manage
standards definitions and industry usage.

This is a licensed product, which may only be used and distributed in accordance with MyStandards License
Terms as specified in MyStandards Service Description and the related Terms of Use.

Unless otherwise agreed in writing with SWIFT SCRL, the user has no right to:
 - authorise external end users to use this component for other purposes than their internal use.
 - remove, alter, cover, obfuscate or cancel from view any copyright or other proprietary rights notices appearing in this physical medium.
 - re-sell or authorise another party e.g. software and service providers, to re-sell this component.

This component is provided 'AS IS'. SWIFT does not give and excludes any express or implied warranties
with respect to this component such as but not limited to any guarantee as to its quality, supply or availability.

Any and all rights, including title, ownership rights, copyright, trademark, patents, and any other intellectual
property rights of whatever nature in this component will remain the exclusive property of SWIFT or its
licensors.

Trademarks
SWIFT is the trade name of S.W.I.F.T. SCRL.
The following are registered trademarks of SWIFT: the SWIFT logo, SWIFT, SWIFTNet, SWIFTReady, Accord, Sibos, 3SKey, Innotribe, the Standards Forum logo, MyStandards, and SWIFT Institute.
Other product, service, or company names in this publication are trade names, trademarks, or registered trademarks of their respective owners.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Group: T2S
Collection: T2S_UDFS_2.1_head.002
Usage Guideline: head.002.001.01_T2S
Base Message: DRAFT2head.002.001.01
Date of publication: 01 October 2015
URL: https://www2.swift.com/mystandards/standardsPractices/mpDescription.xhtml?marketpractice=mp/mx/_LIiBQGg_EeWfEYThn8bcRQ/_LIiBQWg_EeWfEYThn8bcRQ
Generated by the MyStandards web platform [http://www.swift.com/mystandards] on 2015-11-09T09:46:56+00:00
T2S notices : null
-->
<!--
Being not available on MyStandards, this XSD file of "head.002.001.01" message has been remade based
on the "head.002.001.01" PDF description and the "DRAFT2head.002.001.01" XSD file produced and used
by T2S
The XSD file for "ISO20022+" id based and the remade "head.002.001.01" :
- encapsulation of the signature in a "Sgntr" tag
- encapsulation of the payload in a "Any" tag
- restriction of the payload namespaces to ISO20022+ namespaces (SEPA and ISO20022+ reports)
- strict version : import of namespaces + strict validation required
-->
<xs:schema xmlns="urn:iso:std:iso:20022:tech:xsd:head.002.001.01" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:iso:std:iso:20022:tech:xsd:head.002.001.01">
    <xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03" schemaLocation="pacs.002.001.03.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.02" schemaLocation="pacs.003.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.004.001.02" schemaLocation="pacs.004.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.007.001.02" schemaLocation="pacs.007.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02" schemaLocation="pacs.008.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:camt.029.001.03" schemaLocation="camt.029.001.03.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:camt.056.001.01" schemaLocation="camt.056.001.01.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:acmt.022.001.02" schemaLocation="acmt.022.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRA" schemaLocation="pacs.002.001.03CRA.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRB" schemaLocation="pacs.002.001.03CRB.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRT" schemaLocation="pacs.002.001.03CRT.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03FKO" schemaLocation="pacs.002.001.03FKO.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRG" schemaLocation="pacs.002.001.03CRG.xsd"/>
    <xs:element name="Xchg" type="BusinessFileHeaderV01"/>
    <xs:complexType name="ApplicationSpecifics1">
        <xs:sequence>
            <xs:element maxOccurs="1" minOccurs="0" name="SysUsr" type="Max140Text"/>
            <xs:element maxOccurs="1" minOccurs="0" name="Sgntr" type="ISO20022PlusSgntr"/>
            <xs:element name="TtlNbOfDocs" type="Number"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="BusinessFileHeaderV01">
        <xs:sequence>
            <xs:element name="PyldDesc" type="PayloadDescription1"/>
            <xs:element maxOccurs="unbounded" minOccurs="0" name="Pyld" type="ExchangePayload1"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="ExchangePayload1">
        <xs:sequence>
            <xs:element name="Any" type="ISO20022PlusAnyPayload"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="ISO20022PlusAnyPayload">
        <xs:choice>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.004.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.007.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:camt.029.001.03" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:camt.056.001.01" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:acmt.022.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRA" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRB" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRT" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03FKO" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRG" processContents="strict"/>
        </xs:choice>
    </xs:complexType>
    <xs:complexType name="ISO20022PlusSgntr">
        <xs:sequence>
            <xs:any namespace="http://www.w3.org/2000/09/xmldsig#" processContents="strict"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="ISODateTime">
        <xs:restriction base="xs:dateTime"/>
    </xs:simpleType>
    <xs:complexType name="ManifestDetails1">
        <xs:sequence>
            <xs:element name="DocTp" type="Max35Text"/>
            <xs:element name="NbOfDocs" type="Number"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="Max140Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="140"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Max256Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="256"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Max35Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="35"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Number">
        <xs:restriction base="xs:decimal">
            <xs:totalDigits value="18"/>
            <xs:fractionDigits value="0"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:complexType name="PayloadDescription1">
        <xs:sequence>
            <xs:element name="PyldDtls" type="PayloadDetails1"/>
            <xs:element maxOccurs="1" minOccurs="0" name="ApplSpcfcInf" type="ApplicationSpecifics1"/>
            <xs:element name="PyldTpDtls" type="PayloadTypeDetails1"/>
            <xs:element maxOccurs="unbounded" minOccurs="0" name="MnfstDtls" type="ManifestDetails1"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="PayloadDetails1">
        <xs:sequence>
            <xs:element name="PyldIdr" type="Max35Text"/>
            <xs:element name="CreDtAndTm" type="ISODateTime"/>
            <xs:element maxOccurs="1" minOccurs="0" name="PssblDplctFlg" type="TrueFalseIndicator"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="PayloadTypeDetails1">
        <xs:sequence>
            <xs:element name="Tp" type="Max256Text"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="TrueFalseIndicator">
        <xs:restriction base="xs:boolean"/>
    </xs:simpleType>
</xs:schema>
</code>```

答:
This error is telling you that you need to use a JAXB binding file to modify the collection name to be associated with each of the xs:any lines from their default value of "Any".

I found some documentation on the Oracle site at https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html

I also found this related stackoverflow answer that should be useful (it has an example of a complete binding file with a jaxb:property element defined): https://stackoverflow.com/a/4394185/265237

Once you have written a binding file you'll need to pass it to XJC alongside your XSD, the commandline version of this would be:

```<code>xjc schema.xsd -b bindings.xjb
</code>```

Title: Generating JAXB Classes from XSD Issue

Body:
I have a bunch of XSD files and I added them to my project to generate classes from them using JAXB. I am using JDeveloper 11, JDK 1.6 and JAXB 2.0. An XSD file imports other XSD files so I'm generating the content model of the main file, however, I keep getting this error An error was encountered while migrating JAXB. Property "Any" is already defined. Use <jaxb:property> to resolve this conflict.

The rest of the file may contain types of the same name.

I also tried commenting out all the xs:any elements inside the choice and leaving only one, also commenting out their corresponding imports, and was able to generate the jaxb classes. But if I add one more, then I get the error.

I tried the same thing using JDeveloper 12c and using Eclipse but the same thing happened.

What could be the issue here, I also tried looking up the issue, but did not find anything that could work for me.

Below is the main XSD file

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

<xs:schema xmlns="urn:iso:std:iso:20022:tech:xsd:head.002.001.01" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:iso:std:iso:20022:tech:xsd:head.002.001.01">
    <xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03" schemaLocation="pacs.002.001.03.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.02" schemaLocation="pacs.003.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.004.001.02" schemaLocation="pacs.004.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.007.001.02" schemaLocation="pacs.007.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02" schemaLocation="pacs.008.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:camt.029.001.03" schemaLocation="camt.029.001.03.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:camt.056.001.01" schemaLocation="camt.056.001.01.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:acmt.022.001.02" schemaLocation="acmt.022.001.02.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRA" schemaLocation="pacs.002.001.03CRA.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRB" schemaLocation="pacs.002.001.03CRB.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRT" schemaLocation="pacs.002.001.03CRT.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03FKO" schemaLocation="pacs.002.001.03FKO.xsd"/>
    <xs:import namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRG" schemaLocation="pacs.002.001.03CRG.xsd"/>
    <xs:element name="Xchg" type="BusinessFileHeaderV01"/>
    <xs:complexType name="ApplicationSpecifics1">
        <xs:sequence>
            <xs:element maxOccurs="1" minOccurs="0" name="SysUsr" type="Max140Text"/>
            <xs:element maxOccurs="1" minOccurs="0" name="Sgntr" type="ISO20022PlusSgntr"/>
            <xs:element name="TtlNbOfDocs" type="Number"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="BusinessFileHeaderV01">
        <xs:sequence>
            <xs:element name="PyldDesc" type="PayloadDescription1"/>
            <xs:element maxOccurs="unbounded" minOccurs="0" name="Pyld" type="ExchangePayload1"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="ExchangePayload1">
        <xs:sequence>
            <xs:element name="Any" type="ISO20022PlusAnyPayload"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="ISO20022PlusAnyPayload">
        <xs:choice>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.004.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.007.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.008.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:camt.029.001.03" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:camt.056.001.01" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:acmt.022.001.02" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRA" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRB" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRT" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03FKO" processContents="strict"/>
            <xs:any namespace="urn:iso:std:iso:20022:tech:xsd:pacs.002.001.03CRG" processContents="strict"/>
        </xs:choice>
    </xs:complexType>
    <xs:complexType name="ISO20022PlusSgntr">
        <xs:sequence>
            <xs:any namespace="http://www.w3.org/2000/09/xmldsig#" processContents="strict"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="ISODateTime">
        <xs:restriction base="xs:dateTime"/>
    </xs:simpleType>
    <xs:complexType name="ManifestDetails1">
        <xs:sequence>
            <xs:element name="DocTp" type="Max35Text"/>
            <xs:element name="NbOfDocs" type="Number"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="Max140Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="140"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Max256Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="256"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Max35Text">
        <xs:restriction base="xs:string">
            <xs:minLength value="1"/>
            <xs:maxLength value="35"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Number">
        <xs:restriction base="xs:decimal">
            <xs:totalDigits value="18"/>
            <xs:fractionDigits value="0"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:complexType name="PayloadDescription1">
        <xs:sequence>
            <xs:element name="PyldDtls" type="PayloadDetails1"/>
            <xs:element maxOccurs="1" minOccurs="0" name="ApplSpcfcInf" type="ApplicationSpecifics1"/>
            <xs:element name="PyldTpDtls" type="PayloadTypeDetails1"/>
            <xs:element maxOccurs="unbounded" minOccurs="0" name="MnfstDtls" type="ManifestDetails1"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="PayloadDetails1">
        <xs:sequence>
            <xs:element name="PyldIdr" type="Max35Text"/>
            <xs:element name="CreDtAndTm" type="ISODateTime"/>
            <xs:element maxOccurs="1" minOccurs="0" name="PssblDplctFlg" type="TrueFalseIndicator"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="PayloadTypeDetails1">
        <xs:sequence>
            <xs:element name="Tp" type="Max256Text"/>
        </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="TrueFalseIndicator">
        <xs:restriction base="xs:boolean"/>
    </xs:simpleType>
</xs:schema>

Body:
This error is telling you that you need to use a JAXB binding file to modify the collection name to be associated with each of the xs:any lines from their default value of "Any".

I found some documentation on the Oracle site at https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html

I also found this related stackoverflow answer that should be useful (it has an example of a complete binding file with a jaxb:property element defined): https://stackoverflow.com/a/4394185/265237

Once you have written a binding file you'll need to pass it to XJC alongside your XSD, the commandline version of this would be:

xjc schema.xsd -b bindings.xjb


问:
Query document string
I am trying to unwrap the contents of an html document string. I'm being given back a full html document from the froala rich text editor, that includes a head, title, and body tag which I want to remove.

The problem is that any selector I try gives me back an array that has a HTMLTitleElement, and then an array item for each root element in the document contents.

So, for example:

```<code>$('<!DOCTYPE html><html><head><title></title></head><body><h2>Summary</h2><div>Some content here</div></body></html>');
</code>```

gives me back an array that has 3 elements: HTMLTitleElement, HTMLHeadingElement, HTMLDivElement.

I was hoping for a single HTMLBodyElement, or something that I could call .html() on, in order to get the content entered into the editor without all the other html document wrappers.

答:
For my specific situation, I found this produced what I was looking for:</p>

```<code>$('body', $('#editor-container iframe').contents()).html()
</code>```

Title: Query document string

Body:
I am trying to unwrap the contents of an html document string. I'm being given back a full html document from the froala rich text editor, that includes a head, title, and body tag which I want to remove.

The problem is that any selector I try gives me back an array that has a HTMLTitleElement, and then an array item for each root element in the document contents.

So, for example:

$('<!DOCTYPE html><title></title>
Summary

Some content here
');

gives me back an array that has 3 elements: HTMLTitleElement, HTMLHeadingElement, HTMLDivElement.

I was hoping for a single HTMLBodyElement, or something that I could call .html() on, in order to get the content entered into the editor without all the other html document wrappers.

Body:
For my specific situation, I found this produced what I was looking for:

$('body', $('#editor-container iframe').contents()).html()


问:
Virtual vs Physical memory leak
I am just having hard time understanding the difference between virutal memory vs physical memory leak from debugging .net application perspective.

Can anyone elaborate this concept with example how can we have only one type of leak and not other one.

TIA

答:
Virtual memory comprises ranges of a process's address-space that have been marked as available for its use. When you leak memory, virtual memory is almost always involved, since that is the only concept that most programs deal with.

Physical memory is usually consumed only when a program accesses virtual memory, for which the OS must provide physical memory to match. This rarely leaks independently of virtual memory, since it is under the control of the OS.

OTOH, a program can exercise more control over the allocation of physical memory by forcing certain virtual memory pages to remain mapped to physical memory (the mechanisms for this vary between OSes). In such cases, it is possible for a buggy program to leak physical memory.

A softer form of physical memory leak is when a program keeps touching pages of virtual memory that it doesn't logically need to access. This will keep such pages hot and stymie the operating systems efforts to keep the working set (the set of physically mapped pages) small.

Title: Virtual vs Physical memory leak


问:
Enums in Javascript with ES6
I'm rebuilding an old Java project in Javascript, and realized that there's no good way to do enums in JS.

The best I can come up with is:

```<code>const Colors = {
    RED: Symbol("red"),
    BLUE: Symbol("blue"),
    GREEN: Symbol("green")
};
Object.freeze(Colors);
</code>```

The const keeps Colors from being reassigned, and freezing it prevents mutating the keys and values. I'm using Symbols so that Colors.RED is not equal to 0, or anything else besides itself.

Is there a problem with this formulation? Is there a better way?

(I know this question is a bit of a repeat, but all the previous Q/As are quite old, and ES6 gives us some new capabilities.)

EDIT:

Another solution, which deals with the serialization problem, but I believe still has realm issues:

```<code>const enumValue = (name) => Object.freeze({toString: () => name});

const Colors = Object.freeze({
    RED: enumValue("Colors.RED"),
    BLUE: enumValue("Colors.BLUE"),
    GREEN: enumValue("Colors.GREEN")
});
</code>```

By using object references as the values, you get the same collision-avoidance as Symbols.

答:
Is there a problem with this formulation?

I don't see any.

Is there a better way?

I'd collapse the two statements into one:

```<code>const Colors = Object.freeze({
    RED:   Symbol("red"),
    BLUE:  Symbol("blue"),
    GREEN: Symbol("green")
});
</code>```

If you don't like the boilerplate, like the repeated Symbol calls, you can of course also write a helper function makeEnum that creates the same thing from a list of names.

ContentLicense: CC BY-SA 4.0

Title: Enums in Javascript with ES6

Body:
I'm rebuilding an old Java project in Javascript, and realized that there's no good way to do enums in JS.

The best I can come up with is:

const Colors = {
    RED: Symbol("red"),
    BLUE: Symbol("blue"),
    GREEN: Symbol("green")
};
Object.freeze(Colors);

The const keeps Colors from being reassigned, and freezing it prevents mutating the keys and values. I'm using Symbols so that Colors.RED is not equal to 0, or anything else besides itself.

Is there a problem with this formulation? Is there a better way?

(I know this question is a bit of a repeat, but all the previous Q/As are quite old, and ES6 gives us some new capabilities.)

EDIT:

Another solution, which deals with the serialization problem, but I believe still has realm issues:

const enumValue = (name) => Object.freeze({toString: () => name});

const Colors = Object.freeze({
    RED: enumValue("Colors.RED"),
    BLUE: enumValue("Colors.BLUE"),
    GREEN: enumValue("Colors.GREEN")
});

By using object references as the values, you get the same collision-avoidance as Symbols.

Body:
Is there a problem with this formulation?

I don't see any.

Is there a better way?

I'd collapse the two statements into one:

const Colors = Object.freeze({
    RED:   Symbol("red"),
    BLUE:  Symbol("blue"),
    GREEN: Symbol("green")
});

If you don't like the boilerplate, like the repeated Symbol calls, you can of course also write a helper function makeEnum that creates the same thing from a list of names.


问:
Reading data from one-to-many relationship SQL table into my model
I have below two classes which represent my SQL tables (generated by ADO.net entity data model):

```<code>public partial class Parent
{
    public Parent()
    {
        this.Students = new HashSet<Student>();
    }

    public int Parent_Id { get; set; }
    public string Parent1_Last_Name { get; set; }
    public string Parent1_First_Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

public partial class Student
{
        public int Student_Id { get; set; }
        public string Student_Last_Name { get; set; }
        public string Student_First_Name { get; set; }
        public int Parent_Id { get; set; }
        public virtual Parent Parent { get; set; }
}
</code>```

Now I am trying to read the data from my tables in a method as below:

```<code>var parent = new Parent();
var students = new List<Student>();

using (var dc = new SchoolDataEntities())
{
    students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
    parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
    parent.Students = students;
}
</code>```

I am getting a run-time "Invalid Cast" exception error when I reading from Parent table (Students table is working fine).

Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'

Someone please educate me what I was doing wrong?

答:
This part is your problem:

```<code>parent = (Parent)dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
</code>```

The output of "Where" is a collection of Parent rather than just a single parent.

You can use "Single" or "First" rather than "Where" in this case.

Body:
I have below two classes which represent my SQL tables (generated by ADO.net entity data model):

public partial class Parent
{
    public Parent()
    {
        this.Students = new HashSet<Student>();
    }

    public int Parent_Id { get; set; }
    public string Parent1_Last_Name { get; set; }
    public string Parent1_First_Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

public partial class Student
{
        public int Student_Id { get; set; }
        public string Student_Last_Name { get; set; }
        public string Student_First_Name { get; set; }
        public int Parent_Id { get; set; }
        public virtual Parent Parent { get; set; }
}

Now I am trying to read the data from my tables in a method as below:

var parent = new Parent();
var students = new List<Student>();

using (var dc = new SchoolDataEntities())
{
    students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
    parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
    parent.Students = students;
}

I am getting a run-time "Invalid Cast" exception error when I reading from Parent table (Students table is working fine).

Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'

Someone please educate me what I was doing wrong?

Body:
This part is your problem:

parent = (Parent)dc.Parents.Where(p => p.Parent_Id.Equals(parentId));

The output of "Where" is a collection of Parent rather than just a single parent.

You can use "Single" or "First" rather than "Where" in this case.


问:
I want to make the text below the CSS shape be on top
I already tried z-index. I think it has something to do with the pseudo classes, but I don't know what it is, exactly... I'm a newbie so I can only do HTML and CSS for now, I don't know any JS. Thank you! :)

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div class="h1bcg:before h1bcg:after ">
         <h1 class="text-center h1bcg"> Lorem              ipsum dolor sit amet. </h1>
      </div></code>```

答:
I think u are looking for the below result.

For that I've added a neganitve z-index to both psuedo classes (.h1bcg:after and .h1bcg:before).

Hope it helps.

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
  z-index:-1;
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
  z-index:-1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="h1bcg:before h1bcg:after ">
  <h1 class="text-center h1bcg"> Lorem ipsum dolor sit amet.</h1>
</div></code>```

Body:
I already tried z-index. I think it has something to do with the pseudo classes, but I don't know what it is, exactly... I'm a newbie so I can only do HTML and CSS for now, I don't know any JS. Thank you! :)

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

 Lorem              ipsum dolor sit amet.

Body:
I think u are looking for the below result.

For that I've added a neganitve z-index to both psuedo classes (.h1bcg:after and .h1bcg:before).

Hope it helps.

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
  z-index:-1;
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
  z-index:-1;
}

<div class="h1bcg:before h1bcg:after ">
  <h1 class="text-center h1bcg"> Lorem ipsum dolor sit amet.</h1>
</div>


问:
[object Object]undefined on input form (jquery+json+php)
can someone help me displaying that JSON array

{"contenusModeleCarte"{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte0":"pommes au four
  "},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte1":"salade de
  fruits"},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte2":"bananes"}]}

into form inputs.

When I try to do it via this code

```<code>$.each(dataModeleCarte.contenusModeleCarte, function(i,contenusModeleCarte){
  if(contenusModeleCarte.dessertCarte+i == null){
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val('');
  }else{
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val(contenusModeleCarte.dessertCarte);
  }
});
</code>```

I only get as a result :

[object Object]undefined

any help would be greatly appreciated.

Thx

答:
Is that the entire JSON string?  If it is, one issue is you are missing the first colon and square bracket.  It should read:

{"contenusModeleCarte":[{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte0":"pommes au four
  "},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte1":"salade de
  fruits"},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte2":"bananes"}]}

Body:
can someone help me displaying that JSON array

{"contenusModeleCarte"{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte0":"pommes au four
  "},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte1":"salade de
  fruits"},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte2":"bananes"}]}

into form inputs.

When I try to do it via this code

$.each(dataModeleCarte.contenusModeleCarte, function(i,contenusModeleCarte){
  if(contenusModeleCarte.dessertCarte+i == null){
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val('');
  }else{
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val(contenusModeleCarte.dessertCarte);
  }
});

I only get as a result :

[object Object]undefined

any help would be greatly appreciated.

Thx


问:
How to make C# Switch Statement use IgnoreCase
If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?

I have for instance:

```<code>string s = "house";
switch (s)
{
  case "houSe": s = "window";
}
</code>```

Will s get the value "window"? How do I override the switch-case statement so it will compare the strings using ignoreCase?

答:
Sorry for this new post to an old question, but there is a new option for solving this problem using C# 7 (VS 2017).

C# 7 now offers "pattern matching", and it can be used to address this issue thusly:

```<code>string houseName = "house";  // value to be tested, ignoring case
string windowName;   // switch block will set value here

switch (true)
{
    case bool b when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase):
        windowName = "MyWindow";
        break;
    case bool b when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase):
        windowName = "YourWindow";
        break;
    case bool b when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase):
        windowName = "Window";
        break;
    default:
        windowName = null;
        break;
}
</code>```

This solution also deals with the issue mentioned in the answer by @Jeffrey L Whitledge that case-insensitive comparison of strings is not the same as comparing two lower-cased strings.

By the way, there was an interesting article in February 2017 in Visual Studio Magazine describing pattern matching and how it can be used in case blocks.  Please have a look: Pattern Matching in C# 7.0 Case Blocks

EDIT

In light of @LewisM's answer, it's important to point out that the switch statement has some new, interesting behavior.  That is that if your case statement contains a variable declaration, then the value specified in the switch part is copied into the variable declared in the case.  In the following example, the value true is copied into the local variable b.  Further to that, the variable b is unused, and exists only so that the when clause to the case statement can exist:

```<code>switch(true)
{
    case bool b when houseName.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";):
        break;
}
</code>```

As @LewisM points out, this can be used to benefit - that benefit being that the thing being compared is actually in the switch statement, as it is with the classical use of the switch statement. Also, the temporary values declared in the case statement can prevent unwanted or inadvertent changes to the original value:

```<code>switch(houseName)
{
    case string hn when hn.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";
        break;
}
</code>```

Body:
If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?

I have for instance:

string s = "house";
switch (s)
{
  case "houSe": s = "window";
}

Will s get the value "window"? How do I override the switch-case statement so it will compare the strings using ignoreCase?

Body:
Sorry for this new post to an old question, but there is a new option for solving this problem using C# 7 (VS 2017).

C# 7 now offers "pattern matching", and it can be used to address this issue thusly:

string houseName = "house";  // value to be tested, ignoring case
string windowName;   // switch block will set value here

switch (true)
{
    case bool b when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase):
        windowName = "MyWindow";
        break;
    case bool b when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase):
        windowName = "YourWindow";
        break;
    case bool b when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase):
        windowName = "Window";
        break;
    default:
        windowName = null;
        break;
}

This solution also deals with the issue mentioned in the answer by @Jeffrey L Whitledge that case-insensitive comparison of strings is not the same as comparing two lower-cased strings.

By the way, there was an interesting article in February 2017 in Visual Studio Magazine describing pattern matching and how it can be used in case blocks.  Please have a look: Pattern Matching in C# 7.0 Case Blocks

EDIT

In light of @LewisM's answer, it's important to point out that the switch statement has some new, interesting behavior.  That is that if your case statement contains a variable declaration, then the value specified in the switch part is copied into the variable declared in the case.  In the following example, the value true is copied into the local variable b.  Further to that, the variable b is unused, and exists only so that the when clause to the case statement can exist:

switch(true)
{
    case bool b when houseName.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";):
        break;
}

As @LewisM points out, this can be used to benefit - that benefit being that the thing being compared is actually in the switch statement, as it is with the classical use of the switch statement. Also, the temporary values declared in the case statement can prevent unwanted or inadvertent changes to the original value:

switch(houseName)
{
    case string hn when hn.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";
        break;
}


问:
How to join nested values into one column with tidyjson?
I want to join two values in one column instead of spreading

```<code>'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
spread_values(
first.name = jstring("name", "first"),
age = jnumber("age")
) %>%
unite(conc, c("first.name", "age"), sep=" ")
</code>```

But I keep having the following error

All select() inputs must resolve to integer column positions.
  The following do not:
  c("first.name", "age")

My desire output is to have one new column "conc" replacing both first.name and age and that concatenate every string value. such as "jones 32"

Which is weird because if I remove the last line it gives me a proper data.frame and I can access first.name and age.

Any hint?

答:
Though tbl_json objects inherit from tbl_df, they sometimes do not play nicely once you are done parsing and begin to do further manipulation in tidyjson and dplyr.  The reason is that you have additional methods and attributes tagging along that are not really necessary anymore.

As a result, once finished parsing, it is a good habit to use tbl_df or as_data_frame to strip off the tbl_json component of the object.  I prefer tbl_df because it is shorter.

I am using the development version from github: devtools::install_github('jeremystan/tidyjson')

I could not reproduce the error that you mention, but this seems to work:

```<code>library(tidyjson)
library(tidyr)

"{\"name\": {\"first\": \"bob\", \"last\": \"jones\"}, \"age\": 32}" %>%
spread_values(first.name = jstring("name","first")
  , age = jnumber("age")
) %>%
tbl_df() %>%
unite(conc, c("first.name", "age"), sep = " ")

#> # A tibble: 1 x 2
#>   document.id   conc
#> *       <int>  <chr>
#> 1           1 bob 32
</code>```

Other food for thought when concatenating strings is to use paste() or paste0() within mutate.  mutate is supported by tidyjson, as well, so it can be used in the pipeline while parsing JSON.  paste(.,collapse=',') can be really helpful when aggregating multiple rows with summarize, too.

Body:
I want to join two values in one column instead of spreading

'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
spread_values(
first.name = jstring("name", "first"),
age = jnumber("age")
) %>%
unite(conc, c("first.name", "age"), sep=" ")

But I keep having the following error

All select() inputs must resolve to integer column positions.
  The following do not:
  c("first.name", "age")

My desire output is to have one new column "conc" replacing both first.name and age and that concatenate every string value. such as "jones 32"

Which is weird because if I remove the last line it gives me a proper data.frame and I can access first.name and age.

Any hint?

Body:
Though tbl_json objects inherit from tbl_df, they sometimes do not play nicely once you are done parsing and begin to do further manipulation in tidyjson and dplyr.  The reason is that you have additional methods and attributes tagging along that are not really necessary anymore.

As a result, once finished parsing, it is a good habit to use tbl_df or as_data_frame to strip off the tbl_json component of the object.  I prefer tbl_df because it is shorter.

I am using the development version from github: devtools::install_github('jeremystan/tidyjson')

I could not reproduce the error that you mention, but this seems to work:

library(tidyjson)
library(tidyr)

"{\"name\": {\"first\": \"bob\", \"last\": \"jones\"}, \"age\": 32}" %>%
spread_values(first.name = jstring("name","first")
  , age = jnumber("age")
) %>%
tbl_df() %>%
unite(conc, c("first.name", "age"), sep = " ")

#> # A tibble: 1 x 2
#>   document.id   conc
#> *       <int>  <chr>
#> 1           1 bob 32

Other food for thought when concatenating strings is to use paste() or paste0() within mutate.  mutate is supported by tidyjson, as well, so it can be used in the pipeline while parsing JSON.  paste(.,collapse=',') can be really helpful when aggregating multiple rows with summarize, too.


问:
Pandorable way to reference a column of a filtered dataframe
I have a Dataframe that looks like this:

```<code>>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129
</code>```

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

```<code>df[df['Source'] == 'USB']['Log']
</code>```

Is there a better way to do this?

答:
One way would be

```<code>df.Log[df['Source'] == 'USB']
</code>```

It will return

```<code>0           file.txt
2    spreadsheet.xls
</code>```

Body:
I have a Dataframe that looks like this:

>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

df[df['Source'] == 'USB']['Log']

Is there a better way to do this?

Body:
One way would be

df.Log[df['Source'] == 'USB']

It will return

0           file.txt
2    spreadsheet.xls