Adding pagebreaks via VBA doesn't work

Question: I created code to set the pagebreaks in an excel report to deal with the orphan issue (i.e. one line of text spills over onto the next page, etc.). The code works fine when I run it with the report open / visible.
It is part of a larger application which is opened and the code executed from MS Access. Excel is not visible during the process to improve performance.
When I run my code from MS Access it no longer works... it doesn't produce an error, but simply ignores the actual pagebreak setting command.
I read on various forums that in order to avoid this problem, excel needs to be first switched over to ActiveWindow.View = xlPageBreakPreview, but that doesn't work either (I suspect since Excel isn't visible).
I have tested for the following:

Code works when it is started manually or stepped through with F8
Code is executed when called upon from Access (I set breakpoints)
Switching the window view doesn't do anything either

How can I get Excel to change the pagebreaks via code when Excel is run in the background?
This is my code:
Sub TheOrphanProblem()
Dim iPageBrkRow

'Determine if there are page breaks and if so on which row of the document
If FindNthAutoPageBreak(wsRptHolding, 1) Is Nothing Then
    'No pagebreak found so we exit the sub
    Exit Sub
Else
    iPageBrkRow = FindNthAutoPageBreak(wsRptHolding, 1).Row 'Get row
End If

Debug.Print iPageBrkRow

Dim x As Integer
Dim sCase As String
Dim rNewposition As Range
With wsRptHolding

'Code edited out for brevity. This part checks if there is an orphan problem and finds the new position for a pagebreak if needed.
It then provides that position as a range called "rNewposition".
'Moves page break to calculated position
ActiveWindow.View = xlPageBreakPreview
.HPageBreaks.Add rNewposition
ActiveWindow.View = xlNormalView
End With

End Sub

This is the code I use to find the pagebreak positions...
Private Function FindNthAutoPageBreak(Sht As Worksheet, Nth As Long) As Range
'Set page break of the last page so that sub asset groups are kept together

Dim HP As HPageBreak
Dim Ctr As Long
For Each HP In Sht.HPageBreaks
    If HP.Type = xlPageBreakAutomatic Then
        Ctr = Ctr + 1
        If Ctr = Nth Then
            Set FindNthAutoPageBreak = HP.Location
        End If
    End If
Next HP

End Function

Comment: You're not properly qualifying your objects, which will cause you other issues - it shoudl be: `.Applicaiton.ActiveWindow.View = xlPageBreakPreview` not just `ActiveWindow.View = xlPageBreakPreview`
Comment: Unfortunately it didn't do the trick. I'm leaving the proper qualifiers in though... thanks.
Comment: Is the page setup of the sheet set to use any of the fit to pages options?
Comment: Yes... in a sub that runs before this one I set the page width to 1 wide using With `.PageSetup.FitToPagesWide = 1`
Comment: That could add additional pagebreaks but it shouldn't remove the ones you have added. Do you turn `PrintCommunication` off?
Comment: I haven't done anything with `PrintCommunication`. Should I simply turn it off, or turn it off and then back on?
Comment: Don't do anything with it. To clarify, are you seeing **additional** pagebreaks, or just not seeing your manual ones?
Comment: I see the automatic pagebreaks, simply not the manual ones which I want to set by code.
Comment: Does it work if you leave out the `FitToPagesWide` part?
Comment: It did not seem to have any effect.
Comment: Probably need to see all the code then.
Comment: I don't think I can post the entire code without violating some corporate policy or other... but I appreciate your help thus far. If I find out why this is happening or how to get past the issue, I'll post it here.
Answer: Try this
ActiveSheet.DisplayPageBreaks = True

Comment: I tried your answer and unfortunately the page breaks didn't move. I'm beginning to think this is some kind of nasty excel bug.

Adding pagebreaks via VBA doesn't work


How do I prove $\mathbb{Z}\times\mathbb{Z}\times\mathbb{Z}$ and $\mathbb{Z}\times\mathbb{Z}$ are not isomorphic?

Question: Here is how I proved this exercise.
Suppose $\phi:\mathbb{Z}\times \mathbb{Z}\rightarrow \mathbb{Z}\times\mathbb{Z}\times\mathbb{Z}$ is a group isomorphism.
Set $\phi(1,0)=(a,b,c)$ and $\phi(0,1)=(d,e,f)$.
Then, it can be viewed as $span(\{(a,b,c),(d,e,f)\}) = \mathbb{R}^3$. This is obviously false. (Is my argument correct?)
However, is there another way to prove this not using linear algebra, just using group theory?
Comment: @REr I know that.. I'm just asking whether there is a direct way to prove this just using group theory
Comment: @Rubertos How, or from what, do you deduce that if $\;\phi\;$ is a hypothetical isomorphism, then  Span$\,\{\phi(1,0)\,,\,\phi(0,1)\}\;$ **has** to be a generator set of $\;\Bbb R^3\;$ as a linear space (over itself, I presume) ? This much you should detail in your answer, imo.
Comment: Hint: How many elements are in the basis?
Comment: You mean $\mathbb Z^3$ (not $\mathbb R^3$)?
Comment: @TroyWoo No I meant $\mathbb{R}^3$. This was on a graduate school entrance exam.. Should not use module argument
Comment: @Rubertos as you really meant $\;\Bbb R^3\;$, then you must explain how you mix both $\;\Bbb Z^3\;,\;\;\Bbb R^3\;$ in any attempt to prove what you want, which seems to be independent of what happens in $\;\Bbb R^3\;$ .
Comment: @Timbuc As I commented on hunter's answer, isn't it sufficient to show that (1,0,0),(0,1,0),(0,0,1) are linear combinations of (a,b,c) and (d,e,f) over either $\mathbb{Z}$ or $\mathbb{R}$? And this is satisfied by the bijectivity of $\phi$.
Comment: I don't get which part of my argument is not rigorous..
Comment: @Timbuc I see. I was just wondering if my argument is wrong (rather than incomplete). Thank you..
Comment: @Rubertos Well, for sure I'd say it is incomplete as it doesn't include an explanation of the above details. On the other hand I wonder how difficult could it be to prove that a **free** basis of the free abelian group $\;\Bbb Z^n\;$ is *also* a basis of the linear space $\;\Bbb R^n_{\Bbb R}\;$ ...
Answer: If $G= {\mathbb Z}^3$ and $H={\mathbb Z}^2$, then $|G/2G|=8$ and $|H/2H|=4$, so $G/2G \not\cong H/2H$ and hence $G \not\cong H$.
Comment: Beat me to it, though I was going to comment that any homomorphic immage of $\;\Bbb Z^2\;$ is generated by two elements at most, whereas there's an homomorphic image of $\;\Bbb Z^3\;$ which *requires* at least three generators. +1
Answer: Hint:
If $\phi:\mathbb{Z}^2\to\mathbb{Z}^3$ is an isomorphism then so is $\phi^{-1}:\mathbb{Z}^3\to\mathbb{Z}^2$.
Show that some linear combination $\phi^{-1}(1,0,0)$, $\phi^{-1}(0,1,0)$ and $\phi^{-1}(0,0,1)$ is zero and therefore $\phi^{-1}$ is not injective.
Answer: Your argument is basically correct, but isn't so precise. The more precise way to say your same argument, which you probably haven't run into the language for in your course yet, is that $\phi$ cannot be an isomorphism after tensoring with $\mathbb{R}$ for dimension reasons, and thus already cannot be an isomorphism.
You may find one of the other arguments here more useful, just because it's easier to write without having to define too precisely what you call "viewing" the map in $\mathbb{R}^3$.
Comment: That new wording is perfectly precise.
Comment: Why is it not precise? There exsits (n,m) such that $(1,0,0)=n(a,b,c)+m(d,e,f)$. And same for $(0,1,0)$ and $(0,0,1)$. Hence, considering these two tuples as vectors in $\mathbb{R}^3$, they span.


Congratulations, you're no longer in Beta!

Question: This site started private beta before July 2012, so it is no longer "beta", it is a full site by our definition. We've removed the word "beta" from your site banner because we believe that you aren't really a beta site any more, even if you don't get ten questions per day.

What this means for you:

the "Beta" is removed from your banner
the site is moved to the "Launched" sites list on Area 51 - which will also remove the A51 info box from the right sidebar
retain beta reputation levels
full-site elections will be delayed but will be scheduled eventually

