HTTP 409 Conflict on POST request

Question: I am new to Web Development so please don't judge me here:
So, I am building a website where when I am sending a POST request, I am receiving an 409 error. Below is the code:
//Server side:
(index.js)
...
app.use("/jobs", jobRoutes);
...

(models/Job.js)
import mongoose from "mongoose";

const jobSchema = new mongoose.Schema(
  {
    clientId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Client',
      required: true
    },
    title: {
      type: String,
      required: true,
      min: 5,
    },
    categoryId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Category',
      required: true
    },
    description: {
      type: String,
      required: true,
      min: 5,
    },
  },
  { timestamps: true }
);

const Job = mongoose.model("Job", jobSchema);

export default Job;

(controllers/jobs.js)
import Job from "../models/Job.js";

/* CREATE */
export const postJob = async (req, res) => {
  try {
    const { clientId, title, categoryId, description } = req.body;
    const newJob = new Job({
      clientId,
      title,
      categoryId,
      description,
    });
    await newJob.save();

    const jobs = await Job.find();
    res.status(201).json(jobs);
  } catch (err) {
    res.status(409).json({ message: err.message });
  }
};

/* READ */
export const getJobs = async (req, res) => {
  try {
    const jobs = await Job.find();
    res.status(200).json(jobs);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};

(routes/jobs.js)
import express from "express";
import { postJob, getJobs } from "../controllers/jobs.js";
import { verifyToken } from "../middleware/auth.js";

const router = express.Router();

/* CREATE */
router.post("/", verifyToken, postJob);

/* READ */
router.get("/", verifyToken, getJobs);

export default router;

//Client Side:
(components/JobsWidget.jsx)
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setJobs, setCategories } from "../state";
import JobWidget from "./JobWidget";

const JobsWidget = () => {
  const dispatch = useDispatch();
  const { users, jobs, categories, token, userMode } = useSelector(
    (state) => state
  );

  const getJobs = async () => {
    const response = await fetch("http://localhost:3001/jobs", {
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    });
    const data = await response.json();
    dispatch(setJobs({ jobs: data }));
  };

  const getCategories = async () => {
    const response = await fetch("http://localhost:3001/categories", {
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    });
    const data = await response.json();
    dispatch(setCategories({ categories: data }));
  };

  useEffect(() => {
    if (categories.length < 1) getCategories();
    getJobs();
  }, [userMode]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      {jobs.length > 0 ? (
        jobs.map(
          ({ _id, clientId, title, categoryId, description, createdAt }) => {
            const user = users.find((usr) => usr._id === clientId);
            const category = categories.find((cat) => cat._id === categoryId);
            let date = new Date(createdAt);
            date = date.toLocaleDateString();

            return (
              <JobWidget
                key={_id}
                jobId={_id}
                title={title}
                category={category.title}
                description={description}
                clientId={user._id}
                clientPicture={user.picturePath}
                clientName={user.fullName}
                date={date}
              />
            );
          }
        )
      ) : (

          No jobs to show

      )}
    </>
  );
};

export default JobsWidget;

(components/PostJobWidget.jsx)
import {
  Box,
  Modal,
  Typography,
  FormControl,
  InputLabel,
  TextField,
  Select,
  MenuItem,
  useTheme,
  Button,
  useMediaQuery,
} from "@mui/material";
import FlexBetween from "./FlexBetween";
import WidgetWrapper from "./WidgetWrapper";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Formik } from "formik";
import * as yup from "yup";
import { setJobs } from "../state";

const postJobSchema = yup.object().shape({
  title: yup.string().required("required"),
  description: yup.string().required("required"),
});

const initialValuesPostJob = {
  title: "",
  description: "",
};

const PostJobWidget = () => {
  const dispatch = useDispatch();
  const [sort, setSort] = useState("");
  const [filter, setFilter] = useState("");
  const [open, setOpen] = useState(false);
  const [category, setCategory] = useState("");
  const { palette } = useTheme();
  const { _id } = useSelector((state) => state.user);
  const token = useSelector((state) => state.token);
  const userMode = useSelector((state) => state.userMode);
  const categories = useSelector((state) => state.categories);
  const isNonMobileScreens = useMediaQuery("(min-width: 1000px)");

  const handleOpen = () => setOpen(true);

  const handleClose = () => {
    setCategory("");
    setOpen(false);
  };

  const handleSort = (event) => {
    setSort(event.target.value);
  };

  const handleFilter = (event) => {
    setFilter(event.target.value);
  };

  const handleCategory = (event) => {
    setCategory(event.target.value);
  };

  const postJob = async (values) => {
    const { title, description } = values;
    const formData = new FormData();
    formData.append("clientId", _id);
    formData.append("title", title);
    formData.append("categoryId", category);
    formData.append("description", description);

    const response = await fetch(`http://localhost:3001/jobs`, {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
      body: formData,
    });

    const jobs = await response.json();
    dispatch(setJobs({ jobs }));
    handleClose();
  };

  useEffect(() => {}, [userMode]);

  return (
    <WidgetWrapper>
      <FlexBetween gap={"1rem"}>
        <FormControl sx={{ minWidth: 80, width: "20%" }}>
          <InputLabel id="sort-label">Sort</InputLabel>
          <Select
            labelId="sort-label"
            id="sort-select"
            value={sort}
            label="Sort"
            onChange={handleSort}
          >
            <MenuItem value={10}>Date</MenuItem>
            <MenuItem value={20}>Job Status</MenuItem>
          </Select>
        </FormControl>
        <FormControl sx={{ minWidth: 100, width: "30%" }}>
          <InputLabel id="filter-label">Filter</InputLabel>
          <Select
            labelId="filter-label"
            id="filter-select"
            value={filter}
            label="Filter"
            onChange={handleFilter}
          >
            {categories.map((category) => (
              <MenuItem key={category._id} value={category._id}>
                {category.title}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        {userMode === "client" && (
          <>
            <Button
              onClick={handleOpen}
              sx={{
                color: palette.background.alt,
                backgroundColor: palette.primary.main,
                borderRadius: "2rem",
                width: "6rem",
                height: "3rem",
                "&:hover": {
                  color: palette.primary.main,
                },
              }}
            >
              POST JOB
            </Button>
            <Modal open={open} onClose={handleClose}>
              <Box
                sx={{
                  position: "absolute",
                  top: "50%",
                  left: "50%",
                  transform: "translate(-50%, -50%)",
                  width: isNonMobileScreens ? "24rem" : "20rem",
                  bgcolor: "white",
                  border: "2px solid #000",
                  borderRadius: "1rem",
                  boxShadow: 24,
                  p: 4,
                }}
              >
                <Typography
                  fontSize={"1rem"}
                  fontWeight={"600"}
                  marginBottom={"1rem"}
                  textAlign={"center"}
                >
                  Post Job
                </Typography>
                <Formik
                  onSubmit={postJob}
                  initialValues={initialValuesPostJob}
                  validationSchema={postJobSchema}
                >
                  {({
                    values,
                    errors,
                    touched,
                    handleBlur,
                    handleChange,
                    handleSubmit,
                  }) => (
                    <form onSubmit={handleSubmit}>
                      <Box
                        display="grid"
                        gap="20px"
                        gridTemplateColumns="repeat(4, minmax(0, 1fr))"
                      >
                        <TextField
                          label="Title"
                          onBlur={handleBlur}
                          onChange={handleChange}
                          value={values.title}
                          name="title"
                          error={
                            Boolean(touched.title) && Boolean(errors.title)
                          }
                          helperText={touched.title && errors.title}
                          sx={{ gridColumn: "span 4" }}
                        />
                        <FormControl sx={{ gridColumn: "span 4" }}>
                          <InputLabel id="category-label">Category</InputLabel>
                          <Select
                            labelId="category-label"
                            id="category-select"
                            value={category}
                            label="Category"
                            onChange={handleCategory}
                            required
                          >
                            {categories.map((category) => (
                              <MenuItem key={category._id} value={category._id}>
                                {category.title}
                              </MenuItem>
                            ))}
                          </Select>
                        </FormControl>
                        <TextField
                          label="Description"
                          multiline
                          maxRows={4}
                          onBlur={handleBlur}
                          onChange={handleChange}
                          value={values.description}
                          name="description"
                          error={
                            Boolean(touched.description) &&
                            Boolean(errors.description)
                          }
                          helperText={touched.description && errors.description}
                          sx={{ gridColumn: "span 4" }}
                        />
                      </Box>

                      <Box>
                        <Button
                          fullWidth
                          type="submit"
                          sx={{
                            m: "2rem 0",
                            p: "1rem",
                            backgroundColor: palette.primary.main,
                            color: palette.background.alt,
                            "&:hover": { color: palette.primary.main },
                          }}
                          variant="outlined"
                        >
                          POST NOW
                        </Button>
                      </Box>
                    </form>
                  )}
                </Formik>
              </Box>
            </Modal>
          </>
        )}
      </FlexBetween>
    </WidgetWrapper>
  );
};

export default PostJobWidget;

I don't understand where I am making a mistake, can someone please give me any clue where or what I might be doing wrong? This is the error that I am getting:
Error: Job validation failed: clientId: Path `clientId` is required., title: Path `title` is required., categoryId: Path `categoryId` is required., description: Path `description` is required.
    at ValidationError.inspect (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\error\validation.js:50:26)
    at formatValue (node:internal/util/inspect:806:19)
    at inspect (node:internal/util/inspect:365:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2273:40)
    at formatWithOptions (node:internal/util/inspect:2135:10)
    at console.value (node:internal/console/constructor:340:14)
    at console.log (node:internal/console/constructor:377:61)
    at postJob (file:///D:/SIBAU/BSCS-VIII/Project-II/nasrp/server/controllers/jobs.js:18:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errors: {
    clientId: ValidatorError: Path `clientId` is required.
        at validate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaType.doValidate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1330:7)
        at D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\document.js:2905:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'clientId',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    title: ValidatorError: Path `title` is required.
        at validate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaType.doValidate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1330:7)
        at D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\document.js:2905:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'title',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    categoryId: ValidatorError: Path `categoryId` is required.
        at validate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaType.doValidate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1330:7)
        at D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\document.js:2905:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'categoryId',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    description: ValidatorError: Path `description` is required.
        at validate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaType.doValidate (D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\schematype.js:1330:7)
        at D:\SIBAU\BSCS-VIII\Project-II\nasrp\server\node_modules\mongoose\lib\document.js:2905:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'required',
      path: 'description',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Job validation failed'
}

