How short should I trim my nails?

Question: I have been advised by my piano teacher to trim my nails to prevent accidents on the keyboard (like getting a nail stuck between the keys).
How short should I trim my fingernails?
I don't want to cause damage to the inner parts of my fingernails.
Answer: Short enough to not click on the keys when playing with curved fingers. I've just done mine.
Comment: I wouldn't recommend cutting your nails that close to the "meat". If you do that on your toes as well, that's like asking for an ingrown fingernail to happen.
Comment: I cut my left-hand nails that short for playing stringed instruments, and never have trouble with ingrown fingernails.  Maybe I'm just lucky.  The only trouble I had from super short nails is that it felt strange for a few weeks until I got used to it.
Comment: The clicking surely isn't a problem. Nails are there, I guess, to protect the fingertips. Yours look quite vulnerable that short.
Comment: @Tim, I guess you don't play piano?  If they click, and you play with any energy, they eventually become painful and even split
Comment: Played piano for 65 yrs! Still play in two big bands, and one jazz quartet, and keep nails as in my answer. never had any problems. And I give it stick when needed. But if mine were as short as yours, guitar and bass would be problematic. Bit of a compromise, but it's always worked like that for me.
Answer: This guidance really should come from teacher, especially as s/he mentioned it! However, I keep mine at between 1 and 1.5mm from the skin. Bearing in mind I also play guitar and bass,it's a bit of a compromise on r.h. On the other hand (!) as long as you don't have long manicured nails such as thiose found on some ladies, you'll be o.k. Ask teacher.
Comment: The compromise I've personally reached is to leave 1-1.5mm from the pink portion of the nail and leave a longer nail on the right thumb.

How short should I trim my nails?


How to remove all whitespace except for between double quotes, and eliminate text between double slashes

Question: I am developing a programming language, and while parsing it in JS I need to remove all white space except for between double quotes and delete double slashes and everything in between.
Example:
Str ( myString ) = "Hi, my name is Bob.";//This is a string//
//This is a comment//
Num(myNum) = 32;

Would output:
Str(myString)="Hi, my name is Bob.";Num(myNum)=32;

Thanks!
Comment: What type of JS data structure would you use for this kind of input?
Comment: @ChavaG Later on in the code, I separate it into expressions using semicolons and then create an AST JS Object.
Answer: You could try js Compress it's more for minifying code for libraries and such but it may do the trick.
Comment: This would work if I could do it manually, but my code automatically fetches files with Ajax and parses them, non-server-side.


How to dispatch a modified prop to redux store?

Question: I'm struggling with something that should be more obvious to me.
when someone clicks on a antd popconfirm's "yes" option, it's supposed to trigger the onConfirm function and then update a record in my redux store via a dispatch action. All I want to do is to change one field (archived) from false to true in this record. I know that props are immutable so i can't just change the prop. But how to approach this?
I vaguely recall a way to pass a record on and modify a field using a spread operator? is there some easy way to do this? Or do i need to somehow convert my prop object to state so i can modify it and pass it on somehow?
I map my selector via the following.. AFAIK I just need to pass the id of the property i care about along with the object that i want it to replace:
const mapDispatchToProps = (dispatch) => ({
  archiveProperty: (id, property) => dispatch(startEditProperty(id, property))
});

The antd popconfirm block that calls onConfirm. Probably not terrible interesting:
      {
        title: 'Action',
        key: 'action',
        render: (text, record) => (

            Edit
            <Divider type="vertical" />
            <Popconfirm
              title="Are you sure?"
              onConfirm={() => this.confirm(record)}
              onCancel={this.cancel}
              okText="Yes"
              cancelText="No"
            >
              Archive
            </Popconfirm>

        ),
      },

Here is where I think my problem is. It works but i am currently only passing the existing record in. Not a modified version of it. How to pass a version of it that has it's archived field set to true?
confirm = (record)  => {
  message.success('Archived');
  console.log("confirm function.. record");
  this.props.archiveProperty(record.id, record);
}

The entire file if it's useful looks like this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import selectProperties from '../selectors/properties';
import { startEditProperty } from '../actions/properties';
import { Table, Tag, Divider, Popconfirm, message } from 'antd';

export class PropertyList extends React.Component {
  constructor(){
    super();

    this.columns = [
      {
        title: 'Address',
        dataIndex: 'street',
        key: 'street',
        render: text => {text},
      },
      {
        title: 'City',
        dataIndex: 'city',
        key: 'city',
      },
      {
        title: 'State',
        dataIndex: 'state',
        key: 'state',
      },
      {
        title: 'Workflow',
        key: 'workflow',
        dataIndex: 'workflow',
        sorter: (a, b) => a.workflow.length - b.workflow.length,
        sortDirections: ['descend'],
        render: workflow => {
          let color = 'geekblue';
          if (workflow === 'Inspection' || workflow === 'Maintenance' || workflow === 'Cleaning') {
            color = 'volcano';
          }
          else if (workflow === 'Rented') {
            color = 'green';
          }
          return (

              <Tag color={color} key={workflow}>
                {workflow.toUpperCase()}
              </Tag>

          );
        },
      },
      {
        title: 'Action',
        key: 'action',
        render: (text, record) => (

            Edit
            <Divider type="vertical" />
            <Popconfirm
              title="Are you sure?"
              onConfirm={() => this.confirm(record)}
              onCancel={this.cancel}
              okText="Yes"
              cancelText="No"
            >
              Archive
            </Popconfirm>

        ),
      },
    ];
  }

  confirm = (record)  => {
    message.success('Archived');
    console.log(record);
    this.props.archiveProperty(record.id, record);
  }

  cancel = () => {
    message.error('Cancelled');
    console.log("cancel function..");
  }

  render() {
    return (

            {
                this.props.properties.length === 0 ? (

                    No properties. Add some!

                ) : (

 ''}
                  />
                )
            }

    )
  }
};

const mapStateToProps = (state) => {
  console.log("PropertyList mapStateToProps..");
  console.log(state);
  return {
    properties: selectProperties(state.properties, state.filters)
  };
};

const mapDispatchToProps = (dispatch) => ({
  archiveProperty: (id, property) => dispatch(startEditProperty(id, property))
});

export default connect(mapStateToProps, mapDispatchToProps)(PropertyList);

Answer: You should copy the record object and change its one field (archived) from false to true in copied object.
Try this in your confirm method.
confirm = (record)  => {
  message.success('Archived');
  console.log("confirm function.. record");

  // create a new modified object
  const updatedRecord = Object.assign({}, record, {archived: true});

  //now pass this updatedRecord object as a new record to store
  this.props.archiveProperty(record.id, updatedRecord);
}

And in reducer just replace old record object with this updatedRecord object.
Hope it helps.
Comment: this worked and got me to resolve the problem. but when looking at object.assign with some google searches it seems that the recommended approach is to use a spread operator for ES6. in other words instead of the two lines mentioned, I also got it to work by doing "this.props.archiveProperty(record.id, {...record, workflow: "Archived"});"
Comment: Both `Object.assign()` and spread operator do the same thing. You can use either one of those in this case.


Steps for solving this inequality: $ x \geq \frac{6}{x - 1} $

Question: Solve:
$$
x \geq \frac{6}{x - 1}
$$
I figure that I can't really multiply by both sides by $(x - 1)$ since I'm not sure if it will be positive or negative. So I multiplied by $(x - 1)^2$ to get:
$$
x^3 - 2x^2 -5x \geq -6
$$
but wasn't sure how to proceed to an answer.
Comment: In principle, what you did is correct, but it introduces extra solutions. You should multiply by $(x-1)$, move the 6 to the left-hand side, and factorize the resulting inequality. You will then have two cases. Hope this helps; it is better if you do it by yourself.
Answer: You have two straightforward alternatives. One is to go back to the original inequality and split the problem into two cases. You know that $x$ can't be $1$, so either $x>1$, or $x<1$. If $x>1$, then $x-1$ is positive, and you can multiply through by it to get $$x(x-1)\ge 6\quad\text{and}\quad x>1\;,$$ or $$x^2-x-6\ge 0\quad\text{and}\quad x>1\;.$$ The quadratic factors, so you have $(x+2)(x-3)\ge 0$, implying that $x\le -2$ or $x\ge 3$. But this case applies only if $x>1$ so in fact you just get $x\ge 3$.
If $x<1$, on the other hand, $x-1$ is negative, and you have $$(x+2)(x-3)\le 0\quad\text{and}\quad x<1\;,$$ which you can solve in the same general fashion to find the other part of the solution.
The other is to factor the cubic $x^3-2x^2-5x+6$. By the rational root test the only possible rational roots are $\pm1,\pm2,\pm3$, and $\pm6$. $1$ is quickly seen to be a root, so $x-1$ is a factor. Dividing it out leaves the quadratic $x^2-x-6$, which is easily factored. Then you merely solve the inequality $(x-1)(x+2)(x-3)\ge 0$, bearing in mind that $x$ cannot be $1$. However, the solution of this inequality involves looking at essentially the same cases as the first solution, so you've not really gained anything. I'd argue that the solution by cases is actually easier.
Comment: +1 for the elegant and simplified explanation. Thank you.
Answer: You can also solve it by a case by case analysis instead.
First assume that $(x-1) > 0$. Then we can multiply out by $x-1$ without reversing the inequality.
Hence, we get $x^2-x \geq 6$ i.e. $x^2 - x -6 \geq 0$ i.e. $(x-3)(x+2) \geq 0$. This along with the assumption that $(x-1) > 0$, gives us that $x \geq 3$.
Similarly, assume $(x-1) < 0$ and proceed accordingly.
Comment: And don't forget you will be getting two answers.  Will it be that both must be true ("and" logic) or that each one individually is true ("or" logic)?
Answer: $$
x \ge \frac{6}{x-1}
$$
Move everything to one side:
$$
x-\frac{6}{x-1} \ge 0
$$
The common denominator is $x-1$, so we have:
$$
\frac{x(x-1)}{x-1} - \frac{6}{x-1} \ge 0
$$
Simplify:
$$
\frac{x^2-x-6}{x-1}\ge 0
$$
Factor:
$$
\frac{(x-3)(x+2)}{x-1} \ge 0
$$
This changes signs at $-2$, $1$, and $3$.  It is positive if $x>3$, negative if $x$ is between $3$ and $1$, positive if $x$ is between $1$ and $-2$, and negative if $x<-2$.  It is zero when the numerator is $0$, i.e. when $x=-2$ or $x=3$.
So the solution is
$$
x\ge3\text{ or } -2\le x<1.
$$
Answer: $x \ge \dfrac{6}{x-1}$
$x - \dfrac{6}{x-1} \ge 0$
$\dfrac{x^2 - x - 6}{x - 1} \ge 0$
$\dfrac{(x + 2)(x - 3)}{x - 1} \ge 0$
<code>(x-1): ---------------------------o+++++++++++++++++++++++
(x+2): ---------●+++++++++++++++++++++++++++++++++++++++++
(x-3): ---------------------------------------●+++++++++++

 soln: ---------●+++++++++++++++++o-----------●+++++++++++

    <-----+-----+-----+-----+-----o-----+-----+-----+----->
         -3    -2    -1     0     1     2     3     4