This is the start of a process that we are already discussing internally and will be bringing to the network for public discussion once the plan is finalized. My hope is that this will mean the end of the monolith we currently refer to as "Graduation" in favor of a well-defined set of small targets to achieve the various elements that made up "Graduation".
I'm sure you have many questions, please feel free to ask and I'll answer what I can. It helps me out a lot if you can limit answers to focus on a single question/subject rather than asking a dozen questions in one answer.
Please feel free to follow the MSE discussion for more background on this decision. You can ask questions either here or there; I'll try to keep up with all of them. Your mods also have some info, so they may be answering in my stead.
Thanks so much for your patience and stay tuned!
Comment: Hurray for us!!
Answer: I saw the question on the Meta Stack Exchange about reputation requirement levels for site privileges. I'm just here to speak out in agreement for this site that I our current levels should stay the same.
When I truly started using CSE (like half a year or after I signed up and forgot about it!), it took me an extremely long time to reach the editing privileges, since this is somewhat of a small site.
Funnily enough, I think we have just reached out 5000th question (I can't quite count on mobile!) So that makes cause for a double celebration today!  Everybody do the cha-cha and drop it low!
Additionally, welcome to CSE @Catija!


SAPUI5 Can't access a array and give it to a JSONModel

Question: I have problems to access an array, where i put some data from a omodel read. The array is called aData und contains row data for a table. This works fine, all data is in there.
This all code is done after a value help dialog is opened and in his/this table i want to put the data
        var oTestModel = this.getModel();
        oTestModel.read("/shrhelpSet", {
            filters: [oFilterObject, oFilterField, oFilterLang],
            success: function(oRetrieveResults){
                //console.log(oRetrieveResults);

                var oDatas2 = oRetrieveResults;
                var test1 = oDatas2.results;

                var aData = [];
                var index = oDatas2.results.length;
                var i;
                for (i=0; i<index; i++) {

                    aData.push("{Key: '" + oDatas2.results[i].key + "', Value: '" + oDatas2.results[i].value + "'}");
                }

                // aData Array
                console.log("aData: " + aData);

            },

            error: function(oError){
                console.log(oError);
            }
        });

This code is after the omodel read. Here i have an array with column data for my table.
The oModel2 contains the columndata, which i definded in aColumnData
and the rows from above are in aData. And here is the problem. It returns (the array) no data or is showing only object. Do you have tipps for better handling this or a solution for this problem?
        var aColumnData = [{
            columnId: "Key"
        }, {
            columnId: "Value"
        }];

        var oModel2 = new sap.ui.model.json.JSONModel();

        oModel2.setData({
            columns: aColumnData,
            rows: aData // THIS IS THE RESULT OF MY MODEL, the results are in aData but i cant access it here
        });

        oTable.setModel(oModel2);

        oTable.bindColumns("/columns", function(index, context) {
            var sColumnId = context.getObject().columnId;
            return new sap.ui.table.Column({
                id : sColumnId,
                label: sColumnId,
                template: sColumnId
            });
        });
        oTable.bindRows("/rows");

Comment: The success handler will run as soon as data is received from the network. This is asynchronous which means that the code execution will not stop and wait for the data from the backend, it will keep runnung until the data is received. At this point, the success handler will run. You cannot know when exactly the sucess handler will run because it depends on the speed of the backend response. I will add an answer for you to try out.
Comment: Does the second piece of code follow the first one directly? If so, the success method is probably not yet started when you are trying to use the array to fill your model. Is it not an option to bind your table to oTestModel?
Comment: Yes its following directly. Are you sure. Its finished and then it goes to the second piece. I am sure that its successfull to. The problem to bind the table to oTestModel was that i cannot bind it because its a sap.ui.table. I tried it, but the solution what works for me was this what i have. I dont know, maybe i did something wrong too
Comment: Is the aData array empty or is aData not defined? Because it looks like you declare it inside the success handler and try to access it outside. Could you try to declare the variable "aData" before "oTestModel.read(...)". If this doesn't help, then Samleijenhorst might be right because the "read" is asynchronous. This means, the success handler will run when data is received. This might be after your second snipped is run already.
Comment: Now i definded it outside. The aData is empty after the run. Can you explain me please why the code after the read is called first than the read itself. I dont understand this. I am new to sapui5 / javascript
Comment: What possibilities i have to get the data out of a asynchronous call, because i mean, with the recieved data everybody has to work on his application
Comment: Would something like this work: var aData = oModelread...(function (, ) {

    return aResult;
Answer: I think that the problem could be that you are pushing strings and not objects in your array:
aData.push("{Key: '" + oDatas2.results[i].key + "', Value: '" + oDatas2.results[i].value + "'}");

Your object should be something like this:
{
   Key: oDatas2.results[i].key,
   Value: oDatas2.results[i].value
}

Answer: Try to move the code that needs access to the received data into the success handler like this. Also, I think the other answer is right that you need to create objects instead of strings.
this.getModel().read("/shrhelpSet", {
filters: [oFilterObject, oFilterField, oFilterLang],
success: function (oRetrieveResults) {
    var aData = oRetrieveResults.results.map(function (oResult) {
        return {
            Key: oResult.key,
            Value: oResult.value
        };
    });

    var aColumnData = [{
        columnId: "Key"
    }, {
        columnId: "Value"
    }];

    var oModel = new sap.ui.model.json.JSONModel({
        columns: aColumnData,
        rows: aData
    });

    oTable.setModel(oModel);

    oTable.bindColumns("/columns", function (index, context) {
        var sColumnId = context.getObject().columnId;
        return new sap.ui.table.Column({
            id: sColumnId,
            label: sColumnId,
            template: sColumnId
        });
    });

    oTable.bindRows("/rows");
}.bind(this),

error: function (oError) {
    console.log(oError);
}
});

Comment: Thank you very much. This is the solution. I have to get more into the procedure of asynchronous , models, ui5 etc.
Answer: There are no problem with your view.

var oTable = new sap.ui.table.Table({
  rows: '{/rows}',
  title: new sap.m.Title({
    text: "Test"
  })
});

oTable.bindColumns("/columns", function(index, context) {
  var sColumnId = context.getObject().columnId;
  return new sap.ui.table.Column({
    label: sColumnId,
    template: sColumnId
  });
});

var model = new sap.ui.model.json.JSONModel({
  columns: [{
    columnId: "Key"
  }, {
    columnId: "Value"
  }],
  rows: [
    { Key: "K1", Value: "V1" },
    { Key: "K2", Value: "V2" },
  ]
});

oTable.setModel(model);
oTable.placeAt('content');
<!DOCTYPE HTML>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

So it appears that your model is incorrect. Maybe you are trying to change the results in the model like this.
success: function(oRetrieveResults){
    var aData = oRetrieveResults.results.map(function(data) {
        return {
            Key: '"' + data.key + '"',
            Value: '"' + data.value + '"'
        };
    });
    this.setProperty("/results", oData);
},

Comment: No i am not changing it, i am only copying out the key and value to save it in an array


No Card Drops Remaining for CSGO

Question: Does CSGO drop random trading cards? I'm asking this because I never got any card drops and I have 90 hours playtime
Answer: Just like many other games CS:GO drops cards if you purchased the game (which is not relevant since it is free for some time now) or spent some money on in-game purchases. This is what I see if I open my existing CS:GO badge:

So you need to spend about $9 to get a card.

No Card Drops Remaining for CSGO


How Do I include text from functions.php to index.php

Question: I do not know much about PHP. I am creating a settings page for my Wordpress theme. I want to change the text in index.php with the textboxes which is located in functions.php. I tried too many ways. I have assigned name, id, value in tag in index.php Just like aboutustitle in my functions.php source. But I didn't do it. How can I do that?
My code here
<?php
// create custom plugin settings menu
add_action('admin_menu', 'my_cool_plugin_create_menu');

function my_cool_plugin_create_menu() {

//create new top-level menu
add_menu_page('Yankı Tema Ayarlar', 'Tema Ayaları', 'administrator', __FILE__, 'my_cool_plugin_settings_page' , plugins_url('/images/icon.png', __FILE__) );

//call register settings function
add_action( 'admin_init', 'register_my_cool_plugin_settings' );
}

function register_my_cool_plugin_settings() {
//register our settings
register_setting( 'my-cool-plugin-settings-group', 'aboutustitle' );
register_setting( 'my-cool-plugin-settings-group', 'some_other_option' );
register_setting( 'my-cool-plugin-settings-group', 'option_etc' );
}

function my_cool_plugin_settings_page() {
?>

Tema Ayarları

Tema ayarlarınızı buradan düzenleyebilirsiniz

<form method="post" action="options.php">
    <?php settings_fields( 'my-cool-plugin-settings-group' ); ?>
    <?php do_settings_sections( 'my-cool-plugin-settings-group' ); ?>

Hakkımızda Kısmı

        Başlık
        <input type="text" name="aboutustitle" value="<?php echo esc_attr( get_option('aboutustitle') ); ?>" />

        Açıklama
        <input type="text" name="some_other_option" value="<?php echo esc_attr( get_option('some_other_option') ); ?>" />

    <?php submit_button(); ?>

</form>

<?php } ?>

Answer: You can echo option in Wordpress using:

<?php echo get_option( 'option_name' ); ?>

https://developer.wordpress.org/reference/functions/get_option/
Answer: dont know what exactly you meant here
but if you want to include something you can use this
<?php include 'functions.php';?>

for example this is my index php
<!DOCTYPE html>

Welcome to my home page!

<?php include 'functions.php';
echo "I have a $color $car.";
?>

and in my functions php
<?php
$color = "red"
$car = "BMW" ?>

so the output is
I have a red BMW

Comment: Thanks for your help. I mean, there are functions.php and index.php. In functions.php there are a custom page. This custom page has one textbos within form. This forms action is option.php and also methods is post. This textbox integrated with some php codes as you see. In index.php there are `lorem ipsum dolor sit amet`. Now, When I type somethings in this textbox which is located in functions.php, and save settings, this p located in index.php, change to texbox writing.


Angi's camp follower archery

Question: So I am wondering if I bring followers to angi's camp will they use the archery range or just hang out
Answer: As it is not a real player home, but rather a location the followers will not interact with the archery range and just hang out as they do in any other location/vista.
Comment: If I used a mod to change an npcs home hold that work or no
Comment: I need a link to the mod in order to give you a full answer. But in theory, that could work.
Comment: It's the relocate npcs your new home for ps4 on bethesda.net

Angi's camp follower archery


How to troubleshoot HVAC for room that is uncomfortably warm in both hot *and* cold weather?

Question: I have a room in my house that I spend a lot of time in.  It is consistently uncomfortably hot in the summertime.  A thermometer on my desk will read 80 degrees or more in the summertime.  I was told that the HVAC likely isn't pushing enough air into the room.  I was told that I could pay thousands of dollars for a "mini-split" that would push more cold air into the room.  As an alternative, I purchased an evap cooler which works well enough, but at the price of frequently refilling it and keeping the door and window open, which compromises my privacy and comfort.
Now that the mercury is dropping, the evap cooler is in the closet, and it is still uncomfortably warm in this room.  The other day, I was on the phone and I noticed my forehead was sweating and the reading on the thermometer was 82.  This seems to mean that the same HVAC that was pushing "not enough cool air" into this room is now pushing "too much warm air" into this room.  I'm paying money for my HVAC and alternating between sweating my brains out and leaving the window hanging open so that I have to listen to every barking dog in the neighborhood.
All adjoining rooms in the house are a comfortable temperature all year round.
I suspect that if I had purchased that "mini-split" to get more cool air in here, I'd still be unhappy that this room is so hot in the winter time.
What kind of problem am I likely having that a room in my house is uncomfortably warm in both hot and cold weather while the adjoining rooms are all comfortable?
Here is some more information requested:
In answer to some questions that have been brought up, the room only has a single south-east facing window.  It is an ordinary room surrounded by ordinary drywall, like all the rooms with south-east facing windows that are comfortable all year long.  The room is directly above a kitchen that I have never had an HVAC problem with.  The ducts run between the two floors, so it is impossible to take a look at it without tearing holes in the ceiling below.
There is a single compressor that cooler the whole house in summer.  There is a single furnace that cools the wholse house in winter.
There is a single vent blowing air into the room.  We had an HVAC duct cleaning company in the house a while back.  The guy who recommended the mini-split said that duct cleaning companies can be good at finding if there may be a break in the system that causes air to escape.
I want to emphasize that I am not an HVAC expert.  I am handy enough to tackle something from time to time when I have the time and motivation for it, such as when I replaced the blower motor several years ago to avoid paying an inflated price to have a contractor do it.  I don't know all the lingo, but I will do my best to answer questions to help solve my problem.
Comment: Is this room filled with heat producing electronics?
Comment: Where in your house is this room? Does it have lots of south-facing windows?
Comment: Is the room an addition or a type of sun room  or enclosed porch?
Comment: How does air get out of the room?  Is there a return vent in the room?  If not, do you normally keep the door open or closed?
Comment: There is a return vent, @Mark.  Leaving the door open helps with air flow, but no other room requires the door to be continuously open to be comfortable.  This room is my work room and I need my privacy and quiet space.  We have a child in the house.
Comment: Can you feel air blowing out of the supply vent? Is it appropriately warm or cool?  When the system is running, if you hold a piece of paper in front of the return vent does it get sucked up against the vent?  Where are the supply and return vents located (opposite sides of room? Floor? Ceiling?  High or low on the wall?
Comment: If it gets too hot you should be able to block or adjust a vent cover?  Does the door have a small gap at the bottom to allow air to flow out when closed?
Comment: @Mark, yes, the return vent will suck in a piece of paper.  I just now tried it.  I have a single gaming PC and a work PC in this room, but it seems far-fetched that two computers (one being a laptop!) can raise the temperature of the room so much.  I'll have to do some experiments!
Comment: You'd be surprised how much heat a computer can generate! I moved my (very low powered) file server into my office and could feel the temperature increase. It's not as bad as your situation seems to be, but they do produce a lot of heat.
Answer: With the info you have provided we really can't help you, there are mini splits out there you can install for ~1500$  I would want see how your system is set up because your hvac guy sounds like he knows less than my neighbor and I helped him put in a mini split. Unless you can provide some specifics I vote to close.
Comment: What kind of information would you like me to provide that would help you answer my question?  I told you that the room is uncomfortably warm in both hot and cold weather, the the HVAC guy said it sounded like "not enough air" back in the summertime, that the adjoining rooms are all a comfortable temperature.
Comment: What kind of hvac? Is there a separate furnace? How do the trunk lines attach? Any pictures as they leave the unit, is this room duct an afterthought or a separate duct cut into the air handler I could keep on going but a room that is hot all the time could be sitting over a boiler we don't know. Anything about your system.
Comment: I have added information to answer questions to hopefully help you and others help solve my problem.
Comment: Have you tried partially closing off other vent/registers in the house to direct more air to your work space?
Answer: There are 3 things to confirm about your room: 1) excess heat gain from external or internal sources. 2) inadequate air flows (cfm) into and out of the room. 3) actual air and surface temperatures. An IR temperature sensing gun will locate any hot spots on wall, ceiling or floor. Do temperature checks before the room heats up fully, then do it hourly to find hot spots. For airflow checks, tape a garbage bag to a coat hanger hoop like a butterfly net. Count the seconds to inflate or deflate, then do the math to calculate cfm. You can use the hoop to compare airflows in nearby room also.
Comment: Thanks for this answer with all-around helpful information!  As best I can tell, it turns out that my gaming PC is actually the culprit.  I've had computers in my home continuously since I was 10 years old, but newer computers with fancy CPUs and GPUs apparently consume a lot of power, plus I've been running Folding@Home overnight, and that makes the cooling fan on my 2070 GPU spin at full blast.  It just hit me the other day when I plugged in a thumb drive that it may as well be a space heater sitting on my desk.  I shut it off for a few hours and the problem went away.
Comment: One more tip for any room where you prefer to keep the door closed and where there is no return vent. Cut 1 inch off the bottom of the door. It will give you a 30 square inch opening.


Is the determinant of a matrix preserved under permutations of the rows/columns of a matrix?

Question: Is the determinant of a matrix preserved under permutations of the rows/columns of the matrix?
If not, is its absolute value preserved?
Comment: May I ask what do you mean by permutation of the rows?
Answer: Any single exchange of two rows or two column changes the sign of the determinant.  You need to keep track of whether you do an odd or even number of switches of rows or columns.  That is to say, you need to multiply the determinant by $\mathbb{sgn}(\sigma)$, the sign of the permutation $\sigma$ for any given row or column permutation.
Comment: Thanks @Anjan3, i'll fix that, you can also do edit suggestions when you see these :)
Comment: i believe you meant $sgn(\sigma)$ for $(-1)^\sigma$
Comment: your answer is so nice . it cleared my doubt at once ...:-)