Comment: Could you share the error message that is being printed? Adding a console.log in the catch of the post job function in the jobs.js file inside the controllers folder might help you understand the error. Please make sure to share the error printed so that I can help you!
Comment: This is the error:
Error: Job validation failed: clientId: Path `clientId` is required., title: Path `title` is required., categoryId: Path `categoryId` is required., description: Path `description` is required.
Comment: Where are you exactly calling the POST api in the client side? It seems like none of the required fields are being sent to the backend.
Comment: Are you using JSON as the way to send data in your server?
Comment: I am sending key-value pairs using FormData(). You can see this in PostJobWidget.js
Comment: Try checking out this https://stackoverflow.com/questions/76158415/when-attempting-to-formdata-to-an-express-js-the-server-is-not-recognizing-multi
Comment: Thanks but this doesn't help
Answer: Thank you to everyone who helped. I solved the issue as follows:
(components/PostJobWidget.jsx)
  const postJob = async (values) => {
    const { title, description } = values;

    const response = await fetch(`http://localhost:3001/jobs`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        clientId: _id,
        title: title,
        categoryId: category,
        description: description,
      }),
    });

    const jobs = await response.json();
    dispatch(setJobs({ jobs }));
    handleClose();
  };

Answer: Try sending the object as JSON to the API.

const response = await fetch(`http://localhost:3001/jobs`, {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
      body: {clientId: _id, title: title, categoryId: category, description: description},
    });

Comment: didn't work :(
Still same issue
Comment: Can you print the body that you are sending in the client and check it's contents to see if it is a backend issue?
Comment: So, if I am doing this:
if (Object.keys(req.body).length === 0) {
      return res.status(400).json({ message: "No data provided" });
    }

