Copy worksheet into different workbook replacing current data

Question: I am hoping someone can help me.
I have two workbooks.
Wb1 = FAC Trial
Wb2 = ROMAN
There are numerous worksheets within both workbooks. What I would like to happen is that the data in Wb2, worksheet named Format is copied into Wb1 worksheet named Format.
The worksheet in Wb1 is already named and is to be updated on a daily basis from Wb2. The data in Wb1 worksheet Format would be overwritten each time.  I was looking that this would happen at the click of a Command Button.  Wb2 would not be open at the time of clicking the Command Button.
I have found some code but it creates a new worksheet each time the code is run and I am unsure of how to change it to suit my needs.
thank you in advance any help is greatly appreciated
Comment: please edit your question and post the code you were using so far. This will help us to help you.
Comment: The code I was using was
Answer: You can easily record a piece of code to do this yourself, simply use 'Record Macro' on the Developer ribbon.
For now, below should do what you're after (remember to update the filepath for workbook 2).
I have just copied the "Format" worksheet from the ROMAN workbook, then deleted the existing "Format" worksheet and re-named the new one to "Format".
Sub wsCopy()
    Dim wb1 As Workbook, wb2 As Workbook, ws1Format As Worksheet

    Application.ScreenUpdating = False
    Set wb1 = ThisWorkbook
    Set wb2 = Workbooks.Open("[ENTER FILE PATH]\ROMAN.xlsx")
    Set ws1Format = wb1.Sheets("Format")
    Set ws2Format = wb2.Sheets("Format")

    '' Copy the "Format" worksheet to wb1.
    ws2Format.Copy Before:=ws1Format
    wb2.Close

    '' Delete existing "Format" worksheet.
    Application.DisplayAlerts = False
    ws1Format.Delete
    Application.DisplayAlerts = True

    '' Rename new sheet to "Format".
    wb1.Sheets("Format (2)").Name = "Format"
    Application.ScreenUpdating = True
End Sub

Answer: This answer is based on @Ituner before
Sub wsCopy()
    Dim wb1 As Workbook, wb2 As Workbook, ws1Format As Worksheet

    Application.ScreenUpdating = False
    Set wb1 = ThisWorkbook
    Set wb2 = Workbooks.Open("[ENTER FILE PATH]\ROMAN.xlsx")
    Set ws1Format = wb1.Sheets("Format")
    Set ws2Format = wb2.Sheets("Format")

    '' Copy the cells of the "Format" worksheet.
    ws2Format.Cells.Copy

    '' Paste cells to the sheet "Format".
    wb1.Sheets("Format").Paste
    wb2.Close false 'remove false if you want to be asked if the workbook shall be saved.
    Application.ScreenUpdating = True
End Sub

Answer: The code I was using was
Private Sub CommandButton1_Click ()
With Workbooks ("ROMAN.xls")
      .Sheets ("Format").Copy_
      Before:=Workbooks ("FAC Trial.xls").Sheets ("Format")
End With
End Sub
As is obvious I had to have both workbooks open but I just wanted it to copy the data onto the format worksheet without creating a new one
Comment: You could use the code @Iturner posted. He's right that if you would've used the macro recorder you could have got it by yourself too.
However, I will give you another answer based on his code.
Answer: Sub ReplaceSheets(wb1 As Workbook, wb2 As Workbook, SheetName As String)
wb1.Sheets(SheetName).Cells.Clear
wb2.Sheets(SheetName).Cells.Copy wb1.Sheets(SheetName).Range("A1")

End Sub


UTL_SMTP.WRITE_DATA trimming the extra spaces in the email body | Oracle

Question: Oracle Database 19c Enterprise Edition Release 126.96.36.199.0 - Production
Version 220.127.116.11.0
I am using the UTL_SMTP to send an email. Below is code
declare
 l_mail_conn   UTL_SMTP.connection;
  l_boundary    VARCHAR2(50) := '              =abc1234321cba=';
  p_smtp_host VARCHAR2 (100) := 'smtp.cac.com';
   p_smtp_port      NUMBER := 25;
   p_to VARCHAR2(100) := 'firstname.lastname@example.com';
   p_subject VARCHAR2(100) := 'Hello';
   p_html_msg  VARCHAR2(100) :=  '              ' ||'ABC
' || '              ' || 'DEF';
BEGIN
  l_mail_conn := UTL_SMTP.open_connection(p_smtp_host, p_smtp_port);
  UTL_SMTP.helo(l_mail_conn, p_smtp_host);
  UTL_SMTP.mail(l_mail_conn, p_to);
  UTL_SMTP.rcpt(l_mail_conn, p_to);

  UTL_SMTP.open_data(l_mail_conn);

  UTL_SMTP.write_data(l_mail_conn, 'Date: ' || TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') || UTL_TCP.crlf);
  UTL_SMTP.write_data(l_mail_conn, 'To: ' || p_to || UTL_TCP.crlf);
  UTL_SMTP.write_data(l_mail_conn, 'From: ' || p_to || UTL_TCP.crlf);
  UTL_SMTP.write_data(l_mail_conn, 'Subject: ' || p_subject || UTL_TCP.crlf);
  UTL_SMTP.write_data(l_mail_conn, 'MIME-Version: 1.0' || UTL_TCP.crlf);
  UTL_SMTP.write_data(l_mail_conn, 'Content-Type: multipart/alternative; boundary="' || l_boundary || '"' || UTL_TCP.crlf || UTL_TCP.crlf);

  IF p_html_msg IS NOT NULL THEN
    UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || UTL_TCP.crlf);
    UTL_SMTP.write_data(l_mail_conn, 'Content-Type: text/html; charset="iso-8859-1"' || UTL_TCP.crlf || UTL_TCP.crlf);

    UTL_SMTP.write_data(l_mail_conn, p_html_msg);
    UTL_SMTP.write_data(l_mail_conn, UTL_TCP.crlf || UTL_TCP.crlf);
  END IF;

  UTL_SMTP.write_data(l_mail_conn, '--' || l_boundary || '--' || UTL_TCP.crlf);
  UTL_SMTP.close_data(l_mail_conn);

  UTL_SMTP.quit(l_mail_conn);
END;
/

I am able to receive the email but the email body is trimming the repeated spaces whether they are leading or trailing
Output with above code is

Expected output is

Please observe the leading spaces are highlighted in the expected output. I am unable to understand what went wrong with this code.
Thanks for reading, Any help is appreciated.
Comment: Please not above code is taken from google and trying to work on it
Comment: have you tried lpad https://stackoverflow.com/questions/32638626/how-to-add-leading-spaces-in-oracle
Comment: @nbk, lpad is same as additional spaces into the string, here is the problem is with write_data in HTML format.
Answer: It is not about Oracle it is about html. Try to set
   p_html_msg  VARCHAR2(100) :=  '
' || '              ' ||'ABC
' || '              ' || 'DEF';

or
p_html_msg  VARCHAR2(100) :=  '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp' ||'ABC
' || '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp' || 'DEF';

https://blog.hubspot.com/website/html-space
Comment: Used the first solution, perfectly worked. Thanks a ton for quick response.
Comment: With the same Oracle procedure, I am sending a hyperlink(like Click here). When I focus on word *here*, the web page link is appearing, is there a way to hide the display of the link?
Comment: I am not sure if understand your question. Try attribut title:
Click here
Comment: Okay, thats fine to have the link displayed when the mouse is moved. But one more thing, I am using the hyperlink for a file placed on internal shared folder and the file has a single quote as part of its name, when I click on the link, it is not opening as the file name is converted to "Venkat's file.txt'" from its original name "Venkat's file.txt". Any suggestion? Please observe an extra single quote at the end of converted file name. That was added automatically while opening the link
Comment: So You have something like this Click here ?
Comment: Apologies, I missed your message, Yes the file includes the tag. And also, after receiving the email when I move the cursor on the hyperlink name, the file path is being displayed which I want to hide. Hope you understand this.
Comment: I am sorry, I cant help You. Try to create new question with some samples of Your code.


Menu responsivo centralizado

Question: Preciso que este menu esteja centralizado, pois todo meu site é centralizado.
Como fazer? Pois este menu está o tempo todo alinhado à esquerda.
Tento centralizar, mas perde o background.
<!DOCTYPE html>

Home

News

Contact

About

    ☰

Responsive Topnav Example

Resize the browser window to see how it works.

Comment: o seu código exemplo não se encontra formatado e dificulta a leitura. Por favor veja esta ajuda:

http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks
Comment: Cara, use o editor WebStorm da jetbrains. Vi que seu código está um pouco confuso, ele irá te ajudar muito.
Comment: Olá. Agradeço a atenção. Este código foi copiado do próprio w3schools. Na verdade, preciso apenas saber como fazer para centralizar todo o menu. Você sabe?

Segue codigo no w3schools:

http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav
Answer: Substitua a classe cssque atualmente está assim:
ul.topnav li {float: left;
text-align: center;
}

Por esta:
ul.topnav li {
    float: none;
    text-align: center;
    display: inline-block;
}

Veja em funcionamento: Aqui
Comment: Olá. Puxa vida! Muito obrigado !!! Queria apenas perguntar uma coisa, eu tirei o float: none e funcionou centrlizado da mesma forma. Qual a função dele neste caso? É bom manter ou não?

Outra coisa: para que este código funcione no máximo de brwosers possível eui tenho que acrescenter o normalizr.css? Tem mais algum outro código que ajuda na compatibilidade? Abraços.
Comment: Olá @Wendell, na verdade fui testar melhor e parou de funcionar o botão que mostra o menu quando está responsivo. Não está mostrando, apenas está alinhado. O que será?
Comment: @Tesok se você olhar o próprio código que você postou, o menu responsivo já não funciona nele, mas não se preocupe, veja novamente [seu código em funcionamento aqui](https://codepen.io/wendell_chrys/pen/OXmZmb) já com o menu responsivo funcionando!
Comment: Olá @Wendell. Ficou excelente! Não sei como agradecer. Gostaria de perguntar como posso estudar e me aprofundar como você, pela própria internet. Tenho dificuldades para entender o inline-block, inline--etc.... E algumas outras coisas, como quando usar firt-child, not, etc...
Tudo isso vem da sua cabeça ?
Como posso aprender?

Aproveito para perguntar se para funcionar com o máximo de compatibilidade possívei com outros browsers, o normalizr.css (conhecido) é suficiente? Ou tem outros includes que ajudam?

Abraços, amigo. Que você vá muito longe com esta sua generosidade.
Comment: @Tesok primeiramente não esqueça de colocar a sua pergunta como respondida. Você vai conseguir facilmente aprender usando tutoriais na internet. Eu recomendo você ir aprendendo aos poucos e treinando muito, não fique somente na teoria. Quanto ao `inline-block` existe a mesma dúvida parecida com a sua [aqui](http://goo.gl/iblsmj). O normalize.css é uma ótima alternativa pra normalizar os elementos nos mais variados navegadores, existe também a opção do CSS Reset, você pode ver uma comparação entre eles [aqui](https://goo.gl/6vkPPD).

Menu responsivo centralizado


How to improve bandwidth performance for a vm

Question: I have been told to add additional nics to the VM to improve bandwidth performance. Once they are added what is the best way to team them together for best performance?
I tried the Microsoft bridge and it didn't work very well.
Thanks
Answer: a) Don't do this, that's not how to do this at all, b) there's no guarantee any change will work until you show us how things are connected to your VSS/VDS and the uplink ports, either way you don't do in-VM bonding, bad idea all-round.
Comment: We have 2 vSwitches the management network with 2x1Gbe ports (no lag) and the machine network with 4x10gbe ports (lag).
Comment: Still a fraction of what we'd need to help you, you need to look at how the site works and what we expect from question-askers, have a look at the help pages and observe the workings of the site - then you'll realise how little you've given us to help you.
Comment: I have a host with a VM that has teh vmxnet3 driver loaded, its primary purpose is as a file server .. pushing big files out. The VM network / port group is connected to a vswitch with 4 10gbe ports that are connected to a 10gbe switch, and are in a lag group. I am using the IP Hash method and everything is working. I just want to speed up the file transfer for the File Server VM.
Comment: https://serverfault.com/questions/797645/how-can-i-increase-the-throughput-bandwith-of-my-virtual-network?rq=1. This is a thread you answered and I feel I have provided at least as much information as they provided. Did I meet your expectations?