</code>
solution set $= [-2, 1) \cup $[3, \infty)


Simplest rollover/hover technique

Question: I'm curious to know what people think is the current best way to go about a basic roll-over action- JQuery or CSS?
I want a roll-over with these states:

Normal: paragraphs of text within a DIV
Hover: paragraphs of text fade out, a photograph fades in, in same position as text
OnMouseOut: photograph fades out, text fades back in.

DIV & photograph are both known sizes.
90% of CSS-only roll-over effects I've found online are specifically for menus, using sprites, which isn't what I'm after, and the other 10% are bickering about whether :hover is good practise.
I am curious what people think is the most straightforward technique these days- least code, least complexity, most compatible.
Without rollover added yet, HTML is similar to this:

Pitchfork photo booth, DIY cardigan messenger bag butcher Thundercats tofu you probably haven't heard of them whatever squid VHS put a bird on it.

CSS is:
#box1 {
    width:403px;
    height:404px;
    background-image:url('../images/bio_square1.jpg');
    background-repeat:no-repeat;
    color:#fff;
}

Comment: OK- the fading is the least important part of the process, a nice-to-have but not essential. So if it was something that only worked in boutique browsers that would be fine as long as the image-rollover worked in most.
Comment: Fading effects aren't very well established into browsers yet, most of them are in testing.
Answer: I would typically resort to jquery if there's a need to fade in/out an element.
My HTML would be something like this:

         Lorem ipsum

Following that my CSS would go something like:
#box{
   width:500px;
   height:500px;
   padding:0;
}

   .box-img{
       position:absolute;
       opacity:0;
   }

   .box-text{
       position:absolute;
   }

And to end off, I will probably use the jquery library for .mouseover() or .hover():
$("#box").hover(
  function () {
    $(".box-img").fadeTo("100,1");
    $(".box-text").fadeTo("100,0");
  },
  function () {
    $(".box-img").fadeTo("100,0");
    $(".box-text").fadeTo("100,1");
  }
);

This may not be the optimal method but I suppose the rough idea behind what is possible is somewhere there.
You can see the .hover() in action at jQuery API. The demo there has a live example of something similar to what you may be looking for and it is employing another method.
Hope this helps! =)
Answer: For cross-browser compatibility, jQuery will be the way to go. Furthermore, what you want sounds a bit more complicated than simply changing styles on hover. For example, you are binding the fade in of the photograph to the end of the fade in of the paragraph. There is no way to accomplish this in pure CSS.
Answer: As others have said, for cross-browser compatibility jQuery is the way to go. But if you want just CSS here's a quick-and-dirty CSS3 option using transitions: http://jsfiddle.net/wkhQA/2/
Edit: Due to laziness, I only included the webkit prefix for transitions. So I guess test it out in Chrome or Safari. Apologies.
Comment: I'm using this approach for now and it's working well, thank you!

Simplest rollover/hover technique


Google Cloud - Permission denied (publickey)

Question: I have a GCP instance running debian-8-jessie-v20170619 (deprecated). After a reboot, I lost ssh access to the machine (cannot ssh via Web, Terminal, or gcloud cli). Now my MySQL database has issue for my Wordpress blog and I need to ssh. There are tens of questions with the same title, so I read most of them and tried:

Regenerating ssh key, adding to Metadata (both on instance, and in project)
Turning off OS Login and trying ssh. Turning on OS Login and trying ssh.
Serial console method (user is not being created by startup script; so login fails)
Using ssh -i key user@host instead of gcloud cli
Adding key to authorized_keys

None of these worked. Here is the out of $ gcloud compute ssh MyVM --ssh-flag="-vvv"
OpenSSH_8.1p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/Jash/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 47: Applying options for *
debug2: resolve_canonicalize: hostname 22.214.171.124 is address
debug2: ssh_connect_direct
debug1: Connecting to 22.214.171.124 [18.104.22.168] port 22.
debug1: Connection established.
debug1: identity file /Users/Jash/.ssh/google_compute_engine type 0
debug1: identity file /Users/Jash/.ssh/google_compute_engine-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.7p1 Debian-5+deb8u8
debug1: match: OpenSSH_6.7p1 Debian-5+deb8u8 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 18.104.22.168:22 as 'Jash'
debug1: using hostkeyalias: compute.2217424771252360577
debug3: hostkeys_foreach: reading file "/Users/Jash/.ssh/google_compute_known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/Jash/.ssh/google_compute_known_hosts:1
debug3: load_hostkeys: loaded 1 keys from compute.2217424771252360577
debug3: order_hostkeyalgs: prefer hostkeyalgs: firstname.lastname@example.com,email@example.com,email@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,firstname.lastname@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,email@example.com
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,firstname.lastname@example.com
debug2: MACs ctos: email@example.com,email@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,firstname.lastname@example.com,zlib
debug2: compression stoc: none,email@example.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: email@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,email@example.com,email@example.com
debug2: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,email@example.com,email@example.com
debug2: MACs ctos: email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,firstname.lastname@example.com
debug2: compression stoc: none,email@example.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: firstname.lastname@example.com
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: email@example.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: email@example.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:/8U8cYg6EIhbKq5aDfb9DySyrP6JEli2B3iUpLKx6lE
debug1: using hostkeyalias: compute.2217424771252360577
debug3: hostkeys_foreach: reading file "/Users/Jash/.ssh/google_compute_known_hosts"
debug3: record_hostkey: found key type ECDSA in file /Users/Jash/.ssh/google_compute_known_hosts:1
debug3: load_hostkeys: loaded 1 keys from compute.2217424771252360577
debug1: Host 'compute.2217424771252360577' is known and matches the ECDSA host key.
debug1: Found key in /Users/Jash/.ssh/google_compute_known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey in after 134217728 blocks
debug1: Will attempt key: /Users/Jash/.ssh/google_compute_engine RSA SHA256:dHe8jHKOHpUXq/rriZMV3ya/HgaJeyrLqGLTe2+OJnc explicit
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/Jash/.ssh/google_compute_engine RSA SHA256:dHe8jHKOHpUXq/rriZMV3ya/HgaJeyrLqGLTe2+OJnc explicit
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
email@example.com: Permission denied (publickey).
ERROR: (gcloud.compute.ssh) [/usr/bin/ssh] exited with return code [255].