It tells data is not being sent to the server? So where might be the issue?
Comment: Can you print the contents of the form data that you are sending in the body from the client side and share it? Also try to give the link I added as a comment above a look
Comment: If I print formData after appending the values, it prints an empty object but when I print the values individually they are there.
Comment: Did you try using the get function? Like this: formData.get('clientId')
Comment: Can you also try to specify the content type of the data in the body in the headers. By that I mean that you should add another header called 'Content-Type' and set it to be "multipart/form-data".
Comment: formData.get() do give me values.
Comment: "Content-Type": "multipart/form-data", is also not working :(

HTTP 409 Conflict on POST request


asterisk playback sound when someone answers

Question: This is an asterisk CLI question. I want to be able to play a sound byte with the asterisk "originate" command, but only when someone answers, like:
channel originate *insertoutboundlinehere* application Playback *yoursoundhere*

The problem is that I used to be able to do this in a way that the sound would NOT play until someone picked up, WITHOUT a call file involved - just the Playback command on the originate function. Now, it seems my asterisk CLI command history is wiped, so I can't find the command. Has anyone done this?
Answer: From this source and if I understand correctly your question:

https://www.voip-info.org/wiki/view/Asterisk+cli+originate

If you create an Extension, then you can call your own extension, then use

originate Zap/1/123456 extension

In your extension : wait for user Answer and then call your Playback file just after the Answer function (see www.voip-info.org bottom page example).
extensions.conf
[greeting]
exten => 400,1,Answer
exten => n,Playback....
...
>> originate Zap/1/123456 greeting


Statistical test for a series of data over time

Question: I have a set of data that looks at the number of "hits" a specific program makes over the course of time.  The data goes back to September 2010, and includes data up to March 2011, so the data points are monthly.  What I want to see if the most recent data (March 2011) shows a statistically significant decrease in the number of "hits" this program makes.
I have a feeling there might not be a test that would fit this perfectly, as the data is a bit limited.  I can also pull data weekly for the same time frame, which would build 31 points (at which point I would still want to look at the most recent unit for comparison).  There hasn't been a population mean built for this data as of yet, as the data can only be pulled as far back as Jan 2010 (but the data from then is not reliable).
For reference, just 9 weeks data (as i pulled that first) reveals
mean= 1013.67
n=9
st.dev= 53.57
Most recent week= 991
Just eyeballing it does not appear statistically significant as a drop in "hits", however I'll need to perform this analysis every few weeks, and wondering if there's something reliable I can use.  Thanks ahead of time for the input!
Comment: You probably know much more about the mechanisms generating the "number of hits" than written here – that mechanism may be a key point in building the right statistical model. Times series often show autocorrelation or periodicities, modelling should include these if they are present. "Significant decrease" may then be defined as deviation from what was predicted, but it's important to have a good prediction model.
Comment: @Peter why don't you post both the 9 months and the 31 weekly values so we can both "eyeball" and automatically test for exceptional activity.
Answer: As GaBorgulya pointed out one needs to have a model to detect the potential anomaly. This model needs to generate a "white noise" error series or be sufficient to separate signal and noise. With this model in hand based upon older data one could then compare the new value with the prediction interval. This is the classical , albeit limited approach called an "out off model test". A more comprehensive approach is to to include a "pulse variable" i.e. zeros and a 1 for the new data point and to estimate coefficients for the augmented model using all of the data. The probability of observing what you observed before you observed it ( i.e. the new value" ) is then available from the "t value" of the "pulse variable" in this augmented model. In general this approach is referred to as Intervention Detection which scans ( data mines ) the time periods to detect the points where Pulses , Level Shifts , Seasonal Pulses and Local Time Trends have been significantly evidented. In your case you are not searching for the null hypothesis but rather simply is there a potential change point at the last observation i.e. the last "1" period. Your question also suggests solutions that we have seen which detect a significant change in the mean of the last K periods alerting the analyst to the innovation.
Answer: With less than a year of data, it'll be impossible to account for any kind of yearly seasonal effect. (For example, if your data was shopping-related, you would have things like annual holidays, perhaps two sales a year, etc.)
You might want to look at Statistical Process Control tools like http://en.wikipedia.org/wiki/Control_chart perhaps?


PostgreSQL lots of Tables

Question: we am at a point where I have more than a thousand Tables in our PostgreSQL database server. I remember reading that there was a way to speed up the database once it reached more than a thousand Tables, but I cannot seem to find any mention of this on the Web with Google. Any help would be nice.
Thanks
Answer: I don't recall anything specific to a table count that is greater than 1000, but you may have been thinking of using tablespaces to spread db objects/tables over different volumes to enhance performance? (i.e. tables that more write heavy on a different volume to tables that are read heavy, or splitting different sets of heavy use tables over volumes on different channels)
tablespaces are covered here in the postgres docs.
having said this, unless there are specific performance issues you need to address, I wouldn't make the changes arbitrarily...
Answer: PostgreSQL creates a file in the filesystem for every table; depending on your underlying filesystem, you'll eventually run into performance problems when any process (PostgreSQL included) reads the directory metadata. To alleviate this, you'll want to create a number of different tablespaces and place different tables in different tablespaces in order to prevent having thousands of files in the same directory.
It might help to read a bit about the CREATE TABLESPACE and ALTER TABLE commands to move tables into a given tablespace.
Answer: You may be referring specifically to the advice around tuning max_fsm_relations when you have lots of tables. But that requirement was removed in 8.4, and it's now automatically tuned for you.

PostgreSQL lots of Tables


Como pegar os dados selecionados de um checkbox pelo laravel

Question: Olá, tudo bem?
Tenho o seguinte formulario:

    Opções de Estoque
    @foreach($stockOptions as $stockOption)

      <input class="form-check-input" type="checkbox" name="stockOption" value="{{$stockOption->stock_option_id}}">
      {{$stockOption->name}}
      <input type="text" class="form-control" name="stockOptionQuantity" placeholder="Quantidade">

    @endforeach

Isso está dentro de um cadastro do produto onde estou tentando cadastrar as opções de estoque, ele selecionaria as opção de estoque e colocaria quanto é necessário daquela opção para fazer o produto.
No momento não estou sabendo como pegar apenas os "Inputs" selecionados e a quantidade deles para ser pegado no create do laravel.
Answer: Na função pra onde a rota dessa requisição está sendo direcionada, certamente store, você deve pegar os dados da variável $request, podendo atribuir os valores a uma outra variável:
$inputs = $request->all();
ou pegando um campo em específico:
$stockOption = $request->input('stockOption');
Para testar o que está atribuído a uma variável você pode utilizar a função dd():
dd($stockOption);
Você pode encontrar mais informações sobre requisições na documentação do Laravel, segue o link:
https://laravel.com/docs/7.x/requests
Comment: Oh, muito obrigado, deu certo desse jeito. Uma coisa que aprendi no emprego que funfou é colocar o nome dos inputs como "stockAction[]" ae quando pego os valores eles estão dentro de um Array na controller, meio gambis mas funfa


Basic confusion about Restricted Boltzmann Machines (RBM)

Question: As I understand it, the standard restricted Boltzmann machine (RBM) exhibits binary stochastic visible and hidden units. The joint probability of the binary and visible units is given by the Boltzmann factor familiar from statistical physics:
$$ P(v,h) = \frac{e^{-E(v,h)}}{Z} $$
where the energy and partition function are given by
$$ E(v,h) = -(a_i v_i + b_j h_j + v_i W_{ij} h_j) $$
$$ Z = \sum_{\text{configurations}} e^{-E(v,h)} $$
A particular configuration consists of two sets of binary vectors, $(v,h)$, and the sum over all configurations then corresponds to summing over all possible such pairs.
There is another type of RBM, known as a Gaussian RBM, which makes use of continuous units, so that $(v,h)$ are real valued. Clearly the sum over configurations must now be modified.
Consider now the MNIST data set, where the visible units correspond to integer-valued pixel values ranging from 0 to 255. As is, these visible units do not work with either RBM algorithm. One solution would be to expand the 256-valued discrete vectors into larger binary vectors, and to then use the first RBM. Another solution would be to divide the pixels by 255, so that they then lie within the unit interval. They could then be taken to be real, and the Gaussian RBM applied.
My confusion is that I have found a few cases, such as
http://www.pyimagesearch.com/2014/06/23/applying-deep-learning-rbm-mnist-using-python/
https://gist.github.com/dwf/359323
where the data was rescaled to lie within [0,1] AND the RBM was taken to have stochastic binary units. Could someone please explain to me why this is acceptable?
Answer: Have a look at section $\textbf{13.2}$ of Hinton's guide to train an RBM, at equation $\textbf{17}$ or a similar and better description in Salakhutdinov's Learning Deep Generative Models, section $\textbf{2.2}$.
http://www.cs.toronto.edu/~hinton/absps/guideTR.pdf
http://www.cs.cmu.edu/~rsalakhu/papers/annrev.pdf
The Gaussian RBM assumes you have real-valued visible units between interval 0-1 (as is with normalized MNIST) and some variance $\textbf{$\sigma^2$}$. In reality you would have to infer $\textbf{$\sigma^2$}$, but for all purposes, this is chosen prior to training your model, in some cases, variance 0.01.
The tutorial you mentioned uses the scikit learn package BernoulliRBM, which inherently accepts floats as input and sets the variance to 0.01(see the $\textbf{fit}$ function on github). So what they do is allowed and ok but it's done behind the scenes:) Hope this helps!
Patric
Answer: Yeah there are simple extensions to real numbers, but it's kind of an easy trick to scale your data between 0 and 1 (like a probability). Then you can learn using binary stochastic units.
Scaling your data between 0 and 1 is one of many pre-data-filtering tricks to make learning faster - the ultimate goal. Whitening pixels to greyscale is also common. You can convert grayscale to a 0 to 1 value without losing information.
Comment: Treat scaled value as input PROBABILITIES not STATES. You have to be careful about propagating to layers as states, since this is an important regularizing property, but for the last layer (and if you are scaling and using input probabilities), I think it is ok to keep at probabilities...
Comment: Thanks for your answer but I am confused by it. The same basic tension I wrote about in my question exists in your proposal to "scale your data between 0 and 1 (like a probability)", since now the units are real valued (real and within the unit interval) and yet you are using a model that assumes binary values.

Is the resolution of the puzzle that I should not treat the scaled data as a state of the RBM (which makes no sense for binary stochastic RBMs), but as a probability vector for the original state?
Answer: By definition, an RBM with binary visible units can only model binary observations. So in the case of MNIST with integer pixel values in [0, 255], some sort of thresholding can be done to binarize the input. Or, like you suggested, rescale the pixel values to real numbers and use Gaussian visible units to model them. Another alternative is to treat pixel values in [0,1] as probabilities of a binary event and use binomial units as in Hinton (2006) (A fast learning algorithm for deep belief nets).
The author of the pyimagesearch post actually clarified this point in a comment:

I think you might have been confused by my original comment. If assume
  the MNIST digits are already thresholded, then we have two pixels
  values: 255 (white, the foreground) and 0 (black, the background). If
  you divide all pixel values by 255, then they are all in the range [0,
  1].


resizing vector of pointers segfaults

Question: I keep hitting this weird std::vector behavior which I can't make any sense of.
Roughly, the code looks like
#include <iostream>
#include <vector>

class MyClass{
public:
  MyClass():
    v_(),
    w_(init_w())
  {};

  ~MyClass()
  {};

  std::vector<int*> init_w()
  {
    v_.resize(4096);
    return v_;
  };
private:
  std::vector<int*> w_;
  std::vector<int*> v_;
};

int main()
{
  MyClass a;
}

Running this gives me a bad segfault at the resize. If a lower value is chosen for the resize instead, the code might not segfault at all.
Update:
The problem is that, contrary to what the initializer list indicates, w_ get initialized before v_. Hence, in init_w(), v_ state is undefined.
Reverting the order of v_ and w_ in the declarations fixes the problem.
Comment: Please give a minimal, compiling example that displays the problem.
Comment: @chris It shouldn't matter, since the vector element type is a pointer.
Comment: An answer to [this similar question](http://stackoverflow.com/questions/2612447/pinpointing-conditional-jump-or-move-depends-on-uninitialized-values-valgrin) might help you pinpoint the source of the segfault.
Comment: @rhalbersma I've struggled several hours to break down the code into something small and easy that fails, but didn't succeed. I'm aware of the fact that this makes it hard to find the error.
Comment: @Nico: Not hard, impossible. -1 from me I'm afraid.
Comment: @Nico: Your sample code (plus a `typedef int mytype;`, to make it compile) runs fine for me with g++ 4.2.1; valgrind didn't find any issues either. I think the relevant code is missing.
Comment: @chris I've got no idea. `mytype` is a type from a larger library I have no insight in. Might there be a problem, though?
Comment: @Nico this makes it impossible to find the error.
Comment: @Nico: You could test whether `mytype` triggers the issue by temporarily replacing it with, say, `int`. Furthermore, looking at line 591 in your `stl_vector.h` might give some hint as to what's triggering the crash.
Comment: @cdhowie, My mind jumbled it around a bit. You're right.
Comment: Debugging can be hard and frustrating. Make sure you have good tools: http://stackoverflow.com/questions/426569/why-is-debugging-better-in-an-ide
Comment: Replacing `mytype` with `char` or any other POD, this compiles and runs for me.
Comment: I updated the question and added the solution. Thanks again everyone for helping me out!
Answer:
The problem is that, contrary to what the initializer list indicates, w_ get initialized before v_

You inferred that to be the case, but in reality it is not.  The order of the list is not relevant; the order of declaration in the class is.  So, your initialization list should mimic the declaring order if you want to see how the members are actually being initialized.
My question to you is; why are you using a vector of pointers to begin with?  Do you realize that you need to delete every element in the list before your object goes out of scope or suffer a memory leak?
Comment: @Nico: Ah, ok, just be careful with that then (that stinks, but oh well, not much you can do about it.)
Comment: Indeed, it's the order of declaration. Some compilers even warn if the items are declared in another order that they are initialized. The reason why I'm working with vectors of pointers is that the library I use requires that format. In particular, the vector filling routines I call have `std::vector` as argument.
Comment: how does this answer `answers` the question ?
Comment: @JayD: The initialization order is the problem.  `init_w()` calls `_v.resize()` before `_v` is initialized.

resizing vector of pointers segfaults


Decomposition of products of monomial symmetric polynomials into sums of them

Question: I'm trying to make sense of the answer given in: this question
I am stuck at the phrase 'where the partitions $\gamma$ result from adding, respectively, from $\alpha$ all distinct partitions obtained by permuting in all possible ways the parts of $\beta$.'
If I permute (in all possible ways) the parts of a partition, then I obtain a set of integers that is not weakly decreasing anymore; adding that part-by-part to a proper partition does again not conserve the property 'weakly decreasing'.
Q: how should I interpret this?
Yet, there is a tempting structure in this product decomposition that I would like to understand.
Example: $m[1,1]^2= m[2,2]+2 m[2,1,1]+6 m[1,1,1,1]$ (* using 4 variables *)
added 19/05/2013 15:42 CET: @MarcVanLeeuwen: thanks Marc, I got it now. The 'Dim' function was new to me, it turns out to be just the multinomial of the contents (of the zero-padded partitions).
Comment: You should "ping" the user who wrote that answer by writing a comment to the answer pointing to this question. Meanwhile, the most probable interpretation is that "respectively, from" should be "to" (so only addition occurs) and that after the addition you reorder the parts decreasingly.
Comment: Oops, I forgot that you haven't got the reputation require to comment under other people's questions and answers. You can comment to your own question though, I'll do the pinging here to show you how.
Comment: If you are interested, I updated my post with a full reference...
Comment: Your description of Dim seems wrong, at least if you talk about multinomial coefficients. Instead it is a product of factorials, for the multiplicities of repeated parts in the partition; this includes a factorial for the parts $0$ that were added to get the required number of parts (matching the number of indeterminates), and in particular the number depends on the number of indeterminates. See my answer. For instance for $[4,2,2,1,1,1]$ and $11$ indeterminates the Dim number is $1!0!2!3!5!$.
Answer: It is natural to try to manipulate symmetric polynomials as one does polynomials, representing them as a sum of monomials, and to take advantage of the symmetry by representing a whole orbit of monomials only once, as a minimal symmetric polynomial$~m_\lambda$. Also one can now leave the number of indeterminates unspecified, and thus effectively manipulate symmetric functions. This being said, I should warn that the algorithms resulting form this head-on approach to symmetric functions are neither particularly beautiful nor efficient; representation on other bases with more pleasant theoretical properties seems preferable.
Anyway, the best way to understand the multiplication of $m_\mu$ and $m_\nu$ is to try deriving the rule for the coefficients yourself, since only this gives you the right feeling for what kind of complications are needed; reading a ready-made description of the multiplication risks misinterpreting the subtle notions involved. Here I will try to deduce the rule. The first thing to realise it that if $l(\lambda)$ denotes the number of nonzero parts of$~\lambda$, then in the product of symmetric functions $m_\mu m_\nu$ one get terms $m_\lambda$ with $l(\lambda)$ going up to $l(\mu)+l(\nu)$, so one should consider at least that number of indeterminates to faithfully represent that product as a polynomial. If you are only interested in multipliying symmetric polynomials in a fixed number of indeterminates one can of course use that number, which amounts to ignoring the $m_\lambda$ where $l(\lambda)$ exceeds that number.
If $n$ is the number of indeterminates used, it is useful to consider scalar multiples of the $m_\lambda$ obtained by a sum over the whole group $S_n$, namely $$M_\lambda(n)=c(\lambda,n)m_\lambda=\sum_{\pi\in S_n}X^{\pi(\lambda)},$$ where $\def\N{\mathbf N}\pi(\lambda)\in\N^n$ is the result of permuting the parts of$~\lambda$ (including $n-l(\lambda)$ parts zero) by $\pi$; the number $c(\lambda,n)$ is the size of the stabiliser of $\lambda$ in this action, the product of the factorials of the multiplicities of the distinct parts of $\lambda$, including $(n-l(\lambda))!$ for the parts equal to $0$ involved. Now clearly
$$
  M_\mu(n)M_\nu(n)=\sum_{\pi,\sigma\in S_n}X^{\pi(\mu)+\sigma(\nu)}
 =\sum_\lambda C^\lambda_{\mu,\nu}M_\lambda(n),
$$
and once these coefficients $C^\lambda_{\mu,\nu}$ are determined one deduces that
$$
  m_\mu m_\nu=\sum_\lambda c^\lambda_{\mu,\nu}m_\lambda,\qquad
 \text{where }
  c^\lambda_{\mu,\nu}=\frac{c(\lambda,n)}{c(\mu,n)c(\nu,n)}C^\lambda_{\mu,\nu}.
$$
The defining equation for the coefficients $C^\lambda_{\mu,\nu}$ is
$$
  \sum_\lambda C^\lambda_{\mu,\nu}\sum_{\pi\in S_n}X^{\pi(\lambda)}
 =\sum_{\pi,\sigma\in S_n}X^{\pi(\mu)+\sigma(\nu)}
 =\sum_{\pi,\sigma\in S_n}X^{\pi(\mu+\pi^{-1}(\sigma(\nu)))},
$$
which by symmetry can be simplified to
$$
  \sum_\lambda C^\lambda_{\mu,\nu}X^\lambda
 =\sum_{\rho\in S_n}X^{(\mu+\rho(\nu))^+},
$$
where for a composition $\alpha$ the notation $\alpha^+$ means that partition obtained by sorting its parts decreasingly.
Now we can simplify this further by factoring the stabiliser subgroup of $\nu$, to
$$
  \sum_\lambda \frac{C^\lambda_{\mu,\nu}}{c(\nu,n)}X^\lambda
 =\sum_{\alpha\in S_n(\nu)}X^{(\mu+\alpha)^+},
$$
where $S_n(\nu)$ is the permutation orbit, without repetitions. In the end, the recipe is
$$
  c^\lambda_{\mu,\nu}=\frac{c(\lambda,n)}{c(\mu,n)}c'(\lambda,\mu,\nu)
\quad\text{where}\quad
  \sum_{\alpha\in S_n(\nu)}X^{(\mu+\alpha)^+}=\sum_\lambda c'(\lambda,\mu,\nu)X^\lambda;
$$
the right hand side asks for adding all distinct permutations of $\nu$ (which was padded with zero) to $\mu$, sorting the results decreasingly and grouping by equal outcome$~\lambda$.


Images do not load at first time in my swf but the second time they are shown when the browser refresh??

Question: i have written classes in as3...  my swf works fine locally but at live link, images do not load or shown first time but when you refresh the browser again they are loaded and shown.. i know they comes in cache but what is happening first time..
you can clear your browser cache and check the problem happens each time when it is not in cache...
all images are less than 1 mb..
here is the link
http://web.s4spk.com/irfan/loadtest1/project.html
Comment: The images seem to load when I click the link.
Answer: Without seeing your code, it's difficult to know what the problem is.
It is likely that you have a race condition where the code you use to display the images is executing before the images have finished loaded. Once the images are in cache, they obviously load a lot quicker.
If you are using a Loader to load the images in, make sure you are handling the Complete event of the loader and taking appropriate actions there to ready the images for display.
Comment: thanks Dank... u showed me the right way, the code was in race condition, i have used gotoAndPlay(2) that runs before loading of all images but the second time , images are cached in browser and loads before this statement.. so code works..


Pegar imagens da pasta drawable pelo nome

Question: Gostaria de saber como pegar o id de uma imagem da pasta drawable e usar em um ImageView. Estou tentado fazer isso dentro de uma ListView
String nomeImgFilme = filme.getImagem();
int imgID = convertView.getResources().getIdentifier(nomeImgFilme, "drawable", context.getPackageName());

Estou tentando executar esse código, mas ele dá erro :

"Resources$NotFoundException: Resource ID #0x7f060054".

E se eu colocar a imagem diretamente com "R.drawable.circulo_fogo", também diz que não foi encontrado.
Então, como eu faço pra pegar a id de uma imagem pelo nome dentro de uma ListView?
Answer: Você pode utilizar este código para capturar o id a partir do nome do drawable
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("minha_imagem_1", "drawable",
   context.getPackageName());
imageview.setImageResource(resourceId);

Espero que ajude!


como resolvo erros de acentuação ao enviar uma mensagem do Android para uma API em php

Question: Gente, estou com problemas para realizar o envio de strings com acentuação e de strings com 2 linhas ou mais . Quando envio sem acentuação ou e com apenas uma linha ele aceita normalmente, porem, quando envio com acentuação, ele da erro.
Já utilizei um testador de API (Rest Easy), e quando envio por lá, ele aceita normalmente e não apresenta nenhum erro, mas quando envio pelo Android, da erro...
este é o trecho do código relacionado ao envio..
public void enviaDados() {
    new LongOperation().execute("");
}

private class LongOperation extends AsyncTask<String, Void, String> {

    String msg = mensagem.getText().toString();
    String mail = email.toString();

    ProgressBar carrega = (ProgressBar) findViewById(R.id.carregaMsg);

    @Override
    protected String doInBackground(String... params) {
        try {
            Log.v("GG", "Sending sever 1 - try");
            // start - line is for sever connection/communication
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("http://www.meuSite.com.br/mural/listener.php");

            String json = "{\"usuario\":[{\"enviado\":\"" + "1" + "\",\"email\":\"" + mail.toString() + "\",\"msg\":\"" + msg.toString() + "\",\"a\":\"" + "2" + "\"}]}"; //msg.toString()

            StringEntity entity1 = new StringEntity(json);
            httppost.setEntity(entity1);
            //informa o tipo de arquivo. . .
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-type", "application/json");

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            // end - line is for sever connection/communication
            InputStream is = entity.getContent();
            //_______________________________________________________________________
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            result = sb.toString();
            is.close();
            jsonObject = new JSONObject(result);
            //__________________________________________________________________________

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "
                    + e.toString());

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        carrega.setVisibility(View.INVISIBLE);
        try {
            alerta();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mensagem.setText("");
    }

    @Override
    protected void onPreExecute() {
        carrega.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

Caso alguém saiba me ajudar, ficaria muito grato.
Toda dica é bem vinda, agradeço pela atenção!
abraço!
Comment: Qual enconding (charset) o server tá utilizando? O Rest Easy funciona, pois ele usa o mesmo charset configurado na aplicacao Rest que recebe os dados no servidor. Você precisa configurar o mesmo charset na sua aplicacao Android. Ser for UTF-8, tente fazer: httppost.setHeader("Content-type", "application/json; charset=UTF-8");
Comment: Tche, consegui resolver aqui
utilizei sua dica, mas para ela funcionar, tive que alterar a linha  StringEntity entity1 = new StringEntity(json);

Ela ficou desta forma:

StringEntity entity1 = new StringEntity(json, "utf-8");

isso resolveu os acentos
agora só me falta resolver a quebra de linha
por exemplo, digito uma mensagem, dou enter no telefone e sigo digitando na segunda linha

ele acaba quebrando o json em 2 linhas ao invés de reconhecer um \n por exemplo

agora só vou descobrir como resolver isso hehe

brigadão!
Comment: Está dando qual erro?
Comment: Obrigado pela dica, vou tentar aqui agora, caso consiga ou não, aviso vocês

Abraço!
Comment: Obrigado pela dica, tentei desta forma mas, infelizmente ele ainda não reconhece
quando coloco acentos ou mais de uma linha, ele apresenta o mesmo erro. Caso alguém tenha alguma outra ideia para solucionar esta questão, mande por favor.
Comment: Resolvi quera de linha acrescentando android:singleLine="true" no Script XML do editi text

Valew galera e obrigado pela atenção!
Answer: Tenta colocar o \n seguido da palavra da linha seguinte, sem espaços.
Exemplo:
"Olá!\nTudo bem?


What is the name of this scale?

Question: I was noodling around on a piano (I'm not a real pianist) and I came up with this scale, which I liked:

C-Db-E-F-G-Ab-Bb

What is the name of this scale? Does it have a common name such as we find  with "the Hungarian Minor Scale" or "the Fraigish Scale" etc., or would we just name it based on its characteristics and alterations?
It is actually C Phrygian:

C-Db-Eb-F-G-Ab-Bb

Except it has M3 - E, instead of a m3 - Eb.
Maybe it should be called Phrygian Major?
Answer: It's called phrygian dominant. It's the 5th mode of Harmonic Minor.
Comment: @alephzero - _I don't care what note it happens to start on_ - When the bank counts out your money, do you care which number they start on? If they were counting out 7 $100 bills for you, would you be OK with them starting on 4 instead of 1:  _400... 500...600...700 - **there you are sir - $700**._ ...
Comment: @alephzero - Your money isn't worth much. In spite of your protestations, it is not F harmonic minor: it does not begin with F, has a b2 and **no leading tone**.  _I don't care what note it happens to start on_ - nor do I care what you do or don't care about. :) There's nothing complicated about "phrygian". There **is** something "complicated" about giving a scale the wrong name. _Everything should be made as simple as possible, **but not simpler**_ - Albert Einstein. That means you don't simplify when the simplication leads to error, which is exactly what your "simplification" does.
Comment: Also known as *Phrygian major* and *Spanish Phrygian*. So Stinkfoot was right all along!
Comment: Yes - I realized after I wrote the question that M3 with b7 would make it dominant, not major.
Comment: Yet more "phrygian" complicated names for simple things! It's just *F harmonic minor*, in my money - I don't care what note it happens to start on!!!
Comment: @Tim - I like to be right :) - but  I do think dominant is more correct because of the M3/m7.
Comment: @Tim - I was reading through a list of scales today in Jazzology (good book) and he mentions this scale - calls it phrygian major - no other name. But I still think dominant is better.
Comment: @Stinkfoot - yes, it's more apposite with the *dominant* part, although it still has that M3, without which it wouldn't be major - or dominant.

What is the name of this scale?


if taxonomy is set show code html - wordpress

Question: Hi I have a little problem with php/wordpress and can't find answer.
There is a list and one
 I want to show, when anything in custom taxonomy is set:

Taste: <?php printRecipeTaste($post_ID); ?>

I have some php in another
 which is working like I want but only for meta:
<?php if ( get_post_meta( get_the_ID(), 'iba', true ) ) : ?>
     <img class="iba" src="<?php echo esc_url(home_url('/')); ?>/images/iba.jpg" alt="" />
<?php endif; ?>

I tried with get taxonomy_exists and is_taxonomy but I fail.
Anyone can help? Ty.
Answer: You should be able to use get_the_terms($id, $taxonomy). Returns false if no terms of that taxonomy are attached to the post.
https://codex.wordpress.org/Function_Reference/get_the_terms


How to use a class within itself

Question: I'm very, very new to Python (coming from Java and C++) so this is probably very basic and kinda embarassing:
I'm trying to use an instance of a class inside that class, but my IDE (PyCharm) tells me its an unresolved reference
For exmaple (and this really is just an example so please no "just use some already existing Node class")
class Node(object):
    def addChild(self, node: Node): # the word Node here is where the error happens
        self.children.append(node)

I've tried googling all kinds phrasings and ive sat through several tutorials in the last few hours and I just dont understand what it is I'm doing wrong here or how I can declare the class before I define it. Or is what the IDE suggests, adding an additional "class Node(object): pass" above really the way this is done?
Comment: Or this one: https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class
Comment: In old versions of type-hinting, you would use a string, actually, `"Node"`, however, in more updated python versions, this will not throw an error.
Answer: try in this way:
class Node:
  def __init__(self):
    self.children = []
  def addChild(self, node): # the word Node here is where the error happens
    self.children.append(node)
  def showNode(self):
    print(self.children)

nd = Node()
nd.addChild("oi")
nd.addChild("Tchau")
nd.showNode()

Comment: This doesn't address the type hinting at all.

How to use a class within itself


error for size 2 list in merge K sorted List

Question: I am solving a problem on InterviewBit (Link) : https://www.interviewbit.com/problems/merge-k-sorted-lists/
I have to merge k sorted linked lists and return it as one sorted list.
This is my solution:
<code> * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
bool is(const ListNode& x, const ListNode& y) { return x.val < y.val; }
ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    vector<ListNode> m;
    for(int i=0;i<A.size();i++){
        while(A[i]!=NULL){
            m.push_back(*A[i]);
            A[i]=A[i]->next;
        }
    }
    sort(m.begin(),m.end(),is);
    ListNode* k =&m[0];
    for(int i=0;i<m.size()-1;i++){
        m[i].next=&m[i+1];
    }
    m[m.size()-1].next=NULL;
    return k;

}
</code>
You can copy the code and check with any custom input , it works but returns wrong list when only linked list of size 2 are supplied eg. (1->2) or eg.(1->2 and 3->4) it returns 0->2 and 0->2->3->4 respectively .
(I know this has a bad time complexity )
Comment: Well the algorithm is just wrong. You seem to be assuming that all the lists in `A` have a length of one. However, what's your actual question? There doesn't seem to be one above.
Comment: *It works but returns the wrong list* I think that means it doesn't work. What you need to do is remove the nodes from `A` one at a time (and in the right order) and put them on a new list.
Comment: how I am assuming it ? I tried custom input (1->2->3 , 2->5->6->7, 4->6->9) it returned 1->2->2->3->4->5->6->6->7->9
Comment: OK my apologies, I misread the code.
Comment: What you are basically doing, it combining all the nodes into one list and then sorting it. That's not what you are supposed to be doing. It completely misses the point. And there's still no question.
Comment: I know that it does not take advantage of the already sorted list  thats why I wrote at the last 'I know this has a bad time complexity ' I am more concerned that why does it not give correct result for input size of 2 as stated in the question
Comment: All the lists in `A` are sorted, so the lowest node is is one of the nodes at the head of one of the lists in `A`. Find that node, remove it from `A`, add to your new sorted list. Then repeat. Until all the lists in `A` are empty.
Comment: I know that solution , all I want to know is why is the given algo not correct
Answer: The problem with your code is that the list you are returning consists of pointers to nodes which have been destroyed. So your code has undefined behaviour.
<code>ListNode* Solution::mergeKLists(vector<ListNode*> &A) {
    vector<ListNode> m; // this vector contains the nodes of your merged list
    ...
    ListNode* k = &m[0]; // here you take a pointer to the content of m
    ...
        m[i].next = &m[i+1]; // here you make another pointer to the contents of m
    ...
    return k; // here you return that pointer
} // but here m is destroyed
</code>
So the net result is that you return a pointer to a vector which has been destroyed when the function exits. Any subsequent use of that pointer is undefined behaviour.
Comment: I am not returning pointer to a vector but pointer to a ListNode like a head pointer , it is never destroyed .k stores the address of the 1st node and in the for loop I am updating the next pointer of every node
Comment: The `ListNode` is in a vector `m`, and the vector `m` is local to the function, and you are returning a pointer to `m` contents. But if you don't want to believe me, it's your call.
Comment: That might be the reason then why is it working for all the other cases
Comment: Undefined behaviour (which is what you have) means things are unpredictable.
Comment: I'm not claiming you are returning pointer a vector but a pointer to the vectors contents, `m[0]` specifically. And of course all your next pointers are also pointing at `m` contents. So all those pointers become invalid as soon as `m` is destroyed, which happens when you exit the function.
Comment: So how should I return the pointer ? should I make a temporary ListNode inside the for loop and then assign the ListNode pointer to it and subsequently next nodes
Comment: Well if you are doing this properly, your merged list should reuse the nodes that are in `A`, so at the end of the function `A` just has empty lists because all the nodes have been *moved* onto the new list.
Comment: I suppose you could change `m` to be `vector m;` and pop nodes off `A[i]` as you push them onto `m`.
Comment: The other choice would be to allocate new ListNodes (with `new`) which would be even less efficient that what you have currently.
Comment: ListNode* k =new ListNode(m[0]);
    ListNode* temp=k;
    for(int i=1;inext= new ListNode(m[i]);
        temp=temp->next;
    }
    temp->next=NULL;

    return k;


How to convert number to month name in Django?

Question:
This is what my dropdown list looks like

How do I convert the number into a month name?
Because when you sort the data with dropdown user wants to see the month name not the numbers
I used strftime and still getting error.
This is my form which I used to add the data that is the date which is in database:
  <form method="POST" id="personForm" data-cities-url="{% url 'users:ajax_load_cities' %}" enctype="multipart/form-data">
   {% csrf_token %}
    <fieldset class="form-group pr-4">
        <legend class="mb-4">Report Form</legend>

                    {{ form.area|as_crispy_field }}

                    {{ form.country|as_crispy_field }}

                    {{ form.month|as_crispy_field }}

                    {{ form.new_ministers|as_crispy_field }}

                    {{ form.dis_course|as_crispy_field }}

                    {{ form.licenced_ministers|as_crispy_field }}

                    {{ form.upgrade_licence|as_crispy_field }}

                    {{ form.preaching_place|as_crispy_field }}

                    {{ form.new_churches|as_crispy_field }}

                    {{ form.water_baptism|as_crispy_field }}

                    {{ form.holy_ghost|as_crispy_field }}

                    {{ form.constituents|as_crispy_field }}

                    {{ form.total_holy_ghost|as_crispy_field }}

                    {{ form.total_baptized|as_crispy_field }}

                    {{ form.author }}

If you choose wrong name, your info will not be saved

    </fieldset>

     <button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Submit</button>

 </form>

Comment: Can you share your form?
Comment: maybe you should hardwire code it as a fixed list of months, say `["January", "February", ...]` :)
Comment: @WillemVanOnsem I added the form above. It was too big for the comments area
Answer: You can use Calendar API
calendar.month_name[12]  will return december.
or
import datetime
month = 12
print (datetime.date(1997, month, 1).strftime('%B'))

this will show you december as well
:)
Answer: You can make a custom template tag to convert the number to month name. Here is a sample code you can use as a custom tag.
from django import template
import calendar

register = template.Library()

@register.filter
def month_name(month_number):
    month_number = int(month_number)
    return calendar.month_name[month_number]

At first, load your custom tag like this.
{% load month_tags %}

And use with month field as follows.
{{ form.month|month_name }}

Comment: No. It is the custom tag file name. In your app create a directory called `templatetags` and add a file called `month_tags.py`. Then load it by the file name.


Percussion notes in the vocals

Question: This an excerpt from an arragment to the song "Hakuna Matata" from the movie "The Lion King":

Why are there percussion notes in the vocals?
Answer: What you are seeing is the standard notation for something that is spoken, or chanted. The syllables are intoned at a specific rhythm but not at a specific pitch.
Comment: Sometimes you'll see the notes at different positions in the staff, indicating approximate pitches or the general inflection of the speaking voice.  All of the spoken lines in Gershwin's opera "Porgy and Bess" are notated this way.
Answer: The technical term is the German "Sprechgesang" and related, "Sprechstimme". Literally "spoken singing" or "spoken voice". Like other answers have stated, the "notes" in question indicate that the words should be spoken in the notated rhythm according to the stems, but the exact pitch is immaterial.
This technique of writing can be fudged a bit, as the cross-head notes (the standard notation for Sprechstimme) can be placed on different lines to indicate a general rise or fall in the spoken "pitch".
Comment: While you are correct, *Sprechgesang* and *Sprechstimme* are associated with a certain style of musical composition in a certain period in history--say operas and art songs from Wagner to Schoenberg. The example idober gave is a type of notation you see all the time in Broadway and pop music. It's notated pretty much the same, but it's not really related to *Sprechstimme* per se.
Answer: That is because it's spoken and not sung.
This song in the movie:

  (skip to 1:14)

Percussion notes in the vocals


Intuition behind topological conjugacy between the flows of two systems of differential equations

Question: My book defines topological conjugacy between the flows of two differential equations as follows:

Suppose $X' = AX \text{ and } X' = BX$ have flows $\phi ^A$ and $\phi ^B$. These two systems are topologically conjugate if there exists a homeomorphism $h: \mathbb{R}^2 \to \mathbb{R}^2$ that satisfies $\phi ^B (t, h(X_0))= h(\phi ^A (t,X_0))$.

I understand the idea behind homemorphism, but why is conjugacy defined the way it is? Why is $h$ of the initial condition taken on one side while h of the flow is taken on the other? Why isn't it defined like $\phi ^B (t, X_0)= h(\phi ^A (t,X_0))$ instead?
Answer: The idea behind it is that: the image of the orbit is the orbit of the image, with corresponding times. And for that you need to have precisely $$\phi^B (t, h(X_0))= h(\phi ^A (t,X_0)).$$
More precisely, an orbit is $$\mathcal O^A(X_0)=\{\phi ^A (t,X_0):t\in\mathbb R\}.$$ Its image is thus $$h(\mathcal O^A(X_0))=\{h(\phi^A (t,X_0)):t\in\mathbb R\}=\{\phi^B (t,h(X_0)):t\in\mathbb R\}=\mathcal O^B(h(X_0)).$$ Summing up, the image of the orbit is the orbit of the image: $h(\mathcal O^A(X_0))=\mathcal O^B(h(X_0))$.

Incidentally: Do you realize that with your proposed definition (in your last line), taking $t=0$ would give $h(X_0)=X_0$ for all $X_0$ and so $h$ would need to be the identity map?
Comment: No, I didn't realize that my definition would lead to that. Thanks for pointing it out. Could you elaborate a bit on " the image of the orbit is the orbit of the image"?
Comment: @cppcoder Edited.
Comment: I think I get it now, thanks for making it clearer.
Comment: @JohnB How do you show that if A and B are equivalent then they are topologically conjugated?


Overfitting in Cox PH model

Question: I'm conducting a survival analysis using Cox proportional hazards model. The failure in the analysis is crime.
I have a binary covariate (1 = yes, 0 = no) for which I get huge hazard ratio – usually between 2,000-4,000 (depends on the specific model).
I checked and it turns out that around 90% of observations who have the value of "yes" for this variable have 'failed' (i.e., committed a crime).
So I understand why the HR is so high, but is it problematic for my model? Is such a case can be considered as overfitting?
Thanks!
Answer: This seems like this is related to the problem of perfect separation in logistic regression. If a set of predictors is adequate to completely determine the outcome, you get very high odds ratios along with high standard errors of the regression coefficients. In your case you perhaps don't have perfect separation but something close to it.
You need to think carefully about this, based on your understanding of the subject matter. It's possible that this is a real association. You might consider a penalized model, which is also a way to deal with perfect separation in logistic regression. You could just penalize the coefficient for this predictor, leaving the others as is. You can do that with a ridge term in a model fit by the R coxph() function, or use the glmnet package.
The risk is that you've accidentally introduced a problem like survivorship bias into your study. That's why you need to approach this from the perspective of your understanding of the subject matter.
Comment: It really seems like a real association - the predictor is previous criminal activity, so it makes sense that if someone already committed a crime, s/he will commit another one.
Comment: The classic Rossi recidivism data included the number of prior convictions as a possible predictor in a similar situation. See the worked-through examples in [this appendix](https://socialsciences.mcmaster.ca/jfox/Books/Companion-1E/appendix-cox-regression.pdf) to "An R and S-PLUS Companion to Applied Regression" by John Fox. That might give you more predictive power and avoid this apparent problem.

Overfitting in Cox PH model


Dart/Flutter not changing page with Inkwell and Gesture detector

Question: I am trying to use  Inkwell or Gesture detector to navigate to page 2, but it is saying "Undefined name 'context'". Hope someone can help! :))
It is a google maps stack container and other group of containers on the top. When click on the containers on top, it redirects to the 2page.
Main.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'woocommerce/woocommerce_api.dart';

void main() {
  runApp(Page1());
}

class Page1 extends StatelessWidget {

  //********************************** GOOGLE MAPS *****************************************

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MapView(),
    );
  }
}