retaining precision when adding 2 floats

Question: When adding two floats is there a way to retain the precision. For example,
I am adding two floats, 89 and 0.00123 and storing the result in a variable. When I printed out the variable to see what it contained I got 89.0012. What happened to the last digit? Is there a way to ensure that I do not lose that extra digit.
Comment: A single float value can have so many digits of precision. No matter how you arrive at that float, whether by adding, multiplying, deleting, or subtracting, two, three, or a million of other floats, you still end up with just so many levels of precision. The End.
Comment: There is precision, and then there is number of [significant figures](https://en.m.wikipedia.org/wiki/Significant_figures) to be displayed. You probably want to change the latter, since default is 6
Comment: Did you know that your `float` isn't really 0.00123? That is a decimal approximation of the binary value. Talking about "the last digit" is misleading when the computer doesn't use digits.
Answer: You can use std::setprecision():
#include <iostream>
#include <iomanip>

int main() {

    float x = 89;
    float y = 0.00123;

    std::cout << std::setprecision(7) << x + y << std::endl;

    return 0;
}


Prove that a bounded decreasing sequence $\big\{ {x_n} \big\}$ converges

Question: Prove that a bounded decreasing sequence $\big\{ {x_n} \big\}$ converges
I proved this using Bolzano-weierstrass thm but I was wondering how else I could prove it without using that thm.
Comment: https://en.wikipedia.org/wiki/Monotone_convergence_theorem
Comment: The existence of the greatest lower bound (for a decreasing  sequence) or the least upper bound (for an increasing sequence) is enough.
Answer: Think of it like this: for all $i \in \mathbb{N}$, $x_i \geq L$ and since $(x_n)$ is decreasing $x_{n+1} \leq x_n$ and $\inf{x_n} = L$ (if L is the greatest lower bound). We then necessarily have that as $n \to \infty, x_n \to L$.


Create React App not installing complete files

Question: When I type npx create-react-app my-app the command only installs :
a node module folder, a package.json and a package-lock.json.
No src, and no public.
I've tried reinstalling Node.js, I downloaded the correct bit version but something's wrong. Can anybody suggest a fix. Thank you.
Comment: What is the output of create-react-app?
Comment: node_modules, public, src, .gitgnore, package.json, package-lock.json and a readme file.
Answer: try this
$ npm install -g create-react-app
$ create-react-app my-app-name
$ cd my-app-name
$ npm start

Comment: My Powershell's permission to run the script was somehow disabled. It worked. Thank you very much.
Comment: You're welcome, consider approving the answer.


Callng a button made from a for loop from another object's event listener

Question: I made 2 arrays one for names insect parts, the other for the parts of the insects to show light up.  Rolling over the buttons created by the array and for loop, the parts and buttons light up.  But I also want the parts and buttons to light up when rolling over the insect parts.  My problem is I don't know how to call for the buttons from loop when rolling over the insect parts. See function rollHandler2 and outHandler2.
<code>//the arrays look like this...

var parts:Array= [ "Cervical sclerites", "Protonotopleural lobe", "Proepisternum",...]
var shapes:Array = [pt0, pt1, pt2, ...]

for (var i:int = 0; i < parts.length; i++){
    var b:MovieClip = new Btn();
    but.x = 15;
    but.y = ((i)*(b.height+1))+10;
    but.name = "b"+i;
    but.info.text = parts[i];
    but.buttonMode = true;
    but.info.mouseEnabled=false;
    addChild(b);
    but.addEventListener(MouseEvent.ROLL_OVER, rollHandler);
    but.addEventListener(MouseEvent.ROLL_OUT, outHandler);
    //b.addEventListener(MouseEvent.CLICK, outHandler);

}

for (var j:int = 0; j < shapes.length; j++){
    shapes[j].buttonMode = true;
    shapes[j].addEventListener(MouseEvent.ROLL_OVER, rollHandler2);
    shapes[j].addEventListener(MouseEvent.ROLL_OUT, outHandler2);
}

function rollHandler(event:MouseEvent):void {
    for (var i:int = 0; i < parts.length; i++) {
        if (event.currentTarget.name == "b"+i) {
            this.shapes[i].gotoAndStop("over");
            event.currentTarget.gotoAndStop("over");
        }
    }
}

function outHandler(event:MouseEvent):void {
    for (var i:int = 0; i < parts.length; i++) {
        if (event.currentTarget.name == "b"+i) {
            this.but[i].gotoAndStop("start");
            event.currentTarget.gotoAndStop("start");
        }
    }
}

function rollHandler2(event:MouseEvent):void {
    for (var i:int = 0; i < shapes.length; i++) {
        if (event.currentTarget == shapes[i]) {
            this.parts[i].gotoAndStop("over");
                        //How should i call the button b created from the parts loop?
            event.currentTarget.gotoAndStop("over");
        }
    }
}

function outHandler2(event:MouseEvent):void {
    for (var i:int = 0; i < shapes.length; i++) {
        if (event.currentTarget == shapes[i]) {
            this.b[i].gotoAndStop("start");
                        //same problem here.. Not sure how to call it.
            event.currentTarget.gotoAndStop("start");
        }
    }
}
</code>
Comment: Please format your code in the question, it is kinda hard to read it like this.
Comment: someone fixed it for you, but for the next time, use a  tag before your you enter your code
Answer: I've made some modifications in your code. look at the comment and you should get what i mean. All my comments are marked as this: //---This is an example comment---\\
<code>//the arrays look like this...

var parts:Array= [ "Cervical sclerites", "Protonotopleural lobe", "Proepisternum",...];
var shapes:Array = [pt0, pt1, pt2, ...];
var buttons:Array = new Array(); //---Create new array to hold your buttons---\\

for (var i:int = 0; i < parts.length; i++){
    var b:MovieClip = new Btn();
    but.x = 15;
    but.y = ((i)*(b.height+1))+10;
    but.name = "b"+i;
    but.info.text = parts[i];
    but.buttonMode = true;
    but.info.mouseEnabled=false;
    buttons.push(b); //---Push your button into the array each time it loops---\\
    addChild(b);
    but.addEventListener(MouseEvent.ROLL_OVER, rollHandler);
    but.addEventListener(MouseEvent.ROLL_OUT, outHandler);
    //b.addEventListener(MouseEvent.CLICK, outHandler);

}

for (var j:int = 0; j < shapes.length; j++){
    shapes[j].buttonMode = true;
    shapes[j].addEventListener(MouseEvent.ROLL_OVER, rollHandler2);
    shapes[j].addEventListener(MouseEvent.ROLL_OUT, outHandler2);
}

function rollHandler(event:MouseEvent):void {
    for (var i:int = 0; i < parts.length; i++) {
        if (event.currentTarget.name == "b"+i) {
            this.shapes[i].gotoAndStop("over");
            event.currentTarget.gotoAndStop("over");
        }
    }
}

function outHandler(event:MouseEvent):void {
    for (var i:int = 0; i < parts.length; i++) {
        if (event.currentTarget.name == "b"+i) {
            this.but[i].gotoAndStop("start");
            event.currentTarget.gotoAndStop("start");
        }
    }
}

function rollHandler2(event:MouseEvent):void {
    for (var i:int = 0; i < shapes.length; i++) {
        if (event.currentTarget == shapes[i]) {
            this.parts[i].gotoAndStop("over");
                        //How should i call the button b created from the parts loop?
            buttons[i].gotoAndStop("over"); //---Then you call the button like this at each place.---\\
            event.currentTarget.gotoAndStop("over");
        }
    }
}

function outHandler2(event:MouseEvent):void {
    for (var i:int = 0; i < shapes.length; i++) {
        if (event.currentTarget == shapes[i]) {
            this.b[i].gotoAndStop("start");
                        //same problem here.. Not sure how to call it.
            event.currentTarget.gotoAndStop("start");
        }
    }
}
</code>
Hope this helps!
Comment: Thanks thought of using the push method too right after posting.  But had some syntax errors and didn't think it would work.  Figured it out and now it works.  Thanks for clarifying that I used it the right way too.
Comment: You're welcome, since this answer is right and it helped you mark it as accepted answer please (green check mark at the top left of my answer).


Mockito fails when junit3 is on the classpath

Question: I'm working on a project that has a lot of legacy junit3 test. We've recently switched to JUnit 5 and are running the old tests through junit-vintage. For several reasons, we were not able to easily get rid of the junit3 dependency, so it's still on the classpath (which doesn't cause any problems so far).
The problems arise when using mockito.verify(), in a test that catches a difference in arguments:
public class TestTestTest {
    interface Foo {
        void frobnicate(int a);
    }

    @Test
    void testMockito() {
        Foo foo = mock(Foo.class);
        foo.frobnicate(42);
        verify(foo).frobnicate(43);
    }
}

results in
java.lang.VerifyError: Bad return type
Exception Details:
  Location:
    org/mockito/internal/junit/ExceptionFactory$JUnitArgsAreDifferent.create(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/AssertionError; @10: areturn
  Reason:
    Type 'org/mockito/exceptions/verification/junit/ArgumentsAreDifferent' (current frame, stack[0]) is not assignable to 'java/lang/AssertionError' (from method signature)
  Current Frame:
    bci: @10
    flags: { }
    locals: { 'java/lang/String', 'java/lang/String', 'java/lang/String' }
    stack: { 'org/mockito/exceptions/verification/junit/ArgumentsAreDifferent' }
  Bytecode:
    0x0000000: bb00 0259 2a2b 2cb7 0003 b0

    at org.mockito.internal.junit.ExceptionFactory.canLoadJunitClass(ExceptionFactory.java:33)
    at org.mockito.internal.junit.ExceptionFactory.<clinit>(ExceptionFactory.java:12)
    at org.mockito.internal.exceptions.Reporter.argumentsAreDifferent(Reporter.java:313)
    at org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation(MissingInvocationChecker.java:43)
    at org.mockito.internal.verification.Times.verify(Times.java:37)
    at org.mockito.internal.verification.MockAwareVerificationMode.verify(MockAwareVerificationMode.java:27)
    at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:72)
    at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
    at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:35)
    at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:63)
    at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:49)
    at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:128)
    at test.TestTestTest$Foo$MockitoMock$448839763.setValue(Unknown Source)
    at test.TestTestTest.testMockito(TestTestTest.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:513)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)