How to decide which way to triangulate a quad?

Question: Apologies if this is a dumb question... but given four arbitrary (non-coplanar) points in 3D space, there are obviously two different ways to triangulate the quad that they form. One triangulation may produce much more natural results than the other- but how can I determine which one to pick?
Context: I'm doing Dual Contouring, and the quad forms part of an isosurface. I have access to the hermite/gradient data at that point.
Comment: I should say that they're not *totally* arbitrary- they lie on the form corners of a square and it's only the z coordinate that changes
Answer: A simple heuristic that many 3D content creation apps use is to split along the shorter of the two diagonals of the quad. This generally seems to work pretty well. It minimizes the appearance of long, skinny triangles, which are generally undesirable both for visual and performance reasons.
See this article: Deformation and Triangulation in Maya for some further discussion. In particular if you have a dynamically deforming mesh, you ideally want to retriangulate the quads based on the deformed geometry each frame, or you can get some pretty wonky artifacts if you stick with a fixed triangulation:

(image from the above linked blog post)
Comment: The link in this answer is broken here is an updated link: https://noahalzayer.wordpress.com/2017/04/11/deformation-and-triangulation-in-maya/
Answer: One other, albeit more expensive approach, is to subdivide your quad into 4 triangles by putting a point at the centre of each quad. There are some advantages to this in that:

It will be more temporally stable. If your quad vertices are moving and you were otherwise using the "shortest diagonal" approach Nathan has suggested, the tessellation will change pattern every now and then.  Maybe this won't matter too much geometrically, but remember that the UV texture coordinates are also linearly interpolated in world space (obviously hyperbolically in screen space) and so the texturing can jump.

If the quad is quite distorted (e.g non-planar or non-convex),  I think the 4xtri approach will look much better than either of the two 2xtri options

If you instead are just chopping into triangles based on the order of the vertices of your quad, i.e. ABCD always becomes ABC and CDA, then if by chance the modelling package spits out another "identical" quad but ordered as BCDA, then the rendered versions won't match.

Of course, the downside is that you have 2x the number of vertices and triangles, but it may be worth considering.
Answer: This isn't a dumb question.  This is a much more important question than most people realize.
Here's the worst case scenario for triangulating a quad:

No sane artist will ever make this for static geometry, but no sane animator will check every frame of every animation to make sure that we never get this. We have a degenerate quad, with three collinear vertices, and it's being triangulated such that we have a zero area face.  Note that this is shortest diagonal triangulation; shortest diagonal is no proof against this, and neither is longest diagonal.
If we put some normals on there, and treat this as smooth shaded, we'll see that the central vert's normal contributes reasonably to the quads on the left, but not at all to the quad on the right.  This will cause a discontinuity in normals:

This is not some magical thing that only happens at perfect degeneracy.  As our quad is divided into triangles of increasingly different areas, our vertex data will be divided increasingly unevenly across the quad.  That may mean pinched normals, it may mean unsmooth vertex color-- in either case, the triangulation will be increasingly apparent visually.
The best way to prevent this bad situation is to triangulate to minimize the difference in area between triangles.  Triangulation in this way will also give us symmetrical triangulation on symmetrical portions of our mesh, which is also a desirable trait.
For animated meshes, one might be tempted to do this dynamically, but that would be a mistake.  Flipping triangulation will change the interpolation of vertex data across the quad:

All I'm doing here is flipping triangulation.  This is shown with mildly distorted UV, which is an optimistic expectation, but we'll see the same swimming with normals and vertex color, and with data derived from interpolated vertex data, like UV tangents.  Instantaneous change like this-- pop-- is one of the most noticeable kinds of artifacts in animation.
So we don't want to determine triangulation from a deformed state.  To have stably interpolated vertex data, we need to have a consistent triangulation of the mesh.  If our framework allows, we can mark vertices appropriate for triangulation in the pre-deformed state.  If it doesn't, it's better to use something like vertex order, which is stable through deformations, than it is to risk swimming from dynamic triangulation.
Answer: Assuming we are using a separate array for indices into the vertex array, the following pattern for the indices array is the most efficient for splitting a quad. Must be in this specific order:
0 3
1 2

using this exact sequence of triangulation:
(0,1,2) (0,2,3) for splitting the two tris in one diagonal
 OR
(0,1,3) (1,2,3) for the other diagonal

Why? because you just have to add one unit to the two adjacent indices to switch from one diagonal to the other:
const offset = 0 or 1 (*)
(0,1,2+offset) (0+offset,2,3)

(*) 0 or 1 depending on the shortest distance between the two diagonals: abs( length( vertex2 - vertex0 )) and abs( length( vertex1 - vertex3 ))
Obs. all sequences of three numbers (a triangle) above are CCW (counter clockwise) for Front Facing triangles
Obs.2 this array of groups of 4 indices into the vertices array could be treated as a vec4 in glsl ;)


Cooker Hood Shorts When the Outer Cover Touches a Wall Bracket Installed to Stabilise the Cover

Question: I have installed a cooker extractor hood which works fine with the vertical outer cover off. When I rest the hood cover on the extractor base and it touches a high level wall mounted bracket installed to steady the cover (not bolted to the cover) the MCB trips?
Comment: A picture would really be helpful.  Welcome to Home improvement.  Please take the tour at https://diy.stackexchange.com/Tour to get the most out of this site.
Answer: I have a feeling you are in UK or Europe and your MCB includes RCD/RCBO functionality.**
The problem is that your device has residual current leakage, or what we in the states call a "ground fault".   It is leaking current in a way it should not, and which could stun/harm/kill a human. Being stunned unconscious onto a hot cooking surface would not be fun.
When you install the cover, you are causing the problem to manifest in a way that doesn't involve bloody mayhem.  This is a good thing.
The temptation would be to defeat the symptom, but the real problem is the hood is defective.  Sorry.

**if not, tripping the main circuit breaker and not the branch circuit breaker would require an arc flash brighter than the sun, and I'm pretty sure you would not be typing!


ggplot2: how to add the legend for a line added to a scatter plot?

Question: I have some x and y data that I would like to compare on a ggplot2 scatter plot.
I would like to add a unity line (y = x), twofold (y = 2x), half (y = x/2) and smoother lines to help making sense of the data but I cannot find how to add theses lines to the plot's legend. Any idea?
set.seed(123)
x <- runif(20, 1, 10)
y <- 0.8 * x + runif(20, -1, 1)
cat <- factor(c(rep("high", 10), rep("low", 10)))
d <- data.frame(x, y, cat)

ggplot(data=d) +
     geom_point(aes(x, y, colour=cat)) +
     geom_abline(aes(intercept=0, slope=1), col = "red") +
     geom_abline(aes(intercept=0, slope=0.5), col="blue", linetype="dotted") +
     geom_abline(aes(intercept=0, slope=2), col="blue", linetype="dashed")+
     geom_smooth(aes(x, y))

y vs x scatter plot in ggplot2
I would like the labels 'unity line', 'twofold', 'half', and 'smoother' to appear below the 'high' and 'low' labels in the legend.
Following User3640617's answer, I have tried the following code but the result is still not satisfying because the data points now have a linetype and a smoothing linetype linked to them in the legend.
ggplot(data=d) +
     geom_point(aes(x, y, colour=cat)) +
     geom_abline(aes(intercept=0, slope=1, colour="y = x")) +
     geom_abline(aes(intercept=0, slope=.5, colour="y = x/2")) +
     geom_abline(aes(intercept=0, slope=2, colour="y = 2x")) +
     geom_smooth(aes(x,y, colour="smooth")) +
     scale_color_manual(
        values=c("red", "darkgreen", "black", "blue", "red", "blue")) +
     scale_linetype_manual(
        values=c("blank", "blank", "solid", "dashed", "solid", "dotted")) +
     scale_shape_manual(values=c(1, 1, NA, NA, NA, NA))

