How do the $node modifications in hook_node_presave persist?

Question: I was looking at hook_node_presave() and I tested it out and it works as described. The thing I'm puzzled about is that it doesn't take the $node parameter by reference, nor does it return anything from the function, however when I modify $node in this hook, the changes get saved. I'm really confused. Can anyone shed some light and make sense of this? How do I implement something like this?
Answer: Objects are (mostly) passed by reference in PHP. The $node variable is a stdClass object so any changes you make will be reflected on the original object in memory.
You don't need to do anything special to implement this yourself, just accept an object as an argument to a function as usual and let PHP take care of the rest.


including selectOneMenu in datatable

Question: i have created datatable with four selectOneMenu in it
whenever i change the first selectOneMenu values of second selectOneMenu need to be populated on the same row and again on the selection of second selectOneMenu third needs to populate
i had done this by passing row number value to each selectOneMenu (with intention which particular selectOneMenu user must has clicked on) but whenever i pass the value with f:param i am getting null value on the controller but same can be printed with outputText on datatable
please guide
<t:dataTable id="insertTaskDataTable" border="1"
                value="#{insertTask.taskList}" var="taskInfo" rowIndexVar="row"
                iterationStatusVar="it">
                <t:column>
                <h:inputHidden  id="id" value="#{row}"/>
                </t:column>
            <t:column>
                <f:facet name="header">#{bundle['GROUP_HEADER']}</f:facet>
                <h:selectOneMenu id="taskGroup" value="#{taskInfo.groupList.comboValue}" onchange="document.getElementById('addTask:filterButton').click();">
                    <f:param  name="idTaskGroup" value="#{row}"/>
                    <t:outputText  name="id" value="#{row}"/>
                     <f:selectItems value="#{taskInfo.groupList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet  name="header">#{bundle['ACTIVITY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskActivity" value="#{taskInfo.activityList.comboValue}">
                <f:ajax  render="taskSubActivity" listener="#{insertTask.handleActivityChange}"></f:ajax>
                <f:selectItems value="#{taskInfo.activityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet name="header">#{bundle['SUBACTIVITY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskSubActivity" value="#{taskInfo.subActivityList.comboValue}">
                    <f:selectItems value="#{taskInfo.subActivityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet name="header">#{bundle['COMPLEXTIY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskComplexity" value="#{taskInfo.complexityList.comboValue}">
                    <f:selectItems value="#{taskInfo.complexityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>

            <t:column>
                <f:facet name="header">#{bundle['BENCHMARK_EFFORT_HEADER']}</f:facet>
                <t:inputText  value="#{taskInfo.benchMarkHrs}" />
                <t:outputLabel value="hrs"/>
                <t:inputText  value="#{taskInfo.benchMarkMin}" />
                <t:outputLabel value="min"/>

            </t:column>

            <t:column>
                <f:facet name="header">#{bundle['DESCRIPTION_HEADER']}</f:facet>
                <t:inputText value="#{taskInfo.taskdescription}" />
            </t:column>

        </t:dataTable>
    </t:div>

            <a4j:commandButton id="filterButton" style="visibility:hidden;display:none" action="#{insertTask.handleGroupChange}" render="insertTaskDataTable" />

Comment: @kuf I've updated the post. Please check !
Answer: Hi Guys i got solution
here it is,
    <t:dataTable id="insertTaskDataTable" border="1"
                value="#{insertTask.taskList}" var="taskInfo" rowIndexVar="row"
                iterationStatusVar="it" rendered="#{insertTask.taskList[0] != null}" >

            <t:column>
                <f:facet name="header">#{bundle['GROUP_HEADER']}</f:facet>
                <h:selectOneMenu id="taskGroup" value="#{taskInfo.groupList.comboValue}"  onchange="document.getElementById('addTask:insertTaskDataTable:#{row}:groupButton').click();">

                     <f:selectItems value="#{taskInfo.groupList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet name="header">#{bundle['CATEGORY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskCategory" value="#{taskInfo.categoryList.comboValue}"  onchange="document.getElementById('addTask:insertTaskDataTable:#{row}:categoryButton').click();">
                     <f:selectItems value="#{taskInfo.categoryList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet  name="header">#{bundle['ACTIVITY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskActivity" value="#{taskInfo.activityList.comboValue}"  onchange="document.getElementById('addTask:insertTaskDataTable:#{row}:activityButton').click();">

                <f:selectItems value="#{taskInfo.activityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet name="header">#{bundle['SUBACTIVITY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskSubActivity" value="#{taskInfo.subActivityList.comboValue}" onchange="document.getElementById('addTask:insertTaskDataTable:#{row}:subActivityButton').click();">
                    <f:selectItems value="#{taskInfo.subActivityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>
            <t:column>
                <f:facet name="header">#{bundle['COMPLEXTIY_HEADER']}</f:facet>
                <h:selectOneMenu id="taskComplexity" value="#{taskInfo.complexityList.comboValue}">
                    <f:selectItems value="#{taskInfo.complexityList.comboValues}" />
                </h:selectOneMenu>

            </t:column>

            <t:column>
                <f:facet name="header">#{bundle['BENCHMARK_EFFORT_HEADER']}</f:facet>
                <t:outputText  value="#{taskInfo.benchMarkHrs}" style="height: 10px; width: 50px;" />
                <t:outputLabel value=" hrs"/>
                <t:outputText value="#{taskInfo.benchMarkMin}" style="height: 10px; width: 50px;" />
                <t:outputLabel value="min"/>

            </t:column>

            <t:column>
                <f:facet name="header">#{bundle['DESCRIPTION_HEADER']}</f:facet>
                <t:inputText value="#{taskInfo.taskdescription}" />
                <h:commandButton id="groupButton" style="visibility:hidden;display:none" actionListener="#{insertTask.handleGroupChange}">
                    <f:attribute name="groupid" value="#{row}" />
                </h:commandButton>
                <h:commandButton id="categoryButton" style="visibility:hidden;display:none" actionListener="#{insertTask.handleCategoryChange}">
                    <f:attribute name="categoryid" value="#{row}" />
                </h:commandButton>
                <h:commandButton id="activityButton" style="visibility:hidden;display:none" actionListener="#{insertTask.handleActivityChange}">
                <f:attribute name="activityid" value="#{row}" />
                </h:commandButton>
                <h:commandButton id="subActivityButton" style="visibility:hidden;display:none" actionListener="#{insertTask.handleSubActivityChange}">
                <f:attribute name="subactivityid" value="#{row}" />
                </h:commandButton>
            </t:column>

        </t:dataTable>

Answer: The best solution for this is "t:selectOneRow" from tomahawk library
Java Side
private Long selectedRowIndex = -1L; //Along with it's getters and setters

JSP Side
<t:dataTable var="var" value="#{bean.beanList}"
style="border: 1px solid black;">

<t:column>
    <t:selectOneRow value="#{bean.selectedRowIndex}" groupName="selection"
        id="selectBtn">
    </t:selectOneRow>
</t:column>

<t:column>
    <f:facet name="header">
        <h:outputLabel value="Names" />
    </f:facet>
    <t:outputText value="#{var.names}" />
</t:column>

<t:column>
    <f:facet name="header">
        <h:outputLabel value="Address" />
    </f:facet>
    <t:outputText value="#{var.address}" />
</t:column>

When the "selectedRowIndex" is -1L, that means nothing in the row is selected.
Whenever you need to set the page to no radio selected, then set this value to -1L.
The result should be something like this...
Comment: t:selectOneRow and h:selectOneMenu is alltogether different as well as your answer is not adequate to my question.

including selectOneMenu in datatable


Get the value of an attribute Jquery