The underlying reason seems to be a linker error (ArgumentsAreDifferent is a junit4 AssertionError, but not a junit3 AssertionError)
Is there a workaround for this, assuming I cannot get rid of the junit3 dependency?
Comment: Have you tried to add Junit4 to classpath?
Comment: @uli That's already on there (it needs to be for junit-vintage to work).
Answer: I've got the same error with Mockito. However there was com.google.android.tools:dx:1.7 instead of JUnit3. But looks like this dependency contains at least some JUnit3's packages and classes.
The problem here is that Mockito creates ArgumentsAreDifferent class that extends junit.framework.ComparisonFailure. In JUnit 4 ComparisonFailure through intermediate classes extends java.lang.AssertionError what is expected by Mockito. But in JUnit 3 (and com.google.android.tools:dx) ComparisonFailure does not extend AssertionError.
I've fixed it with just excluding this dependency as it was actually not needed for me.
Do not know how to fix this in your case as JUnit3 is required. Maybe classloading order or something. But hope this information will be helpful.


Scrollbar in tkinter, for matplotlib

Question: I have little experience how to combine matplotlib with tkinter or pyqt.
I need a horizontal scroll bar on the matplotlib chart.
I want to zoom the graph horizontally and scroll the graph from the beginning
to the end of the data that is loaded from the file.
After reviewing the examples, I added a scroll bar.
But she's completely unresponsive to the chart.)
And the process doesn't end when I close the window(how to remove not understood, an example taken from here enter link)
import tkinter
from tkinter import *
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

root = tkinter.Tk()

x = pd.read_csv('file.txt',
                    index_col='DATE',
                    parse_dates=True,
                    infer_datetime_format=True)
z = x.iloc[:, 3].values
N = len(z)
ind = np.arange(N)
fig, ax = plt.subplots()
ax.plot(ind, z)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

scrollbar = tkinter.Scrollbar(master=root, orient=HORIZONTAL)
scrollbar.pack(side=tkinter.BOTTOM, fill=X)

tkinter.mainloop()

After adding a row
scrollbar["command"] = canvas.get_tk_widget().xview

As pointed out- MaxiMouse.
The graph scrolls, but not along the entire length.
I need the scroll to work on all the data after zooming in. I displayed this at the end of the video.
Answer: Put this before the tkinter.mainloop() call:
scrollbar["command"] = canvas.get_tk_widget().xview
canvas.get_tk_widget()["xscrollcommand"] = scrollbar.set

Scrollbar in tkinter, for matplotlib


Can SwipeGesture (Present Modely/Show/Show Details/Deprecated Push) can only handle a maximum of 4 View controllers?

Question: In my App I am using 5 ViewControllers. While I try to navigate to last one , It won't display. No error message displayed.
To go to next screen We are giving action to left swipe gesture using segue.
We have tried the solution provided in below link. They said to use push deprecated and then compile. Again use show segue(not specified Show / Show Details) we tried using both and the compile. It will solve the problem as it is issue with Xcode. But this solution doesn't work. I also not able to comment on their post.
Can UINavigationController only handle a maximum of 4 Viewcontrollers?
We have tried all navigation using segue Show, Show Details,Present Modally and
Push Deprecated.
In all segue except Push Deprecated controller neither go to fifth controller neither it give error. Push deprecated gives sigbart error while tried to run on iPhone.
We are using Xcode10 and iOS 12.0.
While developing same app in Xcode 9 Objective C code we have first 2 navigation  are present modally, next two are having show segue and last one is present modally. It works fine on that code. We tried this solution also but it wont work. Currently I am upgrading same code in Swift with latest library and i am facing this issue. Please help.
Answer: There is no limit in number of pushed view controllers. Maybe it would be easier to add gesture recognizer in code on viewDidLoad for instance and put some breakpoints to see what goes on there.
To play around with these things you can try this minimalistic code which will push  a new view controller on every tap. You can create a new project and simply overwrite the content of autogenerated ViewController and all should work:
import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        present(UINavigationController(rootViewController: MyViewController()), animated: true, completion: nil)
    }

}

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap)))
        self.title = "View controller \(navigationController?.viewControllers.count ?? 0)"
    }

    @objc private func onTap() {
        navigationController?.pushViewController(MyViewController(), animated: true)
    }
}

To explain:
An instance of ViewController will be created as a root view controller in your main window which is part of project settings (which storyboard to use) and part of autogenerated storyboard named main.
We need to wait for view to appear of the first view controller before we can present our new navigation view controller. We presented with having a root view controller as our own subclass of view controller called MyViewController. This view controller is not in storyboard.
When an instance of MyViewController comes into hierarchy (using push or present) a viewDidLoad will be called which creates a tap gesture recognizer set to a method to push a new instance of MyViewController. We also set a title depending on the number of view controllers on navigation controller just to have more information.
As said this is a minimalistic code. But in general you would do something like:
override func viewDidLoad() {
    super.viewDidLoad()

    view.addGestureRecognizer({
        let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(onSwipeLeft))
        swipeRecognizer.direction = .left
        return swipeRecognizer
    }())
}

@objc private func onSwipeLeft() {
    let controllerToBePushed = UIStoryboard(name: "my_storyboard_name", bundle: nil).instantiateViewController(withIdentifier: "the_identifier_I_set_in_storyboard") as! WhateverTheTypeOfMyViewControllerIs
    navigationController?.pushViewController(controllerToBePushed, animated: true)
}


Page title set from the title callback doesn't change

Question: I created a simple download module to redirect a user when they click the download button to another page. Now I need to change the the page title every time a new download is triggered.
This is my code.
function custom_download_menu() {
  $items['download-code'] = array(
    'title callback' => 'custom_download_page_title',
    'page callback' => 'custom_download_view',
    'access arguments' => array('access content'),
    'access callback' => TRUE,
  );

  return $items;
}

function custom_download_page_title() {
  if (isset($_POST['title'])) {
    $title = "Downloading " . $_POST['title'] . " Code";
  }
  else {
    $title = "Download Code";
  }

  return $title;
}