class MapView extends StatefulWidget {
  @override
  _MapViewState createState() => _MapViewState();
}

class _MapViewState extends State<MapView> {

  CameraPosition _initialLocation = CameraPosition(target: LatLng(0.0, 0.0));
  GoogleMapController mapController;

  final Geolocator _geolocator = Geolocator();
  Position _currentPosition;

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }
  _getCurrentLocation() async {
    await _geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) async {
      setState(() {
        // Store the position in the variable
        _currentPosition = position;

        print('CURRENT POS: $_currentPosition');

        // For moving the camera to current location
        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: LatLng(position.latitude, position.longitude),
              zoom: 13.0,
            ),
          ),
        );
      });
    }).catchError((e) {
      print(e);
    });
  }

  @override
  Widget build(BuildContext context) {

    // Determining the screen width & height
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;

    //********************************** GOOGLE MAPS SCREEN **********************************
    return Container(
      height: height,
      width: width,
      child: Scaffold(
        body: Stack(
          children: <Widget>[

            GoogleMap(
              initialCameraPosition: _initialLocation,
              myLocationEnabled: true,
              myLocationButtonEnabled: false,
              mapType: MapType.normal,
              zoomGesturesEnabled: true,
              zoomControlsEnabled: false,
              onMapCreated: (GoogleMapController controller) {
                mapController = controller;
              },
            ),

            ClipOval(
              child: Material(
                color: Color(0xffeb5c68), // button color
                child: InkWell(
                  splashColor: Color(0xffda1b2b), // inkwell color
                  child: SizedBox(
                    width: 56,
                    height: 56,
                    child: Icon(Icons.my_location),
                  ),
                  onTap: () {
                    mapController.animateCamera(
                      CameraUpdate.newCameraPosition(
                        CameraPosition(
                          target: LatLng(
                            _currentPosition.latitude,
                            _currentPosition.longitude,
                          ),
                          zoom: 13.0,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),

            //********************************** ORDERS **********************************

            Container(
              padding: EdgeInsets.only(top: 550, bottom: 50),
              child: ListView(
                padding: EdgeInsets.only(left: 20),
                children: getTechniciansInArea(),
                scrollDirection: Axis.horizontal,
              ),
            ),
          ],
        )
      ),
    );
  }

  List<Technician> getTechies() {
    List<Technician> techies = [];
    //For esting...
    // for (int i = 0; i < 10; i++) {

      //Technician myTechy = Technician(name:'Apotheken', phoneNum: 'Address store');
      Technician myTechy = Technician("Store name test", "Address store ", "Address costumer", 529.3, 4, "Available", "fdfd");

      techies.add(myTechy);
    //}
    return techies;
  }

  List<Widget> getTechniciansInArea() {
    List<Technician> techies2 = getTechies();
    List<Widget> cards = [];
    for (Technician techy in techies2) {
      cards.add(technicianCard(techy));
    }
    return cards;
  }
}

Widget technicianCard(Technician technician) {
  return
    InkWell( // when click...
     child:
        Container(
          padding: EdgeInsets.all(10),
          margin: EdgeInsets.only(right: 20),
          width: 180,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: Colors.white,
            boxShadow: [
               BoxShadow(
                color: Colors.grey,
                blurRadius: 0.5,
              ),],
          ),
          child:
          Column(
           crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[

              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                    SizedBox(height: 5,),
                     Text(technician.name, style: TextStyle(fontSize: 19,fontWeight: FontWeight.bold), textAlign: TextAlign.center),
                       SizedBox(height: 10,),
                        Text("AS: " + technician.phoneNum, style: TextStyle(fontSize: 15)),
                         SizedBox(height: 10,),
                          Text("AC: " + technician.address, style: TextStyle(fontSize: 15)),
                           SizedBox(height: 30,),
                ],
              ),

              GestureDetector(
                child:
                          Container(
                            alignment: Alignment.bottomCenter,
                          width: 120.0,
                          height: 40.0,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            color: Color(0xffeb5c68),
                          ),
                              child:
                              Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[

                                Text("REQUEST", textAlign: TextAlign.center,style: TextStyle(color: Colors.white),),
                              ]
                                )
                          ),
                  onLongPress: (){

              Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Page2()),
                );
              },
              )
                  ]
              )
              ),
       onTap: () {

         Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Page2()),
                );
       }
        );
    }

    //********************************** PAGE 2 **********************************
