问:
Attaching an entity of type.. failed because
I am experiencing strange behavior with my Edit action on one of my controllers.

Here is my code:

```<code>public ActionResult Edit([Bind(Include = "ID,FirstName,LastName,Email,deleted,AId")] Information personInformation)
{

    // to stop multiple calls to database
    var lstOfPeople = db.Information.Where(x => x.deleted == false).ToList();

    if (ModelState.IsValid)
    {

        if (lstOfPeople.Any(x => x.Email.Equals(personInformation.Email, StringComparison.CurrentCultureIgnoreCase) && x.ID != personInformation.ID))
        {
            ModelState.AddModelError("", "This email already exists!");
            return View(personInformation);
        }

        db.Entry(personInformation).State = EntityState.Modified; // error here
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(personInformation);
}
</code>```

Now I have pretty much the exact same code in a different controller edit action and it works fine.  Here that is:

```<code>public ActionResult Edit([Bind(Include = "ID,RNumber,DateCreated,PersonWhoCreated,deleted")] OtherTable oTable)
{
    if (ModelState.IsValid)
    {
        if (db.OtherTable.Any(x => x.RNumber.Equals(oTable.RNumber, StringComparison.CurrentCultureIgnoreCase) && x.ID != oTable.ID))
        {
            ModelState.AddModelError("RNumber", "This number already exists!");
            return View(oTable);
        }

        db.Entry(oTable).State = EntityState.Modified; // no error here.. goes through fine.
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(oTable);
}
</code>```

Error I am receiving:

Attaching an entity of type 'ProjectName.Models.Information' failed because another entity of the same type already has the same primary key value.  This can happen when using 'Attach'.. etc.

Any idea on why this is happening?

答:
The db.Entry(personInformation).State attachs the personInformation object to the EF context, the error raises because the EF data context has previously loaded a diferent Information instance with the same id (perhaps in the previous Where() you are doing).

There are at least two basic options:

first one is to use the AsNoTracking() extension for your queries, (as in db.Information.AsNoTracking()) this extension tells EF data context to not keep the entities retrieved from database in memory so you can attach your personInformation entity directly to the context and set the modified state.

second option is retrieve the entity from the ef data context and modify that entity (not the personInformation instance). You can retrieve the entity with db.Information.FindAsync and the EF context will retrieve from memory if it is previously attached.

```    var attachedEntity = db.Information.FindAsync(personInformation.ID);
    attachedEntity.ExampleValue = personInformation.ExampleValue;
    attachedEntity.ExampleValue2 = personInformation.ExampleValue2;
    ...
    and so on```

Body:
I am experiencing strange behavior with my Edit action on one of my controllers.

Here is my code:

public ActionResult Edit([Bind(Include = "ID,FirstName,LastName,Email,deleted,AId")] Information personInformation)
{

    // to stop multiple calls to database
    var lstOfPeople = db.Information.Where(x => x.deleted == false).ToList();

    if (ModelState.IsValid)
    {

        if (lstOfPeople.Any(x => x.Email.Equals(personInformation.Email, StringComparison.CurrentCultureIgnoreCase) && x.ID != personInformation.ID))
        {
            ModelState.AddModelError("", "This email already exists!");
            return View(personInformation);
        }

        db.Entry(personInformation).State = EntityState.Modified; // error here
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(personInformation);
}

Now I have pretty much the exact same code in a different controller edit action and it works fine.  Here that is:

public ActionResult Edit([Bind(Include = "ID,RNumber,DateCreated,PersonWhoCreated,deleted")] OtherTable oTable)
{
    if (ModelState.IsValid)
    {
        if (db.OtherTable.Any(x => x.RNumber.Equals(oTable.RNumber, StringComparison.CurrentCultureIgnoreCase) && x.ID != oTable.ID))
        {
            ModelState.AddModelError("RNumber", "This number already exists!");
            return View(oTable);
        }

        db.Entry(oTable).State = EntityState.Modified; // no error here.. goes through fine.
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(oTable);
}

Error I am receiving:

Attaching an entity of type 'ProjectName.Models.Information' failed because another entity of the same type already has the same primary key value.  This can happen when using 'Attach'.. etc.

Any idea on why this is happening?

Body:
The db.Entry(personInformation).State attachs the personInformation object to the EF context, the error raises because the EF data context has previously loaded a diferent Information instance with the same id (perhaps in the previous Where() you are doing).

There are at least two basic options:

first one is to use the AsNoTracking() extension for your queries, (as in db.Information.AsNoTracking()) this extension tells EF data context to not keep the entities retrieved from database in memory so you can attach your personInformation entity directly to the context and set the modified state.

second option is retrieve the entity from the ef data context and modify that entity (not the personInformation instance). You can retrieve the entity with db.Information.FindAsync and the EF context will retrieve from memory if it is previously attached.

    var attachedEntity = db.Information.FindAsync(personInformation.ID);
    attachedEntity.ExampleValue = personInformation.ExampleValue;
    attachedEntity.ExampleValue2 = personInformation.ExampleValue2;
    ...
    and so on


来源: stackexchange

问:
RegEx Expression for Eclipse that searches for all items that have not been dealt with
To help stop SQL Injection attacks, I am going through about 2000 parameter requests in my code to validate them. I validate them by determining what type of value (e.g. integer, double) they should return and then applying a function to them to sanitize the value.

Any requests I have dealt with look like this

```<code>*SecurityIssues.*(request.getParameter
</code>```

where * signifies any number of characters on the same line.

What RegExp expression can I use in the Eclipse search (CTRL+H) which will help me search for all the ones I have not yet dealt with, i.e. all the times that the text request.getParameter appears when it is not preceded by the word SecurityIssues?

Examples for matches

The regular expression should match each of the following e.g.

```<code>int companyNo = StringFunctions.StringToInt(request.getParameter("COMPANY_NO"))
double percentage = StringFunctions.StringToDouble(request.getParameter("MARKETSHARE"))
int c = request.getParameter("DUMMY")
</code>```

But should not match:

```<code>int companyNo = SecurityIssues.StringToIntCompany(request.getParameter("COMPANY_NO"))
</code>```

答:
Try e.g.

```<code>=\s*?((?!SecurityIssues).)*?(request\.getParameter)\(
</code>```

Notes

Paranthesis ( or ) are special characters for group matching. They need to be escaped with \.
If .* will match anything, also characters that you don't want it to match. So .*? will prevent it from matching anything (reluctant). This can be helpful if after the wildcard other items need to match.

There is a tutorial at https://docs.oracle.com/javase/tutorial/essential/regex/index.html , I think all of these should be available in eclipse. You can then deal with generic replacement also.

Problem

From reading Regular expression that doesn't contain certain string and Regular expression to match a line that doesn't contain a word? it seems quite difficult to create a regex matching anything but not to contain a certain word.

ContentLicense: CC BY-SA 3.0

Body:
To help stop SQL Injection attacks, I am going through about 2000 parameter requests in my code to validate them. I validate them by determining what type of value (e.g. integer, double) they should return and then applying a function to them to sanitize the value.

Any requests I have dealt with look like this

*SecurityIssues.*(request.getParameter

where * signifies any number of characters on the same line.

What RegExp expression can I use in the Eclipse search (CTRL+H) which will help me search for all the ones I have not yet dealt with, i.e. all the times that the text request.getParameter appears when it is not preceded by the word SecurityIssues?

Examples for matches

The regular expression should match each of the following e.g.

int companyNo = StringFunctions.StringToInt(request.getParameter("COMPANY_NO"))
double percentage = StringFunctions.StringToDouble(request.getParameter("MARKETSHARE"))
int c = request.getParameter("DUMMY")

But should not match:

int companyNo = SecurityIssues.StringToIntCompany(request.getParameter("COMPANY_NO"))

Body:
Try e.g.

=\s*?((?!SecurityIssues).)*?(request\.getParameter)\(

Notes

Paranthesis ( or ) are special characters for group matching. They need to be escaped with \.
If .* will match anything, also characters that you don't want it to match. So .*? will prevent it from matching anything (reluctant). This can be helpful if after the wildcard other items need to match.

There is a tutorial at https://docs.oracle.com/javase/tutorial/essential/regex/index.html , I think all of these should be available in eclipse. You can then deal with generic replacement also.

Problem

From reading Regular expression that doesn't contain certain string and Regular expression to match a line that doesn't contain a word? it seems quite difficult to create a regex matching anything but not to contain a certain word.


问:
Select multiple HTML table rows with Ctrl+click and Shift+click
Demo

I want to select multiple rows using Windows Shift and Ctrl keys, like multiple folder selection in Windows.

From table of selected rows I have to get the first column (student id) and pass to server side C# and delete those records from database.

I have written a code in javascript but the classname is not being applied to
 on Shift or Ctrl+ left click.

HTML

```<code><table id="tableStudent" border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Class</th>
        </tr>
    </thead>
    <tbody>
        <tr onmousedown="RowClick(this,false);">
            <td>1</td>
            <td>John</td>
            <td>4th</td>
        </tr>
         <tr onmousedown="RowClick(this,false);">
            <td>2</td>
            <td>Jack</td>
            <td>5th</td>
        </tr>
         <tr onmousedown="RowClick(this,false);">
            <td>3</td>
            <td>Michel</td>
            <td>6th</td>
        </tr>
        <tr onmousedown="RowClick(this,false);">
            <td>4</td>
            <td>Mike</td>
            <td>7th</td>
        </tr>
        <tr onmousedown="RowClick(this,false);">
            <td>5</td>
            <td>Yke</td>
            <td>8th</td>
        </tr>
         <tr onmousedown="RowClick(this,false);">
            <td>6</td>
            <td>4ke</td>
            <td>9th</td>
        </tr>
        <tr onmousedown="RowClick(this,false);">
            <td>7</td>
            <td>7ke</td>
            <td>10th</td>
        </tr>
    </tbody>
</table>
</code>```

JavaScript

```<code>var selectedrow;
function RowClick(currenttr, lock) {
var trs =tableStudent.tBodies[0].getElementsByTagName("tr");
var cnt;
    if(window.event.button==2)
    {
        if(currenttr.className=='selected')
        return false;
    }
alert(trs.length);
if (((window.event.shiftKey) && (window.event.ctrlKey) ) ||(window.event.shiftKey))
    {
        for(var j=0; j<trs.length; j++)
        {
            if (trs[j].className!='normallock')
            {
                trs[j].className='normal';
            }
        }
        var mark=false;

        if (typeof(selectedrow)=="undefined")
        {
            selectedrow=currenttr;
            selectedrow.className='selected'
            return false;
        }
        for(var j=0; j<trs.length; j++)
        {

            if ((trs[j].id ==selectedrow.id) || (trs[j].id ==currenttr.id) )
            {
                if (trs[j].className!='normallock')
                {
                trs[j].className='selected'
                mark = !(mark);
                }
            }
            else
            {
                if(mark==true)
                {
                    if (trs[j].className!='normallock')
                    trs[j].className='selected'
                }
            }
        }
    }
    else if(window.event.ctrlKey)
    {
        //if ctrl key is seelcted while selecting the patients
        // select the patient with currently clicked row plus
        // maintain the previous seelcted status
        cnt=0;
        for(var j=0; j<trs.length; j++)
        {
            if(trs[j].id == currenttr.id)
            {
                if(trs[j].className=='selected')
                {
                    trs[j].className='normal';
                }else
                {
                    trs[j].className='selected';
                }
            }
            if(trs[j].className=='selected')
            {
                cnt++;
            }
        }

        if(cnt==0)
        {
            selectedrow=undefined;
            return false;
        }
    }
    else
    {
        for(var j=0; j<trs.length; j++)
        {
            if(trs[j].id == currenttr.id)
            {
                trs[j].className='selected'
            }
            else
            {
                if (trs[j].className!='normallock')
                trs[j].className='normal';
            }

        }
    }
    selectedrow=currenttr;
}
</code>```

答:
Check this example:

JSFiddle: Highlight list with shift and ctrl

Part of the code:

```<code>switch(e.type) {
    case "keydown" :
        console.log('k_down');
        keysPressed.push(e.keyCode);
        break;
    case "keyup" :
        console.log('k_up');
        var idx = keysPressed.indexOf(e.keyCode);
        if (idx >= 0)
            keysPressed.splice(idx, 1);
        break;
}
</code>```

Sources could be found here:
Source files github

Body:
Demo

I want to select multiple rows using Windows Shift and Ctrl keys, like multiple folder selection in Windows.

From table of selected rows I have to get the first column (student id) and pass to server side C# and delete those records from database.

I have written a code in javascript but the classname is not being applied to
 on Shift or Ctrl+ left click.

HTML

            ID
            Name
            Class

            1
            John
            4th

            2
            Jack
            5th

            3
            Michel
            6th

            4
            Mike
            7th

            5
            Yke
            8th

            6
            4ke
            9th

            7
            7ke
            10th

JavaScript

var selectedrow;
function RowClick(currenttr, lock) {
var trs =tableStudent.tBodies[0].getElementsByTagName("tr");
var cnt;
    if(window.event.button==2)
    {
        if(currenttr.className=='selected')
        return false;
    }
alert(trs.length);
if (((window.event.shiftKey) && (window.event.ctrlKey) ) ||(window.event.shiftKey))
    {
        for(var j=0; j<trs.length; j++)
        {
            if (trs[j].className!='normallock')
            {
                trs[j].className='normal';
            }
        }
        var mark=false;

        if (typeof(selectedrow)=="undefined")
        {
            selectedrow=currenttr;
            selectedrow.className='selected'
            return false;
        }
        for(var j=0; j<trs.length; j++)
        {

            if ((trs[j].id ==selectedrow.id) || (trs[j].id ==currenttr.id) )
            {
                if (trs[j].className!='normallock')
                {
                trs[j].className='selected'
                mark = !(mark);
                }
            }
            else
            {
                if(mark==true)
                {
                    if (trs[j].className!='normallock')
                    trs[j].className='selected'
                }
            }
        }
    }
    else if(window.event.ctrlKey)
    {
        //if ctrl key is seelcted while selecting the patients
        // select the patient with currently clicked row plus
        // maintain the previous seelcted status
        cnt=0;
        for(var j=0; j<trs.length; j++)
        {
            if(trs[j].id == currenttr.id)
            {
                if(trs[j].className=='selected')
                {
                    trs[j].className='normal';
                }else
                {
                    trs[j].className='selected';
                }
            }
            if(trs[j].className=='selected')
            {
                cnt++;
            }
        }

        if(cnt==0)
        {
            selectedrow=undefined;
            return false;
        }
    }
    else
    {
        for(var j=0; j<trs.length; j++)
        {
            if(trs[j].id == currenttr.id)
            {
                trs[j].className='selected'
            }
            else
            {
                if (trs[j].className!='normallock')
                trs[j].className='normal';
            }

        }
    }
    selectedrow=currenttr;
}

Body:
Check this example:

JSFiddle: Highlight list with shift and ctrl

Part of the code:

switch(e.type) {
    case "keydown" :
        console.log('k_down');
        keysPressed.push(e.keyCode);
        break;
    case "keyup" :
        console.log('k_up');
        var idx = keysPressed.indexOf(e.keyCode);
        if (idx >= 0)
            keysPressed.splice(idx, 1);
        break;
}

Sources could be found here:
Source files github


问:
Convert jquery Script into Prototype Scriptaculous?
Hi I hAVE my code here in jquery for my footer chat panel And it is conflict with Scriptaculous. I want it to convert into pure js or Using Prototype Scriptaculous.
Any Help?
Thank you!

$(document).ready(function(){

```<code>$.fn.adjustPanel = function(){
    $(this).find("ul, .subpanel").css({ 'height' : 'auto'});

    var windowHeight = $(window).height(); //Get the height of the browser viewport
    var panelsub = $(this).find(".subpanel").height(); //Get the height of subpanel
    var panelAdjust = windowHeight - 100; //Viewport height - 100px (Sets max height of subpanel)
    var ulAdjust =  panelAdjust - 25; //Calculate ul size after adjusting sub-panel (27px is the height of the base panel)

    if ( panelsub >= panelAdjust ) {     //If subpanel is taller than max height...
        $(this).find(".subpanel").css({ 'height' : panelAdjust }); //Adjust subpanel to max height
        $(this).find("ul").css({ 'height' : ulAdjust}); //Adjust subpanel ul to new size
    }
    else if ( panelsub < panelAdjust ) { //If subpanel is smaller than max height...
        $(this).find("ul").css({ 'height' : 'auto'}); //Set subpanel ul to auto (default size)
    }
};
//Execute function on load
$("#chatpanel").adjustPanel(); //Run the adjustPanel function on #chatpanel
$("#alertpanel").adjustPanel(); //Run the adjustPanel function on #alertpanel

//Each time the viewport is adjusted/resized, execute the function
$(window).resize(function () {
    $("#chatpanel").adjustPanel();
    $("#alertpanel").adjustPanel();
});

    //Click event on Chat Panel + Alert Panel
$("#chatpanel a:first, #alertpanel a:first,#alertpanel2 a:first,#likes a:first,#twiter a:first").click(function() { //If clicked on the first link of #chatpanel and #alertpanel...
    if($(this).next(".subpanel").is(':visible')){ //If subpanel is already active...
        $(this).next(".subpanel").hide(); //Hide active subpanel
        $("#footpanel li a").removeClass('active'); //Remove active class on the subpanel trigger
    }
    else { //if subpanel is not active...
        $(".subpanel").hide(); //Hide all subpanels
        $(this).next(".subpanel").toggle(); //Toggle the subpanel to make active
        $("#footpanel li a").removeClass('active'); //Remove active class on all subpanel trigger
        $(this).toggleClass('active'); //Toggle the active class on the subpanel trigger
    }
    return false; //Prevent browser jump to link anchor
});

//Click event outside of subpanel
$(document).click(function() { //Click anywhere and...
    $(".subpanel").hide(); //hide subpanel
    $("#footpanel li a").removeClass('active'); //remove active class on subpanel trigger
});
$('.subpanel ul').click(function(e) {
    e.stopPropagation(); //Prevents the subpanel ul from closing on click
});
</code>```

答: You can use jQuery with other libraries.</p>

ContentLicense: CC BY-SA 2.5

Body:
Hi I hAVE my code here in jquery for my footer chat panel And it is conflict with Scriptaculous. I want it to convert into pure js or Using Prototype Scriptaculous.
Any Help?
Thank you!

$(document).ready(function(){

$.fn.adjustPanel = function(){
    $(this).find("ul, .subpanel").css({ 'height' : 'auto'});

    var windowHeight = $(window).height(); //Get the height of the browser viewport
    var panelsub = $(this).find(".subpanel").height(); //Get the height of subpanel
    var panelAdjust = windowHeight - 100; //Viewport height - 100px (Sets max height of subpanel)
    var ulAdjust =  panelAdjust - 25; //Calculate ul size after adjusting sub-panel (27px is the height of the base panel)

    if ( panelsub >= panelAdjust ) {     //If subpanel is taller than max height...
        $(this).find(".subpanel").css({ 'height' : panelAdjust }); //Adjust subpanel to max height
        $(this).find("ul").css({ 'height' : ulAdjust}); //Adjust subpanel ul to new size
    }
    else if ( panelsub < panelAdjust ) { //If subpanel is smaller than max height...
        $(this).find("ul").css({ 'height' : 'auto'}); //Set subpanel ul to auto (default size)
    }
};
//Execute function on load
$("#chatpanel").adjustPanel(); //Run the adjustPanel function on #chatpanel
$("#alertpanel").adjustPanel(); //Run the adjustPanel function on #alertpanel

//Each time the viewport is adjusted/resized, execute the function
$(window).resize(function () {
    $("#chatpanel").adjustPanel();
    $("#alertpanel").adjustPanel();
});

    //Click event on Chat Panel + Alert Panel
$("#chatpanel a:first, #alertpanel a:first,#alertpanel2 a:first,#likes a:first,#twiter a:first").click(function() { //If clicked on the first link of #chatpanel and #alertpanel...
    if($(this).next(".subpanel").is(':visible')){ //If subpanel is already active...
        $(this).next(".subpanel").hide(); //Hide active subpanel
        $("#footpanel li a").removeClass('active'); //Remove active class on the subpanel trigger
    }
    else { //if subpanel is not active...
        $(".subpanel").hide(); //Hide all subpanels
        $(this).next(".subpanel").toggle(); //Toggle the subpanel to make active
        $("#footpanel li a").removeClass('active'); //Remove active class on all subpanel trigger
        $(this).toggleClass('active'); //Toggle the active class on the subpanel trigger
    }
    return false; //Prevent browser jump to link anchor
});

//Click event outside of subpanel
$(document).click(function() { //Click anywhere and...
    $(".subpanel").hide(); //hide subpanel
    $("#footpanel li a").removeClass('active'); //remove active class on subpanel trigger
});
$('.subpanel ul').click(function(e) {
    e.stopPropagation(); //Prevents the subpanel ul from closing on click
});


问:
Xamarin.ios run a WCF Service function using await
I've followed the following example which works well.

https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/walkthrough_working_with_WCF/

The only issue is, the example uses button clicks to load data. Now i have two separate calls different functions, and i need one to wait for the other, for example:

So when i call function2 for example, i want to wait for function1 first.

```<code>_client.function1Async();
_client.function2Async();
</code>```

I could put the function2 call inside the function1Completed handler, but i was looking to use async wait with it. When i use async task, i get an error saying cannot await a void. But the web service async function in the example is a void

If i had 6 calls that i wanted to run, it would become very messy.

```<code>void _client_function1Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

void _client_function2Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}
</code>```

Hope this makes sense.

答:
Not sure if I understood well what you are trying to achieve, but I guess you can try something like this:

Given some lengthy (and blocking) methods:

```<code>public void func1()
{
    Console.WriteLine("func1");
    System.Threading.Thread.Sleep(5000);
}

public void func2()
{
    Console.WriteLine("func2");
    System.Threading.Thread.Sleep(5000);
}
</code>```

You could add the ability to run the lengthy stuff asynchronously by doing this:

```<code>public async Task function1Async()
{
   await Task.Run(() => {
      func1();
   });
}

public async Task function1Async()
{
   await Task.Run(() => {
      func2();
   });
}
</code>```

Now you can choose to run 'func1' and 'func2' either asynchronously or synchronously, for example:

```<code>function1Async().Wait();    // will block
function2Async();           // will run asynchronously
</code>```

So, for your particular case, given that you already have the two async methods, I guess that all you need to do is to call them as shown above.

Body:
I've followed the following example which works well.

https://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/walkthrough_working_with_WCF/

The only issue is, the example uses button clicks to load data. Now i have two separate calls different functions, and i need one to wait for the other, for example:

So when i call function2 for example, i want to wait for function1 first.

_client.function1Async();
_client.function2Async();

I could put the function2 call inside the function1Completed handler, but i was looking to use async wait with it. When i use async task, i get an error saying cannot await a void. But the web service async function in the example is a void

If i had 6 calls that i wanted to run, it would become very messy.

void _client_function1Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

void _client_function2Completed(object sender,UpdateOrdersByWardCompletedEventArgs e
{
}

Hope this makes sense.

Body:
Not sure if I understood well what you are trying to achieve, but I guess you can try something like this:

Given some lengthy (and blocking) methods:

public void func1()
{
    Console.WriteLine("func1");
    System.Threading.Thread.Sleep(5000);
}

public void func2()
{
    Console.WriteLine("func2");
    System.Threading.Thread.Sleep(5000);
}

You could add the ability to run the lengthy stuff asynchronously by doing this:

public async Task function1Async()
{
   await Task.Run(() => {
      func1();
   });
}

public async Task function1Async()
{
   await Task.Run(() => {
      func2();
   });
}

Now you can choose to run 'func1' and 'func2' either asynchronously or synchronously, for example:

function1Async().Wait();    // will block
function2Async();           // will run asynchronously

So, for your particular case, given that you already have the two async methods, I guess that all you need to do is to call them as shown above.


问:
Write to fonts (OTF & TTF) Property details with PHP
I am trying to write specific details into the Properties > Details of .otf and .ttf files.

The idea behind this is to be able to insert specific license key information in the font file on download. This way when a font gets shared, we can view the license key.

I know this is easier with phyton, but ideally, we would like to do this with PHP, if at all possible.

答:
Did you tried https://github.com/PhenX/php-font-lib?

By the way, this operation is risky, because if you use a font parser / exporter library that is not complete you could loose some informations from the original font. So you need to check if the library you're using is supporting the features
included in the font.

That's why Python libraries, like FontTools are recommended.


问:
Django - no such column: blog_comment.body error
I am following a tutorial as I am fairly new to Django, and I am trying to add a comments system to my blog. However, whenever I try and use it I get an error message saying the following:no such column: blog_comment.body. I am not sure what is going on, as in my model I have body = models.TextField(), and I am just generally very confused.

答:
This is because you have not run migrations in order to apply the body column to the database.

Just run ./manage.py makemigrations and ./manage.py migrate

Django will ask you to enter a default value since you have declared the body field as not nullable.

If you don't want to enter a default value, write it like this:

```<code>body = models.TextField(blank=True, null=True)
</code>```

and then run the same commads.

Body:
This is because you have not run migrations in order to apply the body column to the database.

Just run ./manage.py makemigrations and ./manage.py migrate

Django will ask you to enter a default value since you have declared the body field as not nullable.

If you don't want to enter a default value, write it like this:

body = models.TextField(blank=True, null=True)

and then run the same commads.


问:
Object-oriented programming (python)
```<code>class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
</code>```

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

```<code>import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)
</code>```

答:
It depends on what do you want to print.

```<code>bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
</code>```

The name of object:

```<code>bow = Weapon('bow', 10, 20)
#               \_______ name of object
</code>```

so you have to:

```<code>print(arrows.weapon_type().name)
# it will print bow
</code>```

or your object itself:

```<code>bow = Weapon('bow', 10, 20)
#  \____________________ object
</code>```

I personally prefer print the name I passed in arguments, so if I call  my object bow and pass "hardened_bow", 10, 20 as arguments it will print "hardened_bow" and not "bow"

Title: Object-oriented programming (python)

Body:
class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)

Body:
It depends on what do you want to print.

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())

The name of object:

bow = Weapon('bow', 10, 20)
#               \_______ name of object

so you have to:

print(arrows.weapon_type().name)
# it will print bow

or your object itself:

bow = Weapon('bow', 10, 20)
#  \____________________ object

I personally prefer print the name I passed in arguments, so if I call  my object bow and pass "hardened_bow", 10, 20 as arguments it will print "hardened_bow" and not "bow"


问:
Creating Wordpress Page That Changes Content Based On Geolocation
We are looking to create a series of landing pages that would be dedicated to different cities or states in the US.

I know that certain APIs are able to use geolocation to cater items such as maps or services in your area. Would there be a way to populate cities and/or states based on a persons location onto a wordpress page?

答:
Use HTML5 geolocation.
Create WordPress pages as per City OR State and you can change front page on the basis of geolocation of person using the website. </p>


问:
How to add new nodes / neurons dynamically in tensorflow
If I want to add new nodes to on of my tensorflow layers on the fly, how can I do that?

For example if I want to change the amount of hidden nodes from 10 to 11 after the model has been training for a while. Also, assume I know what value I want the weights coming in and out of this node/neuron to be.

I can create a whole new graph, but is there a different/better way?

答:
TensorFlow has many advantadges, but dynamic graph modification isn't one of them.

If you truly want to be able to change graphs on the fly, I recommend you PyTorch (http://pytorch.org/). Although it's much more recent than TensorFlow, so the documentation isn't as complete.


问:
google maps API Auto open infoWindow
Code works perfectly. The issue I am seeing is that the maps Markers dont Auto-Open when first loaded.

Here is my code.
My first several attempts was using the "infoWindow.open(map,marker);" in both the For statement and proceeding the conclusion of the for statement.

I also have a codepen with current code. https://codepen.io/designsbycamaron/pen/evPWbL

```<code>jQuery(function($) {
    // Asynchronously Load the map API
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyCHlDHe3KZYAMqQIQoklenAKqi6jE2lxPA&callback=initMap";
    document.body.appendChild(script);
});
function initMap() {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
             mapTypeControl: false,
      draggable: false,
      scaleControl: false,
      scrollwheel: false,
      navigationControl: false,
      streetViewControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("main_map"), mapOptions);

        //Create and open InfoWindow.
        var infoWindow = new google.maps.InfoWindow();

        for (var i = 0; i < markers.length; i++) {
            var data = markers[i];
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });

            //Attach click event to the marker.
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");

                });

            })(marker, data);

        }
        infoWindow.open(map,marker);
    }
</code>```

答:
You need an infoWindow for each marker. Store them in an array. Open them all at the start. There is also an event listener that opens the correct one when clicked and closes the other. Not sure what you wanted to do on maker click...

Link to forked codepen here

```<code>var markers = [{"title": "City A","lat": "44.6299425","lng": "-123.0813560","description": "lore lipsum epsum ipsum", "deptID":"29","provID":"119"},{"title": "City B","lat": "44.5671365","lng": "-123.2745664","description": "lore lipsum epsum ipsum", "deptID":"28","provID":"120"}];
jQuery(function($) {
  // Asynchronously Load the map API
  var script = document.createElement('script');
  script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyCHlDHe3KZYAMqQIQoklenAKqi6jE2lxPA&callback=initMap";
  document.body.appendChild(script);
});

var markersList = [];

function initMap() {

  var mapOptions = {
    center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
    zoom: 10,
    mapTypeControl: false,
    draggable: false,
    scaleControl: false,
    scrollwheel: false,
    navigationControl: false,
    streetViewControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("main_map"), mapOptions);

  for (var i = 0; i < markers.length; i++) {

    var data = markers[i];

    var myLatlng = new google.maps.LatLng(data.lat, data.lng);

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: data.title
    });

    var infowindow = new google.maps.InfoWindow({
      content: "<div style = 'width:200px;min-height:40px'>" + markers[i].description + "</div>"
    });

    marker.infobox = infowindow;

    markersList.push(marker);

    //Attach click event to the marker.
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {

        console.log(i);

        // Close all other infoboxes
        for (var j = 0; j < markersList.length; j++) {
          markersList[j].infobox.close(map);
        }

        // Open correct info box
        markersList[i].infobox.open(map, markersList[i]);
      }
    })(marker, i));
  }

  // Open all on page load
  for (var j = 0; j < markersList.length; j++) {
    markersList[j].infobox.open(map, markersList[j]);
  }
}
</code>```

Title: google maps API Auto open infoWindow

Body:
Code works perfectly. The issue I am seeing is that the maps Markers dont Auto-Open when first loaded.

Here is my code.
My first several attempts was using the "infoWindow.open(map,marker);" in both the For statement and proceeding the conclusion of the for statement.

I also have a codepen with current code. https://codepen.io/designsbycamaron/pen/evPWbL

jQuery(function($) {
    // Asynchronously Load the map API
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyCHlDHe3KZYAMqQIQoklenAKqi6jE2lxPA&callback=initMap";
    document.body.appendChild(script);
});
function initMap() {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
             mapTypeControl: false,
      draggable: false,
      scaleControl: false,
      scrollwheel: false,
      navigationControl: false,
      streetViewControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("main_map"), mapOptions);

        //Create and open InfoWindow.
        var infoWindow = new google.maps.InfoWindow();

        for (var i = 0; i < markers.length; i++) {
            var data = markers[i];
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });

            //Attach click event to the marker.
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    infoWindow.setContent("
" + data.description + "
");

                });

            })(marker, data);

        }
        infoWindow.open(map,marker);
    }

Body:
You need an infoWindow for each marker. Store them in an array. Open them all at the start. There is also an event listener that opens the correct one when clicked and closes the other. Not sure what you wanted to do on maker click...

Link to forked codepen here

var markers = [{"title": "City A","lat": "44.6299425","lng": "-123.0813560","description": "lore lipsum epsum ipsum", "deptID":"29","provID":"119"},{"title": "City B","lat": "44.5671365","lng": "-123.2745664","description": "lore lipsum epsum ipsum", "deptID":"28","provID":"120"}];
jQuery(function($) {
  // Asynchronously Load the map API
  var script = document.createElement('script');
  script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyCHlDHe3KZYAMqQIQoklenAKqi6jE2lxPA&callback=initMap";
  document.body.appendChild(script);
});

var markersList = [];

function initMap() {

  var mapOptions = {
    center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
    zoom: 10,
    mapTypeControl: false,
    draggable: false,
    scaleControl: false,
    scrollwheel: false,
    navigationControl: false,
    streetViewControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("main_map"), mapOptions);

  for (var i = 0; i < markers.length; i++) {

    var data = markers[i];

    var myLatlng = new google.maps.LatLng(data.lat, data.lng);

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: data.title
    });

    var infowindow = new google.maps.InfoWindow({
      content: "<div style = 'width:200px;min-height:40px'>" + markers[i].description + "</div>"
    });

    marker.infobox = infowindow;

    markersList.push(marker);

    //Attach click event to the marker.
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {

        console.log(i);

        // Close all other infoboxes
        for (var j = 0; j < markersList.length; j++) {
          markersList[j].infobox.close(map);
        }

        // Open correct info box
        markersList[i].infobox.open(map, markersList[i]);
      }
    })(marker, i));
  }

  // Open all on page load
  for (var j = 0; j < markersList.length; j++) {
    markersList[j].infobox.open(map, markersList[j]);
  }
}