But most of the time, the title does not change. It seems that it is using the title that is cached before.
I already added the following code so the page will not be cached:
drupal_add_http_header("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
drupal_add_http_header("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
drupal_add_http_header("Cache-Control", "post-check=0, pre-check=0", false);
drupal_add_http_header("Pragma", "no-cache"); // HTTP/1.0
drupal_add_http_header("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

Am I missing something?
Update:
<form id="form1" name="form1" method="post" action="/download-code">
    <input type="hidden" name="title" id="title" value="[node:title]" />
    <input type="hidden" name="download_code" id="download_code" value="[node:field_code_file]" />
    <input type="hidden" name="uri" id="uri" value="[node:url:relative]" />
    <input type="submit" class="downloadButton" value="Download Code">
</form>

Answer: You're missing the title arguments key in hook_menu
e.g:
/**
 * Implements hook_menu
 */
function custom_download_menu() {
  $items = array();

  $items['download-code/%'] = array(
    'title callback' => 'custom_download_page_title',
    'title arguments' => array(1),
    'page callback' => 'custom_download_view',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * hook_menu title callback
 */
function custom_download_page_title($file) {
  if (isset($file) {
    $title = "Downloading " . $file . " Code";
  }
  else {
    $title = "Download Code";
  }
  return $title;
}

If the download link is

download-code/my-file.txt

The page title should then reflect that.
Comment: I'm using $_POST method and not $_GET. So this code still does not work for me.
Comment: You're using HTTP POST to download a file? you should probably use GET
Comment: I can't use HTTP GET because I am using the code above. Please see my update on my post. If I will use GET the file will reveal. I use this because I don't know how to get the file using NID.
Answer: Instead of a title callback, in the page callback for the download-code page, put the check and set title using, drupal_set_title.
Put this code at the top of the callback function:
if (isset($_POST['title']))
        $title = "Downloading " . $_POST['title'] . " Code";
    else
        $title = "Download Code";
drupal_set_title($title);

Please make sure you clear menu cache and check to see if this works
Comment: No. There is a value in the POST method. Please try to look at my site at http://bit.ly/1fPIyst. Click the download button at the bottom of the page and look at the Title of the page.
Comment: just had a look, when directly accessing "download-code" page the title is "Download Code" and when reaching through Download button the title is "Downloading Calculator - My First Basic4Android Application Code". This is what you require no?..Are you getting some different behaviour?
Comment: When you reach the /download-code you will see a "Downloading Calculator - My First Basic4Android Application Code" below the "home" menu. But what I mean is the Title of the page. Look at the title bar of your browser and you will see that the title is "Downloading TTJ- Inventory System Code | Free source code, tutorials and articles"
Comment: To make sure that you understand what I main, access the page source of download-code and look at the title tag within the head tag. The value is: Downloading TTJ- Inventory System Code | Free source code, tutorials and articles.
Comment: I saw this. ok let us try this approach. I updated my answer.
Comment: I already updated the code and flush all cache, but the same problem. This time the title tag has this value "Downloading Dennis Class Example Code | Free source code, tutorials and articles". Is this not because of caching? I'm using memcached.
Comment: I also tried to disable and enable the module to no luck.
Comment: memcache - this might be it. For sure the above code works in clean install and I misinterpreted "cache" in your question to drupal cache. Will let you know if I find anything.


Multilingual comments form missing

Question: I have a website in 2 languages. The site uses panels. The nodes Comments form & comments only shows in English and not in Greek.
Has anyone encountered a similar problem? Thnx in advance.
Answer: The i18n comments can be used for this.  From the project page:

A very simple module which would allow you to show all/any comments
  attached to all node translations. Just a great way to communicate in
  truly multi-lingual environments.
For example I have node in English and Spanish. Drupal natural way
  would be to show comments for en/es translation separately (attached
  to en/es content). But i18n_comments will aggregate all English and
  Spanish comments for any translations. It doesn't matter if user will
  leave a comment to any node translation.
Comment: it is in beta version. will it work properly?

Multilingual comments form missing


Fourier Transform on positive real line

Question: Suppose $f(x)$ is defined only for $x\geq 0$. Is it correct to apply Fourier Transform operator to $f(x)$? I ask because integral of the Fourier Transform operator runs from $-\infty$ to $\infty$, but $f(x)$ is not defined for $x<0$.
P.S. Searching the net reveals examples where Fourier Transform operator is applied to partial differential equations defined over a semi-infinite domain, but that doesn't answer my question (or I don't know how it answers my question). Also I am an engineer and not a mathematician.
Comment: What is your function exactly? Can't you define your function equal to zero on $]-\infty,0]$? Notice that you must have either $\int |f(x)| dx< + \infty$ to apply directly the Fourier Transform.
Comment: You can settle for $\int|f(x)|^2dx<+\infty$ too, no? The Fourier transform can be extended to $L^2$ functions by a density argument if I remember correctly.
Comment: The natural transform to apply on the half line is the Laplace Transform. Typically Fourier transform is applied on the whole line and Fourier Series to finite intervals.
Comment: @Netchaiev My function in the simplest case is simply $e^{-x}$ defined over $x\geq 0$. It is the probability that a droplet does not suffer a collision after it has fallen a distance $x$ (oriented downward). Since a droplet falls and does not rise the probability function is not defined for $x<0$. Assuming it to be zero for $x<0$ is physically erroneous; it is simply not defined.
Comment: @TonyS.F. Please see my comment above.
Comment: @Paul I wish to decompose my function into a sine/cosine basis to employ some linearization arguments to simplify subsequent calculations. So you think Fourier transform is unconditionally inapplicable to my case?
Comment: @Deep you are right for the extension to $L^2$, but even it can be extended by density, it is not straightforward to compute the Fourier Transform. But in your case you are in $L^1$. Now, the important part is that you are wrong about your understanding of the density of the probability : since it is impossible for a droplet to rise, than the probability of such event is $0$, and the associated density on $]-\infty,0]$ is $0$. Your density is perfectly defined on $\mathbb{R}$ itself!
Comment: @Deep : the simple case of your problem is known as exponential distribution, and its Fourier Transform is $\frac{1}{1-it}$. (Again, it is not because an event is impossible that the density is not defined : on the contrary, that is precisely what a $0$ density means!)
Comment: @Netchaiev Thanks for your comment. You have given me food for thought.
Answer: You can also deal with the Fourier transform on $[0,\infty)$ through cosine and or sine transforms
$$
          \int_{0}^{\infty}f(t)\cos(st)dt,\;\; \int_{0}^{\infty}f(t)\sin(st)dt.
$$
Both of these have corresponding inverses:
$$
        \frac{2}{\pi}\int_{0}^{\infty}\left(\int_{0}^{\infty}f(t)\cos(st)dt\right) \cos(sx)ds \sim f(x), \\
        \frac{2}{\pi}\int_{0}^{\infty}\left(\int_{0}^{\infty}f(t)\sin(st)dt\right)\sin(sx)ds \sim f(x).
$$
Obviously there are problems with pointwise convergence at $x=0$ for the Fourier sine transform and its inverse sine transform. There are also issues for the cosine transform at $x=0$. But these are valid transforms in the $L^2$ sense, and the transforms are their own inverses, which is nice. There's also a Parseval $L^2$ identity for each.
Comment: +1 It seems that Cosine/Sine transforms are also defined over $(-\infty,+\infty)$ but for even (odd) functions the integral reduces to Cosine (Sine) transform over $[0,\infty)$ as per https://en.wikipedia.org/wiki/Sine_and_cosine_transforms.
Comment: @Deep : The Fourier sine transform also naturally arises in connection with the spectral theory for $-\frac{d^2}{dx^2}$ on $[0,\infty)$ with $0$ endpoint condition at $x=0$. The cosine transform is associated with the same operator on $[0,\infty)$ but $0$ first derivative condition at $0$.

Fourier Transform on positive real line


Adapt camera view with Surfaceview dimension

Question: I'm developing an application where I read some barcode. In a first step I had a big SurfaceView where I can see well the camera preview, but now I would set the dimensions of Surfaceview like the dimensions of barcode but I have bad camera visualization (it is too small). Can someone help me to stretch camera preview? Thanks
Here manage detector and surfaceview:
public class LettoreBarcode extends Fragment {
View view;
SurfaceView surfaceView;
Handler handler;

private BarcodeDetector detector;
private CameraSource cameraSource;
private TextView code;
SparseArray<Barcode> items;

private static Button btnBack;

String barcode = "" ;
SparseArray<Articoli> groups = new SparseArray<Articoli>();

Context _context = null;
ProductsAdapter.ViewHolder _ViewHolder = null;

public LettoreBarcode(){

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_barcode_scanner, container, false);

   surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);

    detector = new BarcodeDetector.Builder(getActivity()).setBarcodeFormats(Barcode.ALL_FORMATS).build();
    final Dialog d = new Dialog(getActivity());
    btnBack = (Button) view.findViewById(R.id.btnBack);
    handler = new Handler();

    if(!detector.isOperational()){
        Toast.makeText(getActivity(), "Detector non attivabile", Toast.LENGTH_LONG).show();
    }

    cameraSource = new CameraSource.Builder(getActivity(), detector).setAutoFocusEnabled(true).build();

    surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            AttivaCamera();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });

    detector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            items = detections.getDetectedItems();
            if (items.size() > 0){
               getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (items.valueAt(0) != null){
                            //do something

                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    DisattivaCamera();

                                }
                            },10);            //1000
                        }else
                        {
                            d.setContentView(R.layout.dialog_barcode_assente);
                            d.setTitle("Scanner");
                            d.setCancelable(true);
                            d.show();
                            DisattivaCamera();
                        }
                    }
                });

            }
        }

    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    });

   return view;
}

private void AttivaCamera()
{
    try{
        cameraSource.start(surfaceView.getHolder());
    }catch(IOException e){
        Toast.makeText(getActivity(), "Errore nell'avvio della fotocamera", Toast.LENGTH_LONG).show();
    }
}

private void DisattivaCamera()
{
    cameraSource.stop();
}

}
It is how I visualize camera with small surfaceview:
https://i.stack.imgur.com/TMunJ.png
I'm new in android development so I'm sorry if could be a lot of mistake in the code.
Sorry for my english also..
Thanks you guys!
Comment: Where do you set the size of the SurfaceView?
Comment: In my xml. It has width: match_parent and height: 400dp
Comment: So, you expected to display only part of the camera input that corresponds to a barcode, but instead you see the whole picture, distorted, don't you?
Comment: Yes, exactly it is my problem
Answer: In order to display only part of the camera input, i.e. to crop it on the screen, you need a surface view that has dimensions that fit the camera frame aspect ratio, and overlay it with some nontransparent views to leave only part of it visible. Don't put the SurfaeView inside scrolling layout:
So, instead of
<SurfaceView width: match_parent height: 400dp />

you need e.g. FrameLayout as explained here: Is it possible to crop camera preview?
This will not change the frame that arrives to the barcode detector. But this should not worry you; the detector will handle the uncropped image correctly.


Changing to '@mui/material' makes the components not rendered

Question: I have a JS file (react) that looks like this:
import { Grid, TextField, makeStyles } from '@material-ui/core'
import React from 'react'
import {useState}  from 'react'

//remove this function and refresh. see magic.
const useStyle = makeStyles(theme => ({
    root:{
        '& .MuiFormControl-root':{
        width : '80%',
        margin : theme.spacing(.75)
        }
    }
}))

const initialFormValues = {
    id:0,
    name:'',
    username:'',
    email:''
}

export default function EntryForm() {
    const [values, setvalues] = useState(initialFormValues)

    return (
        <form className={useStyle().root}>
            <Grid container>
                <Grid item>
                    <TextField
                    size='small'
                    variant='outlined'
                    label='name'
                    value={values.name} />
                    <TextField
                    size='small'
                    variant='outlined'
                    label='username'
                    value={values.username} />
                    <TextField
                    size='small'
                    variant='outlined'
                    label='email'
                    value={values.email} />
                </Grid>
                <Grid item>
                </Grid>
            </Grid>
        </form>
    )
}

This works fine, and invoked, the fields get rendered along with it's parent components.
However, changing first line to:
import { Grid, TextField, makeStyles } from '@mui/material'

and refreshing the browser makes the whole page empty. Apparently, this happens specifically with makeStyles from '@mui/material' usage. Using Grid and Textfield from '@mui/material' only doesn't cause that.
What is happening here?
Answer: As per docs you should import makeStyles from @mui/styles.
Please try updating the import statement as:
import { makeStyles } from "@mui/styles";


Empty set does not belong to any cartesian product?

Question: I am reading from Halmos naive set theory, for Cartesian product, defined as:
$$
A\times B=\left\{x: x \in P(P(A\cup B))\,\wedge\,\exists a \in A,\exists b \in B,\, x=(a,b)\right\}
$$
Empty set belongs to $P(P(AUB))$, but since in $(a,b)$ for some $a$ in $A$ and some $b$ in $B$ , because of existence quantifier empty set doesn't belong to $A\times B$ right? But still empty set could be an ordered pair.
in Halmos, $(a,b)=\{\{a\},\{a,b\}\}$  , so empty set also an ordered pair but no cartesian product has it as an element. am i correct?
Comment: Any ordered pair has elements, and the empty set has not. So the empty set is *not* an ordered pair. Elements of Cartesian product are ordered pairs, hence are not empty. Be careful with "belong to". It gives confusion between "is element of" and "is subset of".
Comment: is it mentioned that ordered pair should have elements?
Comment: @Arjun: "for some" $a \in A$ and "some" $b \in B$. The word "some" refers to existence.
Comment: This really highlights out some problems with ZFC theory. I define $A\times B$ as follows: $$\forall x,y:[(x,y)\in A\times B \iff x\in A \land y\in B]$$
Answer: The empty set is not an ordered pair; neither intuitively  (what things would form the ordered if you just have an empty set?) nor in the formalization you recall.
Note that $(a,b)= \{\{a\}, \{a,b\}\}$ implies $\{a\} \in \{\{a\}, \{a,b\}\}$.
Whence the set $(a,b)$ cannot be empty, as it has $\{a\}$ as element.
Let me add though that a Cartesian product can be equal to the empty set.
Namely $ A \times B = \emptyset $ when $A= \emptyset $ or $B = \emptyset$.
Yet even in this case the empty set is not an ordered pair, as in this case there are just no ordered pairs at all.
So, $ \emptyset= A \times B $ is possible,
 $\emptyset \in A \times B$ is impossible.