Also, I do not seem to be able to manually change the tinetypes:
scatter plot with ablines and smoother
I know, I could simply choose other colors and there would be less confusion but it should be possible to have a legend with only points for points and lines for lines instead of having point and lines for both points and lines, or is it not?
ggplot2 seems to be bothered by the addition of color or linetype after the aes. The order of the categories seems to be changed when adding the lines to the legend.
Answer: You can just map a character value to an unused aesthetic to trick ggplot into making a legend for you:
ggplot(data=d) +
  geom_point(aes(x, y, colour=cat)) +
  geom_abline(aes(intercept=0, slope=1, lty='unity line'), col = "red")

Use + scale_linetype(name = NULL) or labs(linetype = NULL) to remove the linetype legend title.
Comment: Thank you very much Axeman, this works fine for me! ...except that I have multiple lines that I added and only the unity line is captured in the legend. Sorry, my bad :( I should have mentioned that I had more than one line. I just thought I could extrapolate the solution. I will update my question.
Answer: I guess there is no way around having a second dataset containing your lines.
One way to get a second legend for the lines, is to map the lines by linetypes and hardcode the colors (followed by manually adjusting the colors in the legend).
This could be done like so:

library(ggplot2)

# 1 recreate the data
set.seed(123)
x <- runif(20, 1, 10)
y <- 0.8 * x + runif(20, -1, 1)
cat <- factor(c(rep("high", 10), rep("low", 10)))
d <- data.frame(x, y, cat)

# create the lines-data
d_lines <- data.frame(int = rep(0, 3),
                      sl = c(1, 0.5, 2),
                      col = c("red", "blue", "blue"),
                      lty = c("solid", "dotted", "dashed"))

# extract the linetypes from the data.frame (with names to map the values correclty)
ltys <- as.character(d_lines$lty)
names(ltys) <- as.character(d_lines$lty)
# extract the colors in the order that ggplot will put the names of the lines (dashed, dotted, solid)
cols <- as.character(d_lines$col)
cols <- cols[order(as.character(d_lines$lty))]

# plot the data
ggplot() +
  geom_point(data = d, aes(x, y, colour=cat)) +
  geom_smooth(data = d, aes(x, y)) +
  # add the two different line-colors
  geom_abline(data = d_lines[d_lines$col == "red", ],
              aes(intercept = int, slope = sl, lty = lty), color = "red") +
  geom_abline(data = d_lines[d_lines$col == "blue", ],
              aes(intercept = int, slope = sl, lty = lty), color = "blue") +
  # change the color of the legend
  scale_linetype_manual(name = "Linetype", values = ltys,
                        guide = guide_legend(override.aes = list(colour = cols)))
#> `geom_smooth()` using method = 'loess'

Comment: Thank you David for this solution! I am trying to add the smooth line to the legend and I am really surprised that it does not work easier (using the standard plotting library seems to be more flexible).
Answer: Not a very neat solution perhaps, but you can create an additional data frame with the information for your unity line as follows:
dfabline <- data.frame(intercept=0, slope=1, group="unity line")

ggplot(data=d) +
  geom_point(aes(x, y, colour=cat)) +
  geom_abline(data=dfabline, aes(intercept=intercept, slope=slope,  colour=group))

You can specify the colour of the line and the points using scale_colour_manual.
Comment: Thank you for this useful answer! It works with multiple lines. Going through an extra dataframe does not seem to be necessary, it worked for me without defining the unity line in an additional dataframe. It seems that ggplot2 is bothered as soon as I try to specify the linetype and/or color and it removes the line from the legend. Moreover, the legend displays some symbols with the line, which I need to figure out how to remove. (See my answer below)


How to install eiffel on ubuntu 13.10?

Question: How can I install the eiffel programming language? I run Ubuntu 13.10 (64-bit) but I don't have a window manager, only ssh (as ec2 instance).
Answer: The installation of EiffelStudio on Linux Ubuntu is quite simple. Open a terminal and type the following command lines:
<code>sudo add-apt-repository ppa:eiffelstudio-team/ppa
sudo apt-get update
sudo apt-get install eiffelstudio
</code>
Check this for more information.

How to install eiffel on ubuntu 13.10?


Emulator is loaded, but app is not installed and no error

Question: Emulator is loaded, but app is not installed,
I have tried restarting adb, restarting eclipse, creating new android projects, creating new avd
everthing works like normal, but I couldn't install any app at all. Below is my xml file. thanks for your help
<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eldorado.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="10" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.eldorado.myfirstapp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>
Here is android console
<code>[2013-03-11 21:55:20 - MySecondProject] ------------------------------
[2013-03-11 21:55:20 - MySecondProject] Android Launch!
[2013-03-11 21:55:20 - MySecondProject] adb is running normally.
[2013-03-11 21:55:20 - MySecondProject] Performing com.exapmple.mysecondproject.MainActivity activity launch
[2013-03-11 21:55:20 - MySecondProject] Automatic Target Mode: Preferred AVD 'Gingerbread_WVGA'   is not available. Launching new emulator.
</code>
[2013-03-11 21:55:20 - MySecondProject] Launching a new emulator with Virtual Device      'Gingerbread_WVGA'
   [2013-03-11 21:55:28 - Emulator] emulator: emulator window was out of view and was recentered
    [2013-03-11 21:55:28 - Emulator]
Comment: Please see your `Android Console` and paste here to see what happens there!
Answer: Check the VD you created with any API , or change android:minSdkVersion="10"  to android:minSdkVersion="7" and try again .
Comment: I changed the minsdkversion, but I still have the problem. and by the way what do you mean by VD
Comment: By the way my LogCat is quite empty, any suggestion?


Arquillan InvalidEnvironnmentException, suggests to add an already added plugin to Maven pom.xml

Question: I configured my project and wrote my test class for a multi-module project. A test for a business service call to an AS400 server is written with Arquillan, which gives me an InvalidEnvironnmentException when I run the test.
package com.my.company.theproject.business.service.protect;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.my.company.theproject.common.dataaccess.PojoService;
import com.my.company.theproject.ServiceContext;

@RunWith(Arquillian.class)
public class SampleServiceTest
{

    @Inject
    @PojoService
    SampleService service;

    private ServiceContext context;

    @Before
    public void setUp()
        throws Exception
    {

        context = new ServiceContext();
    }

    @Deployment
    public static WebArchive createDeployment()
    {
        return ShrinkWrap
            .create(WebArchive.class)
            .addClasses(SampleService.class)
            .addAsWebInfResource("META-INF/beans.xml", ArchivePaths.create("beans.xml"))
            .addAsLibraries(
                Maven.configureResolverViaPlugin().importRuntimeDependencies().resolve().withTransitivity().asFile());
    }

    @Test
    public void test()
    {

        List<String> list = new ArrayList<String>();
        list.add("AAA");

        service.getStoredProcedureParameters(context, list);

        fail("To be implemented");
    }
}

I have written down the imports here, in case some were wrong (e.g. javax.inject.Inject ?).
The problem here is that Arquillian gives me this error at test runtime (first exception of the stack trace) :

java.lang.RuntimeException: Could not invoke deployment method: public
  static org.jboss.shrinkwrap.api.spec.WebArchive
  com.sopra.banking.packbanque.business.service.protect.SampleServiceTest.createDeployment()

At the end of the stack trace, I see this :
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.invoke(AnnotationDeploymentScenarioGenerator.java:177)
    ... 50 more
Caused by: org.jboss.shrinkwrap.resolver.api.maven.InvalidEnvironmentException: Configuration from environment requires that user has following properties set, however they were not detected in runtime environment:
    maven.execution.pom-file
    maven.execution.offline
    maven.execution.user-settings
    maven.execution.global-settings
    maven.execution.active-profiles

You should enable ShrinkWrap Maven Resolver Plugin to get them set for you automatically if executing from Maven via adding following to your <build> section:

<plugin>
    <groupId>org.jboss.shrinkwrap.resolver</groupId>
    <artifactId>shrinkwrap-resolver-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>propagate-execution-context</goal>
            </goals>
        </execution>
    </executions>
</plugin>

    at org.jboss.shrinkwrap.resolver.impl.maven.task.ConfigureSettingsFromPluginTask.execute(ConfigureSettingsFromPluginTask.java:71)
    at org.jboss.shrinkwrap.resolver.impl.maven.ConfigurableMavenResolverSystemBaseImpl.configureViaPlugin(ConfigurableMavenResolverSystemBaseImpl.java:119)
    at org.jboss.shrinkwrap.resolver.api.maven.Maven.configureResolverViaPlugin(Maven.java:77)
    at org.jboss.shrinkwrap.resolver.api.maven.Maven.configureResolverViaPlugin(Maven.java:59)
    at com.sopra.banking.packbanque.business.service.protect.SampleServiceTest.createDeployment(SampleServiceTest.java:74)
    ... 55 more

The problem is that this plugin declaration is already in my Maven pom.xml !
<build>
    <plugins>
        <plugin>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-maven-plugin</artifactId>
            <version>2.2.0-beta-2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>propagate-execution-context</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

What is the problem here ?
Answer: I think the problem could be that you need to load the pom file first and then resolve as of now it dosent know that whene to resolve the dependencies from..
I am not sure but you can try this... :)
You can find everything about shrikwrap resolver here :
https://github.com/shrinkwrap/resolver


Clearing values without reloading the page

Question: I've got a series of text boxes and drop downs and the user fills these out, hits "generate" which then concatenates the strings in the text boxes and displays the resulting values on the page.
What I'm having trouble doing is clearing these "outputs" if the user hits generate again. for example if someone changes the text or something like that.
There are multiple groups of textboxes on multiple lines and the resulting strings are placed in a  at the end of the page. Sample code below:
HTML:

Activity Tags

      + -

  <form id="tag-form" class="tag-form">
  <input type="checkbox" class="checkbox nounderscore" name="tfcheck">
    <select class="page_type" title="Page Type">
      <option value="HPG">HPG – Homepage</option>
      <option value="LPG">LPG – Landing Page</option>
      <option value="CNT">CNT – Content</option>
      <option value="RES">RES – Research</option>
      <option value="ENG">ENG – Engagement</option>
      <option value="CNV">CNV – Sale Conversion</option>
    </select>
    <input type="text" class="pagedesc nounderscore" value="Page Description" title="Page Description" onfocus="clickclear(this, 'Page Description')" onblur="clickrecall(this,'Page Description')" />
    <input type="text" class="tagstartdate numberinput" value="Tag Start Date" title="Tag Start Date" maxlength="8" onfocus="clickclear(this, 'Tag Start Date')" onblur="clickrecall(this,'Tag Start Date')" />

  </form>