问:
CWinApp CFrameWindow not shown
i'm trying to create window using CFrameWindow, i used code from "Simulation for applied graph theory using Visual C++" but it didn't had entry point, so it doesn't work any way. So i simplified it as much as i could and now when application is launched in release mode window doesn't appear and in debug mode it throws error that assertion failed. I used MSVS Visual C++ -> General -> Empty project with "Use of MFC" set to Use MFC in a Shared DLL.

Here is the code :

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

class MyWnd : public CFrameWnd
{
public:
    MyWnd()  { Create(0, "MyWnd"); }
    ~MyWnd() { }
};

class MyApp : public CWinApp
{
public:
    virtual BOOL InitInstance()
    {
        m_pMainWnd = new MyWnd;
        m_pMainWnd->ShowWindow(m_nCmdShow);
        return TRUE;
    }
};

int CALLBACK WinMain (_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    MyApp myApp;
    myApp.InitInstance();
    myApp.Run();
}
</code>```

EDIT: updated to call MyApp.Run(), but it still doesn't display anything, also checked Subsystem, none was selected, tried Console, Windows, Native, compiled only with Windows but didn't help.

答:
So, it displays blank white window with titlebar when i make myApp global with myApp.Run() or without it.

EDIT: It worked on my laptop win10, but on pc win7 same code didn't work, so on pc in project properties -> character set was Multibyte, after changing it to Unicode, it started showing window on pc also.

Title: CWinApp CFrameWindow not shown

Body:
i'm trying to create window using CFrameWindow, i used code from "Simulation for applied graph theory using Visual C++" but it didn't had entry point, so it doesn't work any way. So i simplified it as much as i could and now when application is launched in release mode window doesn't appear and in debug mode it throws error that assertion failed. I used MSVS Visual C++ -> General -> Empty project with "Use of MFC" set to Use MFC in a Shared DLL.

Here is the code :

#include <afxwin.h>

class MyWnd : public CFrameWnd
{
public:
    MyWnd()  { Create(0, "MyWnd"); }
    ~MyWnd() { }
};

class MyApp : public CWinApp
{
public:
    virtual BOOL InitInstance()
    {
        m_pMainWnd = new MyWnd;
        m_pMainWnd->ShowWindow(m_nCmdShow);
        return TRUE;
    }
};

int CALLBACK WinMain (_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    MyApp myApp;
    myApp.InitInstance();
    myApp.Run();
}

EDIT: updated to call MyApp.Run(), but it still doesn't display anything, also checked Subsystem, none was selected, tried Console, Windows, Native, compiled only with Windows but didn't help.


问:
HTML code into Javascript function
I am modifying this codepen code because I want to populate the UI with Firebase data.

Inside HTML body

```<code><div class="container positions">
<h2>Job Openings</h2>
<ul>
<li class="pos-card" id="pos_1">
</li>
</ul>
</div>
<div class="return">Return to listings   </div>
<div class="container refer-card" id="jobapp">
</div>

  <script>
  var jobTitle = document.getElementById('jobTitle');
  var jobDescription= document.getElementById('jobDescription');

   firebase.auth().onAuthStateChanged((user) => {
  if (user) {
        database = firebase.database();

       var ref = database.ref('/Jobs/');
    ref.on('value', gotData,  errData);

  }
  })

   function gotData(data) {

  var jobs = data.val();
  var keys = Object.keys(jobs);

  var container = document.getElementById('pos_1');

for (var i = 0; i<keys.length; i++) {
var k = keys[i];
var newCard = `

<li class="pos-card" id="pos_1">
      <div class="content">
        <div class="title new">UI/UX Designer</div>
        <div class="dept">Design</div>
        <div class="date">June 4</div>
        <div class="refer">Refer</div>
      </div>
      <ul class="desc">
        <li>6+ years’ experience designing desktop and mobile apps.</li>
        <li>Deep appreciation for simple solutions to complex problems.</li>
        <li>An amazing portfolio demonstrating successful delivery of innovative design solutions.</li>
      </ul>
     </li>
      <div class="return">Return to listings   </div>
  <div class="container refer-card">
  <div class="modal confirmed"><span class="close-modal"></span>
  <h2>Thank you!</h2>
 <p><span id="refer_name" class="focus"></span> has been submitted for the <span id="refer_pos" class="focus"></span> position.</p>
</div>
<div class="sign-up card">
 <div class="card__header">
  <h1>Employee Referral</h1>
  <div class="description">For more information, please consult the   <a href="#">employee handbook</a>.</div>
 </div>
 <div class="card__content">
  <form class="referral" method="post">
    <div class="field line">
      <input class="req" maxlength="240" type="text" name="name" value="" required="required" id="name"/>
      <label class="placeholder" for="name">Full Name</label>
    </div>
    <div class="field line">
      <input class="req" maxlength="240" type="email" name="email" value="" required="required" id="email"/>
      <label class="placeholder" for="email">Email</label>
    </div>
    <div class="field line inline">
      <input class="req" maxlength="240" type="text" name="position" value="" required="required" id="position"/>
      <label class="placeholder" for="position">Position</label>
    </div>
    <div class="field inline right"><span class="dropdown-wrapper">
        <select class="empty" name="department" id="choice">
          <option value="" selected="selected">Department</option>
          <option value="1">Development</option>
          <option value="2">Sales</option>
          <option value="3">QA</option>
          <option value="4">Design</option>
          <option value="5">HR</option>
          <option value="6">Research  </option>
        </select></span></div>
    <div>
      <input type="submit" value="Submit" disabled="disabled"  id="btn"/>
    </div><a class="reset" href="#">Reset </a>
    </form>
   </div>
  </div>
  </div>

`;
container.innerHTML += newCard;

}
}