class Page2 extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Your orders"),
      ),
    );
  }

Woocommerce_api.dart:
class Technician {
  String name;
  String phoneNum;
  String address;
  double rate;
  String status;
  int rating;
  String occupation;

  Technician(this.name, this.phoneNum, this.address, this.rate, this.rating, this.status, this.occupation);
  //Technician({this.name, this.phoneNum, this.address, this.rate, this.rating, this.status, this.occupation});

}

Answer: You need to send BuildContexti to function. does not see the correct context. likewise, you need to add it to the top. Set the context no matter where you called.
Widget technicianCard(Technician technician, BuildContext context)//add here
 {
      .....
      ...
      ..
    }

Comment: yeap. i forget :)


Understanding use-case of Puppet in Windows deployment automation

Question: I have to automate few tasks in Windows environment. Technologies in use are MS SQL Server 2008, IIS, MSMQ etc. All dependencies for running the application are installed on a single machine. However, on production environment, dependencies are setup on different instances. Installation of dependencies (SQL server, IIS, etc) on any instance are all manual as of now.
First thing that i am planning to do is to create a base image which would contain all the dependent components (softwares). I think Puppet and Powershell along with Jenkins will help me in this. I am new to both Puppet and Powershell.
My goal is:
1) to automate installation of softwares on base machine.
2) use this image on all (or most) environments (Dev, Integration, Staging, UAT, Production)
Both the above steps should be automated.
Now the confusion that i have is if i use Powershell for say, installing SQL server (and other softwares too), then where does Puppet comes into picture? I can invoke this Powershell script from Jenkins to deploy on different environments by using custom config files for environments. Am i not understanding the real use-case of Puppet here? Should i be actually using any other tool such as Docker etc? Please guide me.
Comment: "Now the confusion that i have is if i use Powershell for say, installing SQL server (and other softwares too), then where does Puppet comes into picture? " -- you already appear to have decided to use Puppet earlier in the question. Except you're not sure if you should be using docker, though I'm willing to guess you're not sure how. FIRST TIP: Decide how to solve your problem then decide what tools will be a good fit for that solution; this will work so much better than just throwing every trendy devops tool du jour at the problem and hoping one of them sticks.
Comment: I have not really decided to use Puppet although the subject says so. Actually, the team that i have been assigned to seems to be evaluating Puppet for some time. However, i can still suggest if there's something better. The intent of the question was to hear suggestions from people who have already come across such scenario. I'm definitely open to suggestions as the work is to start almost from scratch. My only concern is that i should not be using a tool just because it's hot in the market. If it fits my requirement and helps ease my work, then i'm game for it.
Comment: My high-level approach to solve the problem is already mentioned in step 1 and 2. If there's a better alternative to it, i'm all ears.
Answer: PowerShell vs Puppet is the wrong question
This isn't even really a thing. Puppet can run PowerShell scripts. But there is another big reason the two are not really comparable.
PowerShell is procedural, Puppet is declarative. You can also use PowerShell with Puppet, provided you use methods to make those calls to the scripts have an idempotence check.
exec { 'rename-guest':
  command   => file('guest/rename-guest.ps1'),
  onlyif    => file('guest/guest-exists.ps1'),
  provider  => powershell,
  logoutput => true,
}