Activity Group

jQuery:
$(document).ready(function() {
    $('.gp').click(generateOutputs);
});

function clearAll() {
    $('.tag_span').each(function() {
        $('.tag_span').html("");
    });
}

You can see from the jQuery above I've tried to use the each() function (as there can be multiple rows) to clear the spans, but this doesn't work. Hope I'm making sense in this post. Will try and explain it better if people don't get this.
Thanks
Comment: you want to clear the span "tag_span" of any data?
Answer: Try using a reset button
     <input type="reset"/>

Otherwise, if you're trying to do this in code, you would do this:
function clear_form_elements(ele) {

    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}

 clear_form_elements('#tag-form');

http://www.electrictoolbox.com/jquery-clear-form/
Comment: I already have a reset button (but I have used `window.location.reload()` on this. I want to be able to clear the contents and run the "generateOutputs"function again
Answer: Try this...  What I did here was put the input for the button inside the form and set it's type to reset.  This allowed me to put the code in the form's onreset attribute so that it will clear out the spans for the current form (which contains the button).
HTML

Activity Tags

      + -

  <form id="tag-form" class="tag-form" onreset="clearAll()">
  <input type="checkbox" class="checkbox nounderscore" name="tfcheck">
    <select class="page_type" title="Page Type">
      <option value="HPG">HPG – Homepage</option>
      <option value="LPG">LPG – Landing Page</option>
      <option value="CNT">CNT – Content</option>
      <option value="RES">RES – Research</option>
      <option value="ENG">ENG – Engagement</option>
      <option value="CNV">CNV – Sale Conversion</option>
    </select>
    <input type="text" class="pagedesc nounderscore" value="Page Description" title="Page Description" onfocus="clickclear(this, 'Page Description')" onblur="clickrecall(this,'Page Description')" />
    <input type="text" class="tagstartdate numberinput" value="Tag Start Date" title="Tag Start Date" maxlength="8" onfocus="clickclear(this, 'Tag Start Date')" onblur="clickrecall(this,'Tag Start Date')" />
    123
    <input type="reset" value="ClearButton" />
  </form>

Activity Group

JavaScript
function clearAll() {
    $(".tag_span").each(function(index,element) {
        element.innerHTML="";
    });
}

See a live example: http://jsfiddle.net/VF2qG/2/
Answer: Here's what I came up with: http://jsfiddle.net/Y2JRJ/
You needed to refer to $(this) instead of referring to tag_span again.
$('.tag_span').each(function() {
    $(this).html("");
});

Answer: If there won't be multiple .tag_span's then just do
$('.tag_span').empty()

That removes stuff inside the element but doesn't delete the element from the dom


Kivy: Hide mouse cursor on desktop

Question: I have a fullscreen app and I'm trying to hide the mouse cursor. The setup is Kivy 1.9.0 on Python 3.4.1 for Windows, using the prepared packages.
I have tried the following approaches, with no success:
1- Using Config object:
from kivy.config import Config
Config.set("graphics", "show_cursor", 0)

2- Editing .kivy\config.ini:
[graphics]
.
.
.
show_cursor = 0

3- Using pygame:
import pygame
pygame.init()
pygame.mouse.set_visible(False)

4- Moving the mouse off-screen:
def move_mouse_away(etype, motionevent):
  # this one doesn't get called at all
  Window.mouse_pos = [1400, 1000]

Window.bind(on_motion=move_mouse_away)

5- Using Clock for a similar effect:
Clock.schedule_interval(self._reset_mouse, 0.05)

def _reset_mouse(self, time):
  Window.mouse_pos = [1400, 1400]

I'm a little out of ideas now.
Comment: using config worked for me
Answer: You can use Window.show_cursor
It was added in kivy version 1.9.1
from kivy.core.window import Window
Window.show_cursor = False

Answer: I just read the documentation, tried it and fixed it (version 1.9.0).  To hide the cursor from the application window permanently (even if you are using a touchscreen) :
>>> from kivy.config import Config
>>> Config.set('graphics','show_cursor','0')
>>> Config.write()
>>> quit()

I use a touch screen (LG 19MB15T) which works 'out_of_the_box'.
Answer: I'm having the same kind of problem: I need to hide or change my mouse cursor in a kivy app.
I don't have a perfect solution only a partial one:
from kivy.uix.widget import Widget
from kivy.core.window import Window
import win32api

class NoCursorWindow(Widget):

    def __init__(self, **kwargs):
        super(NoCursorWindow, self).__init__(**kwargs)

        Window.bind(mouse_pos=self.on_mouse_pos)

    def on_mouse_pos(self, *args):
        win32api.SetCursor(None)

if __name__ == '__main__':
    from kivy.base import runTouchApp
    runTouchApp(NoCursorWindow())

It works only partially:
The problem when you use win32api.SetCursor() is that when the mouse moves, the window gets a WM_SETCURSOR Message which changes the cursor back to default. This is why the win32api.SetCursor() must be triggered for each change of the mouse_pos.
But even like that sometimes we can see the default cursor blinking.
If anyone knows how to hook the WM_SETCURSOR, to prevent the call back of the default cursor, it could solve this...

Kivy: Hide mouse cursor on desktop


Received downvotes for most of my questions

Question: Is someone targeting my questions and downvoting them all? Basically all my questions have downvotes.
Answer:
Is someone targeting my questions and downvoting them all?

I don't think that anyone will target somebody else's question and downvote them. There's a script that runs every day that'll check for unusual voting activity and invalidate it automatically. So generally, when you see something odd, give it a day and see if it clears up. If not then it probably means something is wrong with your question. Try to ask for clarification. Sometimes (or maybe most of the time) people might not give a reply but this is the only way.

Now, let's talk about why your questions have downvotes.
Is there a strategy to win chess960 games? Your this question was a duplicate which means you didn't go for enough research.
What openings are best for white or black in fast games of chess The reason was already specified that it was an opinion-based question.
Is it possible for black to win this? Well, this question wasn't interesting at all. You just gave a puzzle and asked for the best solution (which is right according to me). The problem was that it wasn't a really good puzzle. One could have easily turned on the engine and found the answer. As @PhilipRoe commented on it To make a claim on other people's attention you should be sure that it is interesting.
How would you feel if everyone else starts posting questions like the best way to finish the game or find a mate in 11?
How to learn endgame theory This one is having several downvotes too. I would suggest you add more details on why your question is different from the related one, and try to explain your question more(so that the reader has almost no doubt while answering. )

I personally don't downvote questions unless they are off-topic. I hope you don't take these downvotes seriously (even though sometimes, it becomes frustrating). If your question is good you will automatically get the upvotes.
Comment: *If your question is good you will automatically get the upvotes.*  (+1) Good posts generally get positive scores, especially over time.
Answer: Full disclosure: the troll in me really wanted to downvote this question, just for the lolz, but I managed to resist :-).
Seriously, you can only downvote a post once. 5 downvotes and no upvotes is 5 different people telling you the same thing, that there is something seriously wrong with your post. Time to take the message onboard.
The problem you have with that particular post is that with 2 answers both with positive scores you can't just delete it. It is there for posterity.


How to enable CORS on server side using ng serve option

Question: I have a server side app Using Angular 7 and I need to see if there command line option, like so
ng serve --Access-Control-Allow-Origin

There is quite a bit of online chatter about this but I'm hoping to have a good reference for that works with both Firefox and Chrome.
I did install this (as per one of the suggestions) but it doesn't help.
npm install ember-cli-cors

Comment: Do you have any mini GitHub repository for it? there should be an alternative way to do that. or at least add more details
Comment: Not sure I understand your question. I cant post the code to github.
I am going with the proxy gateway approach to deal with CORS and it works for me.
Answer: Configuration to support CORS  should be done on the server side. There shouldn't be anything to set on the Angular client side.
However if you still want to do that, Refer
Run the npm http-server onto the public or dist folder directly.
It has these attributes:
http-server -o --cors
Also you can set a proxy by creating a proxy.config as mentioned here
Comment: As I mentioned in my question, I am trying this on the server side.

I currently run `ng serve`. What are you suggesting that I try?


My inventory and armor disappeared in LAN multiplayer on Minecraft