</script>
</code>```

The modified code produced the image below:

but the when the refer tab is clicked nothing happens as compared to the original code that fades in the "refer card". Please for better clarity check out the codepen link. When the refer tab is clicked on the original code the refer card fades in. I can't get my code to do that and I am using the same CSS and JS file. How can I execute the same behavior in my loop function?

答:
You are dynamically generating those elements so any listener applied on page load wont be available.
Update your click handler to:</p>

```<code>$('.container').on('click', '.refer', function(e){
    //...
}
</code>```

Title: HTML code into Javascript function

Body:
I am modifying this codepen code because I want to populate the UI with Firebase data.

Inside HTML body

Job Openings

Return to listings

The modified code produced the image below:

but the when the refer tab is clicked nothing happens as compared to the original code that fades in the "refer card". Please for better clarity check out the codepen link. When the refer tab is clicked on the original code the refer card fades in. I can't get my code to do that and I am using the same CSS and JS file. How can I execute the same behavior in my loop function?

Body:
You are dynamically generating those elements so any listener applied on page load wont be available.
Update your click handler to:

$('.container').on('click', '.refer', function(e){
    //...
}


问:
computed property in VueJS
I have an array of objects:

```<code>[
  {
    "value": 4,
    "text": "All Belgium Kendo Federation"
  },
  {
    "value": 33,
    "text": "All United States Kendo Federation"
  },
  // more objects of similar key/value
]
</code>```

I want to create a computed property with the id as parameter, so I can get text with value.

So, I try:

```<code>computed: {
        federationSelectedText: function () {

            this.federations.find(function (elt) {
                return elt.value == this.federationSelected;
            });
        }
    },
</code>```

Where this.federationSelect is the value.

And in HTML {{ federationSelectedText }}

I debugged variables, and both this.federations and this.federationSelected have correct value

It doesn't display nothing, what am I doing wrong?

答:
You need return value and bind this for find

```<code>computed: {
        federationSelectedText: function () {

            return this.federations.find(function (elt) {
                return elt.value == this.federationSelected;
            }.bind(this));
        }
    }
</code>```

For get one variable:

```<code>computed: {
            federationSelectedText: function () {

                var value = this.federations.find(function (elt) {
                    return elt.value == this.federationSelected;
                }.bind(this));

                return value ? value.text : '';
            }
        }
</code>```

Title: computed property in VueJS

Body:
I have an array of objects:

[
  {
    "value": 4,
    "text": "All Belgium Kendo Federation"
  },
  {
    "value": 33,
    "text": "All United States Kendo Federation"
  },
  // more objects of similar key/value
]

I want to create a computed property with the id as parameter, so I can get text with value.

So, I try:

computed: {
        federationSelectedText: function () {

            this.federations.find(function (elt) {
                return elt.value == this.federationSelected;
            });
        }
    },

Where this.federationSelect is the value.

And in HTML {{ federationSelectedText }}

I debugged variables, and both this.federations and this.federationSelected have correct value

It doesn't display nothing, what am I doing wrong?

Body:
You need return value and bind this for find

computed: {
        federationSelectedText: function () {

            return this.federations.find(function (elt) {
                return elt.value == this.federationSelected;
            }.bind(this));
        }
    }

For get one variable:

computed: {
            federationSelectedText: function () {

                var value = this.federations.find(function (elt) {
                    return elt.value == this.federationSelected;
                }.bind(this));

                return value ? value.text : '';
            }
        }


问:
How to make 2 dictionary and group it twice
I am calculating totals per month for each country. I have managed to group data by country, but I get error

An item with the same key has already been added.

when trying to put monthly totals into inner dictionary:

```<code>var totalPerMonth = data.AsEnumerable()
       .Select(x => new
       {
           Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"),
           Country = x.ItemArray[1],
           Revenue = x.ItemArray[2]
       })
       .GroupBy(x => x.Country)
       .ToDictionary(x => x.Key, x => x.ToDictionary(p => p.Date,////this is not unique/// p => Convert.ToDouble(p.Revenue)));
</code>```

how to group it to make Date key unique?

答:
You can either use ToLookup instead of ToDictionary to allow several values for same date.

Or you can use grouping to get unique dates only (assume you want to calculate totals for each month, so use Sum of revenue for each date group dg ):

```<code>var totalPerMonth = data.AsEnumerable()
    .Select(x => new {
       Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"),
       Country = x.ItemArray[1],
       Revenue = Convert.ToDouble(x.ItemArray[2]) // convert here
     })
    .GroupBy(x => x.Country)
    .ToDictionary(
       g => g.Key,
       g => g.GroupBy(x => x.Date).ToDictionary(dg => dg.Key, dg => dg.Sum(x => x.Revenue))
    );
</code>```

Body:
I am calculating totals per month for each country. I have managed to group data by country, but I get error

An item with the same key has already been added.

when trying to put monthly totals into inner dictionary:

var totalPerMonth = data.AsEnumerable()
       .Select(x => new
       {
           Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"),
           Country = x.ItemArray[1],
           Revenue = x.ItemArray[2]
       })
       .GroupBy(x => x.Country)
       .ToDictionary(x => x.Key, x => x.ToDictionary(p => p.Date,////this is not unique/// p => Convert.ToDouble(p.Revenue)));

how to group it to make Date key unique?

Body:
You can either use ToLookup instead of ToDictionary to allow several values for same date.

Or you can use grouping to get unique dates only (assume you want to calculate totals for each month, so use Sum of revenue for each date group dg ):

var totalPerMonth = data.AsEnumerable()
    .Select(x => new {
       Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"),
       Country = x.ItemArray[1],
       Revenue = Convert.ToDouble(x.ItemArray[2]) // convert here
     })
    .GroupBy(x => x.Country)
    .ToDictionary(
       g => g.Key,
       g => g.GroupBy(x => x.Date).ToDictionary(dg => dg.Key, dg => dg.Sum(x => x.Revenue))
    );


问:
JQuery Ajax Done with required textarea
everyone. I have a (set of) form(s) with a textarea inside. This textarea has property required. It works as expected. If the user tries to submit the form without filling the textarea, the browser hightlights it and notify the user.

My problem is that I intercepted form submitting with JQuery AJAX, so I can notify the user without reloading the page. The code is the following:

```<code>$(function () {
$('form').each(function (id, el) {
    $(el).submit(function (event) {
        event.preventDefault();
        var _data = $(el).serialize();
        alert(_data);
        $.ajax({
                type: 'POST',
                url: $(el).attr('action'),
                data: _data
        })
        .done(function(response) {
            $("#notify-modal").find('.modal-body').removeClass('alert-danger');
            $("#notify-modal").find('.modal-body').addClass('alert-success');
            $("#notify-modal").find('.modal-body').text('Já recebemos sua história! Obrigado por compartilhá-la conosco!');
            $("#notify-modal").modal('show');
            $(el).find('textarea').val('');
        })
        .fail(function(data) {
            $("#notify-modal").find('.modal-body').removeClass('alert-success');
            $("#notify-modal").find('.modal-body').addClass('alert-danger');
            $("#notify-modal").find('.modal-body').text("Erro ao enviar história! Contate os administradores do site! " + data.responseText);
            $("#notify-modal").modal('show');
        });
    });
});
</code>```

});

When the user submits a valid information, the AJAX function works as expected posting to my PHP script and displaying the modal that informs the user. But note that in .done() function there's a statement that clears the textarea after the data is submited ($(el).find('textarea').val('');). My issue is that when I clear the textarea it gets highlighted, even if the data was properly submitted, as if had been cleared before submiting. How can I prevent this behaviour?

答:
That is because it is required, regardless of whether or not the user has submitted anything. Check out this answer for how to proceed. Another option though would be to set the value of the text area to a space ' ' instead of nothing ''.

Image of error provided by Mateus Felipe

The second form hasn't been interacted with, which is why it is not showing an error. It will flag as an error only if a value was there, and then removed. If a value was never there, then it would only flag if the user tried to submit the form through a form submit button or input where the default event was not prevented.

Title: JQuery Ajax Done with required textarea

Body:
everyone. I have a (set of) form(s) with a textarea inside. This textarea has property required. It works as expected. If the user tries to submit the form without filling the textarea, the browser hightlights it and notify the user.

My problem is that I intercepted form submitting with JQuery AJAX, so I can notify the user without reloading the page. The code is the following:

$(function () {
$('form').each(function (id, el) {
    $(el).submit(function (event) {
        event.preventDefault();
        var _data = $(el).serialize();
        alert(_data);
        $.ajax({
                type: 'POST',
                url: $(el).attr('action'),
                data: _data
        })
        .done(function(response) {
            $("#notify-modal").find('.modal-body').removeClass('alert-danger');
            $("#notify-modal").find('.modal-body').addClass('alert-success');
            $("#notify-modal").find('.modal-body').text('Já recebemos sua história! Obrigado por compartilhá-la conosco!');
            $("#notify-modal").modal('show');
            $(el).find('textarea').val('');
        })
        .fail(function(data) {
            $("#notify-modal").find('.modal-body').removeClass('alert-success');
            $("#notify-modal").find('.modal-body').addClass('alert-danger');
            $("#notify-modal").find('.modal-body').text("Erro ao enviar história! Contate os administradores do site! " + data.responseText);
            $("#notify-modal").modal('show');
        });
    });
});

});

When the user submits a valid information, the AJAX function works as expected posting to my PHP script and displaying the modal that informs the user. But note that in .done() function there's a statement that clears the textarea after the data is submited ($(el).find('textarea').val('');). My issue is that when I clear the textarea it gets highlighted, even if the data was properly submitted, as if had been cleared before submiting. How can I prevent this behaviour?


问:
NSOperationQueue is not being cancelled
I am using PageViewController where I may have more than one image as a content. I am getting image as follows from the Service. However, when user clicks to dismiss the viewcontroller while network operation still going on, app crashes.

```<code>queue = [[NSOperationQueue alloc] init];
operation = [NSBlockOperation blockOperationWithBlock:^{
            [self addAllImages];
                dispatch_sync(dispatch_get_main_queue(), ^(void) {
                     [self pageViewcontrollerSetup];
            });
        }];
     [queue addOperation:operation];
}

- (void) addAllImages
{
    self.pageImages =[[NSMutableArray alloc] initWithCapacity:self.pageControl.numberOfPages];

    for(id key in [[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"]) {
        NSString *productURL = [NSString stringWithFormat:@"%@%@", PRODUCT_URL, [[[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"] objectForKey:key]];
        NSData* productData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productURL]];

        if ([UIImage imageWithData:productData]) {
                [self.pageImages addObject:[UIImage imageWithData:productData]];
        }
    }
}

- (void)closeBtnClicked {

    [queue cancelAllOperations];
}
</code>```

NOTE : I was using GCD (Grand Central Dispatch) for multi-threading, but I came to know that you cannot cancel it, therefore I swicthed to NSOperationQueue

答: Canceling an operation does not magically halt your code dead in its tracks. It is up to your code in the operation to check periodically to see whether the operation has been cancelled, and to bow out if so.

Title: NSOperationQueue is not being cancelled

Body:
I am using PageViewController where I may have more than one image as a content. I am getting image as follows from the Service. However, when user clicks to dismiss the viewcontroller while network operation still going on, app crashes.

queue = [[NSOperationQueue alloc] init];
operation = [NSBlockOperation blockOperationWithBlock:^{
            [self addAllImages];
                dispatch_sync(dispatch_get_main_queue(), ^(void) {
                     [self pageViewcontrollerSetup];
            });
        }];
     [queue addOperation:operation];
}

- (void) addAllImages
{
    self.pageImages =[[NSMutableArray alloc] initWithCapacity:self.pageControl.numberOfPages];

    for(id key in [[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"]) {
        NSString *productURL = [NSString stringWithFormat:@"%@%@", PRODUCT_URL, [[[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"] objectForKey:key]];
        NSData* productData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productURL]];

        if ([UIImage imageWithData:productData]) {
                [self.pageImages addObject:[UIImage imageWithData:productData]];
        }
    }
}

- (void)closeBtnClicked {

    [queue cancelAllOperations];
}

NOTE : I was using GCD (Grand Central Dispatch) for multi-threading, but I came to know that you cannot cancel it, therefore I swicthed to NSOperationQueue


问:
Math operations from a list
I imported myList from a .txt file (I converted the numbers to integers)

```<code>from math import *
myList = [100, 'sin', 0, 1]
x = pi
</code>```

How would I go about calling the sin function for my given value of x?

```<code>myList[1](pi)
</code>```

I hoped this would simply return sin(pi), but it does not, because it is just the string 'sin(x)'

答:
Do not store functions as string literals, store the actual functions.

```<code>>>> from math import sin, exp, log
>>> funcs = [sin, exp, log]
>>> x = 0
>>> funcs[0](x)
0.0
>>> funcs[1](x)
1.0
>>> funcs[2](2.71)
0.9969486348916096
</code>```

However, if you don't plan to do something more involved with that list of functions, you can just call them directly.

Title: Math operations from a list

Body:
I imported myList from a .txt file (I converted the numbers to integers)

from math import *
myList = [100, 'sin', 0, 1]
x = pi

How would I go about calling the sin function for my given value of x?

myList[1](pi)

I hoped this would simply return sin(pi), but it does not, because it is just the string 'sin(x)'

Body:
Do not store functions as string literals, store the actual functions.

>>> from math import sin, exp, log
>>> funcs = [sin, exp, log]
>>> x = 0
>>> funcs[0](x)
0.0
>>> funcs[1](x)
1.0
>>> funcs[2](2.71)
0.9969486348916096

However, if you don't plan to do something more involved with that list of functions, you can just call them directly.


问:
Zend 2: SQLSRV: $prepareParams is not being set
Can somebody explain me where the

```<code>->setPrepareParams(array $prepareParams)
</code>```

is called in Zend\Db\Adapter\Driver\Sqlsrv\Statement.php?

Specifically, when I used this:

```<code>$this->tableGateway->select(array("Personalnummer = $personalnumber"));
</code>```

It worked.  But when I used this:

```<code>$this->tableGateway->select(array("Personalnummer" => $personalnumber));
</code>```

It did not work.

I tried to debug this and found that the params were not being set with my second method.

答:
Are you looking for this code?

Adapter/Driver/Sqlsrv/Statement::prepare()

Without looking deeper into it, it looks like the way you are calling the select statement, it expects indices that are numbers:  0, 1, 2, 3, ... and so on.

So when you call

```<code>array("Personalnummer = $personalnumber")
</code>```

It is the same as calling

```<code>array(0 => "Personalnummer = $personalnumber")
</code>```

And since code expects a value at index 0, your code works then.  When you use parameterized statements, your code fails. Because it does not expect parameterized arrays (your second way).

Look into how you set your initial parameters.  There may be a configuration option that sets the code to expect parameterized arrays.

Body:
Can somebody explain me where the

->setPrepareParams(array $prepareParams)

is called in Zend\Db\Adapter\Driver\Sqlsrv\Statement.php?

Specifically, when I used this:

$this->tableGateway->select(array("Personalnummer = $personalnumber"));

It worked.  But when I used this:

$this->tableGateway->select(array("Personalnummer" => $personalnumber));

It did not work.

I tried to debug this and found that the params were not being set with my second method.

Body:
Are you looking for this code?

Adapter/Driver/Sqlsrv/Statement::prepare()

Without looking deeper into it, it looks like the way you are calling the select statement, it expects indices that are numbers:  0, 1, 2, 3, ... and so on.

So when you call

array("Personalnummer = $personalnumber")

It is the same as calling

array(0 => "Personalnummer = $personalnumber")

And since code expects a value at index 0, your code works then.  When you use parameterized statements, your code fails. Because it does not expect parameterized arrays (your second way).

Look into how you set your initial parameters.  There may be a configuration option that sets the code to expect parameterized arrays.


问:
How to start a custom binary with options and arguments from a shell script
I somehow can't figure out how to start a self-written programm with arguments from a shell script. If I'm in a folder whose parent folder contains the binary, then I can start the program with

```<code>$ ../binary --opt1 arg1 --opt2 arg2
</code>```

Now, say the arguments and options are listed in a file args in the current folder.

args.txt:

```<code>--opt1 arg1 --opt2 arg2
</code>```

If I'm trying to execute the binary from a shell script in the current folder like:

```<code>$ ./script.sh args.txt
</code>```

script.sh:

```<code>#!/bin/bash

if [ $# != 1 ]
then
    exit 1;
 fi

 params=$(<"$1")

../binary "$params"
# ../binary <<<"$params" doesn't work either.
</code>```

How can I make this work?

Edit (updated script):

```<code>#!/bin/bash

if [ $# != 1 ]
then
    exit 1;
fi

params=$(<"$1")

START=$(date +%s)
../binary "$params"
# ../binary <<<"$params" doesn't work either.
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Test took $DIFF seconds"
</code>```

答:
Use command substituion:

```<code>$ ./script.sh args.txt
</code>```

content of ./script.sh

```<code>#!/bin/bash
../binary $(< "$1")
</code>```

Command Substitution

Command substitution allows the output of a command to replace the command name.  There are two forms:

```<code>          $(command)
   or
          `command`
</code>```

Bash  performs  the  expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.  Embedded newlines are not deleted, but they may be removed during word splitting.  The command substitution  $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \.  The first back‐quote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the  parentheses  make up the command; none are treated specially.

Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

Body:
I somehow can't figure out how to start a self-written programm with arguments from a shell script. If I'm in a folder whose parent folder contains the binary, then I can start the program with

$ ../binary --opt1 arg1 --opt2 arg2

Now, say the arguments and options are listed in a file args in the current folder.

args.txt:

--opt1 arg1 --opt2 arg2

If I'm trying to execute the binary from a shell script in the current folder like:

$ ./script.sh args.txt

script.sh:

#!/bin/bash

if [ $# != 1 ]
then
    exit 1;
 fi

 params=$(<"$1")

../binary "$params"
# ../binary <<<"$params" doesn't work either.

How can I make this work?

Edit (updated script):

#!/bin/bash

if [ $# != 1 ]
then
    exit 1;
fi

params=$(<"$1")

START=$(date +%s)
../binary "$params"
# ../binary <<<"$params" doesn't work either.
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Test took $DIFF seconds"

Body:
Use command substituion:

$ ./script.sh args.txt

content of ./script.sh

#!/bin/bash
../binary $(< "$1")

Command Substitution

Command substitution allows the output of a command to replace the command name.  There are two forms:

          $(command)
   or
          `command`

Bash  performs  the  expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.  Embedded newlines are not deleted, but they may be removed during word splitting.  The command substitution  $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \.  The first back‐quote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the  parentheses  make up the command; none are treated specially.

Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.


问:
git push showing "Everything up-to-date" but compare shows differences
Hello I have this problem I contribute to an opensource repo. Each time I work from the master branch even if what am working on is not for the master branch usually when the code is merged I will pull upstream (The original repo) to get my master branch back to normal. This has caused me problems recently after creating some changes and committed I pulled upstream to get back at the same level with the original repository when I push to my cloned repo it says everything is up to date. But When I do compare on github it shows differences with upstream.
I have tried

git checkout master

pulling upstream again committing and then
pushing again

that did not  work!
I tried checking out commits

```<code> 1. git checkout HEAD~5
 2. git pull upstream master
 3. git add
 4. git commit
 5. git push
</code>```

Did not work still.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch thanks.

答:
I pulled upstream to get back at the same level with the original repository

If you want to replace your cloned/origin repo master with the upstream/master
then one way is to reset your origin/master with upstream/master.

```<code>$ git fetch upstream
$ git checkout master
$ git reset --hard upstream/master      # local/master = upstream/master

$ git push -f origin master             # force push to origin/master
</code>```

Now, there should be no difference between origin/master and upstream/master

Note: force (-f) push will replace your origin/master by your local/master = upstream/master history.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch

You can create and checkout a new branch from upstream/master locally directly.

```<code># no matter in which branch you are now!
$ git fetch upstream
$ git checkout -b quick-fix upstream/master  # chekcout to 'quick-fix' branch with the same history of 'upstream/master'
</code>```

Body:
Hello I have this problem I contribute to an opensource repo. Each time I work from the master branch even if what am working on is not for the master branch usually when the code is merged I will pull upstream (The original repo) to get my master branch back to normal. This has caused me problems recently after creating some changes and committed I pulled upstream to get back at the same level with the original repository when I push to my cloned repo it says everything is up to date. But When I do compare on github it shows differences with upstream.
I have tried

git checkout master

pulling upstream again committing and then
pushing again

that did not  work!
I tried checking out commits

 1. git checkout HEAD~5
 2. git pull upstream master
 3. git add
 4. git commit
 5. git push

Did not work still.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch thanks.

Body:
I pulled upstream to get back at the same level with the original repository

If you want to replace your cloned/origin repo master with the upstream/master
then one way is to reset your origin/master with upstream/master.

$ git fetch upstream
$ git checkout master
$ git reset --hard upstream/master      # local/master = upstream/master

$ git push -f origin master             # force push to origin/master

Now, there should be no difference between origin/master and upstream/master

Note: force (-f) push will replace your origin/master by your local/master = upstream/master history.

I will also like to know a simple way to create a quick-fix branch for every issue and avoid doing everything from my master branch

You can create and checkout a new branch from upstream/master locally directly.

# no matter in which branch you are now!
$ git fetch upstream
$ git checkout -b quick-fix upstream/master  # chekcout to 'quick-fix' branch with the same history of 'upstream/master'


问:
Firebase Database in Unity - Child value into UI text
i just came across the firebase and thats seems to be exactly what I need. At the moment I am trying to implement it in my unity project but first I am just testing a bit to get used to it.

Can someone tell me how I can easily just receive the value of a child in my database and save it in a variable of my unity project? At the end I would like to display the Value in a UI Text. It doesn't need be really dynamic. The easier the better so I can be sure to understand it.

It tried it as follows:

```<code>variableXY.text = FirebaseDatabase.DefaultInstance.GetReference ("Databasename").Child ("Childname").GetValueAsync ().ToString ();
</code>```

The result is, it displays the text : System.Threading.Task.Task1 [Firebase.Database.Datasnapshot]

Only the value is needed.

I would highly appreciate it if someone could help me out

Thanks a lot!

just to show my complete code right now which maybe makes something clearer.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;

public class DBManager: MonoBehaviour {

    public Text MA1Sensor1;
    public Text MA1Sensor2;

    void Start() {

        // Set up the Editor before calling into the realtime database.
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://unityar-6eb13.firebaseio.com/");

        // Get the root reference location of the database.
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        FirebaseDatabase.DefaultInstance
            .GetReference("MA1")
            .ValueChanged += HandleValueChanged;

    }

    void HandleValueChanged(object sender, ValueChangedEventArgs args) {
        if (args.DatabaseError != null) {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }

        Debug.Log (args.Snapshot.GetRawJsonValue());
        MA1Sensor1.text = FirebaseDatabase
            .DefaultInstance
            .GetReference ("MA1")
            .Child ("Zaehler")
            .GetValueAsync ()
            //.Result
            .ToString ();
        Debug.Log (MA1Sensor1.text);

    }

    // Update is called once per frame
    void Update () {

    }
}
</code>```

答:
The Firebase SDK uses Tasks to return values to you asynchronously.
Check out this link on how to retrieve a value.

You can also use Unity's "WaitUntil" if you are inside a Unity coroutine to make it simpler.  Note that you can use DataSnapShot.Value to get a parsed value or GetRawJsonValue() if you wanted to see the underlying Json.  In most simple scenarios, you'd want Value.  You'd use "GetRawJsonValue()" if you were using typed objects and Unity's Json serialization.

```<code>var getTask = FirebaseDatabase
   .DefaultInstance
   .GetReference ("MA1")
   .Child ("Zaehler") .GetValueAsync();

yield return new WaitUntil(() => getTask.IsCompleted || getTask.IsFaulted);

if (getTask.IsCompleted) {
  Debug.Log(getTask.Result.Value.ToString());
}
</code>```

Body:
i just came across the firebase and thats seems to be exactly what I need. At the moment I am trying to implement it in my unity project but first I am just testing a bit to get used to it.

Can someone tell me how I can easily just receive the value of a child in my database and save it in a variable of my unity project? At the end I would like to display the Value in a UI Text. It doesn't need be really dynamic. The easier the better so I can be sure to understand it.

It tried it as follows:

variableXY.text = FirebaseDatabase.DefaultInstance.GetReference ("Databasename").Child ("Childname").GetValueAsync ().ToString ();

The result is, it displays the text : System.Threading.Task.Task1 [Firebase.Database.Datasnapshot]

Only the value is needed.

I would highly appreciate it if someone could help me out

Thanks a lot!

just to show my complete code right now which maybe makes something clearer.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;

public class DBManager: MonoBehaviour {

    public Text MA1Sensor1;
    public Text MA1Sensor2;

    void Start() {

        // Set up the Editor before calling into the realtime database.
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://unityar-6eb13.firebaseio.com/");

        // Get the root reference location of the database.
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        FirebaseDatabase.DefaultInstance
            .GetReference("MA1")
            .ValueChanged += HandleValueChanged;

    }

    void HandleValueChanged(object sender, ValueChangedEventArgs args) {
        if (args.DatabaseError != null) {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }

        Debug.Log (args.Snapshot.GetRawJsonValue());
        MA1Sensor1.text = FirebaseDatabase
            .DefaultInstance
            .GetReference ("MA1")
            .Child ("Zaehler")
            .GetValueAsync ()
            //.Result
            .ToString ();
        Debug.Log (MA1Sensor1.text);

    }

    // Update is called once per frame
    void Update () {

    }
}

Body:
The Firebase SDK uses Tasks to return values to you asynchronously.
Check out this link on how to retrieve a value.

You can also use Unity's "WaitUntil" if you are inside a Unity coroutine to make it simpler.  Note that you can use DataSnapShot.Value to get a parsed value or GetRawJsonValue() if you wanted to see the underlying Json.  In most simple scenarios, you'd want Value.  You'd use "GetRawJsonValue()" if you were using typed objects and Unity's Json serialization.

var getTask = FirebaseDatabase
   .DefaultInstance
   .GetReference ("MA1")
   .Child ("Zaehler") .GetValueAsync();

yield return new WaitUntil(() => getTask.IsCompleted || getTask.IsFaulted);

if (getTask.IsCompleted) {
  Debug.Log(getTask.Result.Value.ToString());
}


问:
Why should I practice Test Driven Development and how should I start?
Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?</p>

答:
There are a lot of benefits:

You get immediate feedback on if your code is working, so you can find bugs faster

By seeing the test go from red to green, you know that you have both a working regression test, and working code

You gain confidence to refactor existing code, which means you can clean up code without worrying what it might break

At the end you have a suite of regression tests that can be run during automated builds to give you greater confidence that your codebase is solid

The best way to start is to just start.  There is a great book by Kent Beck all about Test Driven Development.  Just start with new code, don't worry about old code... whenever you feel you need to refactor some code, write a test for the existing functionality, then refactor it and make sure the tests stay green.  Also, read this great article.


问:
C++ behaviour when const
Here's a basic struct (I hope)

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};
</code>```

And source

```<code>SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
</code>```

The I have a class

```<code>struct SomeClass {
    static const SomeType v;

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

When I then initialise it

```<code>const SomeType SomeClass::v(0,0,0,0);
</code>```

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

答:
Working version:

```<code>#include <iostream>

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);

public:

    void print() const
    {
        std::cout << this->a << std::endl;
        std::cout << this->b << std::endl;
        std::cout << this->c << std::endl;
        std::cout << this->d << std::endl;
    }
};

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

class SomeClass {
    static const SomeType v;

    SomeClass() {}

public:

    static void print()
    {
        v.print();
    }
};

const SomeType SomeClass::v(0.0f,0.0f,0.0f,0.0f);

void main()
{
    SomeClass::print();
}
</code>```

Output will be:
0
0
0
0

Title: C++ behaviour when const

Body:
Here's a basic struct (I hope)

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};

And source

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

The I have a class

struct SomeClass {
    static const SomeType v;

    SomeClass();
};

When I then initialise it

const SomeType SomeClass::v(0,0,0,0);

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

Body:
Working version:

#include <iostream>

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);

public:

    void print() const
    {
        std::cout << this->a << std::endl;
        std::cout << this->b << std::endl;
        std::cout << this->c << std::endl;
        std::cout << this->d << std::endl;
    }
};

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

class SomeClass {
    static const SomeType v;

    SomeClass() {}

public:

    static void print()
    {
        v.print();
    }
};

const SomeType SomeClass::v(0.0f,0.0f,0.0f,0.0f);

void main()
{
    SomeClass::print();
}

Output will be:
0
0
0
0


问:
HTTP Status 500 – Internal Server Error
I am trying to update my DB rows by using primary key.But facing this Exception

Exception

```<code>HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

Controller

```<code>@RequestMapping(value="edit/product/success" ,method=RequestMethod.POST)
public ModelAndView editProduct(@ModelAttribute ("prdt") Product p)
{
ModelAndView model=new ModelAndView("pl");
model.addObject("Update","Updated Successfully");
pd.update(p);
return model;
}
</code>```

Dao Impl

```<code>public void update( Product p) {
Session session=sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
}
</code>```

Jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp"%>
<%@ page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page isELIgnored="false" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#mfg" ).datepicker();
  } );
  </script>
</head>
<body>
<br>

<h2 align="center">PRODUCT FORM</h2><hr>
<div class="col-md-2 "></div>
<div align="center"><div class="container"><div class="col-md-8 ">

<form:form method="POST" action="${pageContext.request.contextPath}/edit/product/success" commandName="prdt" enctype="multipart/form-data" >
<table class="table table-hover">

<tr>
<td> <form:label  path="product_Name"> Enter Product Name</form:label></td>
<td><form:input type="text" path="product_Name" class="form-control" value="${d.product_Name }"/></td>
</tr>
<tr>
<td> <form:label path="descripction"> Enter Product Descripction</form:label></td>
<td><form:input type="text" path="descripction"  class="form-control" value="${d.descripction }"/></td>
</tr>
<tr>
 <td> <form:label  path="price"> Enter Product Price</form:label></td>
<td><form:input type="text" path="price"  class="form-control" value="${d.price }" />
</td></tr>
<tr>
<td> <form:label  path="mfg_Date"> Enter Manufacture Date</form:label></td>
<td><form:input type="text" id="mfg" path="mfg_Date" class="form-control" value ="${d.mfg_Date}"/></td>

</tr>
<tr>
<td> <label> Choose Image</label></td>
<td><form:input type="file" path="image" class="form-control" /></td>
</tr>

</table>
 <input type="submit" class="btn btn-primary btn-block" value="Save Changes" class="form-control"/>

</form:form>

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

please check and let me know my Mistake..i have looked in it.but not found any irregularity.

Note:

Data retrieve works fine.facing trouble in Update only

答:
Try using this approach :

```<code>Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(p);
session.flush();
session.close();
tx.commit();
</code>```

This error usually caused when the hibernate can't find all the rows it needs to update. Meaning that when you try to update some objects that were pulled from the DB they don't really exist anymore (or never existed in the first place).

It might be because another thread is deleting them or that the DB's isolation mode is set to read_uncommited and so rows that were created by another transaction failed to save (due to a transaction failure) and don't exist anymore.

Title: HTTP Status 500 – Internal Server Error

Body:
I am trying to update my DB rows by using primary key.But facing this Exception

Exception

HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Controller

@RequestMapping(value="edit/product/success" ,method=RequestMethod.POST)
public ModelAndView editProduct(@ModelAttribute ("prdt") Product p)
{
ModelAndView model=new ModelAndView("pl");
model.addObject("Update","Updated Successfully");
pd.update(p);
return model;
}

Dao Impl

public void update( Product p) {
Session session=sessionFactory.openSession();
session.update(p);
session.flush();
session.close();
}

Jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp"%>
<%@ page isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page isELIgnored="false" %>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

PRODUCT FORM

<form:form method="POST" action="${pageContext.request.contextPath}/edit/product/success" commandName="prdt" enctype="multipart/form-data" >

 <form:label  path="product_Name"> Enter Product Name</form:label>
<form:input type="text" path="product_Name" class="form-control" value="${d.product_Name }"/>

 <form:label path="descripction"> Enter Product Descripction</form:label>
<form:input type="text" path="descripction"  class="form-control" value="${d.descripction }"/>

  <form:label  path="price"> Enter Product Price</form:label>
<form:input type="text" path="price"  class="form-control" value="${d.price }" />

 <form:label  path="mfg_Date"> Enter Manufacture Date</form:label>
<form:input type="text" id="mfg" path="mfg_Date" class="form-control" value ="${d.mfg_Date}"/>

  Choose Image
<form:input type="file" path="image" class="form-control" />

 <input type="submit" class="btn btn-primary btn-block" value="Save Changes" class="form-control"/>

</form:form>

please check and let me know my Mistake..i have looked in it.but not found any irregularity.

Note:

Data retrieve works fine.facing trouble in Update only

Body:
Try using this approach :

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(p);
session.flush();
session.close();
tx.commit();

This error usually caused when the hibernate can't find all the rows it needs to update. Meaning that when you try to update some objects that were pulled from the DB they don't really exist anymore (or never existed in the first place).

It might be because another thread is deleting them or that the DB's isolation mode is set to read_uncommited and so rows that were created by another transaction failed to save (due to a transaction failure) and don't exist anymore.


问:
Get the different name of column between 2 tables in SQL Server
In my SQL Server database, I have the same table name in different schemas. For instance schema1.card (table 1) and schema2.card (table 2).

There are around 40 tables in my database. I just want to compare both tables and want to know which are the different column names between those 2 tables.

I have attached a screenshot of the tables. I want to find out all columns which are not in table 2 but exist in table 1 and vice versa.

答:
```<code>select Column_Name from information_schema.columns where table_name = 'sysjobs' and table_schema = 'YourSchema1'
except
select Column_Name from information_schema.columns where table_name = 'sysjobservers' and table_schema = 'YourSchema2'
</code>```

Also, what you can do it is create a variable and loop through all schemas and put the difference in a temporary table. This way you do not have to do one by one and you can automate it

Body:
select Column_Name from information_schema.columns where table_name = 'sysjobs' and table_schema = 'YourSchema1'
except
select Column_Name from information_schema.columns where table_name = 'sysjobservers' and table_schema = 'YourSchema2'

Also, what you can do it is create a variable and loop through all schemas and put the difference in a temporary table. This way you do not have to do one by one and you can automate it