Question: Updated Question:
$(this).attr("EmployeeId", 'A42345');

 $.ajax({
       type: "POST",
       url: url,
       data: "{EmployeeId: '" + id + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (response) {
      var obj = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

      var o = obj[$(this).attr("EmployeeId")]; //<<<<undefined

END UPDATE
i am trying to get EmployeeId withitn the DOM something like this:
var o = obj[$(this).attr("EmployeeId")];

but getting undefined
when i debug i see the following:
$(this)[0].data

     data    "{EmployeeId: 'A42345'}"

here is my source code:
$.ajax({
           type: "POST",
           url: url,
           data: "{EmployeeId: '" + id + "'}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
      success: function (response) {
                  var obj = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

                  var o = obj[$(this).attr("EmployeeId")]; //<<<<undefined

Comment: You still haven't given me enough context to see what `this` is. If you are able to assign it, I'm assuming I am correct with my first answer. Did you try what I've suggested?
Answer: this is referring to your function in the example you gave. Therefore your selector isn't matching anything.
I'm guessing you are calling an ajax function from within a click handler or some other type of event handler.
Assign $(this) to a variable in the first function and reference that variable in your success callback.
$(el).click(function() {
    var $this = $(this);
    $.ajax({
       type: "POST",
       url: url,
       data: "{EmployeeId: '" + id + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (response) {
              var obj = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

              var o = obj[$this.attr("EmployeeId")]; //<<<<undefined
// rest of code...

Posting more of your code would help though..
You may also be trying to access the data you were passing in.. in which case, parse it to json, or don't pass it in as a string in the first place.. .attr won't work on $(this) though, as this is referring to the function..
$(this)[0].data is the function's data. Which doesn't have attributes, it's not a DOM element.
You are using some mismatched functionality, it's hard for me to figure out exactly what your intent was.. You said you are trying to get it from the DOM, but you are showing the data of the function, those are two entirely different things.
Comment: also, on an unrelated note, the use of eval is bad.
Comment: and instead of storing "EmployeeId" as an attribute, sotre it as a data- attribute..  ex. `` and use .data("employeeid") to access it.
Comment: you also don't need to send data as a string, `data: {EmployeeId: id},` will work just fine.
Comment: I feel that it is important to explain that in Patrick's example, $this (aka `var self = this`) is a "closure" variable which captures the object reference for use in the callbacks - those values become part of the function object that is passed around since it is declared, referenced within the inner function definition, and the identifier, `$this`, is not reassigned in an intermediate scope.
Comment: it's common to see `var that = this;` which is equivalent to uosɐſ's example of `var self = this;` in javascript, in jquery it's common to see $ before a var name to denote that is already a jquery selector, and it doesn't need to be selected again. Just so if you see any of these, next time you will know.
Comment: Looks like I was right with the first answer, did you try what I've suggested? Though you still haven't given enough context to see what `this` refers to.
Comment: what should i use instead of `eval` ?
Comment: if you return json, you should be able to just access it, if you get a string, you can parse it into json first. Are you using .net (guessing because of the .d)? That's unrelated to this question, and stackoverflow is yelling at me, so I suggest looking elsewhere on stackoverflow, or google about the proper use of eval, or post another question. I'm not saying eval won't work, there are just better and safer ways.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/9973/discussion-between-patrick-scott-and-abu-hamzah)
Answer: I think you have to parse the content of $(this)[0].data to json first.
Maby something like this could work.
var jsonData = jQuery.parseJson($(this)[0].data);
var o = jsonData.EmployeeId;

Get the value of an attribute Jquery


Prove that $p^2 | (p!+p)$ for any prime $p.$

Question: Prove that $p^2 | (p!+p)$ for any prime $p.$
So far I have: If $p$ is prime, then $p$ divides $[(p-1)!+1].$ Therefore
$(p-1)!+1\equiv 0 \operatorname{mod}p.$ Where do I go from there?
Comment: If $a\mid b$ then $ac\mid bc$.
Answer: $(p-1)!+1=0 \pmod p$ is Wilson's theorem.
Answer: multiplying both sides by $ p $
to get
$$ p(p-1)! + p = p( p n) $$
where  $n$ is natural number
hence
$$ p! + p = p^2 n $$
Answer: We have $(p-1)!=px-1$ where $x\in \Bbb Z.$ Therefore $p!+p=p\cdot (p-1)!+p=p(px-1)+p=p^2x.$
Comment: An easy proof of Wilson's Theorem: Let $G$ be a finite commutative group. Let $P$ be the product of all the members of $G$. Members of $G$ that are not their own inverses come in pairs ($x$ & $x^{-1}$) that cancel each other in $P$. So $P$ is the product of those $x\in G$ that are their own inverses. If  $p$ is prime and $G=\{1,...,p-1\}$ with multiplication mod $p$, then the only members of $G$ that are their own inverses are $1$ and $p-1.$


Undefined method 'bool' during migration (Rails Heroku Postgres)

Question: I have a locally-developed app that is working fine on postgres, however, once I uploaded it to heroku, I'm receiving an error in the migration:
undefined method `bool' for #<ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition:0x007fb335472530>/app/db/migrate/20150603202509_devise_create_admins.rb:5:in `block in change'

Line 5 of the referenced migration:
t.boolean :manage_users, default: false

I didn't have any problems locally, just now that it's on heroku. Using pg v0.18.2
Comment: Which versions of postgres and the pg gem are you using? Make sure they are compatible with heroku ;)
Comment: Using `pg v0.18.2` which is the same as another working heroku app. And yes, the migration is being ran on the `t.boolean` line above, which I too thought was strange because it mentioned the "bool" method.
Answer: I ran into this error too.
I did this to cause the error:
$ rails generate scaffold MyObject isGreen:bool

I fixed it by changing bool to boolean:
$ rails generate scaffold MyObject isGreen:boolean


Determine the sample size, statistics

Question: My professor sent us a homework question that had me puzzled. The homework consisted of four questions that were related and fifth one that is totally independent of the first four. The first four dealt with High School test scores so none of their data is applicable to the fifth. This is the fifth question.
"5.    How large must the sample size be for 95% CI to lie w/in ± 4 mg/100ml of the population mean, μ.
To answer the last question, note the following:
Xbar= μ ± m (margin or error)       where m = Z σSDOM = Z (S^ / √N)
Therefore
<code>         N = Z^2(S^)2/m2        "
</code>
I have Z = 1.96 and m =8. I think it is eight because plus or minus 4 totals up to 8. I could be wrong about that part. I have no idea where to get S hat (SD for the population). He did not include any X values or a mean with the homework assignment. I am completely stumped. After several hours of research I found a very crude approximation for the SD. It is SD = Range/4. He did not mention this in class so I am hesitant to use it. I see no way to solve this without the SD or at least some approximation. As mentioned before, the only information I was given is quoted above.
Answer: Professor meant 4 for the margin of error and not the mg/ 100ml part. Otherwise there was no way to solve this. He's an awesome professor but we all make mistakes.

Determine the sample size, statistics


Prove that if $3|a^2+b^2\Rightarrow 3|a ,\, 3|b$

Question: How do i prove that if $$3|a^2+b^2\Rightarrow  3|a ,\, 3|b \,?$$ The book (Problem-Solving Strategies by Arthur Engels, page 43, E9) does not prove this theorem and leaves it as an excercise. I'm relatively new to this kind of problems and I just can't get any ideas. If anyone could prove that or, even better, just give me some hints it would be great. Thanks for your time
Comment: Hint: the number $a$ can be written as $a=3k+m$, where $k$ is an integer and $m$ is $0,1,$ or $2$. If you square $a$, we can further write $a^2=3k_2+m_2$ for new integers. If you know $m$, what is $m_2$?
Answer: Assume $a = 3A + r_1$ and $b = 3B + r_2$ where $r_1$ and $r_2$ are remainders. Then $$a^2+b^2 = 3C + r_1^2 + r_2^2$$
Therefore, if $3\mid a^2+b^2$, then $3 \mid r_1^2+r_2^2$. Since $r_1,r_2 \in \{0,1,2\}$, it is easy to verify that $r_1 = r_2 = 0$.
Comment: Please strive not to add more dupe answers to dupes of FAQs.


Pycharm console startup script not working

Question: I'm using PyCharm Community Edition 4.0.4 on a Macbook running Mavericks. Under Preferences > Build, Execution, Deployment > Console > Python Console there is a text area to input a starting script. Initially it contains import sys; followed by a print statement that prints the file path of the Python framework as well as the file path of the current file. However, when I alter or delete the print statements in this section, and then hit apply and OK, nothing changes in my python console output. I have tried restarting Pycharm and then running a hello world program, but the initial starting script output is still there.
I am just running a simple hello world program, with one package and two files (the other being the default __init__.py). How can I alter the starting script correctly?
Comment: Do you mean the console in the "Python Console" window or the one in the "Debug" window?  It seems that the starting script specified is not run upon starting the "Debug" console.
Comment: I modified the contents of the startup script section under my python console, then hit "reload" on the console.  This did nothing to my suprise!  However, I found that closing the console with the big red X and then reopening it did cause it to run the code from that block.  Hopefully that'll be helpful.
Comment: And why is that, I wonder?
Comment: Does anyone know why the "Starting script" is not loaded in debug more?
Answer: You want to change the startup scripts then. Change called "Starting Script":
Comment: Where is "Starting Script"? I don't see it in the screenshot.
Comment: @flow2k It's the title of the edit box where the code is.


ios6 UIImageView - Loading -568h image

Question: I've seen a couple posts about the UIImage automatically loading the filename-568.png image in the new iOS6, but I can't seem to recreate it in the UIImageView class.
I'm using the Storyboard (not my app, just having to do some checks), and I've a simple layout with just the Image View scaled to fit, no code in the view controller, and I've sure the filename.png and filename-568h.png exist (as well as -email@example.com just in case) but when I load it up in the iOS6 simulator. This has been for iOS 4 and 5, loading the @2x image for retina, doesn't seem to work in iOS6 though. Any ideas?
The image happens to be called Default.png since it is the same as the launch image, could this be the issue?
Thanks for any help in advance
Comment: I found answer here:
- http://stackoverflow.com/questions/12532405/images-for-iphone-5-retina-display
- http://stackoverflow.com/questions/12431445/iphone-5-what-naming-convention-the-new-images-have-to-follow
Answer: iOS6 does NOT automatically load -568h as it does with the @2x images. The only exception is the default screen, but further than that you have to manually set you 568h image yourself.
I created some code to mimic the loading behavior for -568h images when using the <code>[UIImage imageNamed:@""]</code> method, but from the IB I do not know the way. If you are interested in such a solution, check it out at http://angelolloqui.com/blog/20-iPhone5-568h-image-loading
Comment: I tried your code and whilst it works fine in the simulator, it does not compile for a real device.  The #include of  fails to compile.
Comment: Regarding the recursive loop. Check it out that I am swizzling the methods, so the recursive loop that you see is not a recursive loop! it is actually the call to the original method. Just include the class in your project and use everything as you used to. No need to change your code because the methods as I explained are swizzled, and it performs better because this only happens on iPhone5 devices.
Comment: You may want to see the information in the selected answer for this question on how to handle loading of these images from Interface Builder.  http://stackoverflow.com/questions/10398547/are-images-assigned-in-a-xib-cached
Comment: Actually, I've found that if I specify the image within IB as say "image.png", then no matter what type of phone simulator I use, it loads the correct file, [@2x] for 3.5" retina, and [-568h@2x] for 4" retina.

If I try to code it myself using [UIImage imageNamed:] then it doesn't work.

Odd.  I'm going to have to do the same as @Angel Garcia Olloqui above.
Comment: I don't get one thing in the code: returning the same method at the end, doesn't create a recursive loop ?
Comment: I noticed that too.  I suspect the recursion is handled, but I removed it in any case to reduce risk.  Due to my issue with the device based build, I've turned it into a simple category and just call the imageNamed568h instead from within my app.   I know that swizzling seems neat, but I'm not a fan.
Comment: Thanks for the comments. I just updated the code to include #include  instead of the header that was having problems for device. It should work now.
Comment: No, it doesn't create recursive loop. The method actually refers to the old one, this shit happens at run time so everything works out.
Answer: Typically, you should only use 568h for the launch image. If you notice yourself using different image assets within your app for the new display height, you should consider that you might be making your UI too static.
The most obvious place people want to use 568h for images is for background images. An alternative is to just have one asset that has the largest possible dimensions and align it properly using the contentMode property of UIView.
But perhaps you have something floating in the image at the top and the bottom, so contentMode doesn't solve it. You could consider that the top and bottom floaters should probably be separate views anyway.
Remember, we have always been making apps with variable heights. Every time a keyboard pops up, its as if the size of the screen has shrunk.
Comment: I don't agree with your last sentence, the keyboard is shown on top of a view, it does not shrink the view at all. It would make sense that iOS properly detects -568h resources, since it does handle @2x images and the OS itself needs the -568h for splash screen. I think it forces us to write horrible code to handle iPhone 5 screen ratio.
Comment: If you feel Apple is forcing you "to write horrible code", you should probably step back and see if you are needlessly violating any Apple conventions. In iOS, that typically results in more work, less payoff.

ios6 UIImageView - Loading -568h image


Solving second-degree diophantine equation

Question: I'm interested in the following Diophantine equation:
$y^2 - y - x^2 + x = 2xy$
I've managed to find some solutions like $(6, 15)$ and $(35, 85)$, but I need some general method of solving this type of equations. As I understood, it's a hyperbola, which makes it harder to study.
Any help?
Comment: I think you meant $x^2$ where you typed $x^x$
Answer: The equation can be solved for either variable in terms of the other by $y$ is easier than x.
$$y = \frac{\pm\sqrt{8 x^2 + 1} + 2 x + 1}{2}\rightarrow$$
$$ x\in\{0,1,6,35,204,1189,5008,40391...\}\implies
 y\in\{1,3,15,85,493,2871,16731,97513...\}$$
I believe these are all the integer pairs for $x\le100000$.
Comment: cf. [oeis](http://oeis.org/A001109)
Answer: Solution is:
$x=m(1-2n)$
$y=mn$
Where:
$m=(3n-1)/(n^2+2n-1)$
For, $n=(5/12)$  we have:
$(x,y)=(6,15)$
Answer: $y^2 - y - x^2 + x = 2xy \implies (2 y - 2 x - 1)^2 - 2 (2 x)^2 = 1$
This Pell equation.
gp-code:
<code>pell_d2c1()=
{
 D= 2; C= 1;
 Q= bnfinit('x^2-D, 1);
 fu= Q.fu[1]; \\print("Fundamental Unit: "fu);
 N= bnfisintnorm(Q, C); \\print("Fundamental Solutions (Norm): "N"\n");
 for(i=1, #N, ni= N[i];
  for(j=0, 48,
   s= lift(ni*fu^j);
   X= abs(polcoeff(s, 0)); Y= abs(polcoeff(s, 1));
   if(X^2-D*Y^2==C,
    x= Y/2; y= (X+2*x+1)/2;
    if(x==floor(x) & y==floor(y),
     print("("x", "y")")
    )
   )
  )
 )
};
</code>
Some first solutions:
<code>(0, 1)
(1, 3)
(6, 15)
(35, 85)
(204, 493)
(1189, 2871)
(6930, 16731)
(40391, 97513)
(235416, 568345)
(1372105, 3312555)
(7997214, 19306983)
(46611179, 112529341)
(271669860, 655869061)
(1583407981, 3822685023)
(9228778026, 22280241075)
(53789260175, 129858761425)
(313506783024, 756872327473)
(1827251437969, 4411375203411)
(10650001844790, 25711378892991)
(62072759630771, 149856898154533)
(361786555939836, 873430010034205)
(2108646576008245, 5090723162050695)
(12290092900109634, 29670908962269963)
(71631910824649559, 172934730611569081)
(417501372047787720, 1007937474707144521)
</code>
Comment: Nice, how did you come up with this difference of squares? Also, what kind of language is this?
Comment: Like [that](https://math.stackexchange.com/a/3650361/602207). And this lang of [pari/gp](https://pari.math.u-bordeaux.fr) calculator.
Comment: It's interesting to note that quotient of those solutions approach $\frac{1}{1 + \sqrt2}$


How do I upload photos to Instagram with python since Instagram shutdown its API service

Question: How do I upload photos to Instagram with python and selenium without Instagram API
Comment: there are alternatives ... (eg https://github.com/LevPasha/Instagram-API-python)
Answer: You can use Selenium (specifically Chromedriver) in mobile emulation mode to upload photos. Here's a good example: https://github.com/atloftus/IGF
specifically look at the uploadPhoto method. Hope this helps


How do I add a value to all rows in a column if the column name contains a specific value

Question: I have a data frame that looks like this:

City
Cars
Col 1
Col 2
Col 3

Madrid
550000
0
0
2

London
783993
1
3
0

I want to add +1 to all of the columns that contain 'Col' in their title. So the df looks like this:

City
Cars
Col 1
Col 2
Col 3

Madrid
550000
1
1
3

London
783993
2
4
1

My issue is that I have 2000 columns with names from 'Col_1' to 'Col_999'
I was only able to add +1 to all of the columns by using df["Gene1"] = df["Gene1"] + 1
This is unsuitable because I have 2000 columns.
Answer: You can do
df[[col for col in df if col.startswith('Col')]] += 1

Answer: You can also do:
df = df.filter(like="Col")

#or

df = df.filter(regex='Col')

then,
df+1

Answer: Here is an option:
df = df.assign(**df.filter(regex='^Col').add(1))

Output:
     City    Cars  Col 1  Col 2  Col 3
0  Madrid  550000      1      1      3
1  London  783993      2      4      1


User registration form throws validation errors on already unset profiles´ fields

Question: Using Drupal 7 with Profile2: I have a number of profile types, with different fields, some of which I want a registrant to already fill up during the registration process. I´ve checked "Show during user account registration" for all. In my custom module, I´m first taking the registrant´s choice of profile, then unsetting (unset(); also tried hide() and ...[#access]=FALSE) all the other profiles and then rendering the registration form. This 'shows up' correctly because I only get to see the chosen profile fieldset. However, when I submit the form I get validation errors (required fields) on the unset profiles´ fields. So apparently only unsetting/hiding/etc. won´t do the trick. What am I missing?
Appreciate any help!
Best,
Mir
Comment: Have you looked at this post: [Restrict profile2 type per roles](https://www.drupal.org/node/1593230). It allows for profile2 types to be restricted per role.
Answer: The Profile2 Registration Path module  solves the issue!

This module enables administrators to set unique registration paths per Profile2 profile type.
Comment: thanks Krishna, was too excited, thus failing to follow post decorum :)


How to calculate total work & break hours from logins and logouts in excel?

Question: I need to calculate the total work hours and break hours of each employees from their Logins and Logouts. In excel sheet i am having hundreds of login and logout record of employees in the format mentioned below (image). I need a way to calculate the working hours and break hours.
Any help would be appreciated.
Excel
Answer: Your question is a bit broad but I will have a go at answering it in it's current state:
Where E2 is the ID:
<code>=SUMIFS($B$2:$B$7,$C$2:$C$7,"Logout",$A$2:$A$7,E2)-SUMIFS($B$2:$B$7,$C$2:$C$7,"Login",$A$2:$A$7,E2)</code>
This is a simple total time of logouts minus total time of logins, this will work assuming there are equal number of Logins vs Logouts.


Modes: More complicated than it seems?

Question: I've been playing guitar for almost 12 years now. I had never really gotten into what is described as 'modal playing'; I tried years ago and it seemed so hopelessly complicated that I abandoned it.
Recently I returned to the topic, curious if my experience through the years has changed my understanding. Surprisingly, I found that (from what I understood) the concept is actually extremely simple.
Consider the following 3-note per string major scale:

This is known as the Ionian mode. Playing these same notes (compensating at the higher end to make it a full two octaves) starting at the second scale degree gives you Dorian, third gives you Phrygian and so forth.
People write about 'playing in the right mode' against specific chords -- is there anything to this other than simply emphasizing a particular note? Is there some fundamental knowledge that I'm missing that transforms this into something bigger, or is 'modal playing' really just emphasizing a particular note compared to the accompaniment behind it?
Answer: Yes, the concepts are simple.  Each mode keeps the tonality of the diatonic parent scale but starts / ends on different notes.  For example:
Parent Scale / Ionian
- C D E F G A B C
Dorian
- D E F G A B C D
Phrygian
- E F G A B C D E
etc through all of the other scale degrees.
When people discuss "playing in the right mode", they are talking about using harmony / scales for the situation.  Let's look at how we can apply our knowledge of modes to playing / creating music.
Ex. Scale
 - C D E F G A B C
From our Ionian scale, we can derive our three most common chords: C (I)(CEG), F (IV)(FAC), and G (V)(GBD).  If the rhythm guitarist played that chord progression, you could use the Ionian scale to solo over all the changes.  Or, to further your playing, you could "play" the changes.  This means that while using the Ionian mode, you emphasize appropriate chord tones during that same chord in the progression.  Let's take a look in Mixolydian mode.
Ex. Scale - G A B C D E F G (Mixolydian)
Our "I" chord is G (GBD), "IV" is C (CEG), and "V" is Dm (DFA).
Let's say our chord progression went like this: I-V-IV-I
On "I" you would emphasize the notes GBD, on "V", DFA, and on "IV", CEG.

Now, how to know when to play in the right mode.  All it takes is a little more analysis on your part.  Analyze the chord and see which scale fits the chord the best.  Example:
Dm7 = D F A C
Scale = D Dorian (D E F G A B C D)
Fm11 = F Ab C Eb G Bb
Scale = F Dorian (F G Ab Bb C D Eb F)
n.b. Aeolian would also work here just fine and give you a little extra flavor in your playing with the altered sixth degree added.
Em7(b9) = E G B D F
Scale = E Phrygian (E F G A B C D E)
You can also use chromatic approach notes to smooth chord changes.  For example, if going from Fm11->Em7(b9), you could use F aeolian, scoot Db->D->Eb->E->F chromatically to join the two chords and create some tasty dissonance.
Comment: Just a thought. Would, for example, D Dorian 'keep the tonality of the diatonic parent scale' (1st para.), -  C major -  or take on its own tonality more leaning towards D minorish?
Comment: @Tim Great question. The aural implication would definitely lean towards D minorish.  My statement about "keeping the tonality" was  specific to the idea that to play modes in a given key, you shouldn't have to *alter* anything (e.g. non-diatonic notes).  So, while the Final and tonal center are shifted to the new note, the overall tone-region would stay relatively the same.
Comment: When you say 'play modes in a given key' I guess you mean parent key. For me, a lot of modal stuff can easily gravitate towards the parent major key, often only needing that V or V7 to tip the balance. Tone-region/tonal centre/tonality - synonyms?
Comment: @Tim Yes, parent key. All seven modes with parent scale being C Ionian, for example.  Same tonal region, 6 additional tonal centers. You're correct, this is one reason why musica ficta was common practice for many years.  "Tone-region" is like your neighborhood.  "Tonal center" is like your house. "Tonality" is like the fact you *live* in a house, as opposed to outdoors.
Answer: You are right in the way modes can be explained. Using Ionian as a basis - the full major as we know it now, sounds 'right' when we start and finish on the root note/chord. When we use the same set of notes, but use the 6th note/chord as 'home', we think of being in a minor key. This actually often has a sharpened leading note, which makes the change back to 'home' more convincing. It also stops it being the Aeolian mode, and makes it either harmonic or melodic minor.
Each mode will sound major or minor, depending on its 3rd. Dorian and Phrygian are minor. Lydian and Mixolydian are major.
Modal music works pretty well like what we're used to, starting from 'home' and ending there too. So, yes, reference 'home' often, and keep away from the almost inevitable push that may well lead back to the parent key. As in G Mixolydian, the dominant 7th sound tries to push back to the parent key of C major. As with Aeolian, most of the modes have no semitone away from tonic leading note, so it's not quite so convincing getting 'home'.
Listen to a lot of Celtic music - using Dorian and Mixolydian modes, to hear how it works.

Modes: More complicated than it seems?


Output Checked Items in Javascript Using Confirm()

Question: I am trying to output the selected checked items from my list (I am using checkboxes) on the alert message on my page. Essentially, when the user hits the Delete button, I want a confirmation box to pop up and show the user which items they have selected to confirm it's correct (in this case, Serial Numbers). By default, all checkboxes are false (unchecked). If a checkbox is checked, the checkbox variable = true. Below is the function I wrote to do this:
function validateDeleteForm() {
        var checkboxs=document.getElementsByName("pickSerial");
        var okay=false;

        for(var i=0,l=checkboxs.length;i<l;i++)
        {
            if(checkboxs[i].checked)
            {
                okay=true;
            }
        }
        if(okay)
            {
                if (confirm("Do you want to delete the selected Serial Number(s) from casting? Hit OK to Delete or CANCEL to re-select: " + this.checkboxs ) == true) { // this will delete selected serial numbers and display
                    return true;
                }
                //return true;
                else { // this will cancel the delete dialogue and allow user to re-select
                    return false;
                }
            }

        else {
            alert("You have at least one line to be checked");
            return false;
        }
    }

Does anyone see what I am doing wrong? I have tried referencing the checked items doing checkboxs[i].value, this.checkboxs[i], and calling the checkboxs variable but they all show as undefined.
Here is a screenshot of the output currently.
Thank you for any help.
Answer: Using querySelectorAll you can right away select all of the checked elements. There is no need to have to loop to find the check ones with this. You can then turn the html collection into an array to get all of the values. You can then use that array to display the info to the use.
const cbs = Array.from(document.querySelectorAll('[name="pickSerial"]:checked'));
const serials = cbs.map(function (cb) { return cb.value; });
if (serials.length) {
  console.log(serials.join(",");
}

Comment: so you're saying I should create two new variables and instead of using a for loop to iterate through each element, just store them all into the array cbs and use that to grab the checked elements in my Confirm() function?
Comment: thank you for the help,  your answer helped me getting this working how I wanted. You're the best :D
Answer: Adding to your solution, you can create an array to track checked items and then when printing, just use that array
Sample
const checked = [];
// When you are setting okay = true, push that value in checked
checked.push(checkboxs[i].value)

// Now when you are showing it in confirm box just join the array
confirm('text ' + checked.join(', '))

Hope that helps.


How to assure that we still are in feasible set during optimization iterations?

Question: What are methods to force the point remains in the optimization domain ,other than taking projection step after each iteration?I haven't find any other solution for this but this projection step seems to slow down the algorithm.The problem is minimizing $f(x)+g(z)$(using ADMM method) such that $Ax+Bz+b=0$ and $g$ is the indicator function of a set $c$,and I mean that in iterations some time $z$ is not in $c$ as a result $g(z)$ becomes infinity and the algorithm give back $z=NaN$, so I need to turn back into c after each iteration.any hint would be appreciated.
Comment: Provide more details.
Comment: @OnceUponACrinoid Every time the point pop out the feasible set I have to calculate it's projection on the feasible set which is an optimization problem itself,I wonder if there is some more efficient way to deal with this situation
Comment: @MAh2014 what algorithm are we looking at? Limiting the step length is another common method.
Comment: in ADMM, the linking constraints (that link the two sets of variables from the two terms of the objective function) will typically not be satisfied during the iterations.  Are you talking about those constraints or some other constraints?  Please give us your problem and describe the method you're trying to use to solve it.
Comment: Please edit your question to include all of these details.
Comment: @BrianBorchers I just added the details.
Answer: When $g(z)$ is the indicator function of a convex set $C$, then in the associated minimization step of the ADMM method, you'll be finding a $z$ in $C$ that also minimizes the augmented Lagrangian term
$\min_{z \in C} \frac{\rho}{2} \| Bz - (Ax+b) \|_{2}^{2}$
This is the minimization of a quadratic function over $C$.  Your procedure for doing this must return a $z$ in $C$.  There aren't any other steps of the algorithm that would change $z$.


Solve the binomial equation

Question: Solve the binomial equation $$z^4 = -8$$
Below is the steps i have done
1: I have taken  |-8| that is 8 and then done 8^(1/4) which is 2^(1/4).
2: Since $z=r(cos\alpha+isin\alpha)$ leads me to
$r^4(cos4\alpha+isin4\alpha)=-8(cos\pi/2+isin\pi/2)$
Divide by 4 since the z term is raised by four gives $2^{1/4}(cos\pi/8 + k * \pi/2 +sin\pi/8 + k * \pi/2) $
Is this the correct way to solve this problem ? I am asking since i just started with binomic equations and been stuck for some hours with the question.
Comment: See http://math.stackexchange.com/questions/192742/how-to-solve-x3-1
Answer: Another approach that is an efficient way forward is to exploit Euler's Identity and  write
$$z^4=r^4e^{i4\theta}=-8=8e^{i(2n+1)\pi}$$
for all integer $n$.  Thus, upon inverting we have for $z$
$$z=re^{i\theta}=2^{3/4}e^{i(2n+1)\pi/4}$$
for $n=\pm 1, \pm 3$.  Therefore, the $4$ roots of $z$ are
$$\bbox[5px,border:2px solid #C0A000]{z=2^{3/4}e^{\pm i\pi/4}\,\,\text{and}\,\,2^{3/4}e^{\pm i3\pi/4}}$$
or in rectangular form
$$\bbox[5px,border:2px solid #C0A000]{z=2^{1/4}(1\pm i)\,\,\text{and}\,\,2^{1/4}(-1\pm i)}$$
Comment: Please let me know how I can improve my answer.  I really just want to give you the best answer I can>
Answer: $$ z^4 = -8 \Longleftrightarrow $$
$$ z^4 = |-8|e^{\arg(-8)i} \Longleftrightarrow $$
$$ z^4 = 8e^{\pi i} \Longleftrightarrow $$
$$ z^4 = 8e^{\left( \pi + 2 \pi k \right) i} \Longleftrightarrow $$
$$ z = \left( 8e^{\left( \pi + 2 \pi k \right) i} \right)^{\frac{1}{4}} \Longleftrightarrow $$
$$ z = \sqrt[4]{8}e^{\frac{1}{4}\left( \pi + 2 \pi k \right) i} \Longleftrightarrow $$
$$ z = \sqrt[4]{8}e^{\left( \frac{\pi}{4} + \frac{\pi k}{2} \right) i} \Longleftrightarrow $$
$$ z = \sqrt[4]{8}e^{\frac{\pi(2k+1)}{4} i}  $$
With $k \in \mathbb{Z}$ and $k$ goes from $0-3$

So the solutions are:
$$z_0=\sqrt[4]{8}e^{\frac{\pi(2 \cdot 0+1)}{4} i}=\sqrt[4]{8}e^{\frac{\pi}{4}i}$$
$$z_1=\sqrt[4]{8}e^{\frac{\pi(2 \cdot 1+1)}{4} i}=\sqrt[4]{8}e^{\frac{3\pi}{4}i}$$
$$z_2=\sqrt[4]{8}e^{\frac{\pi(2 \cdot 2+1)}{4} i}=\sqrt[4]{8}e^{-\frac{3\pi}{4}i}$$
$$z_3=\sqrt[4]{8}e^{\frac{\pi(2 \cdot 3+1)}{4} i}=\sqrt[4]{8}e^{-\frac{\pi}{4}i}$$
Answer: Notice, $$z^4=-8$$
$$z^4=8i^2$$ $$z=\sqrt[4]{8i^2}$$
$$z=(2)^{3/4}\sqrt{i}$$ $$z=(2)^{3/4}\sqrt{\cos\frac{\pi}{2}+i\sin\frac{\pi}{2}}$$
$$=(2)^{3/4}\left(\cos\frac{\pi}{2}+i\sin\frac{\pi}{2}\right)^{1/2}$$
$$=(2)^{3/4}\left(\cos\left(2k\pi+\frac{\pi}{2}\right)+i\sin\left(2k\pi+\frac{\pi}{2}\right)\right)^{1/2}$$
$$=(2)^{3/4}\left(\cos\left(\frac{(4k+1)\pi}{2}\right)+i\sin\left(\frac{(4k+1)\pi}{2}\right)\right)^{1/2}$$
$$=(2)^{3/4}\left(\cos\left(\frac{(4k+1)\pi}{4}\right)+i\sin\left(\frac{(4k+1)\pi}{4}\right)\right)$$
Setting $k=0$, we get $$z=(2)^{3/4}\left(\cos\left(\frac{\pi}{4}\right)+i\sin\left(\frac{\pi}{4}\right)\right)$$
$$=(2)^{3/4}\left(\frac{1}{\sqrt 2}+i\frac{1}{\sqrt 2}\right)$$
$$z=(2)^{1/4}\left(1+i\right)$$
Setting $k=1$, we get $$z=(2)^{3/4}\left(\cos\left(\frac{5\pi}{4}\right)+i\sin\left(\frac{5\pi}{4}\right)\right)$$
$$=(2)^{3/4}\left(\frac{-1}{\sqrt 2}+i\frac{-1}{\sqrt 2}\right)$$
$$z=-(2)^{1/4}\left(1+i\right)$$
$$\bbox[5px, border:2px solid #C0A000]{\color{red}{z=(2)^{1/4}\left(1+i\right),\  z=-(2)^{1/4}\left(1+i\right)}}$$
Comment: Could someone please explain the reason for what is wrong in the answer?

Solve the binomial equation


Problem generator docxtpl flask - not work save file

Question: I have a problem with my code.
I'm trying to create a docx generator with docxtpl and flask, but I can't get it to work. My intention is to download the file generated with the information acquired from the form.
Here is the code in app.py:
from docxtpl import DocxTemplate
from flask import Flask, render_template, request, redirect, send_from_directory, url_for, send_file

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST',])
def index():
    # generate_report()
    return render_template('index.html')

@app.route('/', methods=['GET', 'POST']) # When the user click to the "submit" button
def download_file():
    if request.method == 'POST':
        result = request.form
        doc = DocxTemplate("templates/template_procuracao.docx")
        context = {
        'autor':result['autor'],
        'nacionalidade':result['nacionalidade'],
        'estadocivil':result['estadocivil'],
        'identidade':result['identidade'],
        }
        doc.render(context)
        doc.save()
        return send_file('templates/output',
        attachment_filename='teste.docx',
        as_attachment=True)

if __name__ == '__main__':
    app.run()

Here is the code in index.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <form action="{{ url_for('index') }}" method="post">
        <input type="text" id="autor" name="autor" placeholder="AUTOR">

        <input type="text" id="nacionalidade" name="nacionalidade" placeholder="NACIONALIDADE">

        <input type="text" id="estadocivil" name="estadocivil" placeholder="ESTADOCIVIL">

        <input type="text" id="identidade" name="identidade" placeholder="IDENTIDADE">

        Submit
    </form>

after clicking the submit button nothing happens.
127.0.0.1 - - [06/Apr/2022 21:00:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Apr/2022 21:00:33] "GET / HTTP/1.1" 200 -
Answer: When you save your document you need to save it in memory to essentially create a file to send (unless you want to save it as a file and then load it again). You are also trying to send a file 'templates/output' and not the document you'd created.
from io import BytesIO

...
def download_file():
    ...
    docx_in_memory = BytesIO()
    doc.render(context)
    doc.save(docx_in_memory)

    docx_in_memory.seek(0)

    return send_file(
        docx_in_memory,
        attachment_filename='teste.docx',
        as_attachment=True)


Objective-C Mutable subclass pattern?

Question: Is there a standard pattern for implementing a mutable/immutable object class pair in Objective-C?
I currently have something like the following, which I wrote based off this link
Immutable Class:
@interface MyObject : NSObject <NSMutableCopying> {
    NSString *_value;
}

@property (nonatomic, readonly, strong) NSString *value;
- (instancetype)initWithValue:(NSString *)value;

@end

@implementation MyObject
@synthesize value = _value;
- (instancetype)initWithValue:(NSString *)value {
    self = [self init];
    if (self) {
        _value = value;
    }
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [[MyMutableObject allocWithZone:zone] initWithValue:self.value];
}

@end

Mutable Class:
@interface MyMutableObject : MyObject
@property (nonatomic, readwrite, strong) NSString *value;
@end

@implementation MyMutableObject
@dynamic value;

- (void)setValue:(NSString *)value {
    _value = value;
}

@end

This works, but it exposes the iVar. Is there a better implementation that remedies this situation?
Comment: Your implementation is the "standard" pattern however it is not what Apple actually uses for most of their mutable classes. They mostly use class clusters as @HotLicks talked about which are extremely complicated and you almost certainly do not want to go down that road, unless you're facing serious performance problems (as some people do with NSString and NSArray). Beware that if self.value was a mutable class, you would have to make a copy of it inside `mutableCopyWithZone:`.
Comment: Note that iOS has several different implementations of NSArray, for example, and some of them are (temporarily) mutable -- the object is created, it's populated (with separate operations), and only then is the object marked immutable.  Exactly how they do this is unclear, though -- it's part of the great mystery of class clusters.
Comment: My question is, are you looking to provide mutable and immutable versions of your class because you want there to be a distinction between the two as part of an API, or do you want to be able to modify your—otherwise immutable—object internally without accessing instance variables? If it's the first, consider why that would be necessary. If it really is, class clusters are an option, but they're not a great design pattern for unless it's really necessary, as @AbhiBeckert mentioned.
Comment: @HotLicks That's not _quite_ how `NS{Mutable}Array` works (believe me, however complicated you think the implementation is, it's at least 100x more complicated and gross, but damn it's fast), but I think you've captured a little bit of the ugliness of class clusters. There's really no good way to make them pretty (unless your class is somewhat trivial, and the majority of the implementation doesn't change between the mutable and immutable versions).
Comment: @ItaiFerber - Yeah, like sausages and laws, NS{Mutable} objects are something you should not watch being made.
Answer: Your solution follows a very good pattern: the mutable class does not duplicate anything from its base, and exposes an additional functionality without storing any additional state.

This works, but it exposes the iVar.

Due to the fact that instance variables are @protected by default, the exposed _value is visible only to the classes inheriting MyObject. This is a good tradeoff, because it helps you avoid data duplication without publicly exposing the data member used for storing the state of the object.
Answer:
Is there a better implementation that remedies this situation?

Declare the value property in a class extension. An extension is like a category without a name, but must be part of the class implementation. In your MyMutableObject.m file, do this:
@interface MyMutableObject ()
@property(nonatomic, readwrite, strong) value
@end

Now you've declared your property, but it's only visible inside your implementation.
Answer: The answer from dasblinkenlight is correct.  The pattern provided in the question is fine.  I provide an alternative that differs in two ways.  First, at the expense of an unused iVar in the mutable class, the property is atomic.  Second, as with many foundation classes, a copy of an immutable instance simply returns self.
MyObject.h:
@interface MyObject : NSObject <NSCopying, NSMutableCopying>

@property (atomic, readonly, copy) NSString *value;

- (instancetype)initWithValue:(NSString *)value NS_DESIGNATED_INITIALIZER;

@end

MyObject.m
#import "MyObject.h"
#import "MyMutableObject.h"

@implementation MyObject

- (instancetype)init {
    return [self initWithValue:nil];
}

- (instancetype)initWithValue:(NSString *)value {
    self = [super init];
    if (self) {
        _value = [value copy];
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    // Do not use the iVar here or anywhere else.
    // This pattern requires always using self.value instead of _value (except in the initializer).
    return [[MyMutableObject allocWithZone:zone] initWithValue:self.value];
}

@end

MyMutableObject.h:
#import "MyObject.h"

@interface MyMutableObject : MyObject

@property (atomic, copy) NSString *value;

@end

MyMutableObject.m:
#import "MyMutableObject.h"

@implementation MyMutableObject

@synthesize value = _value; // This is not the same iVar as in the superclass.

- (instancetype)initWithValue:(NSString *)value {
    // Pass nil in order to not use the iVar in the parent.
    // This is reasonably safe because this method has been declared with NS_DESIGNATED_INITIALIZER.
    self = [super initWithValue:nil];
    if (self) {
        _value = [value copy];
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    // The mutable class really does need to copy, unlike super.
    return [[MyObject allocWithZone:zone] initWithValue:self.value];
}

@end

A fragment of test code:
NSMutableString *string = [NSMutableString stringWithString:@"one"];
MyObject *object = [[MyObject alloc] initWithValue:string];
[string appendString:@" two"];
NSLog(@"object: %@", object.value);
MyObject *other = [object copy];
NSAssert(object == other, @"These should be identical.");
MyMutableObject *mutable1 = [object mutableCopy];
mutable1.value = string;
[string appendString:@" three"];
NSLog(@"object: %@", object.value);
NSLog(@"mutable: %@", mutable1.value);

Some debugging right after the last line above:
2017-12-15 21:51:20.800641-0500 MyApp[6855:2709614] object: one
2017-12-15 21:51:20.801423-0500 MyApp[6855:2709614] object: one
2017-12-15 21:51:20.801515-0500 MyApp[6855:2709614] mutable: one two
(lldb) po mutable1->_value
one two

(lldb) po ((MyObject *)mutable1)->_value
 nil

As mentioned in the comments this requires discipline in the base class to use the getter instead of the iVar.  Many would consider that a good thing, but that debate is off-topic here.
A minor difference you might notice is that I have used the copy attribute for the property.  This could be made strong instead with very little change to the code.

Objective-C Mutable subclass pattern?


How to block the UI thread from another thread or force a form to run within the UI thread

Question: A requirement for my application is if it looses database connectivity then it must pop up a big modal "No Connection.  Try again later" dialog blocking all user interaction until such time that connectivity is regained.
I achieve this by at the start of the application starting an instance of a DeviceMonitor class.  This class creates a System.Threading.Timer and every Tick (usually 1 second) along with a few other things it tries to draw data from the database.  If the draw fails and the cause is determined to be due to a lack of connectivity, the exception is handled by popping up the aforementioned dialog.  Likewise, if the data fetch succeeds and the dialog is currently up hen it is forced closed.
The problem is that although this all works fine, the ConnectionLost dialog does not block the user from interacting with the UI.  This makes sense, since the Timer.Elapsed event is raised within its own thread and  noConnectionDialog.ShowDialog() is called from within the callback it blocks the thread it is on but not the UI Thread.
To my understanding I need to either force the noConnectionDialog.ShowDialog() to run within the UI thread or to block the UI thread until noConnectionDialog.Hide() is called but I don't know how to do either.
Perhaps there is some other remedy or I am missing something here.  Any advice is appreciated.
EDIT: Further information - this is a stylized dialog, not just a messagebox.  It is being created when my application starts by Castle Windsor and injected into a DialogFactory class which gets passed around.  The dialog is therefore accessed by
var d = _dialogFactory.GetNoConnectionDialog();
d.ShowDialog();

I have experimented with putting this code outside of the timer elapsed callback - when a button on UI interface is clicked for example - and it blocks the UI just fine from there so this is not a matter of where the form is created.
Answer: I'm pretty sure what Marc suggested should work.  This is how I would write it to use your dialog instead of MessageBox:
someControl.Invoke((Action)delegate {
    var d = _dialogFactory.GetNoConnectionDialog();
    d.ShowDialog();
}, null);

If that really isn't working I've had success in the past using a Timer control (System.Windows.Forms.Timer) on my form and a queue of Actions with an Tick function that looks like this:
void timer_Tick(object sender, System.EventArgs e)
{
    lock(queue)
    {
        while(queue.Count > 0)
        {
            Action a = queue.Dequeue();
            a();
        }
    }
}

And when your DeviceMonitor class needs to show the UI it would do this:
lock(queue)
{
    queue.Enqueue((Action)delegate
    {
        var d = _dialogFactory.GetNoConnectionDialog();
        d.ShowDialog();
    });
}

That being said, I really want to reiterate that I think Marc's method should work correctly and I would only use my Timer + queue method if you're absolutely certain that Control.Invoke won't work for you.
Answer: If you have access to a UI element, you can push to the UI thread by using things like:
someControl.Invoke((Action)delegate {
    MessageBox.Show(someControl, "Foo");
    // could also show a form here, etc
});

(the someControl in MessageBox.Show helps parent the message-box)
If you don't have access to a UI control, you can also use sync-context:
SynchronizationContext.Current.Post(delegate {
    MessageBox.Show("Foo");
}, null);

But it is easier to keep hold of a control ;-p
Comment: A null sync-context means you don't have a UI-pumping thread, i.e. a primary winform.
Comment: This is not a messagebox however.  Or rather its a stylized message box so it has to be a full form.  I do have a decorator wrapping the dialog that calls Invoke() if necessary so I thought it would be running on the UI thread, but apparently it is not.
Comment: The form will want to run on the thread that creates it. So create the form within the Control.Invoke
Comment: The form is created by Castle Windsor and is being DIed into a dialog factory class so I don't think this is a problem.  When I have it called from a place other than the device monitor it blocks the UI thread just fine
Comment: System.Threading.SynchronizationContext.Current == null !!!!
What the heck could that mean?
Comment: +1 for SynchronizationContext. This still remains a little used feature.
Answer: This is called marshaling and is a very simple concept once you read some good material on it (Google is your friend).
If your background thread has a delegate that calls into an object that is owned by the UI thread, then that method (on the called end of the delegate) simply has to marshal itself back onto the thread that owns its object (which will be the UI thread) and then block. It's very simple code (IsInvokeRequired), you just have to understand how to lay things out. (This is basically restating what Marc said, but from a higher level.)


GET value using ajax

Question: here is my link
<a data-toggle="tooltip" data-placement="top" title="Edit" class="btn btn-info" href="close_case_edit.php?pw_case_close_id= <?php $row['pw_case_close_id']; ?>">

On next page I fetch value using php
$pw_case_close_id = $_GET['pw_case_close_id'];

but i want fetch this value using ajax as i want update this page using
API
Comment: What is the question?
Comment: how can i fetch this data using ajax
Comment: *how can i fetch this data using ajax* <- You might wanna google this first and ask questions if you are having some difficulties.
Answer: You can use .split() along with .attr()
A sample working example:-

$(document).ready(function(){
 var value = $('a.btn-info').attr('href').split('=')[1];
 console.log(value);

});

GET value using ajax


Setting sort in onLazyLoad event triggers infinity loop on p-table

Question: I'm new to Angular and getting a Issue at the PrimeNG p-table.
This is my p-table

When anything changes I come in my loadData Method.
loadData(event): void {

    this.dataservice.loadData(..fields from event...).subscribe(result => {
        this.data = result.data;
        this.sort = result.sort; // <- This run into infinity loop
    })
}

So everytime I change this.sort I am coming into my loadData which will again do a request and so on.
Comment: I have the same issue, any solutions?
Answer: I had the same issue because I set an array variable and re-assign it.
WRONG IMPLEMENTATION
sample.html

sample.ts
public multiSortMeta: any = [];

ngOnInit() {
  this.loadData();
}

loadData(event: any) {
  setTimeout(() => {
    if (event.multiSortMeta !== undefined && event.multiSortMeta.length > 0) {
      const reference = [...this.multiSortMeta];
      event.multiSortMeta.map((sort) => {
        const sortIndex = reference.findIndex((f: any) => { return f.field === sort.field; });
        if (sortIndex > -1) {
          reference[sortIndex].order = sort.order;
        } else {
          reference.push({ field: sort.field, order: sort.order, requireReload: true });
        }
      });
      this.multiSortMeta = [...reference]; // It cause for infinite loop
    }
    this.someService.search(this.params, this.multiSortMeta)
      .subscribe(response => {
        console.log(response);
      })
  }, 0);
}

CORRECT IMPLEMENTATION
Here I added a flag (requireReload) to check whether to reload data or not. Once a function is called we set a flag to true to reload and once it's done then set it back to false, So another time function executes then it will doesn't reload and it breaks the loop.
sample.html NO CHANGE REQUIRED

sample.ts
public multiSortMeta: any = [];

ngOnInit() {
  this.loadData();
}

loadData(event: any) {
  setTimeout(() => {
    // For multiple sorting
    if (event.multiSortMeta !== undefined && event.multiSortMeta.length > 0) {
      event.multiSortMeta.map((sort) => {
        const sortIndex = this.multiSortMeta.findIndex((f: any) => { return f.field === sort.field; });
        if (sortIndex > -1) {
          // When sort change
          if (this.multiSortMeta[sortIndex].order !== sort.order) {
            this.multiSortMeta[sortIndex].requireReload = true // We set a flag here to reload the data
          }
          this.multiSortMeta[sortIndex].order = sort.order;
        } else {
          // When new sort column added
          this.multiSortMeta.push({ field: sort.field, order: sort.order, requireReload: true });
        }
      });

      // Check if any of key require reload
      const requireReload = this.multiSortMeta.some((m: any) => {
        return m.requireReload;
      });

      // It will reload only when a new sort column is added or the previous one is altered
      if (requireReload) {
        this.multiSortMeta.forEach((m: any) => {
          return m.requireReload = false; // Here we false to reload so next time it will not be called and It brakes the infinite loop
        });
        this.multiSortMeta = [...this.multiSortMeta];
        this.loadService();
      }
    } else {
      // For normal pagination and stuff
      this.loadService();
    }
  }, 0);
}

loadService() {
  this.someService.search(this.params, this.multiSortMeta)
    .subscribe(response => {
      console.log(response);
    })
}

Comment: Thanks! This is a great example and it works flawlessly! Thanks again for sharing it.


How to do, if multi value change then event occur

Question: I want to get value from these two id after they changed. How to do that.
$(document).ready(function(){

    $("#Send").change(function(e){
        alert(this.value);
    });

    $("#Receive").change(function(e){
        alert(this.value);
    })

})

I want something like
if( #send change && #receive change ){
    var send
    var receive
}

Actually, I want to see if both values of #send & #receive are changed or not. If both value are changed then I want to receive their value.
Comment: Does this answer your question? [jQuery same click event for multiple elements](https://stackoverflow.com/questions/1313373/jquery-same-click-event-for-multiple-elements)
Comment: I'm not sure I understand what you want, do you want to get both values after they have BOTH been triggered or just when one of them triggers?
Answer: You can so something below

$(document).ready(function(){
  var oldSend = $("#Send").val();
  var oldReceive = $("#Receive").val();
$("#Send, #Receive").change(function(e){

    var _t = $(this);
    /*if(_t.attr('id') == 'Send'){
        console.log('Send ' + _t.val() );
    } else if('#Receive'){
        console.log('Receive ' + _t.val() );
    }*/

    if(oldSend != $("#Send").val() && oldReceive != $("#Receive").val()){
      console.log('changedd ', _t.val())
    }

});

})

<input type="text" id="Send">
<input type="text" id="Receive">
Comment: @user7252501 put the above wording in your question
Comment: I want if both value change then only run a function. How to do that?
Comment: how does both value change at same time?
Comment: I suspect it's a language issue and OP wants to know: when both have changed
Comment: @freedomn-m yes,
Comment: Actually, I want to see if both values of #send & #receive  are changed or not. If both value are changed then I want to receive their value.
Comment: i think you should store old value first in variable, and on change of any input need to compare and both value not same to old one, then make any conditional things. what do you thing @freedomn-m
Comment: @DevsiOdedra I thought you were already updating your answer to do that :)
Comment: @freedomn-m updated, but i dont think both value change at same time.
Comment: No, they won't change at the same time, but I don't think OP wants that - they want to know when both have been changed - which your updated code shows.
Answer: You have two possibilities to do it:

$(document).ready(function(){
$('#Send, #Receive').change(function(e){
 alert(this.value);
});
})

<input type="text" id="Send">
<input type="text" id="Receive">

Or you could do it like that:

$(document).ready(function(){
$('#Send').add('#Receive').change(function(e){
  alert(this.value);
});
})

<input type="text" id="Send">
<input type="text" id="Receive">
Comment: I want after both value changes then run a function


programmatically saving a node doesn't add any record to dblog

Question: When I call node_save to save a node, no record for "a new node has been saved.." is added to watchdog.
Is this normal? If yes, how do I also add a watchdog record? (without calling the watchdog function directly)
Comment: you generally get a message..
Answer: The reason that the save operation is not logged during node_save is because it is done during the node form submission process by node_form_submit which internally uses node_save.
Please refer this elaborate and well-written response of saving the node using drupal_form_submit answered by user Francisco Luz. Pasting the code for the sake of completion here for saving an article resulting in both the watchdog logging and the drupal_set_message of the acknowledgement.
global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'article',
  'language' => 'und',
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['article'] as $field_name => $values) {
  $form_state['values'][$field_name] = array('und' => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body']['und'][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
//$form_state['values']['field_MYFIELD']['und'][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('article_node_form', $form_state, $node);

// Tell watchdog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message',
      array('%message'=> $message, '%field' => $field_name));
  }
}

I did run this once with devel php console and it logged the node during the node creation. Hope this helps.


Probability Question: Drawing balls from an urn

Question: Question:

An urn contains 12 balls where 3 balls colored red, 3 balls colored blue, 3 balls colored  green, and 3 balls colored white. If we draw 4 balls in succession without replacement, what are the probabilities that

the first is not red, the second is not blue, the third is not green, the fourth is not white and all four balls are different color?

the first is not red, the second is not blue, the third is not green, the fourth is not white, and the drawn balls may have same color?

I can answer question no. 1 using derangement and the answer is $!4*\frac{3}{12}*\frac{3}{11}*\frac{3}{10}*\frac{3}{9}=\frac{27}{440}$, but how to answer question no. 2? Any help would be appreciated. Thanks in advance.
Answer: For the second problem, we first find the probability of the complement, that the first is red or the second is blue or the third is green or the fourth is white.
We use Inclusion/Exclusion.
The probability the first is red is $\frac{3}{12}$, with similar expressions for the others. If we add these $\frac{3}{12}$, we get a first approximation $\binom{4}{1}\cdot\frac{3}{12}$.
This first approximation, double counts, for example, the cases where first is red and second is blue. The probability of this is $\frac{3}{12}\cdot\frac{3}{11}$. Subtract all $\binom{4}{2}$ instances. Our second approximation is $\binom{4}{1}\cdot\frac{3}{12}-\binom{4}{2}\cdot\frac{3}{12}\cdot\frac{3}{11}$.
But we have subtracted too much, for example the cases where first is red, second is blue, and third is green. So we add back $\binom{4}{3}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}$. Finally, we subtract the probability of red then blue then green then white.
So the probability of the complement is
$$\binom{4}{1}\cdot\frac{3}{12}- \binom{4}{2}\cdot\frac{3}{12}\cdot\frac{3}{11}+\binom{4}{3}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}-\binom{4}{4}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}\cdot\frac{3}{9}.$$
Comment: You are welcome. The point of my comment with the $5!$ is not the denominators, but the fact that all different colours is structurally a much simpler problem than the not red not blue and so on stuff. And it has a simple answer, no need for Inclusion/Exclusion.
Comment: So the answer would be 147/440? Can we use derangement for the second problem?
Comment: Yes, that is what I got. About derangements, I do not know. I used the first tool that came to mind.
Comment: It's ok. I can understand that the probability the first is red is 3/12 but why must we multiply by C(4,1) again? I don't get it the motivation of it. Would you mind explaining to me, please?
Comment: I am adding the probability that the first is red, the probability the second is blue, the probability the third is green, the probability the fourth is white. Four terms, each equal to $\frac{3}{12}$. I used $\binom{4}{1}\cdot \frac{3}{12}$ instead of $\frac{3}{12}+\frac{3}{12}+\frac{3}{12}+\frac{3}{12}$ or $(4)(3/12)$ because it structurally fits in better with the next term, and the term after that, and suggests what we would do if we had more colours.
Comment: Oh, we can use TeX in the comment. Ok, two more questions Sir (please you bear to the stupid student like me). Using your idea, if the ball is replaced after drawing then the probability of the complement would be $\binom{4}{1}\cdot\frac{3}{12}- \binom{4}{2}\cdot\frac{3}{12}\cdot\frac{3}{12}+\binom{4}{3}\cdot\frac{3}{12}\cdot\frac{3}{12}\cdot\frac{3}{12}-\binom{4}{4}\cdot\frac{3}{12}\cdot\frac{3}{12}\cdot\frac{3}{12}\cdot\frac{3}{12}$, right?
Comment: Yes, same argument but denominators do not change. It seems likely in this case that we can get a simpler argument.
Comment: Also for the probability of drawing 5 balls in succession without replacement and all five balls are different color is $\binom{5}{1}\cdot\frac{3}{12}- \binom{5}{2}\cdot\frac{3}{12}\cdot\frac{3}{11}+\binom{5}{3}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}-\binom{5}{4}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}\cdot\frac{3}{9}+\binom{5}{5}\cdot\frac{3}{12}\cdot\frac{3}{11}\cdot\frac{3}{10}\cdot\frac{3}{9}\cdot\frac{3}{8}$?
Comment: I mean the number of balls is 15 and there are 3 balls colored black for instance.
Comment: For this one there is a much simpler expression. There are $5!$ arrangements of the colours. the probability of getting colour 1 then 2 then $\dots$ is $\frac{3}{15}\cdot\frac{3}{14}\cdots$. Multiply by $5!$.
Comment: Oh, I forgot that the denominator should be 15, 14, .... Thank you very much for your answer and the detail explanations. I owe you big Sir. May God bless you always :)
Comment: I understand Sir. Once again thank you :)


Counting Lattice Points

Question: Lattice points are of great importance. I encountered a problem as follows:- given a circle of radius 'r' as x²+y²=r² the number of lattice points can take values . The options were (0,72,69,140). I tried the problem using complex numbers but couldn't figure out a short and sweet method to tackle the problem so I need help ! Please help me!
Comment: Are you counting the lattice points inside the circle, or the the lattice points on the circle itself?
Answer: Hint, if you believe that exactly one of the 4 given choices is correct: the center of the circle is a lattice point, and has a property all the other lattice points lack.
Comment: Yes.  The number of lattice points inside the circle must be odd: the origin plus twice the number of pairs of non-zero lattice points $\pm\lambda$.
Comment: A great hint. Even though we (ideally) stll need to perform a reality check given that there are two different sizes for the non-trivial orbits of $D_4$.
Comment: Can I do something like n=(complex prime factorisation) and then use  some combinatorics to end up at 4(pi(sigma{X(i^r)})) and thanks for the hint
Comment: Do you mean use Gauss integers factorization ?
Comment: Do we agree that your lattice is $\mathbb{Z} \times \mathbb{Z}$ with center at the origin ?

Counting Lattice Points


Javascript behaviour reuse: What side effects will this approach have?

Question: I'm trying to understand pure prototype-based JavaScript and one specific thing I'm struggling with is reuse (inheritance).
For my project I landed this way of creating objects that can be reused.
// very generic prototype
var Apparatus = (function(){
    var self = Object.create({});
    self.state = false;
    self.on = function() { this.state = true; };
    return self;
})();

// more specific prototype
var Radio = (function(){
    var self = Object.create(Apparatus);
    self.frequency = 0;
    self.setFrequency = function(f) { this.frequency = f; }
    self.getFrequency = function() { return this.frequency; }
    return self;
})();

I then want to "instantiate"/copy the Radio object, creating two different radios.
var kitchenRadio = Object.create(Radio);
kitchenRadio.state = false;
kitchenRadio.on();

var carRadio = Object.create(Radio);
carRadio.state = false;

console.log(kitchenRadio.state, carRadio.state);
// true false

This works, but will it continue to? Can anyone predict any unwanted outcomes?
Comment: I'm not sure if this is unwanted, but `Radio.on()` will set `kitchenRadio.state` to `true`.
Comment: I guess the point is that functions should be inherited, but not properties such as `state`. All radios are turned on in a common way, but each radio has its own state. So, each eventual instance would have its own properties, whereas the functions are inherited.
Comment: So I have to specifically create state properties in both kitchenRadio and carRadio to avoid that. Can I remedy this without changing the approach extensively?
Answer: Like @pimvdb said, remove state and this works well.
// very generic prototype
var Apparatus = (function(){
    var self = Object.create({});
    self.on = function() { this.state = true; };
    return self;
})();

// more specific prototype
var Radio = (function(){
    var self = Object.create(Apparatus);
    self.setFrequency = function(f) { this.frequency = f; }
    self.getFrequency = function() { return this.frequency; }
    return self;
})();

I then use Object.create(Object, params) to instantiate it.


Differentiation/Integration continuous function (metric spaces)

Question: I have the following two questions:

Is differentiation, $f(x) \mapsto f'(x)$ a continuous function from
  $C^1[a,b] \longrightarrow C[a,b]$
and
Is integration, $f(x) \mapsto \int_a^x f(t) \ dt$, a continuous
  function from $C[a,b] \longrightarrow C[a,b]$

$C[a,b]$ denotes the space of continuous real-valued functions on $[a,b]$ with the sup metric and $C^1[a,b]$ denotes the space of continuously differentiable functions on $[a,b]$
So far, I've attempted the first one and I'm trying to use the theorem that a map is continuous if and only if the inverse map applied to some set is closed in $f(x)$ whenever the set is closed in $f'(x)$ but haven't been able to get anywhere (or think of a counterexample)
Answer: You need to specifiy a norm on these spaces to discuss continuity.  Usually, one gives $\mathcal{C}[a,b]$ the sup-norm.  In this case, integration is continuous, since if we define $$T(f)(x) = \int_0^x f(t)\,dt, \qquad t\in[a,b]$$
we have
$$|T(f)(x)| \le \left| \int_0^x f(t)\, dt\right| \le \int_0^x |f(t)|  dt
\le \|f\|(b - a),$$
where the norm denotes the uniform norm.  This map $T: \mathcal{C}[a,b]\to
\mathbb{R}$ is continuous.
If you make the $\mathcal{C}^1$ norm $f\mapsto \|f\| + \|f'\|$, then differentiation is continuous in that norm.
Comment: Sorry, yes, I forgot to include it. It does specify the sup-metric/norm for $C[a,b]$ but mentions nothing for $C^1[a,b]$
Answer: Consider a function f= epsilon * exp (-x^2/epsilon^2) on the domain [-a,a] and epsilon in neighbourhood of 0.
Then supremum /f/ = epsilon
Differentiate f. f' = -2x/ epsilon  * exp (-x^2/epsilon^2)
supremum /f'/ = 1/ epsilon.
As epsilon   tends to 0, supremum /f'/  tends to infinity.
Thus no,  differentiation is not cts function from C' into C.
Comment: Abbreviations tend to be confusing, especially for the users who don't speak English as their first language. Please use "neighborhood" instead of "nhd," "continuous" instead of "cts," etc. In particular, do *not* use "inf" as a substitute for "infinity," especially not in a sentence that also contains "sup"!


Is the sum of trends of two time series the trend of the sum of the time series?

Question: Let's say I have two time-series, A and B. I build time-series C as C=A+B.
I estimate the trend of A, let's say I get +0.5 (Theil-Sen).
I estimate the trend of B, let's say I get -0.4 (Theil-Sen).
Can C have a trend estimate different from +0.1. Can it be negative?
Can you give a simple example when this happens (negative C trend)?
Answer:
Is the sum of trends of two time series the trend of the sum of the time series?

- as a general question, it depends: if the estimator is linear in the data then yes, but in general, no.
On the specific question of using Theil-Sen slope (median pairwise slope) as a trend estimate:
When using a Theil-Sen slope estimate, the trend of the sum can be quite different from the sum of the trends (the Theil-Sen slope is not linear in the observations).
Here's a small example:
Series A:
<code> -1.15
  2.19
  1.32
  1.40
  2.04
</code>
Series B:
<code>-2.63
-0.98
-1.23
-1.68
-5.86
</code>
The Theil-Sen slope for the first (unit-spaced) series is 0.5, the Theil-Sen slope for the second series is -0.4 (as in your question) but the slope for the sum is negative (indeed, it's -0.5575, more negative that for the second series).
Comment: Thinking about how to construct examples with desired properties can be instructive, often teaching quite different sorts of lessons than the resulting examples convey.
Comment: That's an example of a linear estimator, yes. (More specifically, you can write $\hat{y}=Hy$, for a constant-matrix $H$, where for this particular problem the values in $H$ will only depend on the gaps between various observation-times). This is certainly the case for linear regression (though it's not the only such linear estimator)
Comment: Thank you, this example is very interesting. I wonder that a linear estimator would be the slope in a linear regression, right?


json php + javascript

Question: Preciso do seguinte: pego oq foi digitado no input com o código abaixo e passo para a url: http://bonusdogeronimo.com.br/rtv/indez.php

No meu Index.php eu tenho esse código ondem pego o resultado do json passando email e api por GET
<?php
//$email = 'firstname.lastname@example.com';
$apikey = 'xxxxxxxxxxxxxxxxx';
$email = $_GET['email'];

// Inicia o cURL acessando uma URL
$cURL = curl_init("https://bpi.briteverify.com/emails.json?address=" .
$email . '&apikey=' . $apikey);
// Define a opção que diz que você quer receber o resultado encontrado
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
// Executa a consulta, conectando-se ao site e salvando o resultado na
variável $resultado
$resultado = curl_exec($cURL);
$json = json_decode($resultado, true);
// Encerra a conexão com o site
curl_close($cURL);

//print $resultado;
print '
';

    echo 'E-mail: ' . $json['status'];

     print '
';

  ?>

até aqui tudo funciona, porém não consigo receber de volta no meu primeiro código a resposta da api, preciso retornar ao primeiro script o resultado de $json['status']; se é valid ou invalid, assim entrou no IF do primeiro script
if(resultParse.status == "valid"){
        $("form").addClass("valid");
        $("form").submit();
      }else{
        alert("Parece que você digitou um e-mail errado!");
        $("form").removeClass("valid");

Essa URL aqui --> http://egratitude.com.br/src/sources/avulsos/returnpath.php faz exatamente oq eu preciso, porém não consigo ver como o cara fez, pois ao acessar essa url ele já trás o resultado do json.
Comment: Remove todos os `print` no seu PHP e no echo coloque `echo json_encode(array('status'=>$json['status']));` ou dê direto um echo em `$json`.
Comment: Como está funcionando se você está enviando com `$.post` e no PHP você está pegando via `$_GET`..... qual mágica você fez? kkkk
Answer: No envio eu sugiro já colocar o retorno em JSON
$.post("http://bonusdogeronimo.com.br/rtv/indez.php", {
      email : $("form #email").val()
    }, function(result){
      if(result.status == "valid"){
        $("form").addClass("valid");
        $("form").submit();
      }else{
        alert("Parece que você digitou um e-mail errado!");
        $("form").removeClass("valid");
      }
      $("form").removeClass("loading");
    },'json'); // <---- Adição da forma de retorno

No seu PHP, corrigir a forma de recebimento da informação do e-mail
<?php
//$email = 'firstname.lastname@example.com';
$apikey = 'xxxxxxxxxxxxxxxxx';
$email = $_POST['email']; // <---- Correção

No seu retorno, remover os print e colocar o retorno no echo
//print $resultado;
echo json_encode(array('status'=>$json['status']));

Ou dar direto um echo na variável $json
//print $resultado;
echo $json;

json php + javascript


excel dropdown list if cell is colored

Question: I need some help, coz Im not an expert.
CASE:
I have 10 workers in my little company, I want to make a schedule for them.
Each month they send me which days are they available for work.
I made table (2) for this. Verticaly the names, horizontally the days 1-31.
If someone is available the cell for that day is EMTPY or GREEN, otherwise RED.
So, I want table (1) the "final schedule" to contain a dropdown list for each day with the AVAILABE workers so I can choose. (maybe the choosen ones cell automatically goes red on specific day in table (2).  Is this possible, or partly possible? enter image description here
Last thing: is it possible to add a colordropdown option for the cells?
Answer: i will give you a better idea. Goto ur mail and click on Google Drive then add a new sheet.
in that sheet u can add employee names and u can show them datewise, is they are availbale or not with desired colors.
am also attached a pic for easy understand.
enter image description here
Comment: thank you, but unfortunately this is more complex sheet, and I need help for that part. I tried and understand what you described. This drop down question is able to save hours every month for me and my team. Again: thank you!

excel dropdown list if cell is colored


Show that $M=\{(x,y,u,v) \in \mathbb{R}^4 : x^2 + y^2 = u^2 + v^2 = 1\}$ is orientable, explaining the induced orientation.

Question:
Let $M=\{(x,y,u,v) \in \mathbb{R}^4 : x^2 + y^2 = u^2 + v^2 = 1\}$.

Show that $M$ is an orientable subvariety of $\mathbb{R}^4$, explaining the induced orientation.

Consider the $2$-form $\omega = a(x,y,u,v)dx \wedge du$ with $a \in C^\infty(\mathbb{R}^4)$. Compute $\int_M \omega$ in terms of $a$.

Showing that $M$ is a subvariety of $\mathbb{R}^4$ of dimension $2$ is not a problem.
So for 1., by definition, we need to find an everywhere (on $M$) non-vanishing $2$-form $\omega$.
How can I do that? (The same for induced orientation)
For 2. I have some ideas:
$$\int_M \omega = \int_{S^1 \times S^1} a(x,y,u,v)dx \wedge du = \int_0^{2\pi} \int_0^{2\pi} a(cosu,sinu,cosv,sinv) dudv$$
Is this true?
Thanks in advance!
Answer: Let $d\theta =x ~dy - y ~ dx$ and $d\phi = u~dv - v~du$. Then $\omega = d\theta \wedge d\phi$ is such a 2-form.
For the second part, you're not quite on the right track: the parameterization by sine and cosines of two arguments -- $s$ and $t$ might have been better names -- is fine, but you can't just turn "dx" into "ds". Details:
Let
$$
X(s, t) = (\cos s, \sin s, \cos t, \sin t)
$$
so that
$$
x(s, t) = \cos s\\
y(s, t) = \sin s\\
u(s, t) = \cos t\\
v(s, t) = \sin t.
$$
Then observe that
$$
dx = -\sin s ~ ds\\
du = -\sin t ~dt
$$
so that
$$
dx \wedge du = \sin s \sin t ~ds \wedge dt.
$$
so your integral becomes
$$
\int_{[0, 2\pi] \times [0, 2\pi]} a(\cos s, \sin s, \cos t, \sin t) \sin s \sin t ~ ds \wedge dt.
$$
I can never remember what to do at this last step, and always have to look up an example in Spivak's Calculus on Manifolds -- do I need a factor of 1/2? Do I have to integrate ds dt and then integrate dt ds or ... well, as I say, I can't recall. I think that in practice you just drop the wedge and integrate, but I could easily be wrong. :(
Comment: Thanks for answering. What was your idea to take that $\omega$? Can you explain me how to explicit the induced orientation? Thanks
Comment: Since I knew that the surface you'd described is a torus, I said "a volume form on $S^1 \times S^1$ is just the product of the volume form on the two individual factors. And on $S^1$ itself, the form $x dy - y dx$ is pretty much a classic : It's the thing that when integrated around the circle gives $2\pi$ (basically by doing a contour integral like the ones you learned in complex variables). So I just took the product of two of those. I don;t understand your last question -- did you lose a verb? -- so I can't answer...and I have to run off and meet someone in 1 minute...
Comment: A few more details about the final integration added... but not a complete answer. It's been too long since I needed to actually compute anything with a differential form.
Comment: I think it is right (I forgot to put $sin(u) sin(v)$ in the integral) and I think that we can erase the wedge


Maximum product $ab$ for $a+b=k$ - proof based on AM-GM inequality

Question: My question is:
Prove-

If $a,b$ are two positive real numbers such that their sum  is $a+b=k$.  Then the product $ab$ is maximum if and only if
  $a=b=\displaystyle\frac{k}{2}$.

I proved the above theorem above using $(a+b)^2$ but I want to know how can it be proved using A.M.  G.M. inequality.
Answer:
AM-GM inequality: $\displaystyle\frac{a + b}{2} \geq \sqrt{ab}$, with equality if and only if $a = b$.

Substituting $a + b = k$ and taking squares gives us $$\frac{k^2}{4} \geq ab.$$ So the product $ab$ is bounded from above by a constant, and this upper bound can be achieved only by taking $a = b = \frac{k}{2}$.
Answer: This is a maximization problem:
$a+b=k$.  Maximize $ab$.
$a=k-b$, so $ab=(k-b)b$.
$f(b)=(k-b)b$ is maximal if $$\frac{df}{db}=0$$
$\frac{df}{db}=(k-b)-b=k-2b$
This equals $0$ if and only if $k=2b$.  Therefore, $$a=b=\frac{k}{2}$$


Confusion about holomorphic differential on elliptic curve

Question: Let $(a:b)\in\mathbb{C}P^1$ and look at the elliptic curve $C$ given by $y^2=x^3+a^4x+b^6$. It is well known that on this elliptic curve we have the holomorphic differential $dx/y$. I have two questions about this:

I actually don't understand very well why $dx/y$ is a holomorphic differential. What happens when $y=0$? If you have a reference where this is explained well, that would be also nice.
I also wanted to know how does this differential actually change when we use another representative of $(a:b)$, say $(\lambda a:\lambda b)$? We can outside $y=0$ write $\frac{dx}{\sqrt{x^3+a^4x+b^6}}$ and this changes to $\frac{dx}{\sqrt{x^3+\lambda^4a^4x+\lambda^6b^6}}$. Or does $dx$ itself also change?
Answer: If you look at a neighbourhood of a point $(t,0)$, and you project it on the $x$-axis, you see that the projection is $2$-to-$1$.
This means that $(x-t)$ is not a uniformizer for the local ring at that point. The projection map $x : E \to \Bbb P^1(k)$ locally looks just like the map $z \mapsto z^2$ around $0$ (if you work over $\Bbb C$ there are actual charts that give this). So, just like $d(z^2) = 2zdz$ has a single zero, $dx$ has order $1$ at that point.
Meanwhile, if you project that neighbourhood on the $y$-axis, it is then $1$-$1$, and so $y$ is a uniformizer for the local ring, and $dy$ has neither a zero nor a pole. This also means that to get the order of a differential $\omega$ you can just write $\omega = f dy$ and look at the order of the rational function $f$.
Indeed, $dx/y = -2/(3x^2+a^4).dy$, and $-2/(3x^2+a^4)$ has order $0$ at $(t,0)$, so $dx/y$ has order $0$.
Next you need to check that $dx/y$ is holomorphic at the point at infinity.
There is only one point at infinity, where $x$ has a pole of order $2$ (so the projection on $\Bbb P^1(k)$ is $2$-to-$1$ around that point and looks just like $1/z^2$ around $0$, and so $dx$ has a pole of order $3$) and $y$ has a pole of order $3$ (and so $dy$ has a pole of order $4$)
So $dx/y$ has order $-3-(-3) = 0$, and so $dx/y$ is holomorphic everywhere.

When you change the representative, you also have to rescale $x$ and $y$ by some powers of $\lambda$. (you should give different variable names to $x$ and $y$ and write down the actual isomorphism between the two curves or else you will get confused). Then $dx/y$ will also get rescaled by a power of $\lambda$, so nothing much happens.
Comment: Thank you very much. I have one more question: what is actuallu the isomorphism between the elliptic curves $y^2=x^3+a^4x+b^6$ and $y^2=x^3+\lambda^4a^4x+\lambda^6b^6$? I remember my professor mention that they are isomorphic but not the actual isomorphism and I couldnt find it through google either.
Comment: given a point $(x,y)$ on the curve $y^2 = x^3+a^4x+b^6$, you get a point $(x'=\lambda^2 x, y' = \lambda^3 y)$ on the curve $y'^2 = x'^3 + \lambda^4a^4x' + \lambda^6b^6$. When you pullback the differential $dx'/y'$ from the second curve you obtain the differential $d(\lambda^2x)/(\lambda^3y) = \lambda^{-1}(dx/y)$ on the first curve, which is a scalar multiple of $dx/y$.


I found the PDE solution

Question: I found the PDE solution:
$$u_t+u_x=u^2$$
$$u(0,x)=\cos(x)$$
The solution is:
$$u(t,x)=\frac{\cos(x-t)}{1-t\cos(x-t)}$$
Now how do you find the lowest $ t $ to which the solution "explodes" and which point it "explodes". I tried to parse when $t\cos(x-t)$ tends $1$, but I could not find.
Answer: Hint: Write $x=r+t$ and put $f(r,t) = \tfrac{\cos r}{1-t\cos r}$. Then $f$ "explodes" when $1-t\cos r = 0$, i.e., when $\cos r = \tfrac1t$. You can write $u$ in terms of $f$.
Comment: I thought the following: $1-tcos(r)=0 \Rightarrow t=\frac{1}{cos(r)}$ for $cos(r) \neq 0$. therefore $t$ is minimal when $cos (r)$ is maximum, so $t = 1$ is this right?
Comment: The point where it "explodes" would be $(1,1)$
Comment: @Lucas : It explodes along the entire curve defined by $1-t\cos r=0$, which can be written $t = \sec r$.

I found the PDE solution