Question: My friend and I were playing Minecraft over LAN, and my friend was the host, then she logged off. 5 minutes later we tried to log back in and all my stuff was gone, and I wasn't even in the same spot where I was previously.
I don't know what happened. She was playing over Windows and I was using iOS.
I need my stuff back, I was so happy because I had found diamonds for the first time in my life :(
Comment: There is a lot that is unclear here. But let me start by asking whether your inventory was completely empty or reverted to a previous state.
Comment: I assume your friend was playing the Minecraft Windows 10 version, right?
Comment: yes, my inventory was full and i was fully armored.
Comment: yes, my friend was playing on minecraft windows 10 version.
Comment: It probably just didn't save properly when she exited.
Answer: If she was hosting the LAN and she logged off before you could (Save and quit) then it is likely that a saving error occurred on your device, because you couldn't save before the host logged off.  To prevent this you should log-off before the host of the LAN closes.
Comment: You could test to see if the diamonds you found are where you found them before, if they are then it was a saving problem. (If you know where they are)
Answer: If you were not logged in and you changed your name this makes the game think you are a different person playing on the same console/device. Therefore if you were to change your name back to the original your problem would be solved.


Authenticating from a service account. Programmatic IAP authentication fails in Google App Engine

Question: I am trying to do programmatic authentication to a different application (project). We have followed the instructions that were listed here. We are using python 3.7 on app engine standard edition.
The default service account (from where the authentication is initiated) has been added to the access list of the application (that is being accessed).
response = iap_authentication.make_iap_request(url, client_id)

We are stuck with the following error. The make_iap_request class is the code (with no changes) from here. Has anyone had luck making this work? Please help.
exception: Bad response from application: 502 / {'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1613', 'Date': 'Fri, 15 Nov 2019 00:44:06 GMT', 'Alt-Svc': 'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000'} / '<!DOCTYPE html>\n\n <meta charset=utf-8>\n <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
\n <title>Error 502 (Server Error)!!

Comment: do you an App Engine that is secured with IAP configurations? check [here for more information](https://cloud.google.com/iap/docs/app-engine-quickstart).
Comment: Yes. We have enabled IAP configurations for this project (application). There is a default service account (from where the authentication is initiated) added as IAP-secured Web App User to this IAP configuration.
Answer: This is a known issue at the moment and there's currently a public issue tracker addressing the problem. Bookmark the link to keep track of the updates. [1]
[1] https://issuetracker.google.com/144749437


Why does createCapture not work when I run the code?

Question: The project I'm working on should have the code createCapture but it doesn't work when I run the code despite having a createCapture() in the code.
When I run it, I would click to the second page and there should be a createCapture on the second page.
The camera should turn on, When Clicking to the second page
The JS Code:

let screen = 0;
let saveB;
let fullB;
let capture;

function setup() {
    createCanvas(400,400);
}

function draw() {
    if(screen == 0) {
        startScreen();
    } else if(screen == 1) {
        mainScreen();
    } else if(screen == 2) {
        endScreen();
    }
}

function startScreen() {
    background(100);
    fill(250);
    text('Here you are', width / 2, height /2);
    text('Click to Start', width / 2, height / 2 + 20);
    textAlign(CENTER);
}

function mousePressed() {
    if(screen == 0) {
        screen = 1;
    } else if(screen == 2) {
        screen = 0;
    }
}

function mainScreen() {
    background(100, 200, 250);
    text('This is you ', 40, 30);
    saveB = createButton('Save');
    saveB.mousePressed(Savefile);

    fullB = createButton('FullScreen');
    fullB.mousePressed(FullScreen);

    capture = createCapture('VIDEO');
    capture.position(200,200);
    capture.size(100, 100);
    let audio = createCapture('AUDIO');
}

function Savefile() {
    save('Photo.jpg');
}

function FullScreen() {
    let fs = fullscreen
    fullscreen(!fs);
}

function endScreen() {
    background(100,200,200);
    fill(250);
    text('Thank you for looking at yourself', width / 2, height / 2);
    text('Click to restart', width / 2, height / 2 + 20);
}
html, body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

The createCapture should appear on the second page but it doesn't. Thank you in advance.
Comment: There is a typo in the 2nd line of your code: `let, saveB;`
Comment: Oh thank you I didnt see it
Answer: It's possible that you don't have permission to access the camera in the context where you are using this code. If your code is running in an iframe on another website it may have restrictions that prevent it from even requesting access to the webcam.
Other than that your code mostly works. However, when you get to screen 1 (a.k.a. mainScreen) you are currently recreating the buttons and capture every frame, which is not what you want to do. Both buttons and capture objects are persistent, so you only need to create them once.
Additionally, while your code displays the webcam video on the screen it will not be present in the file generated when you click saved. This is because creating a capture object doesn't actually draw the captured images to your canvas. Instead you need to hide the capture object and draw it as an image to the canvas. Here is a working version of your code hosted on p5js.org. And bellow is an abridge version with just the relevant bits:
let saveB;
let capture;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  mainScreen();
}

let mainScreenInitialized = false;

function mainScreen() {
  if (!mainScreenInitialized) {
    mainScreenInitialized = true;
    background(100, 200, 250);
    text('This is you ', 40, 30);

    saveB = createButton('Save');
    saveB.mousePressed(Savefile);

    capture = createCapture('VIDEO');
    capture.hide();
  }

  let aspect = capture.height / capture.width;
  image(capture, 100, 100, 200, 200 * aspect);
}

function Savefile() {
  save('Photo.jpg');
}

Unfortunately I cannot make this into a snippet on StackOverflow because the iframe it runs in does not have permission to request webcam access.


.htaccess modrewrite URL

Question: I am working on mod rewrite code and currently stuck on 1 problem I don't know why problem is happning.
When user search for something url looks like this
/search.php?q=car&limit=150&siz=any

I have converted it to like this. .htaccess automatically convert the link to like this
/car/150/any

But the problem when user search again url changes to something like this
/car/150/any?q=books&limit=150&siz=any

Which I don't want so please tell me what do I do
Here is my .htaccess code
RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /search\.php\?q=(.*)\&limit=(.*)\&siz=(.*?)\ HTTP
RewriteRule ^ /%2/%3/%4? [R=301,L]

RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /search.php?q=$1&limit=$2&siz=$3 [L]

Answer: As I mentioned here before Link conversion in mod rewrite .htaccess
1.I suggest you add ^search as identifier to avoid conflict
2.query search should be end of other parameter, inputing string at first might occured link unreadable
Here my new answerd Edited based on your new question
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^search/([^_]+)/([0-9]+)/(.*).html$ search.php?limit=$1&siz=$2&q=$3 [L]

if you want to call script within you web page, call using link http://yoursite.com/150/any/Your Search String
dont call by search.php?q=book&limit=150&siz=any just past your variable int Your Search String above
Comment: Thanks for answering however I just solved the problem I just changed the action in the form to something like this
"http://example.com/search.php" from "" and it solved the problem also I am using the same code I just mentioned above.
Comment: yes that I was mean, call script with your url rewrite link

.htaccess modrewrite URL


How to output raw JSON from Db

Question: I'm using common Yii2 ActiveController REST implementaion:
class ResultController extends ActiveController
{
    public $modelClass = 'app\models\Result';
    public function actionResultList($id)
    {
        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        return new ActiveDataProvider...

It works all good for me, except one feature - I've got some JSON stored in my Result->rawJson model as string. When I'm outputting it through this controller it gets escaped with slashes, and angular on frontend treats it as a string. The question is how to tell serializer not to serialize several model fields and pass them 'as is'.
I found only this dirty hack to do it, i've added afterFind in my model class:
public function afterFind()
{
    $this->rawJson= json_decode($this->rawJson);
}

I'll appreciate any help on this, thanks in advance.
Comment: it doesn't look dirty as solution to me. I think you made the right choice. it is an array now that you can use anywhere in your app & you can design validators to each of its attributes to verify their content one by one before saving to database instead of making php believe it is just a string, you will just need to convert them back to json within a `beforeSave` method.
Answer: I suggest you leave the original attribute untouched and create a new attribute with a getter-setter pair. Assuming that your original attribute is called rawJson:
public function getProcessedJson()
{
    return json_decode($this->rawJson);
}

public function setProcessedJson($value)
{
    $this->rawJson = json_encode($value);
}

Then just add processedJson to your fields() method, and you're good to go.

How to output raw JSON from Db


Difference between EventEmitter vs Output Decorators in Angular-Cli

Question: Why does EventEmitter and Output Decorator needs to be used together ?,
I cannot see the difference between the two,
If they are required to be used together why not just one decorator to emit as well as bind to selector wherever it is used !
Appreciate any explanation !
Thank You
Answer: EventEmitter is just a Subject.
@Output() is what marks the field as output for Angular event binding.
I haven't tried in Angular TS, but in Angular Dart it was possible to just use a Stream (equivalent to Subject) instead of EventEmitter.
In recent versions EventEmitter was removed completely in Dart Angular.
Perhaps this works in Angular TS as well.
There were plans to extends the API of EventEmitter in a way that might be incompatible with Subject, therefore a custom class was created.
But there are no signs this will actually happen.
Comment: Hi @Gunter,
I understand the difference now,
Thank You
Comment: Hi @Gunter,
Is there a way present to utilize a function by parent component with Output Decorator alone ?

Thank You
Comment: `@Output()` is to emit events that can be consumed by event binding like `(myEvent)="doSomething($event)"`. I don't understand what you mean by "utilize function by parent". Can you please add the code to your question that demonstrates what you try to accomplish?
Answer: EventEmitter allows you to create a custom event, emit from this event and subscribe to this event, react to it.
@Output() allow you to spread these events to parent components :
child.Component.ts
  @Output() myEvent: EventEmitter<string> = new EventEmitter<string>();

parent.component.ts
<app-child-component (myEvent)="reactToChildEvent($event)"></app-child-component>

EDIT :
You can use EventEmitter alone, without @Ouput(), to emit from a service to all subscribed components, or inside the same component.
Comment: `EventEmitter` is just a `Subject` (extends `Subject`) as mentioned in my answer, but it was mentioned several times by the Angular team that `EventEmitter` should not be used for anything else than for `@Output()`s because it's API might change in breaking ways without any notice. There is also no point, because you can just use `Subject` to achieve the same.
Comment: Hi @Boulboulouboule,
Thanks for information !
I am aware of the functionality of each one of them,
was curious with usage of EventEmitter and Output together !
Thank You
Comment: Ok ! Note that EventEmitters can be used without @Output() decorator


Conservative vector field partial derivatives

Question: Given a 3D vector field $\vec{F}=(P,Q,R)$, I know that if $\boldsymbol\nabla \times \vec{F}=\mathbf{0}$, then it is a conservative field.
Moreover, I made an observation that if a vector field is conservative, then $\frac{\partial^2{P}}{\partial{y}\partial{z}} = \frac{\partial^2{Q}}{\partial{x}\partial{z}} = \frac{\partial^2{R}}{\partial{x}\partial{y}}$
Therefore, I am wondering is it true the other way around? i.e. $\frac{\partial^2{P}}{\partial{y}\partial{z}} = \frac{\partial^2{Q}}{\partial{x}\partial{z}} = \frac{\partial^2{R}}{\partial{x}\partial{y}} \implies$ vector field being conservative.
Thank you!
Comment: I assume that when you say "a 3D vector field," you really mean a vector field whose domain is all of $\mathbb R^3.$ I don't believe that $0$-curl is sufficient to conclude that a vector field is conservative in general. We also need our domain to be simply-connected.
Answer: Unfortunately, this is not true in general. Consider the vortex vector field $$\mathbf V(x,y,z) = \bigg \langle \frac{-y}{x^2 + y^2}, \frac{x}{x^2 + y^2}, 0 \bigg \rangle.$$ We have that $\nabla \times \mathbf V = 0 \mathbf i + 0 \mathbf j + \big(\frac{-x^2 + y^2}{(x^2 + y^2)^2} - \frac{-x^2 + y^2}{(x^2 + y^2)^2} \big) \mathbf k = \mathbf 0;$ however, it is also true that $$\int_{\mathcal C} \mathbf V \cdot d \mathbf r = \int_0^{2 \pi} \bigg \langle \frac{-r \sin t}{r^2}, \frac{r \cos t}{r^2}, 0 \bigg \rangle \cdot \langle -r \sin t, r \cos t, 0 \rangle \, dt = 2 \pi,$$ where $\mathcal C$ is parametrized by $\mathbf r(t) = \langle r \cos t, r \sin t, 0 \rangle,$ i.e., $\mathcal C$ is a circle of radius $r > 0$ centered at the origin in the $xy$-plane. One can easily verify that your condition on the partials holds.
Comment: Why the downvote?


what should i do when installing mod_wsgi i lost ap_config.h

Question: Can anybody tell me what's the content in this file(ap_config.h),i want to create this file by myself,but i don't know what's the content in it.please help me ,thks.enter image description here
Comment: Check https://github.com/GrahamDumpleton/mod_wsgi/issues/196
Comment: What platform are you using and what Apache distribution? Some Apache distributions, for Windows especially, are incomplete. On Windows use the ApacheLounge distribution. You can't just recreate the file. If that file is missing then lots others are going to be as well.
Comment: i using windows,apache 24 and python 2.7.what should i do ,if i want to use apache + mod_wsgi ?
Answer: Use ApacheLounge that includes the header.
Comment: Thanks very much.Maybe it works,but i have already tried my best to find this file in ApacheLounge.But i can't find it,and when i wanted to use 'search' ,the webpage didn't show Search Blank to me.


How to create basic game item attributes

Question: I'm trying to make an RPG-type game, without the map part, it's basically a series of battles.  The battles are turn based and have limited animation, mainly just text info.  It's the first game I'm making and I don't have plans to distribute.  Basically I have no idea how to set up my game.  I don't know how to store what level the player is, which enemy they are up to in the story line, what there weapons are and the attributes are, etc.  I'm not looking for code I just need to know what to research, how to set this all up.
Answer: How much experience programming do you have?  If this is truly your very first game, it may be a bit too difficult for you.  The only reason I think this is because by the time I started creating games of this complexity, I had a firm grasp on how to structure them.  On the other hand, if you really think that you're ready for this, grab some paper and a pencil and start planning.  Personally, I find the trick to planning an application to be asking myself "What makes sense?"  For example, it makes sense for there to be some sort of application class, something that controls the program.  It makes sense for there to be a Player class, which holds information such as the level, different stats, health, etc.  It makes sense for there to be some sort of AbstractEnemy class, from which different enemy types inherit from.  Make some sort of chart showing how things will relate with each other and which classes will handle what.


How to find all ring homomorphisms from $\mathbb{Z}$ to $\mathbb{Z}$

Question: I am trying to find all homomorphisms from $\mathbb{Z}$  to    $\mathbb{Z}$. I am looking at a solution, but i do not understand it. Here it is:

Let  $\Phi\colon \mathbb{Z}\to\mathbb{Z}$  be a ring homomorphism. Because $1^2 = 1$, we see that $\Phi(1)$ must be an integer whose square is itself, namely either $0$ or $1$. If $\Phi(1) = 1$ then $\Phi(n)= \Phi(n · 1)= n$, so $\Phi$ is the identity map of $\mathbb{Z}$ onto itself which is a homomorphism. If $\Phi(1)= 0$, then $\Phi(n)=\Phi(n · 1)0$, so  maps everthing onto $0$, which also yields a homomorphism.

I do not understand here what "Because $1^2= 1$, we see that $\Phi(1)$ must be an integer whose square is itself, namely either $0$ or $1$.". All proof is built upon this and I do not understand what it means. Can someone help me with this?
Thank you
Answer: Remember the basic properties of a ring homomorphism: $\Phi$ must be such that
$$\Phi(m+n)=\Phi(m)+\Phi(n)$$
and
$$\Phi(mn)=\Phi(m)\Phi(n)$$
for all $m,n\in\Bbb Z$. Since $1\cdot1=1$, we must have
$$\Phi(1)=\Phi(1\cdot1)=\Phi(1)\Phi(1)\;,$$
i.e., $\Phi(1)^2=\Phi(1)$. The only two integers with the property that $n^2=n$ are $0$ and $1$, so $\Phi(1)$ must be one of them.
Answer: Since $1=1\cdot 1$, and then by definition of a homomorphism, $\Phi(1)=\Phi(1\cdot 1) = \Phi(1)\cdot \Phi(1)$.
Comment: Since $1$ generates $\mathbb Z$, $\Phi(1)$ generates the image of $\mathbb Z$. It is often convenient to examine the effect of a homomorphism on a generating set - if you know one. It is one of the most convenient ways of converting an apparently infinite problem into a finite one - and why finitely generated things are often relatively easy to study. In a similar way, for example, a homomorphism of a vector space is defined for every element once its effect is known on a basis. This property of $\mathbb Z$ will undoubtedly come in handy again.
Comment: Thanks, but why do we start the proof from here? Is it because 1 is the multiplicative identity?
Comment: @bigO Yes, the point is that both the multiplicative and additive identies must map to themselves and this forces, as the proof notes, all other $n$ to go to themselves too. Checking what the images of the identities are is a standard thing to do first.
Answer: By additivity you must have $\phi(n)\phi(1)= \phi(n)=n \phi(1)$ thus if $\phi(1) \neq0$ you get $\phi(n)=n$ and so $\phi$ is the identity on $\mathbb{Z}$, otherwise $\phi=0$.
Comment: $\phi(n)=\phi(1+...+1)$; written in this way should be clear, but it's mathematically freakish.. A correct argument is to proceed by induction on $n$ : $\phi(1 \cdot 1)= \phi(1)= 1\cdot \phi(1)$ and $ \phi(n)= \phi(n-1 +1)=\phi(n-1) + \phi(1)= (n-1)\phi(1) + \phi(1)=n \cdot \phi(1)$
Comment: Thank you, but i am confused how do we know that phi(n)=nphi(1)?


accessing DownloadStringAsync that resides in another class

Question: I'm using the webclient to do an async download from within a class. i.e
public void download()
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri("http://www.url.com"));
}

I'm trying to make use of the CancelAysnc method, I presume I'd use something like:
client.CancelAsync();

But I'd like to use it on, for instance, a click event method. Of course when I try and use the above sample it doesnt know about client. How do I get access to it?
thanks
Answer: You would have to store the client object somewhere other than in a local variable. This way you would have access to it outside of your download() method.
Answer: Scope...
WebClient client;
public void download() {
    client = new WebClient();
    // Further code...
}

public void cancel() {
    client.CancelAsync();
}


Segmentation Fault freeing a vector of pointers

Question: i get a segmentation fault error compiling the code below. this comes from the desctructor implementation when i try to free the vector of pointers. Could you please help?
I also have another question. For me i think i can only delete the pointers inside the vector, and the vector will be deleted automatically. but is it possible that the vector will hold nothing when the pointers are deleted? thanks
<code>#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iterator>

using namespace std;

/* ******************************************************* Node ********************************************************* */

template<class T>
class Node
{
    private:
        T _value;
        vector<Node<T>*> children;

    public:
        Node(T value);
        Node(const Node<T>& node);
        void AddChild(Node<T>* node);
        T getValue() const;
        vector<Node<T>*> returnChildren() const;
        ~Node();
};

template <class T>
Node<T>::Node(T value):_value(value)
{
    children.push_back(NULL);
}

template <class T>
Node<T>::Node(const Node& node):_value(node.getValue()),
                                children(node.returnChildren())
{
}

template <class T>
void Node<T>::AddChild(Node* node)
{
    if (children[0]==NULL){children.pop_back();};
    children.push_back(node);
}

template <class T>
T Node<T>::getValue() const
{
    return _value;
}

template <class T>
vector<Node<T>*> Node<T>::returnChildren() const
{
    return children;
}

template <class T>
Node<T>::~Node()
{
    for (typename vector<Node<T>*>::iterator it=children.begin() ; it!=children.end() ; it++)
    {
        delete *it;
    }
}

int main()
{
    Node<int> n(3);
    Node<int> nn(4);
    n.AddChild(&nn);
    Node<int>* child= new Node<int>(*(n.returnChildren()[0]));
    cout << (*child).getValue() << endl;
}
</code>
Comment: You're calling `delete` on a pointer to an object on the stack. What do you think will happen?
Comment: Oh yes, i created nn on the stack. i just created it with new and it works. thanks!!!!!!
Answer: IMHO There are basically two errors:
1) in ~Node() you should add the check to see if the pointer to the child is null (otherwise deleting a null pointer cause the seg fault)
2) instantiating in the main function nodes as local variable (in the stack of the function and not in the heap) will automatically launch the ~Node() at the exiting of the function: this means another seg fault because you're trying to delete twice the same pointer.
Comment: 1) is incorrect. Deleting null does not cause a seg fault.
Comment: 2) is an accurate identification of the problem, but "delete twice" is not an accurate description.  Calling delete with the address of a local variable once is already enough for a seg fault.