Puppet also has reporting, diffing, automatic correction of changes outside of Puppet (known as configuration drift), and many more features that make it a configuration management tool and not a scripting language.
Puppet + PowerShell is a much more complete solution. Now let's perhaps look at using native resources to really reduce code.
Example - Ensure IIS and ASP.NET Installation
Let's say you want to run a script to ensure the installation of IIS and ASP.NET. You would need to ensure that you provide all of the proper checks so that if that script is run more than once, it would not error. You would basically want to ensure that IIS is installed and ASP.NET is configured and exit otherwise.
Doing this in Puppet is trivial. Say this is deploying to a Windows Server 2012 box:
  windowsfeature { 'Web-WebServer':
    installmanagementtools => true,
  } ->
  windowsfeature { 'Web-Asp-Net45':
  }

This is literally all you need to ensure IIS and ASP.NET is installed. Imagine the amount of lines of PowerShell you would need to write to do the same.
There is a more complete example of this for setting up a website complete with permissions at puppet-chocolatey_server.
Managing SQL Server Install
You can use the SQL Server module. Here is an example (there are more involved examples available):
sqlserver_instance{ 'MSSQLSERVER':
  features              => ['SQL'],
  source                => 'E:/',
  sql_sysadmin_accounts => ['myuser'],
}