Comment: @Arjun you can  essentially say (for all a) (for all b) the set {{a}, {a,b}} is an ordered pair. However a set  {{a}, {a,b}} is **never** the emptyset because it always has {a} as element, so for all a and for all b, {a} is an element of   {{a}, {a,b}}. **Therefore**  {{a}, {a,b}} is **never** the emptyset. This is not altered by the fact that you could quantifiy a over the emptyset, in which case there are no order pairs at all.  But if there are none at all, again none is equal to the empty set. There is none, so how should one be equal to the empty set.
Comment: but we also take {a} itself as ordered, its not needed to take 2 distinct elements, So I thought for single element its already ordered, if no elements nothing to order. But if in ordered pair definition will they say there exists some a and some b , (a,b)={{a{,{a,b}} ? if that is the case then empty set cant be an ordered pair. did you mean this?
Comment: It is true that the elements need not be different however, even for $a= b = \emptyset$ you have that $(\emptyset, \emptyset) = \{\{\emptyset\}  \} $ which has as element $\{\emptyset\}$ and thus is not empty. On the other point, this is what I say in the update: if there are no elements, there is nothing to oder, yes, and the Cartesian product is empty. But this does not mean it has the empty set as element.
Comment: i have this doubt because if {a} is an ordered pair then we are allowing B to be empty (in one sense, I am not talking about a∈A and a∈B ,so {a} is ordered ).  I am saying {a} can also mean a∈A and since no b∈B, we get {a}. So i thought when both A and B are empty we get ∅, so its ordered
Comment: @Arjun "then we are allowing $B$ to be empty" If $B$ is empty then $A\times B=\varnothing$ (as said by quid). So then there are no ordered pairs that belong to it. Second note: $\{a\}$ can only be an ordered pair if $a=\{c\}$ for some $c$. Then $\langle c,c\rangle=\{\{c\},\{c,c\}\}=\{\{c\}\}=\{a\}$.
Comment: Sorry, its {{a}} not {a} .  I understood  ∅∈A×B is impossible by definition . but i am talking about ordered pair (a,b)={{a},{a,b}} why the existential quantifier for this. we could have said (for all a)(for all b) {{a},{a,b}} is an ordered pair. and still we could have the existential quantification for the condition in A×B, so that ∅∈A×B is impossible.
Comment: @Arjun Another notation (without quantifiers) is: $A\times B:=\left\{ \langle a,b\rangle\mid a\in A\wedge b\in B\right\} $.
Do you understand that it equals the RHS of the equality in your question?
Comment: thanks, I got my mistake. if A and B are empty, we get {{a}, {a,b}} ={ {} } . so empty set cant be an ordered pair.
Answer: With the definition,
$$A \times B = \{ X \in P(P (A \cap B)) : \exists a \in A, \exists b \in B[X = (a,b)]\}$$
One should note that we are defining with $\in$, which does not consider the empty set, but $\{\varnothing\} \in A$ is certainly possible, i.e. the set containing the empty set can be an element (also note that there are set-theoretic definition of $0$ such as $\{\varnothing\})$. However, the empty set is still a subset of $A \times B$, which differs from being an element.


Integral $\int_{0}^{T} e^{-jnwt}dt$

Question: I'm representing some function using complex Fourier series and I have to solve this integral:
$\int_{0}^{T} e^{-jnwt}dt$, where $w=\frac{2\pi}{T}$
I got this:
$\int_{0}^{T} e^{-jnwt}dt=...=-\frac{1}{jnw}e^{-jnwT}+\frac{1}{jnw}=\frac{1}{jnw}-\frac{1}{jnw}(\cos(2jn\pi)-\sin(2jn\pi))$
My question is, how cosine and sine terms in brackets behave for different n (n goes from $-\infty$ to $n=+\infty$)?
EDIT: I made mistake, there is of coure no imaginary j as argument of sine and cosine. I'm not concentrated, it's too late :)
Answer: You made an error simplifying the result of the integral. You should have gotten:
$\displaystyle\int_{0}^{T}e^{jnwt}\,dt$ $= -\dfrac{1}{jnw}e^{-jnwT}+\dfrac{1}{jnw} $ $= \dfrac{1-e^{-jnwT}}{jnw}$ $= \dfrac{e^{-jnwT/2}(e^{jnwT/2}-e^{-jnwT/2})}{jnw}$ $= \dfrac{2e^{-jnwT/2}\sin(nwT/2)}{nw}$.
The magnitude of the Fourier coefficients is $\dfrac{2\sin(nwT/2)}{nw}$. As $|n| \to \infty$, this tends to $0$ like $n^{-1}$. Due to the sin term, there could be some oscillations.

Integral $\int_{0}^{T} e^{-jnwt}dt$


Term for functions with results between 0 and 1?

Question: Is there a term for functions $f: x \in \mathbb{R}_{\geq 0} \to [0, 1] $ that have the following properties:

Strictly monotony
$f(0) = 0$
$\lim_{x \to \infty} f(x) = 1$

Functions (found here) I think about are:

$f(x)=1−1/exp(−x)$
$f(x)=1−1/(1+x)$

The reason I'm asking is that I want to search for such functions but don't no what to search for. Therefore as a starting point it would help to know how functions with results between 0 and 1 are called.
Edit: as requested in the comments here my motivation why I could need functions with such properties. Consider I want to transform the repuation of Stackexchange users into a number between 0 and 1 (a "normalization" which allows me to compare this number) to some other number between 0 and 1 (eg the normalized number of badges). So 0 reputation should be 0; 10 reputation should be 0.1; 1000 reputation should be 0.5, 50K reputation should be 0.9; 1 million repuation should be 0.99, and so forth, but always < 1. If I used $f = log$ this would not bound the values to 1.
Comment: Perhaps a "cumulative distribution function"?  It would help to know *why* you are considering functions with these properties...
Comment: @XanderHenderson, except for property 2 (which is fulfilled by some, but not all), cumulative distribution functions fulfill the properties I mentioned. I'm looking for a a function to give small numbers a small value, and high numbers a high values (with the restriction that the small value should be 0 and the high value below 1) - eg. for some kind of ranking.
Answer: I don't think there is any accepted term for these functions, but you could use your own suggestion, after a careful warning. Something like:

For the purpose of this paper, let us introduce a convenient definition. Let us call normalization function a function $f: x \in \mathbb{R}_{\geq 0} \to [0, 1] $ satisfying the following properties:

$f$ is strictly monotone,
$f(0) = 0$,
$\lim_{x \to \infty} f(x) = 1$.
Comment: Thank you for your efforts. As mentioned in the question, I want to *search*  for such functions (and not to properly name such functions in a paper). However, "normalization function" seems to be a good starting point for my Google search.


Interaction effect and plot

Question: I have ran a (mixed) linear model, finding a strong two-way interaction effect between two predictors (p < 0.001).To better understand the interaction in point, I have produced an interaction plot, finding that the two lines in the plot do not cross each other.
To the best of my knowledge, the two lines must cross each other for an interaction effect to be present - this kind of "switch" gives in fact an immediate intuition of what the interaction is about.
Am I correct? Or is it possible to have an interaction effect in which the two lines do not cross?
Any elucidation on this would be much appreciated!
Answer: No, that's not correct. You can even have lines cross that does imply interaction. You can almost think of it as being whether or not the slope of the lines are statistically significantly different. It's just that if the slopes are very different then the lines are likely to cross.
Comment: So, if I understand it correctly, the condition for an interaction to be present is that the slopes of the lines involved must be statistically different. It is crystal clear, thank you so much for the insight!

Interaction effect and plot


Token authentication not working django rest framework

Question: I am using token authentication for my current project but I have one problem, I can not authenticate a use for the life of me. To test my authentication I created a superuser and then the command python manage.py drf_create_token test1. And then created this view:
class HelloView(APIView):
    permission_classes = (IsAuthenticated)

    def get(self, request):
        content = {'message': 'Hello, World!'}
        return Response(content)

In my setting.py file I have:
INSTALLED_APPS = [
    ... # ...
    'rest_framework',
    'rest_framework.authtoken',
    'backend',
    'frontend'
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

And when I test my API I keep geting:
{
    "detail": "Authentication credentials were not provided."
}

What am I missing here? can anyone tell me? Thank you in advance.
Answer: If you use token authentication, then you must send token in all request to server in headers. So, you header request should contain the following entry:
Comment: You make yourself very clear, one problem though see I am new to token authentication and do not know how to do this, if you could provide me a code sample i would be very thankful.
Comment: But if you don't have the time could you at least tell me where can I learn how to do this(resources for learning how to do this)
Comment: here is clear described https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html
Comment: thank you very much for your time and effort, I finaly solved my problem


Views Infinite Scroll doesn't hide pager

Question: I need infinite scrolling for a View.  I installed Views Infinite Scroll, and it will work if I set jQuery Update to version 1.8, but when it loads the next page, it leaves the pager in plain site.  I don't want the pager to display, and I can't figure out how to disable it.  Also, when it's loading the next page of content, it displays that ugly progress GIF.  Is there a way to hide that as well, and just get a nice scroll functionality, like on Twitter?
I don't know if this is causing an issue, but my View results are nodes, using Display Suite view mode.  In these nodes, I have another View that displays product pricing and other fields, using Commerce Add To Cart Extras.  Would this other View (in each node) conflict with the Views Infinite Scroll module for my main View?
If I have to do this through code, what is the best route?  Should I use the Views Ajax API somehow, or is there another JS or jQuery library that I can integrate with Views?
I tried to use the Views Load More with Wayports, but I couldn't get that to work either.  The best I got was the View to just display the "Load More" link, which I don't want.
Comment: If it loads the next page and leaves the pager displayed, it means that probably the CSS is being overridden - inspect element and see if theme's styles are forcing the pager to be visible. If not, check the console log for any JavaScript errors.
Comment: I disabled my theme's CSS for pagers (I'm using Omega 3) and that doesn't help, and there are no JavaScript errors in devtools.  Another anomaly is when I get to the end of the scroll, it doubles up again, except without the images.
Comment: and since it only works with jQuery 1.8, my Views UI behaves oddly.
Comment: Did you try switching the theme to Bartik? If everything works when you switch it, it's probably something in your theme causing the issue.
Comment: I haven't.  It's a live site, so I need to figure out how to try that.
Comment: It's the easiest way at the moment; download it and test it in local or just clone it to `/dev` on the live server, together with the database.
Comment: We're setting up a dev testing site for it anyway, so I'll do that.
Comment: I have the pager hidden by overwriting the CSS.  The views rows double up at the end though.  I'll open another question for that.
Answer: To hide the pager, I just set the display: none in the CSS.
Comment: it works, but surely that is a bug?
Answer: Here's an issue regarding this in Drupal.org.
https://www.drupal.org/node/1234704


Long wait time for website and taking too much CPU+Memory

Question: My drupal site is taking too long wait time, and it uses CPU + memory. My server setting is
16GB RAM, 8 processors. So it is good.
I am using Commerce Kickstart distribution have enabled 180 modules all are required cant disable a single module, I cant use caching coz content is mostly dynamic. My site loads in 8 second (most pages) in which wait time is only 6-7 seconds. Multiple hits takes CPU usage to 100%. I have checked reports with xhprof, top command on server, database tuning script, front page executes 4,52,600 functions, PDO commit taking 31% CPU, Database connections are not properly closed.
I have tried database tuniing module, database tuning script but nothing is working fine right now for me.
Cant use caching even default drupal views caching.
Please suggest some steps, any help will be a big big favor. Website i am building is dynamic so caching is prohibited.
Comment: _"Website i am building is dynamic so caching is prohibited."_ With the greatest respect, I don't think you properly understand what caching is. Dynamic websites _have_ to use caching, _because_ they are dynamic. If you refuse to use caching, you should definitely expect to have a slow site; Drupal is very database heavy
Comment: @Clive Oh, right, Commerce. My bad, missed it. Well, I couldn't agree more with caching in that case. Of course there are some in-RAM solutions with MySQL/Marina interface that can solve it, but they are not cheap, and not quite a drop-in replacements (yet?).
Comment: *enabled 180 modules*? That's some complicated setup. Maybe it's time to replace them with one optimised custom module?
Comment: @Mołot 180 modules isn't that bad for a Drupal Commerce install. The latest one I'm building is currently at 203 (all 'required') and when we enable RMA and other features there will be more. It just makes caching all that more important
Comment: "I have checked reports with xhprof" - What are the top 20 slowest calls?
Comment: Hi, I'm afraid your question has become too broad for our Q+A format. We can't provide one-2-one support here, or help you with your specific Drupal/server config, as we need narrowly-scoped, generically answerable questions, that will remain useful to future visitors, not just to fix your specific situation. Caching strategies for Drupal have been discussed here many times, and there are many resources available on the web that should give you some pointers on how to warm your caches at appropriate times
Answer: There are tons of performance options, I think with the beefy server resources you have we can tune it tremendously by doing the following:

Database tuning

MySQL - make sure QueryCache is setup, and InnoDB is the only table type being used. You'll want to look at the high performance sample my.cnf (config) that ships with MySQL.
Memcache - configuring Memcache will speed up tons of the queries and sub-queries Drupal is notorious for.
Session Cache - for handling a lot of concurrent [unique] login sessions you can consider using a NoSQL database engine like CouchDB/MongoDB, it'll free up your MySQL db from managing those sessions.

Web Serving tuning

OpCode Caching - speeds up PHP a lot, is basically a requirement on all Drupal servers nowadays. I use APC, and there are other solutions but APC will work reliably with very little setup; this one is a no brainer.
Caching - you seriously need to cache at least the home page for anonymous users, and when a user logs in their unique session will be handled correctly. Consider using Varnish (it'll allow your site to handle over 100x more anonymous traffic and there are tons of tips on how to use it with Drupal.

These are just the quick highlights of what you need to utilize. If someone says you can't use caching on your website then there is a flaw in either the product design or the system design. There are literally thousands of popular Drupal sites that manage tons of logins and anonymous traffic working just fine with this recipe.
Comment: Thanks for the reply i have tried memcache, APC, Varnish but issue with all these caching is i am not getting updated content. If content editor adds a content then it should come on desired page just after saving but its not the case when i am using caching

please find attached image of xhprof output. When i see with top command on server it is giving me mysql taking too much CPU 99% of total use of CPU sometime during page load and CPU often touch 100%.

http://i.stack.imgur.com/XrkDD.png
Comment: If MySQL resources are too high, then consider:

1. Moving MySQL to its own dedicated server/layer, if it's not already setup that way.
Comment: If caches are stale (old) after edit/update/adding content then you need to run a Purge subroutine. The "Purge" module for example will help. This is a common issue with edge caches, they need to update from the origin server.

As for MySQL, consider:

1. Move MySQL to its own dedicated server/layer, if it's not already setup this way.

2. Triple-check your MySQL setup, comb over the my.cnf over and over; improper (low) allocation of resources (RAM, ports, caches) will degrade performance! I cannot stress this enough.


Toggle between accelerometer and touchDown in libGDX

Question: I'm using the touchDown method (InputProcessor)to move a sprite in the x-axis, i also want it to be moved using the accelerometer.
Is there a way in libGDX to toggle between the two methods and can they both be implemented together (so that the movement is done using the accelerometer as long as the screen is not touched or will they conflict with each other when phone is tilted and screen is touched)
Answer: You can do polling.
<code>if (Gdx.input.isTouched()) {
  // screen touched logic
} else {
  // check for accelerometer
  float accelX = Gdx.input.getAccelerometerX();
  float accelY = Gdx.input.getAccelerometerY();
  float accelZ = Gdx.input.getAccelerometerZ();
  // do stuff with the accel(s)
}
</code>
Comment: can it be done in a way that i can only let one be usable but both available, so i can later on put it as an option in the game settings to turn accelerometer on and off.
Comment: you can store those options as [preferences](https://github.com/libgdx/libgdx/wiki/Preferences), and check for that preferences when you init your screen `prefs.getBoolean("accelerometerEnabled")`


linq toList gives timeout on wcf client

Question: The WCF client timesout after the return. I have tried increasing the timeout time but that didn't work. When i debug the method there is no problem.
Anyone got a suggestion?
<code>public List<Order> ProductsOfUser(string username, string password)
{
    var user = container.UserSet.FirstOrDefault(u => (u.Username == username && u.Password == password));
    if (user == null)
    {
        throw new Exception();
    }
    var resultuserId = user.Id;
    Console.Out.WriteLine(resultuserId);

    var orders3 = container.OrderSet.Where(o => o.UserId == user.Id).ToList();

    return orders3;
}
</code>
This is the query that linq creates :
<code>{SELECT
[Extent1].[Id] AS [Id],

[Extent1].[CustName] AS [CustName],

[Extent1].[OrderDate] AS [OrderDate]
,
[Extent1].[UserId] AS [UserId]

FROM [dbo].[OrderSet] AS [Extent1]}
</code>
Logfile : http://pastebin.com/Q6VpmhmW
Comment: You could also try to change your query to `container.OrderSet.Where(o => o.UserId == resultuserId).ToList();` since you already capture the ID into a variable.
Comment: How large is the list that's being created?
Comment: Complete shot in the dark, but make sure the service reference is up-to-date.
Comment: Another thought: Maybe try removing the ToList and just return a very simple list with 1 or 2 elements just to see if the issue goes away.
Comment: there is only one element in the list. Service reference is also updated :)
Comment: Realize that the underlying query is not executed until `ToList` is called, so the problem is likely you have a poorly-performing query.  Use a tracing tool to determine what the query is and see if it can be optimized by adding an index or two.
Comment: Also, authenticating a user in the same method that you return related data seems like a bad design.  You should probably factor that out into a separate method for reuse.
Comment: for the authentication i'm going to use a separate method, and i already tried to use the ID from the variable. But i always get the same timeout. i'm going to try optimizing the query
Comment: added the query that linq creates in the topic, for me it looks ok.
Comment: What is consuming this WCF service?
Comment: i'm testing it with the WCF Test client. added logfile to the post see pastebin log
Answer: Ok fixed it
added [DataContract(IsReference = true)] to the User class and everything works smoothly now.

linq toList gives timeout on wcf client


how to read paquet file having compressed with snappy to get rid of out-of-memory error?

Question: I have dataset in format of snappy.parquet (https://cernbox.cern.ch/files/public/show/hqz8zE7oxyPjvsL?items-per-page=100) of about 760 MB having 3 files. The dataset 4 feature x_jets, _ ,_  and y . I only require X_jet and y. I tried using pandas  below is the code.
df=pd.read_parquet('/kaggle/input/glucon/QCDToGGQQ_IMGjet_RH1all_jet0_run0_n36272.test.snappy.parquet',columns=['X_jets','y']) # this is just one file

df.memory_usage(deep=True)

Index         128
X_jets    4062464
y          290176

I try to change the datatype y.
df['y']=df['y'].astype('float16')
df.memory_usage(deep=True)

Index         128
X_jets    4062464
y           72544
dtype: int64

import fastparquet
print(fastparquet.ParquetFile('/kaggle/input/glucon/QCDToGGQQ_IMGjet_RH1all_jet0_run0_n36272.test.snappy.parquet').schema)

- schema: REQUIRED
| - X_jets: LIST, OPTIONAL
|   - list: REPEATED
|     - item: LIST, OPTIONAL
|       - list: REPEATED
|         - item: LIST, OPTIONAL
|           - list: REPEATED
|             - item: DOUBLE, OPTIONAL
| - pt: DOUBLE, OPTIONAL
| - m0: DOUBLE, OPTIONAL
  - y: DOUBLE, OPTIONAL

The datatype of X_jets is object. So is there any to reduce the memory of X_jets.
Another thing is i tried using dask reading the parquet file but at the end i need to convert it torch or tensor to train the model which again required lot of memory. Also pyspark also crashes.
Is there efficient way to read large parquet file and train it in the model. Or is there way read file using random sampling.
Comment: Is X_jets actually a deep nested, variable length field? You could do `print(fastparquet.ParquetFile().schema)`.
Comment: @mdurant yes i have also updated above. how Schema looks like ```- schema: REQUIRED
| - X_jets: LIST, OPTIONAL
|   - list: REPEATED
|     - item: LIST, OPTIONAL
|       - list: REPEATED
|         - item: LIST, OPTIONAL
|           - list: REPEATED
|             - item: DOUBLE, OPTIONAL
| - pt: DOUBLE, OPTIONAL
| - m0: DOUBLE, OPTIONAL
  - y: DOUBLE, OPTIONAL```
Comment: You can try the package Polars or modin
Answer: I recommend you try your data with awkward ( https://awkward-array.org/doc/main/ ), which is built to process non-tabular nested/variable length data like this.
import awkward as ak
arr = ak.from_parquet()
Awkward was originally written for high-energy physics particle data, which is what I suspect you are looking at. It provides numpy semantics and vectorised operation over your ragged data.
There is also a nascent package, awkward-pandas ( https://github.com/intake/awkward-pandas ) to provide the best of both, but it is not very mature.


Flex set function not getting called

Question: Okay, I've been banging my head against the wall with this one. I have the following set function in Flex.
    public function set periodChangeAmount(value:int):void
    {
        _PeriodChangeAmount = value;
        refreshStartEndDates();
    }

If I set the periodChangeAmount to -1 or 1 the set method gets fired. If I set it to zero it doesn't get fired. What's the deal? Does anyone know why it wouldn't get called when setting it to zero. If I change the object type to a number or even an object it still doesn't work as expected. Any help would be greatly appreciated.
Comment: This works fine for me.  Can you provide the code you are using to test this?
Answer: Did you put a trace in the setter to make sure it isn't called?
Is periodChangeAmount a Bindable read-write property? In that case flex internally calls the getter to make sure that the value to be set is not the existing value. If the current value of the property (as returned by the getter) is same as the value to be set, the setter is not called.
private var privateVar:Boolean = false;

[Bindable]
public function set readWriteProp(value:Boolean):void
{
    trace("set called with " + value + " current is " + privateVar);
    privateVar = value;
}
public function get readWriteProp():Boolean
{
    trace("get called : " + privateVar);
    return privateVar;
}
//...
a.readWriteProp = true;
a.readWriteProp = true;

Traced output:

get called : false
  set called with true current is false
  get called : true

Note that the getter was called twice but the setter was called only once. In the second assignment, since the current value and value to be set are same (true), the setter is not called.
I believe flex dev team did it this way to avoid redundancy in binding.
Comment: Bummer. Is there any way around this if I need to leave the object as Bindable?
Comment: check for the value of periodChangeAmount before calling the setter and call refreshStartEndDates() explicitly if it is the same value.
Answer: In order to solve above problem you can add an bindable Event and dispatch that event before setting any properties as shown below.
private var privateVar:Boolean = false;
[Bindable( "bindableEventProperty" )]

public function set readWriteProp(value:Boolean):void
{
    trace("set called with " + value + " current is " + privateVar);
    privateVar = value;
}
public function get readWriteProp():Boolean
{
    trace("get called : " + privateVar);
    return privateVar;
}

dispatchEvent( new Event( "bindableEventProperty" ));
a.readWriteProp = true;
a.readWriteProp = true;

This event make sure that set method of the property is called even though property value is same.

Flex set function not getting called


How to add picture to every panel?

Question: I am using the panels module and the mini panels modules.
I have mini panel with two section (left and right).
For my design, I want to add a picture on the left side of each section. These pictures are not supposed to come from any node or content, they are just pictures for design purpose only.
How can I do that?
If you suggest CSS, I will be happy to understand how?
I am a newbie, and building my first Drupal site, so I will appreciate any help.
Thanks.
Answer: All your panels have a common class. Probably .panels. You need to see if your left panels also have a common class, probably .panel-left or something. You can use your browsers element-inspector to see this. It will show you something like this (simplified example) if you select your node that has panels:

    content

This gives you a clue where to set your background in CSS.
.panels .panel-left {
  background:url('path/image');
}

You need to find classes that the elements you want to style have in common, but are unique enough so that you style only those.
Comment: Thanks a lot!I did that, and it's working nicely.
But, I am using responsive theme, and when I am re-sizing the window, the text & info of the panels are going on top of the picture, something I want to avoid. I don't want the text covering the picture. how can I prevent this from happening?
Comment: set margins to the field inside the panel.

How to add picture to every panel?


Large Deviations Question

Question: Let $\left(X_n\right)_{n\geq 1}$ be i.i.d random variables on $\left(\Omega,\mathcal A, \mathbb P\right)$, $X_1$ with mean $\mu$, and
$$
L(\lambda) =
\begin{cases}
\log\mathbb E\left(e^{\lambda X_1}\right)<\infty, & \text{if }\mathbb E\left(e^{\lambda X_1}\right)<\infty \\
+\infty, & \text{otherwise, }
\end{cases}
$$
If $$\displaystyle L^{*}(x)=\sup\left(x\lambda-L(\lambda)|\lambda\in\mathbb R\right)$$
Prove that for any $\alpha >0$ and $n \geq 1$,
$$\mathbb P\left(\frac{X_1+...+X_n}{n}-\mu\geq \alpha\right)\leq e^{-nL^{*}(\mu+\alpha)}$$
Answer: Without loss of generality take $\mu = 0$ and fix any $\lambda \in \mathbb{R}$.  Call $S_n =\sum_{i=1}^n X_i$.  Then
$$ P\left( \frac{1}{n}S_n \geq \alpha\right) = P\left(e^{\lambda S_n} \geq e^{n \lambda \alpha}\right)$$
$$ \leq e^{-n \lambda \alpha} E[e^{\lambda X_1}]^n$$
$$ = e^{-n(\lambda \alpha - L(\lambda))} $$
Now take the supremum over $\lambda$ to get the result.
Comment: Should the $X_1$ be in the exponent?
Comment: yeah that's a formatting error, I'll fix it.
Comment: Can you help me understand why $P(e^{\lambda S_n} \geq e^{n \lambda \alpha})\leq e^{-n \lambda \alpha} E[e^{\lambda X_1}]^n$?
Comment: Apply Markov's inequality.

Large Deviations Question


Verificar erros em arquivo PHP executado por url externa

Question: Bom dia,
eu estou trabalhando com o serviço de checkout da Cielo e estou com problema na hora de fazer o tratamento da url de retorno, ou seja, o arquivo é chamado quando há uma atualização no pagamento, logo eu nunca acesso diretamente o arquivo, ele é chamado através da url pela própria Cielo.
O problema é que eu não estou conseguindo executar alguns códigos sql e também não consigo fazer o debug deles.
Quando eu apenas faço a verificação do arquivo que chega eu uso esse código:
$data = $_POST;
$filename = microtime(true);
$fp = fopen($filename.'.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);

Isso gera um arquivo com todos os dados corretamente. Mas quando eu tento algo assim:
require_once('server.php'); //Aqui está a conexão com o banco e funções de query
$query = sql('SELECT * FROM ...');

$filename = microtime(true);
$fp = fopen($filename.'.json', 'w');
fwrite($fp, json_encode($query));
fclose($fp);

Nenhum arquivo é escrito no servidor, logo eu não consigo verificar o que está acontecendo.
Como posso contornar esse problema?
Comment: Mas você quer gravar o arquivo JSON? com seu SQL e sem tela é isso, deixa pergunta porque esta usando microtime? nem recomendo isso.
Comment: @KingRider eu preciso obter os dados do POST e executar alguns códigos SQL, por exemplo, verificar qual é o pedido de referência e depois atualizar o status do pagamento conforme recebido pelo cielo. Não preciso fazer nada com JSON, eu só estou usando ele para escrever o arquivo pois foi o único modo que encontrei de fazer um debug do que está acontecendo no arquivo de retorno. Mas eu só preciso receber o POST e fazer um SELECT e posteriormente um UPDATE
Comment: _CMCarlo: entendi se falou, querer postar dahora, veja sobre `curl` + `file_get_contents` para isso trabalhar postar. (https://secure.php.net/manual/pt_BR/book.curl.php e https://secure.php.net/manual/pt_BR/function.file-get-contents.php)
Comment: Você pode debugar gerando um arquivo qualquer com as informações obtidas no PHP. Por exemplo, se você quer saber o conteúdo da variável $exemplo, faça file_put_contents($exemplo, 'log.txt', FILE_APPEND); Dessa forma, quando a URL de retorno for requisitada, ele irá gerar um arquivo com o conteúdo da variável $exemplo e você poderá visualizá-lo posteriormente.
Answer: Passei pela mesma situação há algum tempo, e consegui debugar consultando os arquivos de log do servidor.
Além disso, utilizei o método error_log do PHP para gravar mensagens personalizadas no arquivo de logo, a fim de facilitar a depuração dos erros.


Looping through a list that contains dicts and displaying it a certain way

Question: These are 3 dicts I made each with the 4 same keys but of course different values.
lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

I stored the dicts in a list.
students = [lloyd, alice, tyler]

What I'd like to do is loop through the list and display each like so:
"""
student's Name: val
student's Homework: val
student's Quizzes: val
student's Tests: val
"""

I was thinking a for loop would do the trick for student in students: and I could store each in a empty dict current = {} but after that is where I get lost. I was going to use getitem but I didn't think that would work.
Thanks in advance
Comment: Those dictionaries are basically a poor man's class.  If you're familiar with Python's classes and object-oriented programming, you could create a `Student` class with a `transcript` method (or just override the `__str__` magic method).  You'd then just print `student.transcript()` or `str(student)` in a `for student in students:` loop.  (If the next function or program that will handle that data expects a `dict` though, leave the data in a `dict`.)
Comment: ChrisSlightGhost do keys print order is important for you ?
Answer: You can do this:
students = [lloyd, alice, tyler]

def print_student(student):
    print("""
        Student's name: {name}
        Student's homework: {homework}
        Student's quizzes: {quizzes}
        Student's tests: {tests}
    """.format(**student)) # unpack the dictionary

for std in students:
    print_student(std)

Comment: Thanks bud I really appreciate it.
Answer: Use loop below to display all students data without hardcoding keys:
# ...
# Defining of lloyd, alice, tyler
# ...

students = [lloyd, alice, tyler]
for student in students:
    for key, value in student.items():
        print("Student's {}: {}".format(key, value))

Good Luck !
Comment: Two points: first, `iteritems` doesn't exist in modern Python anymore, but `items` works in both 2 and 3, so you might as well use it.  Second, while you don't hardcode the keys, this loses the desired output order because dicts are unordered; for me, "name" comes third in the output, which feels weird.
Comment: @DSM Thanks for your suggestions, it's really use full, i've updated `iteritems` to `items`.


Things to check for with a orthogonal matrix or vector

Question: What are there different rules you need to check for with an orthogonal matrix or vector? Why does an orthogonal matrix need to nxn but a orthogonal vector does not?
$$\begin{bmatrix}
1\\
0\\
1\end{bmatrix}\begin{bmatrix}
0\\
1\\
0\end{bmatrix}$$
dot product
1*0 + 0 * 1 + 1 *0 = 0
What else do I need to check for besides dot product with a matrix? Why does this have to be nxn?
\begin{bmatrix}
1 & 0\\ 0 & 1\\ 1 & 0
\end{bmatrix}
dot product
1*0 + 0 * 1 + 1 *0 = 0
What else do I need to check for besides dot product with a vector?
What about one like this? Why is this not orthogonal?
\begin{bmatrix}
1 & 1\\ 1 & -1
\end{bmatrix}
dot product 1*1 + 1 * -1 = 0
Comment: @LiChunMin It's not a *completely* different concept. The columns/rows of an orthogonal matrix are pairwise orthogonal.
Comment: $Q^TQ$ is not $I$. You need to normalize both row/column vector to have it match the definition.
Comment: No…orthogonal matrix is something different. You know what a orthogonal vector is. A orthogonal matrix, however, is a matrix such that its transpose is its inverse and is a completely different concept
Comment: If it isn't a square matrix, then it doesn't make sense to talk about inverse. Although the name "orthogonal matrix" is misleading, just stick to the definition and study what is the use of such kind of matrix.
Comment: True. Thanks for the remark. I should have established this relationship in my previous comment.
Comment: This is rather important since if you get enough orthogonal vectors, you get a orthogonal basis. If normalize each and form a matrix, it is a orthogonal matrix with the aforementioned desired property.
Comment: @LiChunMin Why is the one at the bottom not orthogonal?
Comment: @amd Why is the one at the bottom not orthogonal?
Answer: A matrix whose columns are orthonormal vectors is called an Orthogonal matrix.  If A is orthogonal, you can verify by multiplication that ATA is identity, where AT is A transposed.  This is true even if A is rectangular.  But AAT is not identity.  If A is square then A*AT is also identity and then Ainverse=AT
Comment: This is a good answer, but please use MathJax to format mathematical expressions. You can find a basic tutorial [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).


If higher order moment is finite, then lower order moment finite?

Question: I'm trying to prove the theorem below.

If $E(|X|^n)<\infty$ for some positive integer $n$, then $E(|X^k|)<\infty$ for every positive integer $k$ such that $k<n$

Here's what I've tried.
ref1) Proof that if higher moment exists then lower moment also exists
ref2) Probability and Statistical Inference, 2nd Edition
Robert Bartoszynski, Magdalena Niewiadomska-Bugaj

[Step 1] set inequality about $|X|^k$ and $|X|^n$
if $|X|\ge1$, then $|X|^k\le|X|^n$, while if $|X|<1$, then $|X|^k\le1$.
consequently, $|X|^k \le \max(1, |X|^n) \cdots (1)$.

[Step 2] prove the right-hand side of (1) has finite expectation
if $E(|X|^n)<\infty$, then $E(|X|^n) = \int^{1}_{-1}|X|^nf(x)dx \;+\; \int_{|X|\ge1}|X|^nf(x)dx$
and it follows that $\int_{|x|\ge1}|x|^nf(x)dx<\infty$ as a difference of two finite quantities.
Thus, $E(|X|^k))\le E\left\{\max\left(1, |X|^n\right)\right\} = \int^{1}_{-1}f(x)dx \;+\; \int_{|X|\ge1}|X|^nf(x)dx < \infty$

[Question 1] In [Step 1], Why contains "=" in $|X|^k\le1$?
As I think, "If $|X| < 1$, then $|X|^k<1$" is right.

[Question 2] In [Step 2], what are 'two finite quantities' referring to?
$E(|X|^n)$ and $\int^1_{-1}|X|^nf(x)dx$?
Comment: A broad generalization of this inequality is proven at https://stats.stackexchange.com/questions/234048/finite-kth-moment-for-a-random-vector/250834#250834.  I also recall this question was asked and answered before, but I'm unable to turn up the thread in a search.
Answer: [Question 1] : (Since k>0,"=" is just an implication)
[Question 2] : we only need to know $E(|X|^n)$ is some finite value for the proof.
  while $\int^1_{-1}|X|^nf(x)dx <=1$ can be derived.
below is the Proof:
given, $E(|X|^n)$ is finite.  some $k$,  $0<k<=n$.
if $|X|<1$ then $|X|^k≤1$, So $\int^1_{-1}|X|^kf(x)dx <= \int^1_{-1}1f(x)dx <=1$ (by definition)
if $|X|>=1$ then $|X|^k≤|X|^n$, So $\int_{|X|\ge1}|X|^kf(x)dx <=\int_{|X|\ge1}|X|^nf(x)dx <= E(|X|^n)$
from above 2 cases, we get $E(|X|^k)<= 1 + E(|X|^n)$. hence $E(|X|^k)$ is finite.
Comment: Your limitation of the integral endpoints to $\pm 1$ trivializes the problem: it's then impossible for *any* positive moment to be infinite, period.  The interest lies in its generality: that is, its applicability to *all* random variables.


Convergence of Shanks Transformation

Question: If sequence $A_n \rightarrow 0$ as $n \rightarrow \infty$, and the Shanks Transformation of $A_n$ defined as $$S\left(A_n\right)=\frac{A_{n+1}A_{n-1}-A_n^2}{A_{n+1}+A_{n-1}-2A_n}$$ also converges, prove $S\left(A_n\right)$ converges to zero.
It's problem 8-1 in Carl M. Bender's book, Advanced Mathematical Methods for Scientists and Engineers. I tried the definition of limit but couldn't finish the proof.
Answer: Equivalently $S(A_n)=A_{n-1}-\frac{(\Delta A_{n-1})^2}{\Delta^2 A_{n-1}}$ with the forward difference operator $\Delta u_n:=u_{n+1}-u_n$. (Note the problem statement should have included $\Delta^2 A_n\ne 0$.) Thus $$\frac{S(A_n)}{A_{n-1}}=1-\frac{\Delta A_{n-1}}{A_{n-1}}\cdot\frac{\Delta A_{n-1}}{\Delta^2A_{n-1}}.$$By Stolz–Cesàro this has limit $1-1=0$, so $S_n$ has limit $0\times 0=0$.
Comment: @MathAvengers The second forward difference, i.e. $\Delta^2 u_n:=u_{n+2}-2u_{n+1}+u_n$.
Comment: Thanks. I haven't heart about Stolz–Cesàro theorem before but wiki says that it can be viewed as a l'Hôpital's rule for sequences, which makes this easier to grasp. However, the statement of Stolz–Cesàro theorem says that the sequence in the denominator is strickly monotonic and divergence, while in our case, the sequence $A_{n-1}$ is neither monotonic nor divergence. So why can we apply this theorem?
Comment: @Bruce You can get divergence by working with sequences such as $1/A_n$.
Comment: @J.G. Hey, I am wondering what is $\delta ^2 A_{n-1}$ ? Is that the second directive ?

Convergence of Shanks Transformation


Plugging an Active Bass into M-Audio Profire

Question: so I'm going to record direct input but apparently this bass is an active bass (which I think means there's a pre-amp built into the bass. Can I just plug this thing directly into my profire? Trying to be cautious so I don't break my interface or his bass.
Answer: Yes, you can plug it straight in - no instrument input should be damaged by the output from an active bass, though you may have to take care to avoid clipping. Switch the input to 'Inst', and adjust the gain control to a point where you have plenty of level but where the clip light isn't coming on. Use the "Pull : -20dB" option on those controls if you need - or you can always turn the output on the bass down.


Finding equilibrium and bifurcation points for first order ODE's

Question: I'm trying to find the equilibrium and bifurcation points for $$\frac{d}{dx}=rx+xe^{-x}.$$ I started by noticing that $x=0$ is an equilibrium point for all $r$. Also, I then set the RHS equal to zero and solved for $x$. I found that $x=-\ln(-r)$ so this means that $r=-1$ also creates an equilibrium point. I'm not exactly sure where to take this problem further to solve for the bifurcation points. I know that I need to create a bifurcation diagram, and I think that I need to sketch a graph with $x$ in the vertical axis and $r$ as the independent variable. Is $x=-\ln(-r)$ what I want to sketch?
Answer: Yes. The system has trivial equilibrium point $x_0=0$ and interior equilibrium point $x^*=-\ln(-r)$ provided $r<0$. So for positive values  of $r$, the interior equilibrium point does not exist.
Also you can draw the bifurcation diagram in $x-r$ plane as you mentioned, what type of bifurcation the system exhibit. An easy method for checking what type of bifurcation the system exhibit is to use MATCONT software which is based on MATLAB package.

The eigenvalue of the Jacobian matrix calculated at the equilibrium point $x_0$ and $x^*$, of the system are $r-1$ and $r\ln(-r)$. So $x_0$ is locally stable for $r<-1$ and $x^*$ is locally stable for $r<0$, which is also existence condition for  $x^*$. So the stability of $x_0$ changes at $r=-1$. Therefore $r=-1$ is the bifurcation point. In the above figure the point $r=-1$ is shown as a branch point.
Comment: Thank you for your guidance. I'm trying to work with the MATCONT software and there's a learning curve associated with it.
Comment: How did you get the point of the BP shown on the plot?
Comment: @Peetrius, Using MATCONT software.
Comment: I understand that, I have the plot. Where in MATCONT did you get the coordinate to show on the graph?
Comment: When you plot the bifurcation diagram in $x-r$ plane, MATCONT by default shows the coordinate on the graph.
Comment: Interesting, I didn't get that for my plot, or for my other plots.
Comment: Then you manually add the axes on the plot by editing the MATLAB figure through   axis properties.


How can I find the c-ctatistic or AUROC using logistic regression in R?

Question: I am running a logistic regression to see how these factors/variables affect an outcome (Neurological Complication).
How can I obtain the c-statistic -- also known as the area under the Receiver Operating Characteristic (AUROC) Curve?
    NeuroLogit2 <- glm(Neurologic Complication? ~ HTN + stroke + Gender + Embol + Drain, data=Tevar.new, family=binomial)
    summary(NeuroLogit2)

Answer: Well, obviously I don't have your data, so let's make some up. Here, we'll pretend we're modelling the probability of people catching a cold in any given year based on age and sex. Our outcome variable is just a 1 for "caught a cold" and 0 for "didn't catch a cold"
set.seed(69)
outcome <- c(rbinom(1000, 1, seq(0.4, 0.6, length.out = 1000)),
             rbinom(1000, 1, seq(0.3, 0.5, length.out = 1000)))
sex     <- rep(c("M", "F"), each = 1000)
age     <- rep((601:1600)/20, 2)

df      <- data.frame(outcome, age, sex)

Now we'll create the model and have a look at it:
my_mod  <- glm(outcome ~ age + sex, data = df, family = binomial())

summary(my_mod)
#>
#> Call:
#> glm(formula = outcome ~ age + sex, family = binomial(), data = df)
#>
#> Deviance Residuals:
#>     Min       1Q   Median       3Q      Max
#> -1.3859  -1.0993  -0.8891   1.1847   1.5319
#>
#> Coefficients:
#>             Estimate Std. Error z value Pr(>|z|)
#> (Intercept) -1.20917    0.18814  -6.427 1.30e-10 ***
#> age          0.01346    0.00317   4.246 2.18e-05 ***
#> sexM         0.61000    0.09122   6.687 2.28e-11 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for binomial family taken to be 1)
#>
#>     Null deviance: 2760.1  on 1999  degrees of freedom
#> Residual deviance: 2697.1  on 1997  degrees of freedom
#> AIC: 2703.1
#>
#> Number of Fisher Scoring iterations: 4

Looks good. Older people and men are more likely to catch colds.
Now suppose we wanted to use this model to get a prediction of whether someone of a given age and sex will catch a cold in the next year. If we use the predict function with type = "response", we get a probability estimate for each of the people in our data frame based on their age and sex.
predictions <- predict(my_mod, type = "response")

We can use these probabilities to construct our ROC. Here I'll use the pROC package to help:
library(pROC)

roc(outcome, predictions)
#> Setting levels: control = 0, case = 1
#> Setting direction: controls < cases
#>
#> Call:
#> roc.default(response = outcome, predictor = predictions)
#>
#> Data: predictions in 1079 controls (outcome 0) < 921 cases (outcome 1).
#> Area under the curve: 0.6027

So the area under the ROC is 60.27%. We can plot the ROC itself to see what this looks like:
library(ggplot2)

ggroc(roc(outcome, predictions)) +
  theme_minimal() +
  ggtitle("My ROC curve") +
  geom_segment(aes(x = 1, xend = 0, y = 0, yend = 1), color="grey", linetype="dashed")
#> Setting levels: control = 0, case = 1
#> Setting direction: controls < cases

Created on 2020-06-07 by the reprex package (v0.3.0)
Comment: @bdg67 you don't need to have a binary outcome prediction. If you just want the AUC for the model you can remove the "round". I have updated my answer - apologies if I led you astray there.
Comment: for some reason the round function in "round(predict(my_mod, type = "response"))"  is making everything 0s and the AUC is coming out as 0.5. is this supposed to happen? my variables are all categorial (1s and 0s) not continuous like the "age" example you used -- perhaps this changes things?
Comment: That is much better! Now my AUC is 0.7951 - is this the same as the c-statistic? Also, running into one other problem that you might be able to provide some insight on. Using this for another variable (mortality): When I get to the roc(outcome, predictions) step, R gives me an error that says "Response and predictor must be vectors of the same length." even though they are both categorical. Any idea how to address this?
Comment: @bdg67 yes, c-statistic is the same as AUC. In your mortality data, you need a prediction for each patient and a measured outcome for the same patients, so the two vectors need to be the same length: one prediction and one outcome per patient
Comment: Yep, there were a few missing values that I had to fix. Last thing: How can I go about finding the 95% CI and Odds Ratios of the logistic regression you did? When I ran them using "exp(cbind(OR = coef(NeuroLogit2), confint(NeuroLogit2)))" (for your data, NeuroLogit2 would be my_mod) I kept getting weird values with e's. Any ideas?
Comment: values with e's --- also known as exponents haha
Answer: While there are indeed several contributed packages which compute this, it can also be accomplished via the survival package's concordance method. survival is a 'recommended' package which means it is likely already bundled with your R installation.
survival::concordance(NeuroLogit2)