Comment: Could you please update your question with your startup script code?
Comment: In addition, you should collect logs: 1. Go to `Compute Engine` -> `VM instances` -> click on `NAME_OF_YOUR_VM` -> at the VM instance details find section `Logs` and click on `Serial port 1 (console)` 2. Reboot your VM instance (if possible). 3. Check full boot log for any errors or/and warnings. 4. Share full log by using [pastebin.com](https://pastebin.com).
Answer: Unfortunately you didn't provide serial port logs. I provided typical SSH troubleshooting steps below. Feel free to update your question to get more specific guidance.
Check serial port logs at Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM -> at the VM instance details find section Logs and click on Serial port 1 (console). It's better to reboot VM instance to get the full picture.
If you found errors/warning related to disk space you can try to resize it accordingly to the documentation Resizing a zonal persistent disk or follow this article Recovering an inaccessible instance or a full boot disk:
Try again to troubleshoot your VM instance via serial console (I've used this startup script many times and it works):

Enable serial console connection at Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> click on EDIT -> go to section Remote access and check Enable connecting to serial ports

Create temporary user and password to login: shutdown your VM and set a startup script by adding at the section Custom metadata key startup-script and value:
 #!/bin/bash
 useradd --groups google_sudoers tempuser
 echo "tempuser:password" | chpasswd

and then start your VM.

Connect to your VM via serial port at Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> and click on Connect to serial console
if no luck with connection again, you can check serial port logs again to see details about startup-script execution.

Check what went wrong.

Disable access via serial port at Compute Engine -> VM instances -> click on NAME_OF_YOUR_VM_INSTANCE -> click on EDIT -> go to section Remote access and uncheck Enable connecting to serial ports. More details you can find at the documentation Interacting with the serial console.

If you weren't able to connect via serial console, try follow the documentation Troubleshooting SSH section Inspect the VM instance without shutting it down and inspect the disk of your VM on another VM. Same way you can transfer your data to another working VM instance.
Comment: @JashSayani Does this [answer your question](https://stackoverflow.com/help/someone-answers)?


Using Date data type in where clause in Oracle DB, string literal error

Question: So I pull this value out of a column (columnA) in my database:
2014-01-05 00:00:00.0

I want to perform a query which uses this value in the where clause such that:
WHERE columnA = '2014-01-05 00:00:00.0'

But I am getting an error: ORA-01861: literal does not match format string
I assume this has something to do with the fact that it is a DATE data type; however I just pulled this value from the database so I know its formatted correctly. Do I still need to do some sort of explicit conversion to make this work?
Comment: Use explicit cast to date type with `to_date('2014-01-05 00:00:00.0', 'yyyy-mm-dd hh24:mi:ss.f')` ==> http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm
Comment: or use ANSI DATE format: `where columnA = DATE '2015-08-18'` :)
Comment: @kordirko - you can't use the F format with `to_date`, only with `to_timestamp`. Though that trailing `.0` also implies the date pulled from the database actually came from a timestamp column; or has been retrieved by Java (say) and displayed natively as a timestamp.
Comment: What database client do you use?
Answer: Look at NLS_DATE_FORMAT Oracle parameter. It defines a format applied by default to string literals during convertion to date. Different oracle instances or sessions may have own values of this parameter. By default this parameter has value determined by server locale or NLS_TERRITORY parameter. For more details see documentation.
For example (SQL Plus):
test@ORADEV> select current_date from dual;

CURRENT_DA
----------
2015.08.18

test@ORADEV> alter session set NLS_DATE_FORMAT = 'yyyy.dd.MM';

Session altered.

test@ORADEV> select current_date from dual;

CURRENT_DA
----------
2015.18.08

test@ORADEV> alter session set NLS_DATE_FORMAT = 'yyyy.dd.MM hh24';

Session altered.

test@ORADEV> select current_date from dual;

CURRENT_DATE
-------------
2015.18.08 18

The same query in TOAD returns 18.08.2015 18:31:32 because TOAD has own preferences for date formating.
What client do you use?
Moreover look at the example below (SQL Plus again):
test@ORADEV> set autotrace on trace explain
test@ORADEV> select current_date from dual where current_date <> '2015.18.08 18';

Execution Plan
----------------------------------------------------------
Plan hash value: 4034615273

-----------------------------------------------------------------
| Id  | Operation        | Name | Rows  | Cost (%CPU)| Time     |
-----------------------------------------------------------------
|   0 | SELECT STATEMENT |      |     1 |     2   (0)| 00:00:01 |
|*  1 |  FILTER          |      |       |            |          |
|   2 |   FAST DUAL      |      |     1 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(CURRENT_DATE<>TO_DATE(' 2015-08-18 18:00:00', 'syyyy-mm-dd hh24:mi:ss'))

Oracle can use its own date format after literal is converted with NLS_DATE_FORMAT (syyyy-mm-dd hh24:mi:ss).
So use explicit cast to date type with exact format or use NLS_DATE_FROMAT/NLS_TIMESTAMP_FORMAT (if it is safe in your case).


(deep learning) Is there a type of layer that can reverse the max-pooling operation?

Question: As far as I know, we have deconvolutional layer to reverse the convolutional layer. Is there something like that for max-pooling?
Also, I want to add this reverse max-pooling into an autoencoder, is there any existing example of it?
Answer: As Zeiler says in his paper "Visualizing and Understanding Convolutional Networks" :
"In the convnet, the max pooling operation is non-invertible, however we can obtain an approximate inverse by recording the locations of the maxima within each pooling region in a set of switch variables."
Check up the Zeiler's paper in the Unpooling section.
Answer: Have you checked this paper Stacked Convolutional Auto-Encoders for Hierarchical Feature Extraction?

Here we introduce a max-pooling layer that introduces sparsity over the hidden
  representation by erasing all non-maximal values in non overlapping subregions.

Basically it's the same as alviur's answer. Since they used only one max pooling layer, instead of actually doing the down-sampling for each box, they just erased all the non-maximal values, and the sparse representation is used for reconstruction.
Answer: MaxPool is not generally invertible, but PyTorch for example provides a function which computes a pseudo-inverse, where all elements other than the max are set to 0:

MaxUnpool2d takes in as input the output of MaxPool2d including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.


Permission denied when run Firebase pubsub scheduler function

Question: I am totally stuck here. I created one pubsub scheduler function as below.
const functions = require("firebase-functions");
exports.addTasksToQueueScheduler =  functions.pubsub
    .schedule('every 5 minutes')
    .onRun((context) => {
        console.log('This will be run every five minutes!');
  return null;
});

It is really simple function. I deploy it using

firebase deploy --only functions

I can see my function is created the firebase function.

I logged into firebase cloud scheduler and there I can see the function. I click on "Run Now" buttons but I am getting Result= failed.

I added roles like Cloud Functions Admin,
Cloud Scheduler Admin,
Cloud Tasks Admin,
Editor,
Owner,
Pub/Sub Admin,
Pub/Sub Publisher,
Cloud Run Invoker,
Storage Object Viewer to default "App Engine default service account". This is really getting frustrating that they don't provide a proper documentation that which roles/permission required to run this. They just give all and you need to find out. A newbie can totally be lost it.
Can anyone help please?
Comment: You mention that you're getting a "permission denied" error, would you kindly post it here? They often come with an error code if they don't specify the precise role needed, if it's a Cloud Error, so that might make troubleshooting this a little smoother.
Comment: did you ever solve this?
Answer: Try deploying to the same region (this depends which default resource location you've set):
exports.addTasksToQueueScheduler = functions.region('europe-west1').pubsub
    .schedule('every 5 minutes')
    .onRun((context) => {
        console.log('This will be run every five minutes!');
        return null;
    });

Think it needs roles/pubsub.subscriber, so that the function can be invoked.
Comment: I applied region and assigned ```roles/pubsub.subscriber``` but it is still showing the same error.


Really weird collision in hash algorithm: coincidence or error?

Question: I made a hash algorithm that uses MD5 for some low-security key generation. Basically, it takes the characters of a String and sums their indexed products, then takes the modulo of a random number, before MD5-ing that. In Java:
BigInteger bi = BigInteger.ZERO;
char[] array = input.toCharArray();
for (int i = 0; i < array.length; i++) {
    bi = bi.add(BigInteger.valueOf(i + 1).multiply(
            BigInteger.valueOf(array[i])));
}
final int moduloOperator = 52665; // random constant
final byte[] moduloResult = bi.remainder(
        BigInteger.valueOf(moduloOperator)).toByteArray();
MessageDigest md;
try {
    md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
    nsae.printStackTrace();
    return null;
}
md.update(moduloResult);
return new BigInteger(1, md.digest()).toString().substring(0, 7);

I have the substring at the end because it needs to be easily readable.
At first glance, it works as intended: different inputs give different outputs, but the result is consistent across runs.
However, when playing with it a bit, I noticed the following:
hash("")        = "1963546"
hash("1963546") = "1322048"
hash("1322048") = "2101764"
hash("2101764") = "3234562"

Looks fine so far. Suitably random. But then:
hash("3234562") = "3234562"
hash("3234562") = "3234562" [etc.]

This dumbfounded me. I would guess that there's about a one in ten million chance that the hash of a 7-digit number is itself. Did this really happen on only the fifth iteration, or is there something wrong with my setup? More importantly, could there be any other similar errors that could have a serious impact on my hash?
Thanks.
Comment: Could you write this in a mathematical formula, or at least explain it slightly clearer? I can't read Java code.
Answer: The "random" part of your code is doing more harm than good.
First, the code adds together several uncorrelated numbers:
for (int i = 0; i < array.length; i++) {
bi = bi.add(BigInteger.valueOf(i + 1).multiply(
        BigInteger.valueOf(array[i])));
}

Let's see the result of this for "2101764" and "3234562".  I'll use Python for brevity.
In [0]: sum((i+1)*int(digit) for (i, digit) in enumerate("3234562"))
Out[0]: 107

In [1]: sum((i+1)*int(digit) for (i, digit) in enumerate("2101764"))
Out[1]: 107

Well, there's your problem.
Remember the Central Limit Theorem?  The sum of random numbers is much more predictable than the individual numbers themselves.  Back of the envelope, for a 7 digit input the sum will have a distribution with a variance of 13.16 and mean of 115.5.   It would be safe to infer at least of all 60% of sums will be within a 50 number range, 95% of sums within a 100 number range, and all sums within a 189 number range -- if anything, I think this is generous about the entropy of the sum.
After destroying information through addition, the algorithm takes the sum modulo 52665.  There are only 52665 possible numbers modulo 52665, so this code can only ever produce 52665 hashes in the best of circumstances.
And...There's no reason to do any of this!  Random code does not make random numbers.  Making a good hash function is hard.  You're not going to improve on a hash by hacking up some code to slice and dice things.  On the contrary, you are likely destroy sources of randomness.  If you want a random hash, use one that someone else has written.
Say, for example, MD5!
Answer: The algorithm is definitely going through all the steps before doing the md.update call.
Note that you are not picking random numbers. Effectively, you are testing whether your algorithm, under repeated application, finds a fixed point that is an attractor for your input value, reached in only a few iterations.
I found another fixed point attractor after testing a few one digit strings:
hash("3") = "3147559"
hash("3147559") = "1874964"
hash("1874964") = "1874964"

I suggest doing more testing, using the types of input that you intend to use it for, and without feeding the result back into the algorithm. Run a few million random strings with appropriate characteristics, and see if some values show up a lot more than others.


Hide or show fields based on whether the node is published

Question: I'm looking to show and hide form fields based on the current progress of a node using contributed modules like Workflow, Maestro or rules.
For example, I would like to show certain fields if a post is published and hide those same fields if it is in draft.  I would like to avoid writing a custom module if possible.
Is there a simple way to interact with the Drupal 7 FormAPI to show and hide fields based on the status of a node using Rules, Workflow, Maestro or other contributed modules?
Also, is there an easy way to modify 'select lists' produced with the FormAPI using any of the noted plugins?
Answer: You might be able to piece something together using Conditional Fields, but a custom module (using hook_form_alter()) would definitely be the recommended path here, because it sounds relatively custom.
Conditional fields are simply hidden using JS, while it sounds like you might need to make it so people can't access the fields (so, #access property = FALSE) on the edit form in certain situations.
Rules doesn't have much integration with content editing forms; but you could probably set some field to a different value if the status of a node is changed from draft to published, or something like that, which could trigger something with Conditional Fields... but I think doing it in a custom module would be better in this case, and would definitely be more robust.
Comment: I don't think hook_form_alter is useful here. The question is about (not) viewing fields, not about editing. hook_form_alter will not be called in this case.
Comment: I would assume the OP would want the fields to not appear in either editing or viewing. Maybe implementing hook_field_access() would be the best bet to cover both situations.
Answer: +1 for a new module, but hook_node_view_alter() makes more sense.
In fact I thought I'd try it out. This will hide a field called field_hide_me if the node is published:
/**
 * Implements hook_node_view_alter().
 *
 * If the node is published then we hide a field
 * called 'field_hide_me'.
 */
function if_published_node_view_alter(&$build) {
  // only for full view mode
  if ($build['#view_mode'] == 'full') {
    // check whether our field exists
    if (isset($build['field_hide_me'])) {
      // grab the node
      $node = $build['#node'];
      // status is 1 for published, 0 unpublished
      if ($node->status) {
        unset($build['field_hide_me']);
      }
    }
  }
}

Sandbox here: http://drupal.org/sandbox/Mile23/1415030
Answer: I don't know about aGUI only solution. You can of course implement hook_field_access. It allows to implement fine grained access control for fields.


why spring handles only unchecked exceptions

Question: I want to know why spring handles only unchecked exceptions..... can any one explain what is the reason behind this .
Spring is using any design patterns which will avoid checked exceptions ?
Answer:
Spring is using any design patterns which will avoid checked
  exceptions ?

Not a design pattern but Best Practices for Exception Handling.
Consider below code:
public void consumeAndForgetAllExceptions(){
    try {
        ...some code that throws exceptions
    } catch (Exception ex){
        ex.printStacktrace();
    }
}

What is wrong with the code above?
Once an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.
How about the following?
public void someMethod() throws Exception{
}

This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? Java does not stop you from doing this.

I want to know why spring handles only unchecked exceptions?

Personally I prefer unchecked exceptions declared in the throws cause. I hate having to catch exceptions when I'm not interested in them. I agree the spec needs to a few more exception types, but I disagree that they should be checked. Most frameworks rely on unchecked exceptions, not only Spring framework.
Best Practices for Designing the API

If the client can take some alternate action to recover from the exception, make it a checked exception.
If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.

The Java API has many unchecked exceptions,
 such as
NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.
See Also:

Unchecked Exceptions
Best practices in exception handling
Comment: Declaring unchecked exceptions in a method signature improves readability and also gives tools (like IDE) a chance to suggest useful catch blocks in code that calls such a method. It's really just a courtesy, but it can be pretty useful for callers.
Comment: Mostly I agree with your answer, especially the "Best Practices" part.  However, if unchecked exceptions are the ones where the client cannot take useful action, why declare them in the throws clause?  No useful action can be taken anyway.
Comment: How can a provider assume a client can or cannot do anything useful with an Exception?
Answer: Spring's central theme is Dependency Injection and IOC. Checked exceptions add unncessary code and create more dependency. As such, the dependency costs of checked exceptions outweigh their benefits. They reduce the ability to test code. They lead to lower cohesion and higher coupling. The goal of your code should be high cohesion and low coupling. Spring is focused towards the S.O.L.I.D principles of design.


What's this weird sound coming from my speakers?

Question: I keep hearing bursts of static from the speakers of my electronic keyboard. At first I thought there was a loose electrical connection, but sometimes it has a rhythmic pattern to it, like "rat tatatat tatatat tatatat." And once I think I heard it coming from my computer speakers too. What is causing these strange noises?
Comment: This used to happen a lot with my computer speakers, and I never could figure out why, despite extensive web searching. Happened last night with my keyboard, and my fiancée immediately knew what was wrong. So happy to finally figure this out!
Comment: My old radio used to always do that - it got to where I could pick up my phone and answer it almost before it started ringing.
Answer: The noises are caused by electronics picking up wireless signals from your mobile phone and translating the interference into sound. Well-shielded circuits won't have this problem, but it's common in consumer electronics and some musical equipment, notably guitar leads. There's no damage to your equipment, and if the sound is a problem just keep the phone away from your electronic components and signal cables.
Comment: If it's the speaker wires picking up signals, then it will happen when the amp. is not turned on. Bet it doesn't. It's more likely to be RF picked up by the amp. circuitry and sent to the speakers (through their wires).Generally a guitar lead will act as an aerial to pick up RF.
Comment: It tends to be much worse with electric-guitar equipment, which is notoriously susceptible to any interference because of its (technically questionable, but you know, _vintage_) high-impedance design.
Comment: Oh cool! I have not personally experienced that yet, but hopefully this question and answer will help people who do.
Comment: @Tim Thanks for the feedback. I've edited the answer to indicate that it isn't necessarily the speaker wiring picking up the interference, and also incorporated other comments.
Answer: The above two answers are correct, however, here is some more details:
It's called electrostatic interference. It's caused by unbalanced cables picking up radio waves, basically acting as a radio antenna. If you are using an amplifier or a loud speaker this may be fixed by running a balanced cable instead or an unbalanced cable. If you go to purchase one this is what you want to look for:

https://i.stack.imgur.com/1VX0w.jpg
Comment: Looks like a good option for guitarists. Unfortunately won't help with the integrated speakers in my keyboard! Thanks for pointing out this solution for some musicians, +1!
Comment: Sorry I guess I missed that part. Well, keeping it away from electronics will definitely help. Anything that emits radio waves. Do you use this for playing gigs or is it just stationary at your house?
Comment: Balanced cables actually won't have much benefit for an electric guitar, since guitars don't send balanced signals. You can use them but it only sends a mono signal so it will only be using one of the connections, I think. Plus, balanced cables are WAY more expensive.
Comment: Ah ok, thanks for the clarification! The specific device that prompted this is my practice keyboard, which I primarily use to **study** music, as I'm more of a singer and guitarist. But I've run across the problem with other kinds of sound equipment too and figured it was a common enough problem to q&a here.
Comment: It could be electromagnetic interference which will be a hum or a buzz. It can be caused by the power source. If the power source is internal and it is a cheaper electric piano, this could be your problem. If the power source is outside the equipment (a black box attached to the power cable) move it away from the equipment.
Comment: This was definitely caused by the mobile phone. The keyboard is a Yamaha E323, by the way. The static is consistent on AC or battery power.


Performance of site when loading 3000+ variables

Question: I test all modules (custom + contrib) in one drupal base itself which has resulted in lot of variables.
I was just curious what happens if live site had 3k variables ?
Since all variables will be eventually global variables will it not require huge amount of PHP memory ? or is it not limited at all  ?
What is the alternate here ? cache_get with new cache table instead of variable_get every where
Answer: Yes, large variable tables are a problem.
Variables should only be used for small configuration flags and settings and not to store large structures for example.
But given a large amount of modules, dynamic variables like per-content type things you will sooner or later get into trouble.
No, there is no solution to this problem. The variables system will be replaced with the new configuration system from the CMI initiative for Drupal 8 which will hopefully be better at dealing with this.
Answer: My suggestion is,
We should not use cache_get or cache_set.Because this will reduce the php memory, but highly increase the slow down the site by querying the DB.
Your mentioned case is very rare.so use variable_get.
Comment: Considering memory advantages , going for cache_get makes sense , and I checked with timers it indicates 0.50 ms avg for cache_get and variable_get is also the same ! So in this case cache_get turns out good isnt it ?
Comment: are you checked in your local?
Comment: yeah localhost that s where I have a huge collection of variables
Comment: in localhost it may be same time.Why i am saying is, the variable_get is a simple function but cache_get is oops functionality written in php(drupal 7).Another one reason is each cache_get using a mysql query which will take time in live site.
Answer: The solution is to use something other than your DB to hand off info like this to your application. If you're on a shared or VPS host this will likely be memcached if you have the option I recommend using Redis.
Your cache, cache_bootstrap, and as of about D.22 your field info will be served from in-memory caching nicely.


translating static text

Question: I have just built a view for one of my modules.
In there, I have this line; %of Applicants Admitted`
I already installed modules like "Locale", "Content Translation" and "Internationalization" is already enabled.
But I dont understand how these modules will translate this text to other languages.
When I put it in t('') how will I know that it will translate it correctly. Can I manually enter the translation?
Thanks
Answer: Translations have to be entered manually... always.  There is no "automatic machine translation" function provided by Drupal core or the Internationalization suite of modules.
Putting a string inside t() simply makes it available to Drupal's translation subsystem for translation; the string will still be displayed "as is" until it is translated manually.
To translate strings manually from the UI, if you have the Locale module enabled, you can go to the Translate interface page.  (On Drupal 7: /admin/config/regional/translate/translate)
Comment: Thanks for the answer Patrick. What I dont get is, I put `quick stats` inside `t()` but I only get quick on the `translate interface` page. `` itself
Comment: Have you tried clearing the cache?

translating static text


The diophantine equation $ a^2 + p b^2 = c^2 + p d^2 = q $ and related ring theory questions.

Question: Inspired by norms of integral domains I started to think about the related diophantine equation for the norms.
Let $2 < p,q $ be given primes.
Consider the diophantine equation for positive integers
$$ a^2 + p b^2 = c^2 + p d^2 = q $$
Where $0 < a,b,c,d$ and $0 < (a-c)^2 + (b - d)^2$.
In other words we want 2 distinct representations of the prime $q$ by norms of the form $x^2 + p y^2$. This is basicly studying the norm for $\Bbb Z[\sqrt{-p}]$.
How to handle this ?
Quadratic residues probably relate to this.
Also I am unsure how this relates to $\Bbb Z[\sqrt{-p}]$ being a UFD or not , or to the the class number of it.
And I am also insecure about how it relates to Euclidean norms or multiplicative norms.
I know for instance the Gaussian integers or Eisenstein integers have multiplicative norms :
if $j,k$ are elements then $A = j k $ implies $N(A) = N(j)N(k)$.
and I know they only have one representation of a prime $q$.
In fact that is used in the proof of their UFD and in justifying factoring methods for them.
It seems these 2 properties combined, implies being a UFD ?
I say combined here because I know for instance that the norm $a^2 + 17 b^2$ for the ring $\Bbb Z[\sqrt{-17}]$ is multiplicative yet the ring $\Bbb Z[\sqrt{-17}]$ is not a UFD !!
Not sure how this relates to these diophantines.
Maybe it does not relate to these diophantines or norms at all and it is just my imagination ?
Is the number of representations (here $2$) equal to the class number if the norm is multiplicative ?
I read some stuff about ring theory but I did not learn or at least did not understand how to do these things and look at them properly.
My apologies for asking maybe more than 1 thing but I suspect they are all related and understanding one implies understanding the other.
The extra questions are more a kind of context.
The main question is the diophantine and an answer to that could get the accept.
I am aware of the  Brahmagupta–Fibonacci identity , but that does not answer my question(s).
For those who want to give a very general answer, I am mainly into rings that have a finite amount of units.

edit
I am aware that apparantly Euler and others came up with a method to solve the related equation but for COMPOSITE $q$.
Maybe that can help.
say $q = A q_2$
$$ a^2 + p b^2 = c^2 + p d^2 = A q_2 $$
If $0 < gcd(a,b,c,d,q_2)$ we might be in business.
Then again Euler did not even attempt the case for none-composite and the idea might miss solutions.
So I am not very optimistic yet.

edit 2
A few insightful links :
Norms are always multiplicative :
When is the norm of a ring $\Bbb Z[\sqrt{-p}]$ multiplicative?
and the general equation here
A generalization of Euler Factorization with $N = m a^2 + n b^2 = m c^2 + n d^2$
( it has a bounty at the moment !)
Comment: -1 Please gather your thoughts into a coherent question before posting them here. As it stands this is just some rambling sprinkled with buzzwords.
Comment: This looks very similar to this question here :  https://math.stackexchange.com/questions/4712807/a-generalization-of-euler-factorization-with-n-m-a2-n-b2-m-c2-n-d2
Answer: See:
Primes of the form $x^2+ny^2$?
Suppose $\mathbb{Z}[i \sqrt{p}]$ is a UFD then there is unique factorization of $q$ into prime elements in the ring.
Lets say we have unique factorization of $q$ as : $q = \prod_i z_{i}$
where $z_i$ are prime elements in the ring and various solutions come from various ways of grouping this product.
Since we have $q = (a+i\sqrt{p}b) \times (a-i\sqrt{p}b)$,
2 non-trivial factorizations exist iff $a+i\sqrt{p}b$ is not a prime element and can be further factorized assuming $\mathbb{Z}[i\sqrt{p}]$ is a UFD. This is because if $a+i\sqrt{p}b$ is a prime element there is only one unique way of combining the factorization of $q$ into solutions.
Hence,
$a+i\sqrt{p}b = (c+i\sqrt{p}d) \times (c'+i\sqrt{p}d')$
But then $Norm(a+i\sqrt{p}b) = Norm(c+i\sqrt{p}d) \times Norm(c'+i\sqrt{p}d')$ which cannot be prime unless $Norm(c+i\sqrt{p}d) = 1$
But $Norm(c+i\sqrt{p}d) = 1$ has only $c = 1,-1$ as solution.
Hence there exists a unique solution if $\mathbb{Z}[i\sqrt{p}]$ is a UFD.
Check if this ring is a UFD.
Further Analysis in case the ring is not a UFD:
$$a^2+pb^2 = c^2 + p d^2 = q$$
Now, $$a^2 + pb^2 = c^2 + p d^2 \implies a^2 - c^2 = p (d^2 - b^2) \implies (a+c)(a-c) = p(d^2-b^2) \implies (a+c)(a-c) = p (d^2 - b^2) = p(d+b)(d-b) $$ $$\implies \ one \ possible \ two \ solutions \  a =(p(d+b) + d-b)/2, c = (p(d+b) - (d-b))/2  \ for \ any \ b,d$$
The only thing we need to conclude is that $a^2 + pb^2 = q$ is a prime number $\implies$ for any  $$q = \frac{(p(d+b) + d-b)^2}{4}+pb^2$$ a prime number, we have two different solutions.
So two solution exists if there exists a solution $d,b$ to the equation,
$$q = \frac{(p(d+b) + d-b)^2}{4}+pb^2 = Norm \left(\frac{(p(d+b) + d-b)}{2}+i\sqrt{p} b \right)$$ or for some $d,b$ this number turns out to be prime.
Hence for this possible factorization of $p(d+b)(d-b)$ into $(a+c)(a-c)$, we have that, if there exists a solution $a^2+pb^2 = q$ then another solution exists iff $$a = \frac{(p(d+b) + d-b)}{2}$$ is solvable for some value of $d$. In other words iff $2a+b-pb$ is divisible by $p+1$.
By various possible factorizations of $p(d^2-b^2)$ into $(a+c)(a-c)$ and solving for $a,c$, you can find out all possibilities for existence of two solutions.
Comment: $a$ is even $c$ is odd is just one of the cases i am considering. See that i have also mentioned the case that all solutions are of $a$ and $c$ even or both odd also.
Comment: For example, for $q \leq p$ there is no solution at all whether UFD or not. UFD guarantees only uniqueness if solution exists and not the solution. For $q = p+4$ there cannot be 2 solutions since $a = 2$ uniquely and hence $b = 1$ for this case whether it is a UFD or not. So not being a UFD does not mean 2 solution exsits since it does not happen for $q = p+4$, if $p+4$ is a prime. for $q = p+4$, $a = 2$, $b = 1$ is a unique solution. For example $p = 223$, $ q = 227$ has unique solution but $p = 223$ is not a UFD.
Comment: I have given a formula for when 2 solution exists. This is only one of the situation where 2 solution exists. From the derivation you can deduce when all 2 solution exists. Cheers !. If you are happy with my answer, accept it by clicking to the left of my answer.
Comment: if there exists a solution, $a,b$  then solve for $d$ using $a = \frac{p(d+b)+d-b}{2}$ (if possible) and you obtain $c =  \frac{p(d+b)-(d-b)}{2}$. So given $a,b$ i am solving for $c,d$, a new solution if $a = \frac{p(d+b)+d-b}{2}$  is solvable. You can derive  new conditions by other factorization of $p(d+b)(d-b)$ and equating the factors to $(a+c)$ and $a-c$. Although in a convoluted way finally have $c,d = f(a,b)$ iff certain $a = g(d,b)$ is solvable. The point is $g(d,b)$ is linear in factors of $p(d+b)(d-b)$. So it helps to solve a linear function although for each possible factorization.
Comment: From $(a+c)(a-c) = p(d+b)(d-b)$we consider by one possible factorization $a+c = p(d+b)$, $a-c = d-b$. Now solve for $a,c$ from these 2 equations. Consider different factorization and you get different solutions. I have edited the answer to finally tell the conclusion.
Comment: Sure..but atleast this should help you work out some explicit cases.
Comment: why is $a$ even and $c$ odd ? WHY can they not both be even or both be odd ?
Comment: if both are even or both are odd then $a^2+pb^2$ will be even which cannot be equal to odd prime $q$.
Comment: no ! a and c ! not a and b !
Comment: Does a non-UFD imply two solutions for at least one $q$ ? ( I think so )
You set conditions on p when there are two solutions , but you do not explain when one has 2 solutions or what they are ?
I assume maybe knowing if there are 2 solutions is equivalent to being a non-UFD or not ?
Comment: knowing there are 2 solutions imply the ring is not UFD. I mentioned that "further analysis in case ring is not UFD". If the ring is UFD solution is unique.
Comment: Yes but does a non-UFD imply there are 2 solutions ?
Comment: Can you give a formula for$ a, b, c, d$ when given a $q$ ?
Comment: I will consider it ! thanks !
Comment: I did not downvote. Who did and why ?
Comment: I Dont know man
Comment: Ok , the part about UFD is correct. But the non-UFD part is not so good. Notice that having $a$ or $b$ is equivalent, we compute the one from the other. Similar with $c$ and $d$. Now that also implies having $a,c$ or $b,d$ is already have our 2 ways.
Then we see you writing a formula for $a$ and $c$ in terms of $b,d$. This does not help, we do not have $b,d$ if we did we were already done by the above argument. Then you go on asking to factor a function of $d,b$ into $(a+c)(a-c)$ what is even worse ; having $d,b$ is already the solution as is having $a,c$. Now you may argue ...
Comment: ...they are not explicitly given , but you also did not give a formula for those $b+d$ etc so that does not help. We do not know how to compute $ " b+d " $ without a formula for it , unless we have $b$ and $d$ already ... but that would mean already having solved the problem.
Let me go on , maybe you think but what if one of the forms is known , you can compute the other ?
Well for instance your formula for $a$ involves $b$ and $d$ but having $b$ implies knowing $a$ already , INDEPENDANT if we know $d$ or not. See the problem ?
Comment: thanks , I will look into it. I advice to clarify it in the answer ( to avoid downvoters and confusion )
Comment: How did you find that formula for $a$ resp $c$ anyway ??
Comment: I finally accepted. Might add additional questions as new question. I could let you know here. But I will think and compute myself first.


Como colocar um valor de input para ser analisado em uma Promise?

Question: "Crie uma função que recebe a idade de um usuário e retorna uma Promise que depois de 2
segundos retornará se usuário é maior ou não que 18 anos"
Quando abro a página depois de 2 segundos o resultado carrega mesmo sem eu ter inserido um valor. E logo após, quando coloco um valor (maior ou menor que 18) o resultado diz sempre que é menor.
O meu código:
function clicado() {
    var inputIdade = document.querySelector('input.idad').value;
    return inputIdade;
}

function checaIdade(idade) {
    return new Promise(function(resolve,reject){
        setTimeout (function() {
            if(idade > 18) {
                resolve();
            } else {
                reject();
            }
        }, 2000 );
    })
}

checaIdade(clicado())
    .then(function() {
        console.log("Maior que 18");
    })
    .catch(function() {
        console.log("Menor que 18");
});

Comment: Bem vindo ao Stack Overflow em Português :-) ... Mas qual o problema com o seu código? Aconteceu algum erro? Detalhe mais a sua pergunta.
Comment: Obrigado :) Então, quando abro a página depois de 2 segundos o resultado carrega mesmo sem eu ter inserido um valor. E logo após, quando coloco um valor (maior ou menor que 18) o resultado diz sempre que é menor.
Answer: Do jeito que fez, vc já está executando o setTimeout() por isso depois de 2 segundos já é mostrado o valor o que também faz o código sempre cair no catch() que seria o reject(), pois o valor está vazio, logo nunca será maior que 18. Repare que se envolver a execução da Promise no setTimeout() e inserir um valor chumbado no input, verá que será mostrado o console corretamente:

function clicado() {
  var inputIdade = document.querySelector('input#idad').value;
  return inputIdade;
}

function checaIdade(idade) {
  return new Promise(function(resolve, reject) {
    if (idade >= 18) {
      resolve();
    } else {
      reject();
    }
  })
}

setTimeout(() => {
  checaIdade(clicado())
  .then(function() {
    console.log("Maior que 18");
  })
  .catch(function() {
    console.log("Menor que 18");
  });
}, 2000)
<input type="text" id="idad" value="36">

Agora se pretende mostrar o console com a idade que for inserida no input, vc pode adicionar um evento tipo onblur(), por exemplo, para fazer o if/else conforme o valor digitado:

function clicado() {
  var inputIdade = document.querySelector('input#idad').value;
  return inputIdade;
}

function checaIdade(idade) {
  return new Promise(function(resolve, reject) {
    if (idade >= 18) {
      resolve();
    } else {
      reject();
    }
  })
}

document.querySelector('input#idad').addEventListener('blur', () => {
  setTimeout(() => {
    checaIdade(clicado())
    .then(function() {
      console.log("Maior que 18");
    })
    .catch(function() {
      console.log("Menor que 18");
    });
  }, 2000)
})
<input type="text" id="idad">

OBS: Na condição tbm coloquei um maior ou igual 18, pq se for 18 já e maior de idade!


Fundamental Theorem of Calculus - Derivative of the integral

Question: Given $\displaystyle y=\int^{\tan(x)}_0 \frac{1}{1+t^2}\,dt$, how can I prove that $ \dfrac{dy}{dx} = 1$ ?
attempt:
by the Fundamental Theorem of Calculus we have:
$\displaystyle \frac{dy}{dx} = \frac{1}{1+\tan^2(x)\cos^2(x)} = \frac{1}{1+\sin^2(x)}$
and not 1.
can anyone help with this problem?
thanks!!
Comment: You need to multiply the entire denominator $1+\tan^{2}x$ by $\cos^{2}x$, not just the $\tan^{2}x$.
Answer: Put $$F (t)=\int_0^t \frac {du}{1+u^2}$$
then $$F'(t)=\frac {1}{1+t^2} .$$
$$y=F (\tan (x)) $$
$$\frac {dy}{dx}=F'(\tan (x))(\tan (x))'$$
$$=\frac {1}{1+\tan^2 (x)}(1+\tan^2 (x)) $$
$$=1$$
Answer: The FTC implies
$$
\frac{dy}{dx}
 = \frac{\sec^2 x}{1+\tan^2 x}
 = \frac{1}{\cos^2 x+\sin^2 x}
 = 1
$$
Answer: Just note that $\int{\frac{1}{1+x^2}}=arctan(x)+C$. So integrating you get that
$y=arctan(t)|_{0}^{tan(x)}$=x$. Then differentiating with respect to x gives the result.
Comment: only If x∈(−π2,π2) then arctan(tanx)=x !
Comment: Sure. What's your point? Did you specify that it could not be.


Does the equivalence ($P \rightarrow Q$) $\iff$ ($\lnot P \lor Q$) hold in intuitionistic logic?

Question: Does it maybe hold in one direction but not the other?
Comment: What are the axioms you're using? Specifically, is $\vee$ an abbreviation or do your axioms define it?
Comment: The answer will be the same for any usually-accepted axiomatization of intuitionistic propositional calculus. In none of these axiom-sets is much of any connective treated as an abbreviation, except that  $\lnot P$ is (arguably) defined as an abbreviation for $P\rightarrow\bot$
Comment: Isn't $P\leftrightarrow Q$ an abbreviation for $(P\rightarrow Q)\land(Q\rightarrow P)$?
Comment: ↔ needn't occur at all in those axiomatizations.  There is a difference between a definition and an axiom, usually.  An occurrence of a term that has a definition that is an abbreviation can be eliminated (the left/short side of the definition can be eliminated in favor of the right/long one).  ↔ is more syntactic icing than cake. It makes some things easier to say but it's truly optional.  Negation is a little more critically basic than that.  Here is an example: https://www.encyclopediaofmath.org/index.php/Intuitionistic_propositional_calculus
Comment: Please avoid stating the problem you want help with only in the title.  The body of a Question provides ample space for the specific details you've been asked to provide, and adding a series of Comments is less desirable than making a full self-contained problem statement in the body of the Question.
Comment: "the specific details you've been asked to provide"?? Nobody asked me to provide any details!  I asked the question!  Nobody asked *me* anything!
Answer: $\Leftarrow$ holds but $\Rightarrow$ does not hold.
To show that $\Leftarrow$ holds,
suppose $\neg P \vee Q$ holds. Then if $P$, I claim that $P \to Q$ holds. In the first case, $\neg P$ and $P$ form a contradiction, so $Q$. If $Q$, then clearly $Q$. Thus $P \to Q$.
To show that $\Rightarrow$ does not hold,
find a model of intuitionistic logic where $P \to Q$ holds but $\neg P \vee Q$ does not hold. Intutionistic logics are modeled by Heyting algebras, so to prove that $P \to Q$ does not imply $\neg P \vee Q$, it suffices to find a Heyting algebra where $((P \to Q) \Rightarrow (\neg P \vee Q))$ is not 1.  An Heyting algebra where this is true is given by the third example on this Wikipedia page. Let $P = ½$, $Q = ½$. Then $P \to Q = 1$ but $\neg P \vee Q = ½$. Then $((P \to Q) \Rightarrow (\neg P \vee Q)) = 0$, which is not 1, so we are done.


If $G_1$, $G_2$ and $G_3$ are subgroup of $G$ then does the equality $\big\langle⟨ G_1\cup G_2⟩\cup G_3\big\rangle=⟨ G_1\cup G_2\cup G_3⟩$ holds?

Question: So it is a well knew result that any intersection of subgroup is a subgroup and even it is a well knew result that the union of subgroup is not generally a subgroup. However, if $\mathcal S(G)$ is the collection of subgroups of any group $G$ then for any subset $X$ of $G$ then the collection
$$
\mathcal G(X):=\{Y\in\mathcal S(G):X\subseteq Y\}
$$
is not empty so that its intersection $\langle X\rangle$ is a subgroup containing $X$ which is moreover the less subgroup containing it: thus if $\mathcal H$ is a collection of subgroups then we can say that
$$
\langle\mathcal H\rangle:=\Big\langle\bigcup\mathcal H\Big\rangle
$$
is the subgroup generated by $\mathcal H$.
Now I know that the equality
$$
\tag{1}\label{1}\begin{equation}\langle\mathcal H\rangle=\Big\{x_1\cdots x_n:x_i\in\bigcup\mathcal H\text{ for all }i=1,\dots, n\text{ with }n\in\omega\Big\}\end{equation}
$$
holds (right?) so that by this I asked if even the equality
$$
\tag{2}\label{2}\begin{equation}\langle G_1\cup G_2\cup G_3\rangle=\big\langle\langle G_1\cup G_2\rangle \cup G_3\big\rangle\end{equation}
$$
holds for any $G_1,G_2,G_3\in\mathcal S(G)$.
So first of all I observed that
$$
G_1\cup G_2\cup G_3\subseteq\langle G_1\cup G_2\rangle\cup G_3\subseteq\big\langle\langle G_1\cup G_2\rangle\cup G_3\big\rangle
$$
holds so that I conclude that
$$
\langle G_1\cup G_2\cup G_3\rangle\subseteq\big\langle\langle G_1\cup G_2\rangle\cup G_3\big\rangle
$$
However, by \eqref{1} any element of $\big\langle\langle G_1\cup G_2\rangle\cup G_3\big\rangle$ is a finite product of elements of $\langle G_1\cup G_2\rangle$ and $G_3$ so that if by \eqref{1} any element of $\langle G_1\cup G_2\rangle$ is a product of elements of $G_1$ and $G_2$ then by associativity and by \eqref{1} we conclude that
$$
\big\langle\langle G_1\cup G_2\rangle\cup G_3\big\rangle\subseteq\langle G_1\cup G_2\cup G_3\rangle
$$
Finally we conclude that the equality \eqref{2} holds.
So I ask if actually \eqref{2} holds because I do not know if really \eqref{1} holds since my textbook do not write it explicitly although, at least it seems, it proves it. Moreover if \eqref{2} holds then is it possibile to prove it using associativity of intersection? For sake of completeness here a reference from my textbook - in Italian, sorry. Could someone help me, please?
Comment: You can also prove the opposite inclusion directly without needing to use (1): we have $G_1 \cup G_2 \subseteq \langle G_1 \cup G_2 \cup G_3 \rangle$, so $\langle G_1 \cup G_2 \rangle \subseteq \langle G_1 \cup G_2 \cup G_3\rangle$.  And also $G_3 \subseteq \langle G_1 \cup G_2 \cup G_3 \rangle$; therefore, $\langle G_1 \cup G_2 \rangle \cup G_3 \subseteq \langle G_1 \cup G_2 \cup G_3 \rangle$...
Comment: Since $\cup\mathcal{H}$ is closed under inverses (that is, if $x\in\cup\mathcal{H}$ then $x^{-1}\in\cup\mathcal{H}$, the set of all finite products of elements of $\cup\mathcal{H}$ and the set of all finite products of elements of $\cup\mathcal{H}$ *and their inverses* is exactly the same thing.
Comment: Let $G$ be a group and $X\subseteq G$. There are equivalent definition of subgroup of $G$ generated by $X$: $\langle X\rangle$ is the smallest subgroup of $G$ containing $X$$\iff$$\langle X\rangle =\bigcap_{i\in I} H_i$, where $\{H_i|i\in I\}$ is family of all subgroup of $G$ which contains $X$$\iff$$\langle X\rangle = \{a_1^{n_1}\cdots a_t^{n_t}\mid a_i\in X\text{ and }n_i\in \Bbb{Z}\}$. Definition of generator given in D&F is worse (or at least misleading IMO), [see post](https://math.stackexchange.com/q/4662724/861687). You may also check conversation between user lulu and I in comments.
Comment: @user264745 thanks for the comment and even for the upvoted whether you did the last I received. ;-)
Comment: @user264745 Yes, I understand. However, for sake of completeness, I have to point out that if $G_1$, $G_2$ and $G_3$ are simply closed an analogous result holds as [here](https://math.stackexchange.com/q/4657648/736008) you can see by yourself.
Comment: @DanielSchepler Oh fine!!! Anyway could I ask if (1) actually holds?
Comment: @ArturoMagidin Perfect, all clear now.
Comment: As noted in a comment on my answer, you should either specify that your collection of subgroups is *nonempty*, or else you need to allow $n\in\omega$ and not merely in $\omega_+$, so that you can get the identity element (either as a nonempty product if $\cup\mathcal{H}\neq\varnothing$, or as the empty product in any case).
Comment: @ArturoMagidin Okay, I understand. Only one question before to edit: if I put $\omega$ rather than $\omega_+$ then I have not to change $x_1\dots x_n$ with $x_0\dots x_n$ if I do not require $\cal H$ is not empty, right?
Comment: You should *not* change it to $x_0$ in any case. The whole point is that when $n=0$, the product $x_1\cdots x_0$ has no factors, and therefore equals the identity by definition. If you change it to $x_0$, then when $n=0$ you still have one factor. The whole point is to allow the empty product.
Comment: @ArturoMagidin Perfect: so I edited the question changing $\omega_+$ with $\omega$ so that $\cal H$ could be even empty. Thanks for the indication! :-)
Comment: @AntonioMariaDiMauro I forgot to mention main thing. Your proof is correct but it uses $G_1,G_2,G_3$ are subgroups of $G$. If subgroup conditions are removed, then $\langle \mathcal{H} \rangle$ is not correct. We can prove desired equality just with $G_1,G_2,G_3\subseteq G$ condition, as shown in answer by Arturo Magidin,. You don't really have to explicitly say that you're using associative law. Just prove generalised associative law once and for all.
Answer: Yes, both hold.
For any family $\{H_i\}_{i\in I}$ of subsets (not necessarily subgroups) of $G$, $\langle H_i\rangle$ is the subgroup $K$ that satisfies the following two conditions:

$H_i\subseteq K$ for each $i\in I$; and
if $M$ is any subgroup of $G$ such that $H_i\subseteq M$ for every $i\in I$, then $K\subseteq M$.

This is the "top-down description" of the subgroup generated. You use these properties in the second displayed equation after $(2)$.
We want to show that
$$\bigl\langle G_1\cup G_2\cup G_3\bigr\rangle = \Bigl\langle \bigl\langle G_1\cup G_2\bigr\rangle\cup G_3\Bigr\rangle.$$
(We don't even need to assume these are subgroups).
$\subseteq)$ Note that
$$\begin{align*}
G_1\cup G_2\subseteq \langle G_1\cup G_2\rangle &\subseteq \Bigl\langle \bigl\langle G_1\cup G_2\bigr\rangle\cup G_3\Bigr\rangle\\
G_3\subseteq \langle G_1\cup G_2\rangle\cup G_3 &\subseteq \Bigl\langle \bigl\langle G_1\cup G_2\bigr\rangle\cup G_3\Bigr\rangle
\end{align*}$$
Therefore,
$$(G_1\cup G_2)\cup G_3 = G_1\cup G_2\cup G_3 \subseteq
\Bigl\langle \bigl\langle G_1\cup G_2\bigr\rangle \cup G_3\Bigr\rangle,$$
and since $\langle G_1\cup G_2\cup G_3\rangle$ is the smallest subgroup that contains $G_1\cup G_2\cup G_3$, we have
$$\langle G_1\cup G_2\cup G_3\rangle \subseteq \Bigl\langle\bigl\langle G_1\cup G_2\bigr\rangle\cup G_3\Bigr\rangle.$$
$\supseteq)$ Since $G_1\cup G_2\subseteq G_1\cup G_2\cup G_3\subseteq \langle G_1\cup G_2\cup G_3\rangle$, we have
$\langle G_1\cup G_2\rangle \subseteq \langle G_1\cup G_2\cup G_3\rangle$.
We also have $G_3\subseteq G_1\cup G_2\cup G_3\subseteq \langle G_1\cup G_2\cup G_3\rangle$.
Since both $\langle G_1\cup G_2\rangle$ and $G_3$ are contained in $\langle G_1\cup G_2\cup G_3\rangle$, their union is contained there as well, so
$$\langle G_1\cup G_2\rangle\cup G_3\subseteq \bigl\langle G_1\cup G_2\cup G_3\bigr\rangle,$$
and therefore
$$\Bigl\langle  \bigl\langle G_1\cup G_2\bigr\rangle \cup G_3\Bigr\rangle \subseteq \bigl\langle G_1\cup G_2\cup G_3\bigr\rangle,$$
as desired. $\Box$
More generally, for any family $\{B_i\}_{i\in I}$ of subsets of $G$, and any partition $\{I_j\}_{j\in J}$ of $I$ (so $\cup_{j\in J}I_j=I$), we have
$$\left\langle \bigcup_{i\in I}B_i\right\rangle = \left\langle \bigcup_{j\in J}\left\langle \cup_{i\in I_j}B_k\right\rangle\right\rangle.$$
As to whether your description of $(1)$ is accurate, note that in general if $S$ is a subset of $G$, $\langle S\rangle$ is the collection of all finite products of elements of $S$ and their inverses. But if $S$ is closed under inverses, that is, if $S$ satisfies the condition
$$\text{if }s\in S,\text{ then }s^{-1}\in S,$$
then this is exactly the same thing as the collection of all finite products of elements of $S$. (Note the empty product is a finite product and gives the identity element). Since your $\cup\mathcal{H}$ is a union of subgroups, it is certainly closed under inverses; and you can ignore the empty product since the set already contains $e$; so your description of $\langle \cup\mathcal{H}\rangle$ is accurate if the family of subgroups is nonempty.
Comment: In the given version of (1), it is required for $n \in \omega_+$, so in the generalization, you might also want to require that $S$ is nonempty (which of course it is in the case of a nonempty union of subgroups).  (Then of course, if you allow the empty product and say that that product evaluates to the identity, you can also allow $\langle \emptyset \rangle = \{ e \}$ to be a special case.)
Comment: @DanielSchepler: I say "finite products", rather than use $\omega_+$, but I'll note it for the OPs set.
Comment: Oh, very nice answer! Thanks really for it and so for your assistance. :-)
Comment: @DanielSchepler Thanks for the observation!!! :-)


Probability of at least one triangle in Erdos-Renyi graph

Question: This is a well-known problem in random graph theory, where we show that if $X$ is the number of triangles in $G(V,E,p)$ with $p=o(\frac{1}{n})$, we can show that
$$
P(X \geq 1) \geq 1-o(\frac{1}{n}) \to_n 1
$$
using Chebyshev inequality and asymptotic expansion of binomial coefficients, $\binom{n}{k} \sim \frac{n^k}{k!}$.
What I don't understand is the part where the second moment is used for indicator variables:
$$
\mathbf{E}X^2 = \mathbf{E} (\sum_{k=1}^{\binom{n}{3}} X_k)^2 = \sum_{k=1}^{\binom{n}{3}} \mathbf{E}X^2_k +\sum_{k \neq j}\mathbf{E}X_k X_j
$$
Specifically, I don't understand the absence of 2 in front of the second sum. The explanation is that triangles are ordered. This means that selecting triangle $X_j$ and then $X_k$ is different to $X_k$ and then $X_j$. Could someone explain why?
Answer: The issue seems to be just about understanding the notation in the summation index, that is, nothing to do with the specifics of the graph problem.
$\sum_{k\neq j}$ refers to summing over all $(k,j)$ with $k,j \in \{1,\ldots,n\}$ such that $k\neq j$. So, both $(i,l)$ and $(l,i)$ for any $i\neq l$. Since $\mathbb{E}X_k\,X_j = \mathbb{E}X_j\,X_k$, we have
\begin{equation}
\sum_{k\neq j} \mathbb{E}(X_k\,X_j) = 2\,\sum_{k<j} \mathbb{E}(X_k\,X_j),
\end{equation}
where $\sum_{k<j}$ refers to all pairs of indices where $1\leq k < j \leq n$. You are probably thinking about this latter summation.
For example, when $n=2$, $\mathbb{E}((X_1+X_2)^2)$  can be expressed either as
\begin{equation}
\mathbb{E}(X_1^2+X_1\,X_2+X_2\,X_1+X_2^2) = \mathbb{E}(X_1^2)+\mathbb{E}(X_2^2)+\mathbb{E}(X_1\,X_2)+\mathbb{E}(X_2\,X_1)
\end{equation}
which is the notation appearing in the question unfolded. Or, since $X_1\,X_2=X_2\,X_1$, this is equal to
\begin{equation}
=\mathbb{E}(X_1^2) + \mathbb{E}(X_2^2) + 2\,\mathbb{E}(X_1\,X_2)
\end{equation}
which is the $\sum_{k<j}$ notation unfolded.
Comment: I'm sorry i don't quite see how this answers my question. The source here:https://www.ndsu.edu/pubweb/~novozhil/Teaching/767%20Data/chapter_3.pdf: 'Here Here we assume that all possible triples are ordered and labeled.we assume that all possible triples are ordered and labeled.'. I understand the labelled part (hence $\binom{n}{3}$ number of choices, but why is it ordered? Like triangle 1 and 2 vs 2 and 1 are different. Why?
Comment: Can you give a page number? See page 5, "Here the sum in the second term is taken through all the ordered pairs of $i\neq j$, hence there is no "2" in the expression."
Comment: I maybe misunderstood your question, since I thought you are asking about why $E(\sum(X_i)^2) = \sum_i(E(X_i)^2) + \sum_{i\neq j}(X_i\,X_j)$ rather than $E(\sum(X_i)^2) = \sum_i(E(X_i)^2) + 2\, \sum_{i\neq j}(X_i\,X_j)$
Comment: You looked at Thm 3.4 and 3.5, this is exactly my problem. I don't understand why there's not 2 in front of this sum over $\mathbf{E} X_i X_j$ or, rewording it, why the triangles are ordered
Comment: Please add a reference/link to the source into the question and clarify that you are asking about the proof of Thm 3.4 on page 5 (if you are asking about something else, clarify that...)
Comment: Also, if you add the context about triangles into the answer, I (or someone else) can show how the part of the proof can equivalently be written using unordered pairs (so th e $2\sum_{j<k}\mathbb{E}(X_j\,X_k)$) part, but currently it's a bit difficult as the question does not explain the whole context (and uses different notation than the linked material, note that there $n$ is the number of nodes in the graph, not the number of triangles)
Comment: My apologies, I edited the question to reflect the fact that the sum is over all possible triangles, $\binom{n}{3}$. I do refer to Thm 3.5 in the linked lecture.
Comment: Essentially I don't understand why $\mathbf{E}X_k X_j \neq \mathbf{E} X_j X_k$


How to restrict input to what is needed? ( eg: no numbers where letters are supposed to be inputted )

Question: Can anyone tell me what is the best way to check input type? For example if I ask someone to enter their name, I want to make sure that they don't enter numbers. OR the same way around when I ask for their age, I don't want letters to be imputed. I've tried using switch statements, but this doesn't seem  to be good idea.
Comment: Use functions like `isdigit` and `isalpha` to test whether a character is a number or a letter.
Comment: You might consider reading http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ before you write more code that manipulates names.
Comment: What have you tried so far? Is the input in the form of a C string? Do you have a "regular expression" library available? That would be the simplest way to check. Otherwise you have to examine the string character by character and check isalpha(), isdigit() etc.
Comment: `sscanf()` idea:  `char buf[100]; fgets(buf, sizeof buf, stdin); int n = -1; sscanf(buf, " %*[A-Za-z ]%*[\n]%n", &n);  if (n > 0 && buf[n] == '\0') GoodName();`
Comment: Best to use `strtol()` family of functions for testing number input.
Comment: So `Thurston Howell the 3rd` is not a name?
Comment: What about C3P0 and R2D2, for that matter?
Answer: isalpha() in C only works for characters. Build a function that iterates through a string and checks if all characters are accepted by isalpha()
See:
int string_is_name(char *s)
{
    int i;
    int valid = 1;
    for (i = 0; i < strlen(s); i++) {
        if (!isalpha(s[i])) {
            valid = 0;
            break;
        }
    }
    return valid;
}

Comment: 1) Better to use `!isalpha((unsigned char) s[i])` to prevent UB.  2) Better to use `size_t i;`
Comment: Which is clearer `int`, `unsigned`, `size_t` is a subjective question - so no definitive answer is readily possible.  But using `size_t` technically is correct for both `size_t` is the return type of `strlen()` and `size_t` is well defined for indexing arrays from the base `s`.  `int` suffers from negative indexing (not applicable here) and range as you mentioned.  "would that really happen here?": not likely unless someone writes a virus on a 64-bit machine to take advantage of the `int` range weakness.  I recommend practicing safe indexing.
Comment: @chux you use size_t for your loop indices? Why is that a better approach?
Comment: @chux The only reason I can think of is because of overflow (if you had more than MAX_INT elements in your array), but would that really happen here? It is clearer to use int or unsigned int, no?
Comment: Thank you for your insight. I'll keep this in mind for the future.


WPF/XAML animation using own event

Question: I've used WPF for quite some time now, but I've never looked serious into animation. I'm trying to achieve the following, but until now, not successful.
I have a class called "Property". This class has the ability to fire an event:
public class Property
{
    // ...

    public event System.Windows.RoutedEventHandler Attract;

    // ...
};

The properties are shown on the screen. Sometimes I need to attract the user's attention to a certain property. I want to fire the "Attract" event on the property. Then, from XAML start an animation.
I would expect something like this:
<Storyboard x:Key="blinkingAnimation">
    <DoubleAnimation From="0" To="1" Duration="0:0:5" RepeatBehavior="3x" AutoReverse="True" Storyboard.TargetProperty="(UIElement.Opacity)" />
</Storyboard>

<DataTemplate x:Key="PropertyTemplate" DataType="{x:Type GridViewColumn}">
    <TextBox>
        <TextBox.Triggers>
            <EventTrigger RoutedEvent="Attract">
                <EventTrigger.Actions>
                    <BeginStoryboard Storyboard="{StaticResource blinkingAnimation}"/>
                </EventTrigger.Actions>
            </EventTrigger>
        </c:NumericTextBox.Triggers>
    </TextBox>
</DataTemplate>

Is this the proper way to do it? At runtime, the compiler fails to resolve the "Attract" event. What am I doing wrong?
Answer: That's not the proper way to declare a routed event. See msdn (http://msdn.microsoft.com/en-us/library/system.windows.routedevent.aspx) for reference.
Comment: Thanks. Solved it acutally using this link: http://www.hardcodet.net/2009/05/trigger-wpf-animations-through-attached-events

WPF/XAML animation using own event


Failed to load resource jQuery function after published

Question: In Visual Studio 2012, I'm using MVC 4 and C#. I have three dropdownlists. Each is based on and related to another with binding and that works fine, but after I published, it has not worked because I have a jquery function to read data from jsonresult and it doesn't allow access to the function options.url = "/invoice/GETCompanyByID";.
if ($("#Area").val() != "Please select") {
    var options = {};
    options.url = "/invoice/GETCompanyByID";
    options.type = "POST";
    options.data = JSON.stringify({ stateid: $("#Area").val() });
    options.dataType = "json";
    options.contentType = "application/json";
    options.success = function (states) {
        $("#state").empty();
        $("#inv").empty();
        for (var i = 0; i <= states.length; i++)
        {
            $("#state").append("<option selected value=" + states[i].Value + ">" + states[i].Text + "</option>")
            $("#contract").val($("#state").val())
            $("#state").prop("disabled", false);
        }
    };
    options.error = function () { alert("Error retrieving states!"); };
    $.ajax(options);
}
else {
    $("#state").empty();
    $("#state").prop("disabled", true);
}

$("#areaid").val($("#Area").val())
});

[HttpPost]
public JsonResult GETCompanyByID(int stateid)
{
    return Json(new SelectList(DAL.Get_All_Contract(stateid), "IDContract", "ContractNo"));
}

Comment: XHR failed loading: POST "http://192.168.191.4/invoice/GETCompanyByID".
Comment: what was the actual error when it failed? What status code, and what message?
Comment: Why are you using POST when you could have used GET request? And also, what is the error message you are getting from that request?
Comment: i using post method  and finally i solved my error which was came from             options.url = "/invoice/GETCompanyByID";
and i should to use Url.contant("~/invoice/GETCompanyByID")
Answer: Finally i solved my error which came from
options.url = "/invoice/GETCompanyByID";

while I should use
Url.content("~/invoice/GETCompanyByID")

Comment: You're sure that it is `Url.contant`, not maybe `Url.content`?


Postfix Maildir delivery failure due to read-only file system

Question: Postfix fails to deliver messages with error "Read-only file system":
status=bounced (maildir delivery failed: create maildir file /home/deploy/Maildir/tmp/... : Read-only file system)

My directory permissions are set to 700 and 750 with owner set to deploy:deploy as suggested by this questions Postfix unable to deliver to user's Maildir.
    +-- /home/deploy: 700
        +-- Maildir: 750
            +-- cur: 750
            +-- new: 750
            +-- tmp: 750

Edit 1:
The output of mount is below. Everything is rw except tmpfs, which is ro:
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
devtmpfs on /dev type devtmpfs (rw,nosuid,size=240844k,nr_inodes=60211,mode=755)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)
tmpfs on /run type tmpfs (rw,nosuid,nodev,mode=755)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_prio,net_cls)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpuacct,cpu)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
configfs on /sys/kernel/config type configfs (rw,relatime)
/dev/vda1 on / type ext4 (rw,relatime,data=ordered)
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=32,pgrp=1,timeout=300,minproto=5,maxproto=5,direct)
mqueue on /dev/mqueue type mqueue (rw,relatime)
debugfs on /sys/kernel/debug type debugfs (rw,relatime)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)
tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=50044k,mode=700,uid=1000,gid=1000)

Edit 2:
/home/deploy/Maildir/tmp/ is on dev/vda1:
$ df -h /home/deploy/Maildir/tmp
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        20G  2.7G   16G  15% /

Edit 3:
Rebooting the server and running dmesg -H to see if there are any read/write or I/O errors. dmesg -H prints the following for vda1:
EXT4-fs (vda1): mounted filesystem with ordered data mode. Opts: (null)
EXT4-fs (vda1): re-mounted. Opts: (null)

Edit 4:
The status of SELinux is disabled:
$ sestatus
SELinux status:                 disabled

The user postfix cannot write to /home/deploy/Maildir/tmp/:
$ sudo -H -u postfix bash -c 'pwd && touch test'
/home/deploy/Maildir/tmp
touch: cannot touch 'test': Permission denied

Comment: "read-only file system" is not related to the permission, it means, typically, that the filesystem encountered some errors and it was remounted read only to make sure problems do not propagate... Run the `mount` command to see the current status and have a look at your system logfile they should tell why and when the filesystem got remounted as read-only.
Comment: @PatrickMevzek I updated my post to show the output of `mount`. Everything is mounted as `rw` except `tmpfs`.
Comment: Please add output of `df -h /home/deploy/Maildir/tmp/...` so it would show what device is underneath.
Comment: @kubanczyk it's on `/dev/vda1`
Comment: Check dmesg for IO errors. However it should affect all writes if this is the root filesystem
Comment: @eckes What am I looking for in particular with `dmesg`? I ran `dmesg -H` and did not find anything related to `/home/deploy/Maildir/tmp/..`
Comment: It should print something like "mounting Filesystem / read-only" because of disk errors.
Comment: @eckes I updated the original post with Edit 3 printing everything for `/dev/vda1`. I didn't find anything along those lines.
Comment: try yourself as postfix user `touch /home/deploy/Maildir/tmp/foobar`, do you get any error message? Also, do you use SELinux ?
Comment: @PatrickMevzek The original post was updated to Edit 4 with your suggestions. SELinux is disabled, but `postfix` cannot write to the directory with a permission denied error.
Answer: The initial error message seems misleading as with your latest edits we can clearly show that this is a permission problem.
From the own answer you link to:

In order for mail to be delivered, postfix must be able to enter the user's home directory,

And you said:

My directory permissions are set to 700 and 750 with owner set to deploy:deploy

But Postfix runs as user "postfix", so clearly no postfix process could enter /home/deploy which has permission rwx------- and owner/group deploy:deploy.
So you need to fix that.
If /home/deploy is only used for emails and nothing else (no user access to it), the simplest way would be to give ownership to user postfix for all files.
On the contrary if users access /home/deploy (I suppose a user called deploy and that you have many others under /home, but if you could it would be better to store user's email outside of their own directory if they are supposed to use it for other needs too), I would recommend something like:
/home/deploy deploy:postfix rwxr-x---
    Maildir postfix:postfix rwx------
        cur postfix:postfix rwx------
        new postfix:postfix rwx------
        tmp postfix:postfix rwx------

or
/home/deploy deploy:postfix rwxr-x---
     Maildir deploy:postfix rwxrwxs---
         cur deploy:postfix rwxrwxs---
         new deploy:postfix rwxrwxs---
         tmp deploy:postfix rwxrwxs---

(note the s as a big difference from above, to make sure all files are create with postfix group and hence readable/writable by it)
But it also depends if you want users to get, with their shell, access to Maildir or not. It also depends how email is picked up then, by some IMAP daemon maybe?
Another option is to configure Postfix to do the delivery with the user account UID, so that you have nothing to do regarding permissions. This depends on what MDA is used by Postfix.
Comment: I would also recommend to use /var/mail/deploy then you do not need to mess with parent directories and can use the group mail writeable for the actual user mailbox directory.


100% width sliding multi-level ULs

Question: I am working on a navigation system where I would like the parent ul and all children uls to span 100% width and when you click an li with a child ul, the parent slides off to the left and the child slides in from the right. Here's what I have so far:

$(function() {

  $('.list-container ul > li.has-child').each(function() {
    $(this).find('ul').prepend('
< Back
');
  });

  $(document).on('click', '.list-container ul > li', function(e) {
    e.stopPropagation();
    var children = $(this).find('ul');
    if (!$(this).hasClass('back')) {
      if (children.length > 0) {
        $(this).parent().css('left','-100%');
        $(this).find('ul > li').css('display','block');
        $(this).find('ul').css('left','100%');
      }
    }
  });

  $(document).on('click','li.back', function(e) {
    e.stopPropagation();
    $(this).parent().parent().parent().css('left','0');
    $(this).parent().css('left','200%');
  });
});
html,body {
  height:100%;
  margin:0;
}
.list-container {
  overflow:hidden;
  width:100%;
}
ul {
  width:100%;
  list-style-type:none;
  padding:0;
  margin:0;
  position:absolute;
  transition: all 0.5s ease;
}

li {
  padding:10px 0 10px 15px;
  border-bottom:1px solid black;
}
  li.has-child:after {
    display:inline-block;
    content:">";
    float:right;
    margin-right:15px;
  }
li > ul {
  display:block;
  left:200%;
  top:0;
}
li > ul > li {
  display:none;
}

Test 1

Test 1 sub-menu

Test 1 sub-sub-menu

Test 1 sub-menu a

Test 2

Test 2 sub-menu

Test 2 sub-menu a

Test 2 sub-sub-menu

Test 3

Test 3 sub-menu

Test 3 sub-menu a

Test 3 sub-sub-menu

This code is working as intended for the first/second level of items, but once you try to click through to the 3rd level(ie "Test 1 sub-menu") it gets messed up. I realize now that it probably would have been better to use divs for this rather than uls, but can anyone suggest how to get this working without modifying the HTML structure? Open to completely changing the jQuery/CSS if there's a better way to accomplish this functionality.
Answer:
This code is working as intended for the first/second level of items,
  but once you try to click through to the 3rd level(ie "Test 1
  sub-menu") it gets messed up.

That is because, you are shifting the ul by a constant 200%, while the child ul gets shifted by a constant +/-100%. At the same time you reset the main ul at 0. Apart from this when you show the menu using display block, you do not hide those back. While this works for the first-level, it breaks apart from second-level onward.

I realize now that it probably would have been better to use divs for
  this rather than uls

Yes, you would probably be better off with divs because it would be easier for you to handle those as against the hierarchical uls. But then, ul would be more semantic for a hierarchical structure.
If you do not want to change the HTML structure, then the easiest and best bet for you would be to specify the level each sub-menu is in. This can be done by simply adding a data- attribute on each li that has further sub-items and you can get rid of the .has-child class. Once you have the levels defined in the data- attributes, you can use those to shift each level by a corresponding factor.
Below is a crude demo. Please note that although you've tagged this with jQuery, I created this demo in plain old vanila JavaScript because that is easier and faster for me. You may convert this to jQuery if you wish, but otherwise this should work as-is without any problems.
Demo Fiddle: https://jsfiddle.net/abhitalks/euLzo2dg/
Demo Snippet:

// keep things outside the global scope
(function (window, document) {
  var attachTo = document.getElementsByClassName('list-container')[0];
  prepareNav(attachTo); // attach nav to the div

  function prepareNav(nav) {
    // prepare nav by creating back links, setting styles, and click handler
    var
      navBar = nav.firstElementChild,
      navElems = nav.querySelectorAll('li[data-level] > ul')
    ;
    for (i=0; i < navElems.length; i++) {
      var backLink = document.createElement('li');
      backLink.className = 'back';
      backLink.textContent = '\u3008' + ' Back';
      navElems[i].insertBefore(backLink, navElems[i].firstElementChild);
    }
    navBar.style.left = '0%';
    nav.addEventListener('click', function(e) {
      startNav(e, navBar, navElems);
    }, false);
  }

  function startNav(e, navBar, navElems) {
    // click handler
    if (e.target.dataset && e.target.dataset.level) {
      // move main ul by negative multiples of level
      navBar.style.left = -(e.target.dataset.level * 100) + '%';
      // reset all menus by hiding those
      [].forEach.call(navElems, function(ne) { ne.classList.remove('show'); });
      // show the parent menu
      e.target.parentNode.classList.add('show');
      // show the current menu
      e.target.firstElementChild.classList.add('show');
    }
    if (e.target.className === 'back') {
      // move back the main ul by 100 (not to 100)
      var leftPos = parseInt(navBar.style.left);
      navBar.style.left = (leftPos + 100) + '%';
    }
  }

})(window, document);
* { box-sizing: border-box; margin: 0; padding: 0; font-family: sans-serif; }
html, body { height:100%; }
.list-container {
  overflow: hidden; position: relative;
  width: 100%; min-height: 128px;
}
.list-container ul {
  width: 100%; background-color: #eee;
  list-style-type: none;
  position: absolute; left: 0%; top: 0%;
  transition: all .5s ease;
}
.list-container li {
  padding: 10px 0 10px 15px;
  cursor: pointer; border: 1px solid #aaa;
}
.list-container li:first-child { border-bottom: none; }
.list-container li:last-child { border-top: none; }
.list-container li.back + li:last-child { border-top: 1px solid #aaa;  }
.list-container li[data-level]::after {
  display: inline-block; content: '\003009';
  float: right; margin-right: 15px;
}
.list-container li[data-level]:hover,
.list-container li.back:hover { background-color: #ddd; }
.list-container li[data-level] > ul { left: 100%; top: 0; display: none; }
.list-container li[data-level] > ul.show { display: block; }

Test 1

Test 1 sub-menu

Test 1 sub-sub-menu

Test 1 sub-menu a

Test 2

Test 2 sub-menu

Test 2 sub-menu a

Test 2 sub-sub-menu

Test 3

Test 3 sub-menu

Test 3 sub-menu a

Test 3 sub-sub-menu

Comment: This is wonderful, thank you for the detailed explanation, very helpful!

100% width sliding multi-level ULs