Installing Software
This becomes trivial when you use Chocolatey.

Yes, Chocolatey builds on unattended installations and PowerShell.
Yes, Chocolatey works with zips and runtime binaries.
No, it does not require internet.
Nor does it require you to download things at runtime from the internet.

Chocolatey is a complete software management tool that integrates right into Puppet.
Organizations that typically use Chocolatey do not use the community package repository (https://chocolatey.org/packages) because the packages offered there are subject to distribution rights and need to download from official locations at runtime. Organizations typically have a very low tolerance for breakages, so they create and host their own packages (internally they do not have the distribution legalities). In that way the process is completely secure, repeatable, and reliable.
package { 'notepadplusplus':
  ensure   => latest,
  provider => 'chocolatey',
  source   => 'https://internal/odata/repo/',
}

Comment: Thanks for the detailed reply! :) Just to clarify, i do know that comparing Powershell with Puppet isn't the right thing. I was just not sure whether using the two together will make sense in the overall picture. From your reply, it seems i can just use Puppet to accomplish my task.
Comment: By the way, i was hearing the term Desired State Configuration (DSC) for some time but never really checked. A day ago, read that it's Microsoft's approach to configuration management on similar lines as Puppet, Chef etc. However, from what i read, going with Puppet would be better for now. DSC is relatively new and Puppet is anyways providing support for several DSC resources.


Chord progression if the chords are not part of the scale?

Question: I've been learning about harmony, and the harmonisation of major scales.
I can recognise simple chord progressions, and I try and practice by listening to popular songs.
For a major scale, we have:

I ii iii IV V vi vii-dim

Here's my question : what if the chords in a song do not match any pattern known for a major scale ?
Here is an example I'm lost with - It's "Hey Joe" by Jimi Hendrix.

C G D A E

No minor chords, only major. I have no idea how to approach this !
Comment: https://www.youtube.com/watch?v=DVvmALPu5TU
Answer: There are many ways to deviate from the pattern. In this example a very common pattern emerges from the circle of 5ths.
The chords don't belong to any one key, but rather come from multiple keys. You start with a C and go to G (I to V in the key of C), then you go from a G to a D(I to V in the key of G),  then you go from a D to a A(I to V in the key of D), then you go from a A to a E(I to V in the key of A). From there in the E chord you have the notes E, G#, B and to get back to a C the G# goes down to a G by half step, the B goes up to a by half step, and E is common.
Keep learning more theory including modes, secondary dominants, substitutions, etc., and you will be able to recognize and utilize these deviations.
Comment: Plausible theory, but I think it doesn't explain how the song actually feels. :) The most natural way to hear the C - G - D - A part to my ear is IV - I - V - II in G, and then the E major - and perhaps the preceding A _major_ is the only real "surprise" with a touch of key change feeling, because E minor was expected. To make it feel like the suggested circle-of-fifths thing with a series of I - V (or IV - I?) motions requires adding something that I don't hear in Jimi's singing in the song.
Comment: If this is the officially correct internet truth on Hey Joe, it should at least mention other perspectives. On the C, supposed "I" chord, if you try to play a cadence C - F - G - C ... that's just wrong. It's not I - V in C, it's IV - I in G.
Answer: Just done a trawl through sheet music, to find it's been written with key signatures of C, G and E. The original, which lands on A, has no key sig.
Most of the solo work seems to be using E minor pent/blues.
It could be construed that it's in E, as that's the chord it gravitates to each verse.
Or the chords could be explained (in E) as coming from parallel keys: C- from Em; G- from Em; D- from Em; A- from E major.
Most songs with more than three chords use the extras to go through part of the cycle of fourths/fifths. As in key C, they may stray to A, then D, then G to return to home - C.
Hey Joe does the opposite. From C, the cycle goes backwards until it gets to E. This gives the opportunity for the bass riff, which follows the chords with the same pattern for each, until E is reached.
Answer: In rock music it is not uncommon for the root notes of chords to follow a scale, while the chords all are major chords (or distorted fifths, i.e. power chords which have an overtone series much like a major triad). Therefore it can be more meaningful to analyze the harmony of a rock song by considering what scale/mode the root motion implicates. Many of the theories of harmony, such as considering the quality of chords (minor, major etc.) based on a diatonic collection of notes (major or minor scale), are mostly useful for analysing common practice period tonal music.
In Hey Joe the chord sequence can also be considered a type of subdominant chain (like a dominant chain, but instead of a V of V ... of V movement, the previous chord is always the subdominant of the following chord, as in a IV of IV of chain). A somewhat similar chord sequence can be found in the song Alright by Jamiroquai.
Answer: What's to "approach"?  Those are the chords.  They don't fit any neat system of all being in one scale.  It would be ridiculous to invent constant modulations.
Lots of music does this.  If your system of theory doesn't "allow" it, find a better system!
Answer: interesting ! I never noticed this about Hendrix's Hey Joe (although I've been playing for ages) ..
One trick that I suggest is to listen to the melody of the voice : if you notice, the first notes of the melody are a C (high) and a B (high) : and the first chord change is C moving to G : this , is a first progression, that seem to claim : "we are in the key of G" -meaning that G is the chord that stays in the mind for a little time, just to say we can relax for a while (my explanation of "tonality"..ehm)
of course everything happens so fast , so when you hear D and A and E
you dont know what you do , this needs to study music theory with a deeper approach ( and good methods)
In music, we can see the same identical things (such as chord progressions) in different ways: for example, playing the song, to me it sounds like the D chord can be see :
as a bridge to a new tonal center (the final E) built on a minor pentatonic scale in Em , chord that changes abruptly in the end (a technique they use since classical music times)
E pentatonic minor's notes are   E G A B D E     so the roots of the chords of D and A , and E ,,are present , here
it's only a question of studying more kinds of music theory, because here, the basics of Classical Theory are not enough-
Jazz theory could help, but first of all, you need to comprehend how you can shift from one tonality (key) to another one in a matter of seconds
Answer: It has intrigued me for some time that "Hey Joe" seems to go "the wrong way" (resolution->tension, ie backwards) through the cycle of fifths.
Quite a few "garage"-type rock songs feature this contrary motion in fourths. Try "Hurt" by Chris Spedding.
In fact, it's possible to harmonise it like this: IVmaj7(#11), Imaj7, V7, iim7, vim7. It's not "Hey Joe", but with some fiddling around voicing the chords, and threading a new melody through them, it sounds quite nice, if a bit doom-laden. Improvising in Phrygian on iii seems to work.
Another curiosity: it's almost, but not quite, the first few chords of "All the things you are", backwards. In fact, it's quite fun to try to try to re-melodicise the first 16 bars of ATTYA backwards...
Comment: So, given that the sequence is C G D A E, you're putting it in key G? Sort of works, as Jimi solos on Em blues, relative minor.
Answer: Could you clarify what you mean by "approach"?
If by "approach" you mean "notate the harmonic analysis", take your pick

     1  5  2  6  3 (in C)
     4  1  5  2  6 (in G)
    b7  4  1  5  2 (in D)
    b3 b7  4  1  5 (in A)
    b6 b3 b7  4  1 (in E)

I'll leave the Roman numerals to you.


Find a function $g : [−1, 1] \to \mathbb R$ with $|g(x)| < |x|^4$ for which $g ′′(0)$ does not exist.