OpenGL Unable to retrieve the values of data sent to shader using textures

Question: I've been following these tutorials and i can't figure out how to send data to shaders using textures.
https://en.wikibooks.org/wiki/OpenGL_Programming/Scientific_OpenGL_Tutorial_02
In this tutorial they are using GL_LUMINANCE which has been removed from OpenGL 3.1 and above. I was wondering what should i use instead of GL_LUMINANCE? I tried GL_RGB, GL_RED but i was unable to retrieve the values.
Answer: What GL_LUMINANCE as a texture format actually does is store one component of data per pixel that is used for the red, green and blue color components. So, a classic greyscale image (It doesn't use it for the alpha component, though, that's why there was also GL_LUMINANCE_ALPHA for two compnent storage and GL_INTENSITY that broadcasts it to all components).
When using shaders you don't actually need this distinction anymore, though, since you can do the swizzling yourself in the shader. So you just use a proper typed 1-component internal format, most probably GL_R8 (i.e. 8-bit normalized fixed point red) in your case, but depending on your exact data type requirements really. And for setting it you would (in that case) use GL_RED as the format of the data in your RAM storage. So something like:
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, <width>, <height>, 0, GL_RED, <type>, <data>);

And in the shader you can do with that red color component whatever you want. If you just need a single value per pixel, you use that. If you need a grey color (i.e. GL_LUMINANCE behaviour), you swizzle it to the RGB components, and if you need it as color and opacity, you swizzle it into all four components. Or whatever else you want to do.
float data = texture(...).r;
vec4 luminance = texture(...).rrra;
vec4 intensity = texture(...).rrrr;