Question: For this question, I couldn't think of one function for g, based on what I know, $g'(c)= \frac{g(a)-g(b)}{a-b}$. and $g''(c)= \frac{(g'(a)-g'(b))}{(a-b)}$, but how do we exactly show $g''(0)$ doesn't exist?
Comment: Try $g(x) = x^{\alpha} \sin(x^{-\beta})$ for some well-chosen $\alpha, \beta > 0$.
Comment: (The above, but it won't work at $x=0$ for the question as stated because you cannot have the strict inequality $|f(0)|<0$ for any value of $f(0)$)
Comment: I assume the strict inequality is just a typo.
Comment: @Raoul or the inequality was meant to hold everywhere except 0. Regardless the main point of the exercise is contained in your comment
Answer: Consider $f:[-1,1]\to\mathbb{R}$ defined by :
$$f(x)=x^4\sin\left(\frac1{x^2}\right)\text{ if }x\neq0\text{ and }0\text{ otherwise}$$
It is clear that $f$ is $C^\infty$ on $[-1,0)\cup (0,1]$.
Since $\vert f(x)\vert\leqslant x^4$ for all $x\in [-1,1]$, we see that $\displaystyle{\lim_{x\to 0}f(x)=0=f(0)}$. This proves that $f$ is continuous at $0$.
Moreover, for all $x\neq0$ :
$$\frac{f(x)-f(0)}{x}=x^3\sin\left(\frac{1}{x^2}\right)\underset{x\to 0}{\rightarrow}0$$which proves that $f$ is differentiable at $0$ and $f'(0)=0$.
For all $x\neq0$ :
$$f'(x)=4x^3\sin\left(\frac{1}{x^2}\right)-2x\cos\left(\frac{1}{x^2}\right)\underset{x\to 0}{\rightarrow}0=f'(0)$$which proves that $f'$ is continuous at $0$.
Now, for all $x\neq0$ :
$$\frac{f'(x)-f'(0)}{x}=4x^2\sin\left(\frac{1}{x^2}\right)-2\cos\left(\frac{1}{x^2}\right)$$doesn't have any limit at $0$.
This proves that $f$ is not twice differentiable.
EDIT
Finally, if we multiply $f$ by some $A\in(0,1)$ (say $A=0.9$ for example), we get a function with the desired properties (strict inequality for any $x\in[-1,0)\cup (0,1]$).
Comment: one can multiply by a small constant to achieve $<|x|^4$ except at 0
Comment: @CalvinKhor That's true ... Let me edit my answer.


Projecting self-adjoint operator onto closed subspace

Question: Let $H$ be a complex Hilbert space and let $(Q, D(Q))$ be a closed, densely defined, positive semidefinite, Hermitian quadratic form on $H$.
(That is, $D(Q)$ is a dense subspace of $H$, $Q$ maps $D(Q) \times D(Q)$ to $\mathbb{C}$, $Q$ is linear in its first variable and conjugate-linear in its second, $Q(x,y) = \overline{Q(y,x)}$, $Q(x,x) \ge 0$, and $D(Q)$ is a Hilbert space under the inner product $\langle x,y \rangle + Q(x,y)$.)
Let $(A, D(A))$ be the generator of $Q$, i.e. the unique self-adjoint operator such that $D(A) \subset D(Q)$ and for all $x \in D(A)$, $y \in D(Q)$, we have $Q(x,y) = \langle Ax, y \rangle$.
Suppose now that $K$ is a closed subspace of $H$, and that $D(Q) \cap K$ is dense in $K$.  Then the restriction $(Q, D(Q) \cap K)$ is a  densely defined, positive semidefinite, Hermitian form on $K$, and it is not hard to check that it is also closed.  Let $(B, D(B))$ be its generator (a self-adjoint operator on $K$).
Question. Is it true that

$D(B) = D(A) \cap K$; and
$B$ is the restriction to $D(B)$ of $P_K A$, where $P_K$ is the orthogonal projection onto $K$.

The main difficulties seem to be that $P_K$ may not map $D(Q)$ into $D(Q)$,  and that $A$ may not map $D(A) \cap K$ into $K$.  But I also cannot come up with a counterexample.
I have a specific example in mind, but I am trying to figure out whether this is true on general principles, or requires more specific knowledge.
Answer: Assume there is a non-zero $v \in \mathcal{D}(Q)\setminus \mathcal{D}(A)$, and let $K$ be the one-dimensional subspace spanned by $v$. Then $K\cap \mathcal{D}(Q)=K$, and $K$ is closed in $H$. The restriction of the form $Q$ to $K$ is finite-dimensional, and positive-semidefinite. $B$ is trivially defined, but $\mathcal{D}(B)\ne\mathcal{D}(A)\cap K=\{0\}$.
The above works so long as $\mathcal{D}(Q)\ne \mathcal{D}(A)$. If $\mathcal{D}(Q)=\mathcal{D}(A)$, then $A$ is less interesting.
Comment: Nice and simple, thanks.  Of course if $D(Q) = D(A)$ then $A$ is bounded and everything is trivial.  There may be further updates on this question (or new questions) as I figure out more relevant information about my specific situation.


Proper REST API design for like dislike and unvote

Question: I have a system where logged in users can vote like or dislike on posts. If they try to like a post which has already been liked, they ll remove its vote. Same applies for dislike. As a REST newbie I am trying to come up with a url scheme for this and it is confusing
Currently, my urls look like this
POST /news/vote/social/:feedItemId/:vote(like|dislike|reset)

A single endpoint is doing everything and logged in users are the ones who can actually vote
After reading some other answers on stackoverflow it seems there are other possibilities as well like
PUT /news/vote/social/:feedItemId/(like|dislike)
DELETE /news/vote/social/:feedItemId

I have seen other answers where the userId is also included in the url because it says REST API design should not reflect statefulness
PUT /news/vote/social/feedItemId/:userId/(like|dislike)
DELETE /news/vote/social/:userId/:feedItemId

The problem with these urls is any person can update any userId s vote unless some backend check is involved
My question, is what is the right way to handle these considering only logged in people should be able to update only their vote?
Comment: `unless some backend check is involved`. It **must** be involved otherwise you have security breach in your API
Answer: It sounds like you probably should take a look at Custom Methods.
Since this is a per-user action, it makes perfect sense to have custom methods that upvote and downvote, where each one acts as a toggle for +1 or -1. For example:

POST /items/1234:upvote on a new post would add +1 (points=1)
POST /items/1234:upvote on that same post again would take away the upvote (points=0)
POST /items/1234:downvote on that same post again would add -1 (points=-1)
POST /items/1234:downvote on that same post again would take away the downvote (points=0).

One extra consideration is the following sequence:

POST /items/5678:upvote would bring points to 1.
POST /items/5678:downvote right after would both take away the upvote and apply the downvote, bringing points from +1 to -1.

(and vice-versa for the reverse sequence)
You mention that this requires some back-end check, which is absolutely correct. If you implement your API where any user can apply upvotes or downvotes from any other user as long as they know the user ID, you've got a security risk. So the correct way to handle this is to use the back-end to pull the user ID from the session after they've signed in (and not from the URL where anyone can fill in the blank for which user they're voting on behalf of).


Jmeter - Extract id from json

Question: I'm using Json path extractor to fetch id from the json
getid = $.id

But it is not fetching any value. The json is:
Json
..Data
....abcd = dlkf
....id = 038443
....ksdhf= ofkj
..success = true

Answer: Use the following JSONPath Extractor configuration:

Destination Variable Name: any name of your choice, i.e. getid
JSONPath Expression: $..id[0]

Refer extracted value as ${getid} where required.
References:

JSONPath Extractor Documentation
JSONPath Syntax
Using the XPath Extractor in JMeter (scroll down to "Parsing JSON") - installation instructions and XPath to JSONPath mappings
Answer: Please share what value do you want to fetch from JSON? Is it 038443?
I believe issue is not with with JSON extractor but the regular expression you have written. Please share more details so a solution could be proposed.

Jmeter - Extract id from json


what permission is need to access to content page?

Question: I have created a role and a user assigned to it. I want to give access to  '?q=admin/content/node' to this role to see all the contents of the site. what permission should I set for this role? I am using Drupal 6.26.
Answer: According to the node module a user must have a role that is allowed for 'administer nodes'.
Comment: I've given 'administer nodes' permission. but no admin menu is shown to user. should I create a special menu for this user and pur this link inside it?
Comment: Yes definitely if you do not want to add more privileges to that role then create a manual link. otherwise 'access administration pages' will show links in navigation menu for administration.
Answer: You need to set the 'Access the content overview page' permission ('Node' section on permissions page).
Comment: Tested with Drupal 7.34


Limit involving the exponential of an expression plus a small-o

Question: I'm trying to formalize the following limit:
$$\lim_{x \to \infty} \left[1+\frac{a}{x}+o\left(\frac{1}{x}\right) \right]^x= e^a$$
however I can't see how to rigorously show this identity.
Any suggestions?
Comment: Try showing the logarithm of this identity.
Comment: For any $\epsilon>0$, can you show that it is greater than $e^{a-\epsilon}$ and less than $e^{a+\epsilon}$?
Comment: Ok, I've solved it using @QiaochuYuan's hint, re-expanding with Taylor the logarithm etc. Thanks :)
Comment: @robjohn Yep, now I see... I had just to apply the definition... I have to be ashamed by the mental lazyness that brings me to ask somebody before to ask myself one more time... Thank you
Comment: the one trickiness about using my hint is that you should use $\liminf$ and $\limsup$.
Comment: yes, I meant the definition of little-o
Answer: Since you've solved it using Qiaochu's logarithm hint, let's try another way. I am guessing that you already know that
$$
\lim_{x\to\infty}\left[1+\frac{a}{x}\right]^x=e^a\tag{1}
$$
and that the new twist is the little-o term.  Little-o here means that for any $\epsilon>0$, there is an $M>0$ so that for $x>M$
$$
\left|o\left(\frac{1}{x}\right)\right|\le\frac{\epsilon}{x}\tag{2}
$$
Condition $(2)$ means that for $x>M$
$$
\left[1+\frac{a-\epsilon}{x}\right]^x\le\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x\le\left[1+\frac{a+\epsilon}{x}\right]^x\tag{3}
$$
Inequalities $(3)$ imply that
$$
e^{a-\epsilon}\le\liminf_{x\to\infty}\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x\le\limsup_{x\to\infty}\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x\le e^{a+\epsilon}\tag{4}
$$
and since inequalities $(4)$ hold for any $\epsilon>0$, we have that
$$
\lim_{x\to\infty}\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x=e^a
$$
Note that we cannot apply the Squeeze Theorem to $(3)$ because the limits of the upper and lower bounds are not equal. Since $\epsilon>0$, $e^{a-\epsilon}\not=e^{a+\epsilon}$; however, since $\epsilon$ can be chosen arbitrarily small, $(4)$ allows us to squeeze the $\liminf$ and $\limsup$ together to produce a limit.
Comment: @Ragib: However, $\epsilon$ was arbitrarily small, so $(4)$ says that $\liminf=\limsup$, so the limit exists and is equal to them. The Squeeze theorem only holds if the limits of the two bounds are equal, which they are not here.
Comment: I am confused about the need for the inferior and superior limits. After attaining (3), doesn't the Squeeze theorem establish not just the value, but the existence of the limit as well?
Comment: In $(3)$, we have chosen a **fixed** $\epsilon$, which gives us $M$. All we know is that for $x>M$, $\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x$ is somewhere between $\left[1+\frac{a-\epsilon}{x}\right]^x$ and $\left[1+\frac{a+\epsilon}{x}\right]^x$, but it could be *anywhere* between those two values. The limit of the lower bound is $e^{a-\epsilon}$ and the limit of the upper bound is $e^{a+\epsilon}$, so as $x\to\infty$, $\left[1+\frac{a}{x}+o\left(\frac{1}{x}\right)\right]^x$ could be bouncing around between those values. So $(3)$ only gives a bound on $\liminf$ and $\limsup$.
Comment: Aah thank you @robjohn, I didn't absorb that subtlety even when looking for one! Perhaps you could incorporate your comments into the answer, it may inform other people like me.
Comment: @Ragib: so incorporated.