Though, this requires your shader to be somewhat aware of what texture you're working with. But if you want to use a more generic shader working with a 4-component color from an arbitrary texture, this might be too much of a hassle. In this case what you can also do is have the texture itself control its own swizzling behaviour. This is an OpenGL 3.3+ feature and can be set with glTexParameter and for good old GL_LUMIMANCE behaviour this would be:
glTexParameter(..., GL_TEXTURE_SWIZZLE_R, GL_RED);
glTexParameter(..., GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameter(..., GL_TEXTURE_SWIZZLE_B, GL_RED);
glTexParameter(..., GL_TEXTURE_SWIZZLE_A, GL_ONE);

So then you can retrieve a normal 4-component color from your texture in the shader and get the 1-component it's storing conveniently broadcast into the RGBA components of the result.


Show that a lower bound of a set need not be unique but the infimum a given set is unique

Question: I just want to see if my proof is verified. It seems pretty straightforward I combined two remarks from the book.
Proof: If a set $E \subseteq \mathbb{R}$ and is non-empty and has one lower bound then it has infinitely many. Let $M_0$ be a lower bound. Then so to is $M$ for any $M \lt M_0$. Therefore the lower bound a set is not unique.
However, if a set has one infimum then it has only one. Let $i_1$ and $i_2$ be infimums of the set $E$. Then by definition they are both lower bounds of the set and follows that $i_1 \leq i_2$ and $i_2 \leq i_1$ Therefore by the trichotomy property $i_1 = i_2$. So it is obvious that the infimum of a set is unique.
Comment: The last part needs more justification: $i_1$ and $i_2$ are both lower bounds so $i_1\leq i_2$ and $i_2\leq i_1$. As stated, this isn't quite correct (the conclusion is correct given $i_1$ and $i_2$ are infimums of the set $E$, but you must use the fact that each is an infimum and not just that they are lower bounds for the set).
Comment: I don't think you explained why $i_1\leq i_2$, since $i_1,i_2$ aren't necessarily in $E$. For your proof of the lower bound statement, what you have done is fine, but just as a technical note, you proved something stronger.
Comment: What did I accidently prove then?
Answer: Your proof for non-uniqueness  of lower bound is good.
For the uniqueness of the infimum you missed some important points.
You let $i_1$ and $i_2$ be infimum of the set $E$
Since $i_1$ is infimum of $E$ it is the greatest lower bound of $E$ therefore it is greater than or equal to $i_2$ which is a lower bound of $E$ that is $$i_1\ge i_2$$
Similarly we have $$i_2 \ge i_1$$
Thus $i_1 =i_2$ which proves the infimum is unique.
Comment: That does make more sense
Comment: Thanks for your attention.


SweetAlert showLoaderOnConfirm not displaying

Question: i am using sweetalert to display delete confirmation,and process it later while displayin a loading action,though it is not working,thi is the code,that doesn't work (it is supposed to display a loading animation,but it actually is not doing so) any thoughts ?
This the javascript
document.querySelector('div.test').onclick = function() {
swal({
title: 'Ajax request example',
text: 'Submit to run ajax request',
type: 'info',
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function(){
 setTimeout(function() {
  swal('Ajax request finished!');
}, 2000);
});
};

Html

<button>show alert</button>

this is the fiddle
Answer: Sweetalert is unsupported anymore. You might want to switch to sweetalert2:

Swal.fire({
  title: 'Ajax request example',
  text: 'Submit to run ajax request',
  icon: 'info',
  showCancelButton: true,
  showLoaderOnConfirm: true,
  preConfirm: function() {
    return new Promise(function(resolve, reject) {
      // here should be AJAX request
      setTimeout(function() {
        resolve();
      }, 1000);
    });
  },
}).then(function() {
  Swal.fire('Ajax request finished!');
});

Answer: I assume your include files are wrong (old for instance).
The snippet:

$(function () {
  $('div.test').on('click', function (e) {
    swal({
      title: "Ajax request example",
      text: "Submit to run ajax request",
      type: "info",
      showCancelButton: true,
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
    }, function () {
      setTimeout(function () {
        swal("Ajax request finished!");
      }, 2000);
    });
  })
});

<link href="https://rawgit.com/t4t5/sweetalert/master/dist/sweetalert.css" rel="stylesheet">

    <button>show alert</button>

Comment: Thank,you this did the trick,i did not know my includes were wrong,since it worked almost fine,though thank you for the hint(btw that jquery made a conflict with my datatables,so i simply didn't use it,am using my 1.12.3 jQuery) thanks for th hint saved me


Jquery Ajax Promise does not work

Question: I'm making a app and I'm unable to fire a promise, I breaked the code to the a simple example that still does not work, I'm using EasyPHP...
ajaxDialog = function( destiny ) {
    // Promise to let me know when complete
    return $.ajax({
      url: destiny,
      dataType: 'json',
    }).promise();

  };

  teste = ajaxDialog('data.json');

  teste.done( function() { alert("sadasassa"); })

Comment: What does not work? Have you tried an error handler?
Comment: `ajaxDialog = $.getJSON`?
Comment: Its a function, right at the beginning of the code sample ;)
Comment: I know you declared it, but it looks too similar to the already existing [`$.getJSON` function](http://api.jquery.com/jQuery.getJSON/). Why not use that directly?
Comment: Don't ever post a question saying "it doesn't work" without explaining exactly what happened and any error messages, if there are no errors, please state so! Are you sure that you're not getting an error calling `promise()` ?
Comment: $.getJSON just points to $.ajax :)
Comment: I don't believe `data.json` is a valid URL for ajax.
Comment: @JuanMendes No, I dont get any messages, it simply dont do nothing :|
Comment: @MarkSchultheiss: Of course it is. Even `""` can be resolved to a valid url.
Comment: If it dont do nothing that means it does something right XD??
Comment: Try adding `teste.always(function(){alert(1)})` to see what happens
Comment: @BrunoTeixeira Side note: You don't have to return `$.ajax().promise()`. You can just return `$.ajax()`, since that function returns a promise.
Comment: @JasonP As @Bergi, explained, calling `promise()` gives you something that is a promise only, not a jqXHR, which is a good thing so that you're not passing around heavy objects
Comment: with current jQuery ajax you should not need to return `.promise()` return the ajax should suffice
Answer: Your ajax is failing and going to the fail handler. If you do the following you will see an alert.
  // This does get called
  teste2.fail( function() { alert("sadasassa"); });

Here's a jfiddle that proves that if you do reach your server, it gets called http://jsfiddle.net/L6bJ2/367/
$(function() {

    ajaxDialog = function( destiny ) {
        // Promise to let me know when complete
        return $.ajax({
          url: '/echo/json/',
          dataType: 'json',
        }).promise();
    };

    teste2 = ajaxDialog('data.json');
    teste2.done( function() { alert("sadasassa"); });

});

Comment: Yeah, I thought that at first too, but jQuery defines its `Promise` interface as "*objects that have a [`.promise()` method](http://api.jquery.com/deferred.promise/)*" :-) So it is indeed available on jqXHR objects as well
Comment: I guess OP doesn't want that because it's *more* than a promise…
Comment: @Bergi  I was looking for some documentation on a `promise()` method of a `jqXHR` and I didn't find it, I thought that would be the problem
Comment: Jeffrey Way does it like I'm doing it and it works, I really dont understand, is there some url that I can try to make a fiddle out of this just to be sure its nothing related with EasyPHP?
Comment: @BrunoTeixeira Here's an example of using jsfiddle and XHR, use that to create something we can play with. http://jsfiddle.net/L6bJ2/6/
Comment: @JuanMendes It fires with fail, but how? data.json file is in the same directory
Comment: Okay it was EasyPHP fault, I knew it, I restarted it and it worked, oh God Why, thank you all!
Comment: @BrunoTeixeira Did you even sniff the  network to see if the ajax is working? That's the least you should do in this case. Like my code shows, it's not getting your XHR, one reason why you should always have error handlers
Comment: It is working and I did, but it was so simple that I was going crazy
Comment: @BrunoTeixeira If you had really looked, you would see that there was something wrong with the request, no?
Comment: The request works fine, I didn't changed nothing, I just restarted EasyPHP, it is working as I posted it. I know my english aint very good but I think i'm being very clear
Answer: try this:
when(ajaxDialog('data.json')).then(function() { alert("aaaa"); });

Comment: What would that change?
Comment: No luck, nothing happens :/
Answer: Check if this would work:
return $.ajax({
  url: destiny,
  dataType: 'json',
}).promise(function(){alert("This is a test");});

I don't know what would that change but everything is worth trying!
Answer:
a simple example that still does not work

The JavaScript works well. Probably your server does not work and does not return a JSON document from the data.json url.
Use
teste.done( function() {
   alert("sadasassa");
}).fail( function(x, s, e) {
   alert(s+": "+e);
});

and debug with the Networks tab in your browser devtools what is happening.

Jquery Ajax Promise does not work


C++ Compiler or Linker optimization

Question: I'm trying to create an autoload class system using class mapping as specified in best answere of this post:
Is there a way to instantiate objects from a string holding their class name?
so i've created this code based on my needs:
<code>// ScriptLoader.h
template<class TScript> void createScript() {
    new TScript;
}

struct ScriptFactory {
public:
    typedef void(*ScriptCreatorFunc)();
    typedef std::map<std::string,ScriptCreatorFunc> ScriptCreatorStorage;

    static ScriptCreatorStorage ScriptCreators;

    static bool RegisterCreator(std::string const& s,ScriptCreatorFunc creator)
    {
        ASSERT(ScriptCreators.find(s) == ScriptCreators.end());   // prevent registering the same script twice
        ScriptCreators.insert(std::make_pair(s,creator));
        return true;
    }
};

template<class TScript>
struct ScriptReg : ScriptFactory {
    ScriptReg(std::string const& s) {
        ScriptFactory::RegisterCreator(s,&createScript<TScript>);
    }
};

class ScriptLoader {
public:
    static void AddScripts()
    {
        for (ScriptFactory::ScriptCreatorStorage::iterator itr = ScriptFactory::ScriptCreators.begin(); itr != ScriptFactory::ScriptCreators.end(); ++itr)
            itr->second();
    }
};

#define REGISTER_DEC_TYPE(NAME) \
    static ScriptReg<NAME> reg

#define REGISTER_DEF_TYPE(NAME) \
    ScriptReg<NAME> NAME::reg(#NAME)

// ScriptLoader.cpp
ScriptFactory::ScriptCreatorStorage ScriptFactory::ScriptCreators;

// foo.cpp
class foo:
{
    public:

        foo()
        {
                /* code */
        }

    private:
        REGISTER_DEC_TYPE(foo);
};

REGISTER_DEF_TYPE(foo);
</code>
and of course i've defined REGISTER_DEC_TYPE in a foo class and at bottom of foo.cpp file i've put: REGISTER_DEF_TYPE(foo) ... ( AddScripts function instead is called by main program so it's normally linked in binaries )
it compiles well but when i try to debug , i cannot set breakpoints in visual studio that shows this tip: "No executable code is associated with this line. Possible causes include: preprocessor directive or compiler/linker optimization"
and in foo.cpp it shows: "any symbol has been loaded for this document"
so i guess the compiler don't find any "normal" call to these functions/classes removing them from the binary code.
Is there any way to avoid this kind of optimization? i'm finding a crossplatform solution to this problem.
thanks in advance
Comment: Can you explain exactly which line(s) in your code you are setting breakpoints at?
Comment: any lines of RegisterCreator and createScript function or everywhere in foo class of foo.cpp ( AddScripts function instead is called by main process so it's normally linked by compiler )
Comment: Are you sure you can compile it? static `ScriptReg reg` requires the default ctor, but there is only one that takes `std::string const& s`
Comment: yes it compiled, anyway i've cleaned a bit the code and edited first post , it continues to compile but doesn't work yet..foo class and other pieces of code are not linked in binaries.
Answer: Deadstripping is a common problem with factory code. What you usually have to do is have a function somewhere that uses all of your types. It's ugly but unfortunately there are no particularly elegant portable solutions.
Comment: so is it required to call all classes somewhere in main process to be registered in map?
Comment: Most compilers remove unused symbols (deadstripping) so that you don't end up with unused cruft in your executable. Unfortunately in this case, it's over enthusiastic so, yes, you need to use them. Making all your register calls in a central `register` function will achieve this.

C++ Compiler or Linker optimization