Enabling CORS in Cloud Functions for Firebase

Question: I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:
exports.test = functions.https.onRequest((request, response) => {
  response.status(500).send({test: 'Testing functions'});
})

The function sits in this url:
https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events
This is how I did it:
var cors = require('cors');

exports.test = functions.https.onRequest((request, response) => {
   cors(request, response, () => {
     response.status(500).send({test: 'Testing functions'});
   })
})

What am I doing wrong? I would appreciate any help with this.
UPDATE:
Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.
Comment: wrapping the incoming request in cors() like above was the only thing that worked for me
Comment: Also a sample in the docs [here](https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-headers)
Comment: I have some functions that work with the solution provided but now am trying a new function which essentially adds open graphs to the top of my index.html and returns the updated index.html and I can't get it to work :( keep getting the ACCESS-CONTROL--- error
Comment: can you edit your "update" to underline that the cors middleware is required? This will save some people some time
Comment: In 2023, [the relevant docs are here](https://firebase.google.com/docs/functions/callable?gen=2nd#cors)
Answer: For Cloud Functions v2:
You can simply define the function to accept CORS requests as shown in the documentation:
const { onRequest } = require("firebase-functions/v2/https");

exports.sayHello = onRequest(
  { cors: true },
  (req, res) => {
    res.status(200).send("Hello world!");
  }
);

For Cloud Functions v1:
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

Time server with date formatting
HTTPS endpoint requiring Authentication

The second sample uses a different way of working with cors than you're currently using.
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});

And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        // your function body here - use the provided req and res from cors
    })
});

Comment: To anyone willing to add CORS support to their back-ends: please make sure you understand the consequences and how to properly configure it. "origin: true" is cool for testing but it defeats the whole purpose :)
Comment: It looks like this is where the whitelist of domains to allow access is defined? And setting `origin: true` allows any domain to access? (https://www.npmjs.com/package/cors)
@Doug Stevenson Do you think firebase could write up a doc on the basics needed for client/server https functions? The samples repo is good, but we had missed this extra bit of require.
Comment: google cloud functions do not allow the wildcard origin: https://cloud.google.com/functions/docs/writing/http#authentication_and_cors
Comment: As others have mentioned, can you update your answer to point out that cors middleware is indeed required? If we skim through your answer, we think that the only step needed is to write `const cors = require('cors')({origin: true});`, but it's not the case
Comment: Just a reminder for everyone still importing cors like Doug brilliantly mentioned, don't forget to wrap the response like Andrey did, otherwise it won't work!
Comment: @AntoineWeber Yes, I know the author of those samples, and I disagreed with him over the use of unnecessary and misleading returns throughout, but nothing changed.   ¯\\_(ツ)_/¯
Comment: ANd how would this same problem be solved for "onCall" Cloud functions? Because these functions are not quite like express endpoints and I don't have to define middleware supposedly
Comment: @dSebastien, could you give an example of cors with specific origin which I assume that's what you mean it should be used? I have problem getting it to work
Comment: Hey Doug, I've posted a question on Firebase, it's been awhile with no answer and am kind of desperate for it otherwise wouldn't bug you here. Appreciate any comment/reply. https://stackoverflow.com/q/50053798/5601401
Comment: TypeError: 'origin' is undefined.
Comment: response.set('Access-Control-Allow-Origin', '*'); this works fine for me. Do check this solution by @deanwilliammills
Comment: Doug, you forgot the `return` keyword in your snippet. It should be: `return cors(req, res, () => {..` instead.
Comment: @AntoineWeber So, what happens if you don't add it?  HTTP functions don't require a return value.  They just require a response be sent via the `res` parameter.
Comment: Ok it works without the `return`. But the sample function uses `return` for some reason. I guess I got confused by that inconsistency
Comment: I needed to `npm i cors` and `@types/cors` for this work. Thank you!
Comment: will this works for onCall too?
Comment: @AntoineWeber does this approach work on a per-router basis as well?
Comment: finally, a working solution
Comment: If anyone is still having issues after adding `{ cors: true }` to Cloud Functions v2, I found that it sometimes helps to delete the function from the firebase console before deploying it again.
Answer: You can set the CORS in the cloud function like this
response.set('Access-Control-Allow-Origin', '*');

No need to import the cors package
Comment: I added that line into my cloud function, and my localhost fetch is still blocked by CORS policy.
Comment: @CoreyCole I _think_ that's only if you need to add the `Authorization` header. The above seems to work ok.
Comment: This works perfectly for my case, a cloud function that makes a XHR call to Mailchimp API.
Comment: google cloud functions do not allow the wildcard origin: https://cloud.google.com/functions/docs/writing/http#authentication_and_cors
Comment: Where to place this line of code? Which part of the cloud function?
Comment: @elersong check whether you have `http` rather than `https` for your localhost.
Comment: @AntonioOoi you can put it anywhere within the function
Answer: For anyone trying to do this in Typescript this is the code:
    import * as cors from 'cors';
    const corsHandler = cors({origin: true});

    export const exampleFunction= functions.https.onRequest(async (request, response) => {
           corsHandler(request, response, () => {
             //Your code here
           });

    });

Comment: Solution will make you lose logging on cloud functions (very bad) and proper async / await functionality, you risk the function content being prematurely ended inside the callback on long calls.
Comment: @YayoArellano , thanks. Your answer helped me, however I made a slight change: `corsHandler(request, response, () => { YOUR CODE HERE });`
Comment: google cloud functions do not allow the wildcard origin: https://cloud.google.com/functions/docs/writing/http#authentication_and_cors
Comment: @OliverDixon do you have a better solution that does not have the downside of possibly risking the function content to being prematurely ended during long calls? Probably wrapping it in a Promise that only resolves once the callback "completed"?
Comment: @OliverDixon Can you explain "you risk the function content being prematurely ended inside the callback on long calls." please?
Comment: lose logging on cloud functions v it doesn't work === prefer the former
Comment: @OliverDixon Why will the function content be prematurely ended inside the callback?
Answer: One additional piece of info, just for the sake of those googling this after some time:
If you are using firebase hosting, you can also set up rewrites, so that for example a url like (firebase_hosting_host)/api/myfunction redirects to the (firebase_cloudfunctions_host)/doStuff function. That way, since the redirection is transparent and server-side, you don't have to deal with cors.
You can set that up with a rewrites section in firebase.json:
"rewrites": [
        { "source": "/api/myFunction", "function": "doStuff" }
]

Comment: This is a great feature indeed, but it currently only works if the functions live in the default region (us-central1). I wanted to deploy my functions to europe-west1 for latency reasons and ran into this issue: https://github.com/firebase/firebase-tools/issues/842
Comment: imo, this is the best answer, since it solves the actual problem without adding any additional security problems. This way the cloud functions are served from the same domain as the rest and you dont even need any cors.
Comment: Is there any way to use this rewrite with the httpCallable? Or do we need to resort to normal web functions at that point?
Comment: The redirect works fine and makes the URL cleaner, but I haven't figured out how to pass GET parameters. The function (after rewrite) seems to be called without parameters.
Comment: using firebase Hosting? if yes, then your cloud function MUST be in "us-central1" region, this is still true in  june 2021.
Comment: Here's the link to the docs if anyone is curious: https://firebase.google.com/docs/hosting/full-config#rewrite-functions
Comment: This didn't work for me and doesn't make sense. The documentation says, "Use a rewrite to show the same content for multiple URLs." The example is to redirect 404 requests to index.html. The documentation shows how to put "Access-Control-Allow-Origin" in the headers, which didn't work either. I'll ask a new question.
Answer: No CORS solutions worked for me... till now!
Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...
tl;dr - check your firebase function logs if no CORS solutions work and debug any errros you have
Comment: this drove me crazy. in my case it wasn't even error in code! it was
```Error: quota exceeded (Quota exceeded for quota group 'NetworkIngressNonbillable' and limit 'CLIENT_PROJECT-1d' of service 'cloudfunctions.googleapis.com
```
so basically free quota was exceeded and functions returned cors error
Comment: Happend a couple of times here, same error is returned from the server aswell as cors: Error: internal is basically the error. This error will also happen if you run the wrong function, for example mistyping a function name
Comment: At our company, we have a staging and prod environment. The last thing I did was deployed to prod so my firebase CLI environment was set to prod. I was back in staging running my functions locally and got a CORS error. All I needed to do was switch my firebase CLI env back to staging with `firebase use staging` (replace staging with whatever environment you have setup).
Comment: When you try to request for Google reCAPTCHA verification within cloud function, the browser throws you the CORS error too. When I check the Firebase Console function log, it says `access to external network resources not allowed if the billing account is not enabled`. After enabling the billing account, it works perfectly. This is also one of the non-cors related examples but a cors error is thrown.
Comment: In my case, the issue was that I wasn't logged in under the correct Firebase project (`firebase use ` on the command-line) before running the emulator.
Comment: Same scenario here, very misleading cors error
Answer: Updated answer: using cors library with Typescript support:
install cors
npm i -S cors
npm i --save-dev @types/cors

index.ts:
import * as cors from "cors";
const corsHandler = cors({ origin: true });

// allow cors in http function
export const myFunction = functions.https.onRequest((req, res) => {
corsHandler(req, res, async () => {

// your method body

 });
});

Old answer:
(not working anymore)
Found a way to enable cors without importing any 'cors' library. It also works with Typescript and tested it in chrome version 81.0.
exports.createOrder = functions.https.onRequest((req, res) => {
// browsers like chrome need these headers to be present in response if the api is called from other than its base domain
  res.set("Access-Control-Allow-Origin", "*"); // you can also whitelist a specific domain like "http://127.0.0.1:4000"
  res.set("Access-Control-Allow-Headers", "Content-Type");

  // your code starts here

  //send response
  res.status(200).send();
});

Comment: This did not work for me, because it didn't support the OPTIONS method "preflight check" before the GET/POST request.  I had to switch to the `cors` package (or recreate the `OPTIONS` special response, which ended up being more trouble than it's worth)
Comment: This worked for me  adding `res.set("Access-Control-Allow-Origin", "*")`; only did not work  `res.set("Access-Control-Allow-Headers", "Content-Type");`  solved my issue
Answer: I have a little addition to @Andreys answer to his own question.
It seems that you do not have to call the callback in the cors(req, res, cb) function, so you can just call the cors module at the top of your function, without embedding all your code in the callback. This is much quicker if you want to implement cors afterwards.
exports.exampleFunction = functions.https.onRequest((request, response) => {
    cors(request, response, () => {});
    return response.send("Hello from Firebase!");
});

Do not forget to init cors as mentioned in the opening post:
const cors = require('cors')({origin: true});

Update: Any response function that takes time risk a CORS error with this implementation because this doesn't have the appropriate async/await. Don't use outside of quick prototyping endpoints that return static data.
Comment: this worked when other SO answers with setting the headers manually did not
Comment: 2 errors here guys.

First one. Anything after the cors function will run twice (since the first request is preflight). Not good.

Second, @SpiralOut your solution will make you lose logging on cloud functions (very bad) and proper async / await functionality, you risk the function content being prematurely ended inside the callback.
Comment: Having learned a lot about gcf in the last year, I wouldn't recommend this answer anymore. It could be handy for quick prototypes, but avoid this in real production cases
Comment: @JaapWeijland please update your answer with any info why this approach is bad for production code. As eventually all (seemingly working) examples from stackoverflow sooner or later end up in production...
Comment: This works but it can cause TSlint error if you had it enabled and you cannot deploy to firebase. Put the response inside the cors closure to overcome it `cors(request, response, () => {
    return response.send("Hello from Firebase!");
});`
Comment: @SpiralOut you can simply disable tslint
Comment: @SpiralOut i mean remove tslint command from firebase build script only
Answer: This might be helpful.
I created firebase HTTP cloud function with express(custom URL)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const main = express();

app.post('/endpoint', (req, res) => {
    // code here
})

app.use(cors({ origin: true }));
main.use(cors({ origin: true }));
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));

module.exports.functionName = functions.https.onRequest(main);

Please make sure you added rewrite sections
"rewrites": [
      {
        "source": "/api/v1/**",
        "function": "functionName"
      }
]

Comment: To anyone reading this considering putting express inside their cloud function - just don't. Spinning up express takes up extra resources, etc, and you already have all that functionality implemented. Firebase functions !== node.
Comment: It may literally spin up a new express server *per request*. I'm really not sure why they have this stuff in the official docs.
Comment: One downside of this is that the streaming is not working in this case.
Answer: Simple solution using the Google Cloud Console Dashboard:

Go to your GCP console dashboard:

https://console.cloud.google.com/home/dashboard

Go to menu

"Cloud Functions" ("Compute" section)

Select your cloud function, e.g. "MyFunction", a side menu should appear on the right showing you the access control settings for it

Click on "Add Member", type in "allUsers" and select the role "Cloud Function Invoker"

Save it -> now, you should see a remark "Allow unauthenticated" in the list of your cloud functions

Access is now available to everybody from the internet with the correct config to your GCP or Firebase project. (Be careful)
Comment: That worked. The Google Cloud Console Dashboard has changed. Now you go to `Resources`, then `Cloud Functions`. From your list of Cloud Functions, click on the function, to the `PERMISSIONS` tab, click `GRANT ACCESS`, then under `Add principals` type in `allUsers`, then under `Assign roles` select `Cloud Functions` and then `Cloud Function Invoker` and then `SAVE`. This should work for development but I'm going to revoke this permission for production.
Answer: Cloud Functions for Firebase v2
Cloud Functions for Firebase v2 now allow you to configure cors directly in the HTTP options. It works without the need for any 3rd party package:

import { https } from 'firebase-functions/v2';

export myfunction = https.onRequest({ cors: true }, async (req, res) => {
  // this will be invoked for any request, regardless of its origin
});

Beware:

At the time of writing, v2is in public preview.
Only a sub-set of regions is currently supported in v2.
Function names are restricted to lowercase letters, numbers, and dashes.
You can use v1 and v2 functions side-by-side in a single codebase. For improved readability, update your imports to access firebase-functions/v1 or firebase-functions/v2 respectively.
Comment: This is not working for me.
Comment: This was the only solution that worked for me; it allowed for the creation of a 'proxy server' on Firebase Functions for utilising Google's Places API on a web interface.
Comment: How do I allow only specific domains?
Comment: @MalachiBazar: instead of setting `cors` to `true`, you can set it directly to the domain you want to allow. In addition to specifying a `string`, it even supports working with Regex or array of strings in case you want to handle multiple domains.
Comment: To be more precise, the string/array is "origins" not domains - they match against the "origin" request header. I found you have to include the scheme prefix (https://) in the list/string else it doesn't match. Unless you use a regex without an ^.
Answer: If you don't/can't use cors plugin, calling the setCorsHeaders() function first thing in the handler function will also work.
Also use the respondSuccess/Error functions when replying back.
const ALLOWED_ORIGINS = ["http://localhost:9090", "https://sub.example.com", "https://example.com"]

// Set CORS headers for preflight requests
function setCorsHeaders (req, res) {
  var originUrl = "http://localhost:9090"

  if(ALLOWED_ORIGINS.includes(req.headers.origin)){
    originUrl = req.headers.origin
  }

  res.set('Access-Control-Allow-Origin', originUrl);
  res.set('Access-Control-Allow-Credentials', 'true');

  if (req.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    res.set('Access-Control-Allow-Methods', 'GET,POST','PUT','DELETE');
    res.set('Access-Control-Allow-Headers', 'Bearer, Content-Type');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
  }
}

function respondError (message, error, code, res) {
  var response = {
    message: message,
    error: error
  }
  res.status(code).end(JSON.stringify(response));
}

function respondSuccess (result, res) {
  var response = {
    message: "OK",
    result: result
  }
  res.status(200).end(JSON.stringify(response));
}

Answer: If there are people like me out there: If you want to call the cloud function from the same project as the cloud function it self, you can init the firebase sdk and use onCall method. It will handle everything for you:
exports.newRequest = functions.https.onCall((data, context) => {
    console.log(`This is the received data: ${data}.`);
    return data;
})

Call this function like this:
// Init the firebase SDK first
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);

Firebase docs: https://firebase.google.com/docs/functions/callable
If you can't init the SDK here is the essence from the other suggestions:

If you use firebase hosting and host in the default location, choose rewrites: https://firebase.google.com/docs/hosting/full-config#rewrites
Or use CORS like krishnazden suggested: https://stackoverflow.com/a/53845986/1293220
Comment: actually when I use onCall func on browser I got cors error. Could I set costom headers in this request ?
Comment: For those also getting onCall cors error, try this post: https://stackoverflow.com/q/50278537/1411473
Answer: A cors error can occur if you don't catch an error in a function. My suggestion is to implement a try catch in your corsHandler
const corsHandler = (request, response, handler) => {
    cors({ origin: true })(request, response, async () => {
        try {
            await handler();
        }
        catch (e) {
            functions.logger.error('Error: ' + e);
            response.statusCode = 500;
            response.send({
                'status': 'ERROR' //Optional: customize your error message here
            });
        }
    });
};

Usage:
exports.helloWorld = functions.https.onRequest((request, response) => {
    corsHandler(request, response, () => {
        functions.logger.info("Hello logs!");
        response.send({
            "data": "Hello from Firebase!"
        });
    });
});

Thanks to stackoverflow users: Hoang Trinh, Yayo Arellano and  Doug Stevenson
Comment: Thanks for the comment :) The 500 response code is because is not an error related to cors, because of that I think is more appropriate to use a status code >= 500 rather than 403. What do you think?
Comment: Good answer but one nit: As far as the status code of the error, rather than a 500, I think that it's probably better to response with a 403. That's (roughly) what the spec recommends at https://fetch.spec.whatwg.org/#http-responses. And in general, IMHO, it seems not optimal to send a 500 from application code — because that's gonna make it harder for you to distinguish cases of your application code throwing an intended error from cases of the server/runtime code hitting some other kind of internal failure (maybe even before it ever executes your application code).
Comment: I have tried almost all answers on this page and this is the only one that worked. Thank you!
Comment: I'm happy that worked! :)
Answer: Only this way works for me as i have authorization in my request:
exports.hello = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true'); // vital
if (request.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    response.set('Access-Control-Allow-Methods', 'GET');
    response.set('Access-Control-Allow-Headers', 'Content-Type');
    response.set('Access-Control-Max-Age', '3600');
    response.status(204).send('');
} else {
    const params = request.body;
    const html = 'some html';
    response.send(html)
} )};

Comment: google cloud functions do not allow the wildcard origin: https://cloud.google.com/functions/docs/writing/http#authentication_and_cors
Comment: where do i put in my function body? I have posted my code here https://stackoverflow.com/questions/68646425/firebase-function-no-access-control-allow-origin-header-is-present-on-the-req
Answer: Changing true by "*" did the trick for me, so this is how it looks like:
const cors = require('cors')({ origin: "*" })

I tried this approach because in general, this is how this response header is set:
'Access-Control-Allow-Origin', '*'

Be aware that this will allow any domain to call your endpoints therefore it's NOT secure.
Additionally, you can read more on the docs:
https://github.com/expressjs/cors
Answer:
Go into your Google Cloud Functions. You may have not seen this platform before, but it's how you'll fix this Firebase problem.
Find the Firebase function you're searching for and click on the name. If this page is blank, you may need to search for Cloud Functions and select the page from the results.
Find your function, click on the name.
Go to the permissions tab. Click Add (to add user).
Under new principles, type 'allUsers' -- it should autocomplete before you finish typing.
Under select a role, search for Cloud Functions, then choose Invoker.
Save.
Wait a couple minutes.

This should fix it. If it doesn't, do this AND add a CORS solution to your function code, something like:
  exports.sendMail = functions.https.onRequest((request, response) => {
  response.set("Access-Control-Allow-Origin", "*");
  response.send("Hello from Firebase!");
});

Comment: Wont this will make your function public and available to anyone if you don't handle the authentication yourself inside the function.
Comment: For me, this is what it took to get the thing working and save my sanity. I worked backwards and implemented security measures from there. How that is handled is outside the scope of what I'm answering, but it is worth mentioning.
Comment: Update in April 2023: Click Add is now Click "GRANT ACCESS" but otherwise the instructions are as is. Hey... it wouldn't be the cloud if you could use instructions from a year ago :-)
Answer: I have just published a little piece on that:
https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html
Generally, you should use Express CORS package, which requires a little hacking around to meet the requirements in GCF/Firebase Functions.
Hope that helps!
Comment: Not sure what you mean by hacking ? Care to elaborate a bit? Read your post but I don't see you mentioning it
Comment: That link is broken https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html
this is why its better to put the content(summary) of external resources rather than external links
Comment: author of the cors module here; by "hacking" mhaligowski simply meant that he had to wrap the call to the cors module to make it match the way Express calls middleware (i.e. supply a function as third parameter after req & res)
Answer: For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
Comment: also make sure you add your `[project-id]` as this was the issue i faced
Answer: If You are not using Express or simply want to use CORS. The following code will help resolve
const cors = require('cors')({ origin: true, });
exports.yourfunction = functions.https.onRequest((request, response) => {
   return cors(request, response, () => {
        // *Your code*
    });
});

Comment: I think `cors` requires the `express` package; without it you'll get this error (at least I did): "Cannot read properties of undefined (reading 'origin')"
Answer: Adding my piece of experience.
I spent hours trying to find why I had CORS error.
It happens that I've renamed my cloud function (the very first I was trying after a big upgrade).
So when my firebase app was calling the cloud function with an incorrect name, it should have thrown a 404 error, not a CORS error.
Fixing the cloud function name in my firebase app fixed the issue.
I've filled a bug report about this here
https://firebase.google.com/support/troubleshooter/report/bugs
Answer: If you're testing firebase app locally then you need to point functions to localhost instead of cloud. By default, firebase serve or firebase emulators:start points the functions to server instead of localhost when you use it on your web app.
Add below script in html head after firebase init script:

Make sure to remove this snippet when deploying code to server.
Answer: I got the error because I was calling a function that didn't exist on the client side. For example:
firebase.functions().httpsCallable('makeSureThisStringIsCorrect');

Answer: From so much searching, I could find this solution in the same firebase documentation, just implement the cors in the path:
import * as express from "express";
import * as cors from "cors";

const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);

Link firebase doc: https://firebase.google.com/docs/functions/http-events
Answer: See below for how I set up my Express with CORS.
The 'https://pericope.app' is my custom domain for my Firebase project.
It looks like all other answers recommend origin:true or *.
I'm hesitant to allow all origins since it would allow anyone else access to the api. That's fine if you are creating a public service, but if you're doing anything with your data it is risky since it is a privileged environment. For example, this admin SDK bypasses any security rules you have setup for Firestore or Storage.
//Express
const express = require('express');
const app = express();

const cors = require('cors');
app.use(cors({
  origin: 'https://pericope.app'
}));

Comment: Hi @Joel, did you add this config only to the express level or did you change also something at the cloud function definition or in the firebase.json? I have something like this in the index.js: exports.api = functions
    .runWith(runtimeOpts)
    .https.onRequest(apiImpl.app()); . I'm asking because whatever string I put in the origin, the function always replies without any issue.
Comment: Hi @Paolo! I don't see anything in my firebase.json for that project that relates to CORS. My functions/index.js contains the code block I posted above - so effectively my single Cloud Function is like it's own express server. So that might be were the expected rejections are occurring.
Answer: If you prefer to make a single handler function (reference answer)
const applyMiddleware = handler => (req, res) => {
  return cors(req, res, () => {
    return handler(req, res)
  })
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))

Comment: This is an ideal solution if you might need to add more handlers or have many functions
Answer: I'm a very beginner with Firebase (signed up 30 minutes ago). My issue is that I called my endpoint
https://xxxx-default-rtdb.firebaseio.com/myendpoint

Instead of
https://xxxx-default-rtdb.firebaseio.com/myendpoint.json

If you just started with Firebase, make sure you don't forget the .json extension.
Answer: I have been trying this for a long time.
It finally finally worked when I made this change.
app.get('/create-customer', (req, res) => {
  return cors()(req, res, () => {
    ... your code ...

The Big difference is that I used cors()(req, res... instead of directly cors(req, res...
It Now works perfectly.
Answer: With the same access allow control origin error in the devtool console, I found other solutions with also more modern syntax :
My CORS problem was with Storage (and not RTDB neither the browser...), and then I'm not in possession of a credit card (as requested by the aforementioned solutions), my no-credit card solution was to :

install gsutil :
https://cloud.google.com/storage/docs/gsutil_install#linux-and-macos

to create a cors.json file to be loaded via terminal with gsutil

gsutil cors set cors.json gs://[ your-bucket ]/-1.appspot.com

https://firebase.google.com/docs/storage/web/download-files#cors_configuration
Answer: In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link.  Please refer to article for more info
Comment: Please provide some explanation of linked material in your answer, why is it relevant and such
Answer: If none of the other solutions work, you could try adding the below address at the beginning of the call to enable CORS - redirect:

https://cors-anywhere.herokuapp.com/

Sample code with JQuery AJAX request:
$.ajax({
   url: 'https://cors-anywhere.herokuapp.com/https://email@example.com,
   type: 'GET'
});

Comment: this is no longer possible.
Answer: Use cors on your https.onRequest with Typescript like this:
import * as cors from 'cors';
const corsHandler = cors({origin: true});

export const pingFunctionWithCorsAllowed = functions.https.onRequest((request, response) => {
  corsHandler(request, response, () => {
    response.send(`Ping from Firebase (with CORS handling)! ${new Date().toISOString()}`);
  });
});

From Source
Answer: Cloud functions logging helps, check that if you are stuck.
My issue turned out to be a type error on my cloud function where I had a number where a string was expected:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type number (1)

For some reason this gave me the cors error on front-end, and it became a few wasted hours.
Answer: I tried the below methods, but none worked.

Installing the cors package.
Adding the cors flag to the firebase.json file.
returning cors as a part of request options.

The solution is to add a cors option to the function.
functions.https.onCall(handler, {
  cors: true
})

Answer: You can set the headers in firebase.json like this:
"hosting": {
  // ...

  // Applies a CORS header for all font files
  "headers": [ {
    "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)",
    "headers": [ {
      "key": "Access-Control-Allow-Origin",
      "value": "*"
    } ]
  } ]
}

More on Firebase docs.


Decoding a base64 encoded field in a csv with powershell

Question: Apologies if this a stupid question or I'm asking it in the wrong place.
I have a .csv file with a bunch of network logs in the following format sourceIP,port,destinationIP,port,packetdata. The "packetdata" field contains ASCII information which has been base64 encoded. I need to import the CSV file, convert that single field from base64 back to the original and then export the whole file without touching the other rows.
I know I need to use import-csv to get the data in and I know there's a FromBase64String conversion method but I'm kind of lost.
This is what I have at the moment, which is pretty much hacked together from other code and doesn't actually complete when I try and run it...
import-csv c:\testbase64.csv|foreach-object {$_.packetdata =  [text.encoding]::utf8.getstring([convert]::FromBase64String($_.packetdata))|Export-Csv -Path "C:\outputtest.csv" -NoTypeInformation

[text.encoding]::utf8.getstring([convert]::FromBase64String($variable)) does work if run seperately on the commandline with a standard variable with base64 data in as the data source
I'd appreciate any help anyone can give on this, it would make reading these files much less painful.
Comment: you missed the curly brace at the end of foreach-object...
Comment: Agh. Thanks for that, now it actually runs! Unfortunately the output file is empty, so there must be something more fundamental wrong.
Answer: Save this as import.ps1 and use as follows: .\import.ps1 C:\test.csv. It will output a CSV in the current directory called Output.csv.
You'll also need to change the Port columns so one is SourcePort and one is DestPort - you can't have 2 columns with the same name when using Import-Csv.
$csv = Import-Csv $args[0]

$csv | ForEach-Object { $_.PacketData = [text.encoding]::utf8.getstring([convert]::FromBase64String($_.PacketData)) }

$csv | Export-Csv "Output.csv" -NoTypeInformation

Comment: Awesome. Thank you very much, this solves my problem.


Interpret Wolfram Alpha Closed Form Equation

Question: The closed form number pattern equation for 1, 1, 2, 6 on Wolfram Alpha is:
$a_n = (1)_{n-1}$
What does this mean?
i.e. $a_n = n$ is for 1, 2, 3, 4
Note: "n" starts at 1 (1st term)
Comment: $(x)_k$ stands for $x(x+1)(x+2)\cdots(x+k-1)$. This means $(1)_{n-1} = 1\cdot 2\cdot 3\cdots n = n!$.
Comment: @A_for_Abacus The difference is not limited to rising/falling factorials.  many notations on WA is different from the one documented on wiki. My personal experience is rising factorial is more common as they appear in the definition of hypergeometric function: ${}_2F_1(a,b;c;z) = \sum_{k=0}^\infty \frac{(a)_n (b)_n}{n!(c)_n} z^n$.
Comment: what exactly is the question here?
Comment: What does the notation $a_n = (1)_{n-1}$ mean?
Comment: what have you typed?
Comment: Typed 1,1,2,6 @ http://www.wolframalpha.com/widgets/view.jsp?id=d9976f1c2c0c972d1cee0c3647cbd194
Comment: @achillehui  You're right, it's a rising factorial notation a.k.a. Pochhammer function. However, the notation being used by wolfram alpha seems a bit off from the convention seen here: https://en.wikipedia.org/wiki/Falling_and_rising_factorials

Is that a mistake?
Answer: Looking at the output from wolfram alpha that is the pochhammer symbol
Comment: The Online Encylopedia of Integer Sequnces has 139 pages for this entry. The first is the ordinary sequence of factorials, which is in fact the Pockhammer $(1)_n$ with the right starting point. http://oeis.org/search?q=1%2C+1%2C+2%2C+6&language=english&go=Search


Kullback-Leibler Divergence continuous for measures?

Question: in one of the commments to this post concerning the application of Kullback-Leibler-divergence between measures that do not fulfill the necessary absolute continuity (e.g. point mass vs. continuous) , as an extension it is proposed to define the KL-Divergence with respect to the sum of measures.
That is, given measures $P,Q$ define $D_{KL}(P||Q) := \int \frac{dP}{d(P+Q)} \ln \frac{\frac{dP}{d(P+Q)}}{\frac{dQ}{d(P+Q)}} d(P+Q) $,  (possibly taking value $\infty$)
What I would be interested now: is this continuous in measures in some sense?
As an example take specific situation, where we have some fixed $Q$ and $P_n$  (both absolutely continuous w.r.t. Lebesgue measure) and then some limit $P$ that is eg. a point mass  -
do we get
$  \underset{n \rightarrow \infty} {\lim} D_{KL} (P_n||Q) = D_{KL} (P||Q) = \infty $
take for example $P_n := \mathcal{N}(0,\frac{1}{n}) \overset{d}{\rightarrow} \delta_0$  and $Q$ arbitrary.
Answer: First, note that as long as the base measure $\mu$ dominates both $P$ and $Q$, it doesn't matter what $\mu$ you choose (for any $f$-divergence). So if both measures are absolutely continuous wrt Lebesgue, then this distance is just exactly the standard KL.
A special case of your specific example is easy to see: taking $P_n = \mathcal N(0, 1/n)$ and $Q = \mathcal N(0, 1)$, plugging in the KL formula for normals gives that $D_{KL}(P_n \| Q) = \log n + \frac{1}{2 n^2} - \frac12 \to \infty$.
KL, however, is not continuous in the most common sense, that of the weak topology (convergence in distribution); for an example, take $P_n = \delta_{1/n} \xrightarrow{d} Q = \delta_0$, so that $D_{KL}(P_\infty \| Q) = 0$, but $D_{KL}(\delta_{1/n}, \delta_0) = \infty$ for any $n$. (For any two distributions with disjoint support, $\frac{\mathrm d P}{\mathrm d (P+Q)}(x) = \begin{cases} 1 & x \in \operatorname{supp}(P) \\ 0 & \text{o.w.}\end{cases}$, so that $D_{KL}(P \| Q) = \int_{\operatorname{supp}(P)} 1 \log\frac{1}{0} \mathrm d x = \infty$.) Its topology is stronger than the total variation topology (by Pinsker's inequality) which is stronger than the weak topology, but I don't know much more about it; there are a handful of notes here.


Openstack cannot access to the controller node from the other network

Question: I've installed the Openstack without any issue. I'm facing the issue that cannot access the controller host from the other network.
In my work environment, I have many VLAN configured on Cisco Switch.

The user VLAN is (10.10.10.0/24.)
The server VLAN is (192.168.100.0/24).

The controller server ext IP (192.168.100.100), after creating network/router on the controller the network from the user (10.10.10.0/24) cannot ping/access to 192.168.100.100, but on the same network of the controller (192.168.100.0/24) still can ping to controller node.
It means only the same network of the controller can reach it the other network cannot.
So how to make it available to all networks?
Some results from the controller:
tcpdump:
verbose output suppressed, use -v or -vv for full protocol decode
listening on vxlan-1, link-type EN10MB (Ethernet), capture size 262144 bytes.

IP address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever

2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:87:7c:e8 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.11/24 brd 10.0.0.255 scope global ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::250:56ff:fe87:7ce8/64 scope link
       valid_lft forever preferred_lft forever

3: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master brq2d2d66af-87 state UP group default qlen 1000
    link/ether 00:50:56:87:d6:1c brd ff:ff:ff:ff:ff:ff

6: tap96c05264-57@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master brq2d2d66af-87 state UP group default qlen 1000
    link/ether 72:b8:0a:01:9d:36 brd ff:ff:ff:ff:ff:ff link-netns qdhcp-2d2d66af-87f8-4c5e-9329-dbb903debc0d

7: tape473efb7-92@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue master brq98128308-8d state UP group default qlen 1000
    link/ether 96:e0:72:ac:06:18 brd ff:ff:ff:ff:ff:ff link-netns qdhcp-98128308-8d26-4ef5-947d-0620396348d7

8: vxlan-1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue master brq98128308-8d state UNKNOWN group default qlen 1000
    link/ether ee:48:01:ef:1f:03 brd ff:ff:ff:ff:ff:ff

9: brq98128308-8d: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default qlen 1000
    link/ether 02:d5:28:7f:48:8f brd ff:ff:ff:ff:ff:ff
    inet6 fe80::5093:1dff:feaa:1698/64 scope link
       valid_lft forever preferred_lft forever

10: brq2d2d66af-87: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 00:50:56:87:d6:1c brd ff:ff:ff:ff:ff:ff
    inet 192.168.100.100/24 brd 192.168.100.255 scope global brq2d2d66af-87
       valid_lft forever preferred_lft forever
    inet6 fe80::250:56ff:fe87:d61c/64 scope link
       valid_lft forever preferred_lft forever
    inet6 fe80::70dc:72ff:fe53:152f/64 scope link
       valid_lft forever preferred_lft forever

11: tape188178b-33@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue master brq98128308-8d state UP group default qlen 1000
    link/ether 02:d5:28:7f:48:8f brd ff:ff:ff:ff:ff:ff link-netns qrouter-50ae9644-5fe8-4bc3-9813-c96c22c294ff

12: tap97c393cc-e5@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master brq2d2d66af-87 state UP group default qlen 1000
    link/ether 1a:c8:66:85:59:c6 brd ff:ff:ff:ff:ff:ff link-netns qrouter-50ae9644-5fe8-4bc3-9813-c96c22c294ff

ip route
default via 10.0.0.1 dev ens160 proto static

default via 192.168.100.1 dev brq2d2d66af-87 proto static metric 100

10.0.0.0/24 dev ens160 proto kernel scope link src 10.0.0.11

192.168.100.0/24 dev brq2d2d66af-87 proto kernel scope link src 192.168.100.100

Thank you!
Comment: Can you explain your network architecture? Is the user network related to the OpenStack cloud? If yes, how, and how did you configure Neutron?
Comment: User network: 10.10.10.0/24
Openstack network: 192.168.100.0/24 (external network), 10.0.0.0/24 (internal network)
Basically, Networks for users and OpenStack can reach each other by configured routing on Cisco Switch.
I've to install Openstack on Ubuntu 20. After creating the virtual network in Openstack such as (provider, self-service, router), set gateway for router then from user network cannot ping or access to Openstack dashboard anymore.
I think the issue on Openstack since the brq2d2d66af-87 interface created.
Comment: I understand that the user network is outside of OpenStack. A device, e.g. PC, with address 10.10.10.x needs a route to the OpenStack controller 192.168.100.100. You tell me that this router is implemented on the switch, but you can't reach 22.214.171.124. To me, this looks like a router misconfiguration. Can you run `tcpdump` on the controller to see if any ICMP packets come from the router? Can you reach other devices on 188.8.131.52? **More questions**: How did you deploy this cloud? Can you update the question with the output of `ip address` and `ip route` on the controller?
Comment: I updated the question. I deploy the OpenStack manually by following the installation guide from Openstack. My environment only has 2 machines, 1 for controller and 1 for compute, on each machine has 2 NIC. By the way, the router I mentioned above is on Openstack.
Comment: What is the second network used for (10.0.0.0/24, ens160)? I may be wrong, but you have two default routes, and the first default via 10.0.0.1 has the highest priority, since it uses default metric 0. My networking knowledge is not that profound, but I would at least temporarily remove the first default, then try again (`ip r del default via 10.0.0.1` should do the trick, though the route will reappear after a reboot).
Comment: To see if packets arrive at the controller, run `tcpdump -i ens192 icmp` on the controller and `ping 192.168.100.100` on a device with address 10.10.10.X. `tcpdump` should report incoming echo requests. If it doesn't, the problem is not on the controller. If it does, the question is whether echo replies are generated, and via which interface they leave the controller. They might leave via ens160, the wrong interface, due to that route. You could then see them with `tcpdump -i ens160 icmp`. If, however, they leave via ens192, the question would be why the sending device doesn't receive them.
Comment: This command saves my life ip r del default via 10.0.0.1. You are right since the ens160 is the internal interface and the first interface of this controller. So the metric is the highest priority.
Comment: You also need to remove the route permanently, so that a reboot doesn't recreate it. How to do that depends on how the route is defined in the first place, and that depends on the network management tool you use.
Answer: ip route
default via 10.0.0.1 dev ens160 proto static
default via 192.168.100.1 dev brq2d2d66af-87 proto static metric 100
it due to the default route is the internal interface so the user cannot reach Openstack. After doing the below command, the issue solved.
ip route del default via 10.0.0.1
Many thank for your help Mr.Berndbausch


Não consigo pegar todos os dados do arquivo XML e salvar em um txt

Question: Esse é o XML:
<cv>
    <pessoa id="1">
        <dadosPessoais>
            <nome></nome>
            <sexo></sexo>
            <idade></idade>
        </dadosPessoais>
        <formação>
            <instituição nome="" país="">
                <curso anoIni="" anoFim="" nível="">
                </curso>
            </instituição>
        </formação>
        <formação>
            <instituição nome="" país="">
                <curso anoIni="" anoFim="" nível="">
                </curso>
            </instituição>
        </formação>
    </pessoa>
</cv>

Minha dificuldade é em ler os elementos que estão na tag Formação. Como existe mais de uma tag com o mesmo nome (formação), quando eu coloco para salvar em um txt, só mostra até os dados da primeira tag formação e no meu projeto a pessoa pode adicionar quantas formações quiser.
try {
    doc = builder.build(f);
    root = (Element) doc.getRootElement();

    List<Element> pessoas = root.getChildren();

    for (int i = 0; i < pessoas.size(); i++){
        Element pessoaS = pessoas.get(i);

        try { // criar
            File diretorio = new File("c:\\CV");
            diretorio.mkdir(); //cria, se possível

            File arquivo = new File(diretorio, "cv_"+ pessoaS.getAttributeValue("id") +".txt");
            FileWriter fw;
            fw = new FileWriter(arquivo);
            BufferedWriter b = new BufferedWriter(fw);
            b.write("Nome: " + pessoaS.getChild("dadosPessoais").getChildText("nome"));
            b.write("\r\n");
            b.write("Sexo: " + pessoaS.getChild("dadosPessoais").getChildText("sexo"));
            b.write("\r\n");
            b.write("Idade: " + pessoaS.getChild("dadosPessoais").getChildText("idade"));
            b.write("\r\n\r\n");
            b.write(pessoaS.getChild("formação").getChild("instituição").getChild("curso").getAttributeValue("nível") + ": " + pessoaS.getChild("formação").getChild("instituição").getAttributeValue("nomeDaInstituicao")+ " (" + pessoaS.getChild("formação").getChild("instituição").getAttributeValue("nomePaisCurso") + ")");
            b.write("\r\n");
            b.write("Curso: " + pessoaS.getChild("formação").getChild("instituição").getChildText("curso"));
            b.write("\r\n");
            b.write("Início: " + pessoaS.getChild("formação").getChild("instituição").getChild("curso").getAttributeValue("anoIni"));
            b.write("\r\n");
            b.write("Término: " + pessoaS.getChild("formação").getChild("instituição").getChild("curso").getAttributeValue("anoFim"));

            b.write("\r\n\r\n");

            b.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} catch (JDOMException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Answer: Você precisa precisa recuperar uma lista de Element a partir do elemento pessoa, então depois percorrer esta lista. Da forma que você faz, recuperando um único Element formação irá recuperar apenas o primeiro nó formação encontrado no XML. A forma de recupera a lista de formações é simples, parecida com a forma com você está recuperando as pessoas:
final List<Element> formacoes = pessoa.getChildren("formação");

Depois disto, basta percorrer cada formação, algo assim:
for (int j = 0; j < formacoes.size(); j++) {
    final Element formacao = formacoes.get(j);

    // faz o que precisa ser feito
}

Este é um exemplo completo fazendo o que você precisa, acredito eu, usando JDom versão 2.0.2:
final SAXBuilder builder = new SAXBuilder();
final File xml = new File("F:/CV/CV.xml");

final Document doc = builder.build(xml);
final Element root = doc.getRootElement();

final List<Element> pessoas = root.getChildren();

for (int i = 0; i < pessoas.size(); i++) {
    final Element pessoa = pessoas.get(i);

    final File diretorio = new File("F:/CV");

    final File arquivo = new File(diretorio, "cv_" + pessoa.getAttributeValue("id") + ".txt");

    try (final FileWriter fw = new FileWriter(arquivo); final BufferedWriter b = new BufferedWriter(fw)) {

        final Element dadosPessoais = pessoa.getChild("dadosPessoais");

        b.write("Nome: " + dadosPessoais.getChildText("nome"));
        b.write("\r\n");
        b.write("Sexo: " + dadosPessoais.getChildText("sexo"));
        b.write("\r\n");
        b.write("Idade: " + dadosPessoais.getChildText("idade"));
        b.write("\r\n\r\n");

        final List<Element> formacoes = pessoa.getChildren("formação");
        for (int j = 0; j < formacoes.size(); j++) {
            final Element formacao = formacoes.get(j);
            final Element instituicao = formacao.getChild("instituição");
            final Element curso = instituicao.getChild("curso");
            b.write(curso.getAttributeValue("nível") + ": ");
            b.write(instituicao.getAttributeValue("nome"));
            b.write(" (" + instituicao.getAttributeValue("país") + ")");
            b.write("\r\n");

            b.write("Curso: " + curso.getText());
            b.write("\r\n");
            b.write("Início: " + curso.getAttributeValue("anoIni"));
            b.write("\r\n");
            b.write("Término: " + curso.getAttributeValue("anoFim"));
            b.write("\r\n\r\n");
        }
    }
}

Como viu, percorremos tanto a lista de pessoas quanto a lista de formações da pessoa. O arquivo TXT gerado, usando este XML:
<cv>
    <pessoa id="1">
        <dadosPessoais>
            <nome>Bruno César</nome>
            <sexo>M</sexo>
            <idade>26</idade>
        </dadosPessoais>
        <formação>
            <instituição nome="UFG" país="Brazil">
                <curso anoIni="2009" anoFim="2014" nível="Graduação">Engenharia de Software</curso>
            </instituição>
        </formação>
        <formação>
            <instituição nome="UFSC" país="Brazil">
                <curso anoIni="2015" anoFim="2017" nível="Mestrado">Pós-Graduação em Ciência da Computação</curso>
            </instituição>
        </formação>
    </pessoa>
</cv>

Possui este conteúdo:
Nome: Bruno César
Sexo: M
Idade: 26

Graduação: UFG (Brazil)
Curso: Engenharia de Software
Início: 2009
Término: 2014

Mestrado: UFSC (Brazil)
Curso: Pós-Graduação em Ciência da Computação
Início: 2015
Término: 2017

Como dica, se possível for, evite usar caracteres especiais em nomes de tags e atributos do seu XML, isto poderá lhe gerar problemas no futuro.
Comment: Muito obrigada!! Funcionou perfeitamente :D


Hexagonal Tessellation on a sphere

Question: I want to detect collision of a sphere with another object and to find out(show) the deformation of the sphere. I have come to know that hexagon(regular)tessellation of a sphere is the most appropriate one. What are the advantages of tessellating a sphere with regular hexagons over squares and triangles? How can I use this regular hexagon tessellation on the sphere to detect collision and find out in which part of the sphere deformation has occurred?
Why regular hexagons are better than squares or triangles? I want a detailed explanation on this topic.
Comment: How did you  "come to know that hexagon [...] tessellation of a sphere is the most appropriate"? btw: [tag:game-theory]? Are you trying to create a computer game?
Comment: How have you "come to know"? What references led you to that?
Comment: No not really a computer game. But a small part of the game like collision detection of objects and deformation after collision. my object is a sphere. I have come to know about regular hexagonal tessellation from net. They say that it is much better than square or triangular tessellation. please help me
Comment: They say that any points (which we call it as pixelS)on a regular hexagon are equidistant from each other.There are no corner to corner connectivity in a regular hexagon tessellation. But in a square or triangular tessellation we have to consider corner connectivity along with edge connectivity. Actually, I am asking this question that why hexagonal(regular one) tessellation is better? I want answer to this question.
Comment: Can any one explain me this with diagram. Help is needed
Comment: Come on, do not leave us in the dark about who "they" are. Are you sure "they" were talking about a sphere? Links please, so we can check whether you misunderstood "them".
Comment: I am not leaving anyone in dark. you can search it in net. Also the natural example is a honeycomb. Why honey bees have chosen hexagons only?link is http://www.academia.edu/7556020/SquareHexagonalComparison_of_Square-Pixel_and_Hexagonal-Pixel_Structure_in_Image_Processing
Comment: Here they are talking about natural tessellation. But I have to tessellate a sphere? So is hexagon tessellation the best one?
Answer: It is impossible to tessellate (regularly or otherwise) a sphere with hexagons, at least when three hexagons meet at each vertex.
If you have $F$ hexagons, this means you must have $3F$ edges (since each hexagon has six edges, shared by two hexagons) and $2F$ vertices (since each hexagon has six vertices, shared by three hexagons). Plugging into the Euler characteristic formula you get
$$V-E+F = 2F-3F+F = 0\neq 2$$
which cannot be a topological sphere.
What if you allow three or more hexagons to meet at a vertex, instead of exactly three? You get that $V \leq 2F$ and you're in the same boat, since now $V-E+F$ is still $\leq 0$.
To get Euler characteristic two you must therefore have some vertices where only two hexagons meet. For example, you could take two hexagons, glue them on top of each other, and call that a "sphere." I would consider any such tiling to be degenerate, but if that's what you really want, it is at least possible to construct.
Note that you could instead use a mix of hexagons and pentagons. These tesselation are well-known (consider the soccer ball, or geodesic dome).

Now back to your original question. I can't think of any plausible reason you would want a hexagonal (or mostly-hexagonal) tesselation of the sphere for simulation or collision detection purposes. If you have a complicated object, it's common to build a conservative collision cage around the object using discrete oriented polytopes (k-DOPs) and the common $18$-DOP will contain hexagons and squares. But I don't see why you'd want to discretize the object itself as a hexagonal mesh, especially if the object is going to deform, since you then have your pick of two unpleasant poisons: 1) maintaining a planarity constraint on the faces as the hexagons deform, or 2) allowing nonplanar hexagons and interpolating the boundary using your choice of generalized barycentric coordinates, and any choice you pick is going to do the exact opposite of simplifying collision detection.
Answer: A sphere cannot be tessellated using only regular hexagons. You need to place twelve pentagons with sides the same as those of the hexagons; the pentagon centers must be at the face centers of a dodecahedron.  Then you can complete the tessellation using some number of hexagons; for example, I think the old-fashioned standard soccer ball uses 12 pentagonal and 20 hexagonal faces.
I strongly suspect, however, that you will have a better time with your collision detection and deformation algorithms if you then move to a triangular covering, by placing another vertex at the center of each such hexagon or pentagon, and connecting that vertex to the 6 or five corners.
The advantage of triangular tessellation is that for a hexagon, there can be multiple solutions to the local deformation, which would be easy to disambiguate by eye, but which require great care to reliably disambiguate algorithmically.  You get the best of both worlds by basing the triangular tessellation on that nearly-regular hexagonal pre-tessellation, because a square pre-tesselation does not generalize to an arbitrarily fine grid, while the hexagonal one does.
Using triangular tessellation, you then can model collision deformation by simulating a damped stiff spring between each neighboring pair of vertices (on each colliding sphere), and giving vertices in different "spheres"  a repulsive potential with force steeper than $1/r^2$ but with some cutoff range so that you don't have to sum forces over every pair of vertices.  The spring stiffness, repulsion and range must be chosen, however, such the sort of collisions you want don't completely collapse any spring, and such that a foreign vertex coming in between 3 springs encounters enough net repulsion (in the collisions you are considering) to prevent it crossing through the plane of the triangle.
Comment: Slight nitpicking regarding the first paragraph: You do not **need** to use pentagons. You could -for example- use triangles instead.
Comment: True, but if you want to use equal, regular hexagons and you want your covering to have a maximal symmetry group. the set of triangles or other shapes you need to add must add up to the areas of those 12 pentagons.

Hexagonal Tessellation on a sphere


IVm6 or IVm7? (in major)

Question: (Note: using the key of C major as generic instead of roman numerals.)
Yesterday I was reading the book "Hearin' the Changes" (by Coker, Knapp and Vincent), which discusses Fm7-B♭7-C as an ubiquitous formula called "backdoor cadence" used to return from tonal centre F to home key C.
However, the New Real Book's sheet for All of Me, for example, has F6-Fm6-C (measures 25-27).
Both formulas seem very similar in purpose (return from IV) and chords used. Both sources seem pretty reputable.
My question is: after an F chord (typically F triad or F6) established as tonal centre, which chord, Fm6 or Fm7, makes more sense to you? Why?
My own thoughts on this don't amount to much. I wonder if maybe Fm6 makes more sense when B♭7 is omitted and Fm7 makes more sense when B♭7 is present. However, I'm unsure about the use of Fm7 because generally I haven't seen the tone E♭ (or D♯) appear much at all (blues aside, such as in IV7 and ♯IVo7).
I'm particularly interested in the use of IVm in jazz standards, but any comments will be appreciated.
Comment: Bear in mind that Fm6 is an inversion of Dm7b5 (D half-dim). That may (or may mot) have a bearing.
Answer: Both versions occur frequently. As usually, let your ears decide. Theoretically speaking, the Fm6 chord just uses one note outside of the C major scale (the third A♭), whereas Fm7 also uses an E♭. So by using Fm7 you temporarily move a bit further outside the scale. It's true that if the Fm chord is followed by a B♭7 chord, then it's more natural to use Fm7, simply because then you have a standard II-V unit, and you have the additional resolution E♭ → D when moving from Fm7 to B♭7.
Note that there's also a third option, which occurs less often, but which is also interesting: Fm maj7: F - A♭ - C - E. Just like Fm6 it only lowers the A to A♭ without changing any other scale notes.
Also note that the corresponding chord scales are different. For Fm6 and Fm maj7 you would normally use the F melodic minor scale, whereas for Fm7 (or Fm7-B♭7) you would use F dorian ( = B♭ mixolydian = C aeolian).
Answer: As the other answers suggest, both options have equal validity when considered exclusively from the perspective of a successful cadence, because they both provide good resolution back to the I chord. So the question "which makes more sense?" won't have an answer--they are equally correct, and both are used.
However, if we leave the vacuum of pure cadential expectations, then (a) melody, (b) soloist preference, and (c) musical genre/style can dictate why one progression might be preferred over another.
Let's consider measure 12 of "When the Saints Go Marching In," assuming we're working in CMaj. As MattL explains, there are three options:

| Fm6 | CΔ7 |
| Fm7 Bb7 | CΔ7 |
| FmΔ7 | CΔ7 | (the simplest spelling of FmΔ7 is F-Ab-C-E, called "F minor major seven")

Which of these do we use in m. 12? We would probably choose Fm6 or FmΔ7, because the melody features an E♮ in m. 12. So Fm7 could clash with the melody because Fm7 contains an Eb rather than E♮.
In other circumstances, the soloist or person improvising might express a preference. If a soloist starts playing an Eb over measure 12 of "When The Saints Go Marching In," then the band would probably want to adjust the Fm6 to Fm7 or to Fm7-Bb7.
Finally, when composing, you can evaluate the style you are working within. ii-V progressions tend to be more common in swing and bebop, whereas Fm6-CΔ7 might tend to be more typical of gospel, rock, blues, bluegrass, or popular music. These are not black-and-white rules, and you can certainly make either progression work in any genre, but both options are not used with equal frequency in all genres.
Answer: I won't write a long answer. The theory explained in other answers is good. Whether you want to play Fm6 or Fm7 largely depends on the kind of music you desire to play.
Comment: Point taken, thanks :-) Maybe my field of interest, expressed as "jazz standards" at the end of the OP, is just too broad. Still, I'm confused, because the two sources I mention (this music sheet and book) are basically covering the same stylistic area, that's your typical classic jazz standard, likely 32 measure AABA or ABAC form, etc.
Answer: C7-F6-Fm6-C is called the sub-dominant cadence in Jazz (o when the saints go marchin' in), also as final ending below the octave note C.
Fm7-B♭-C is equivalent with Ab6-B♭-C (as you say the "back door cadence). Billy Shears ending cadence.
Mostly they are exchangeable - if the main-tune allows it! If you play alone or arrange a piece you can do what you like. If you play or sing with others, listen carefully what they're doing!
Comment: I too associate C7-F6-Fm6-C to When the Saints Go Marching In. I came across the chord sequence again recently in the beautiful song Si tu vois ma mère by Sidney Bechet.
Comment: @Alex: Bb7 sounds fine. Ab can resolve to C or G, F to G or E. In wiki we can read *The notes A♭ and F serve as upper leading-tones back to G and E*. https://en.wikipedia.org/wiki/Backdoor_progression
Comment: I notice you use Bb (triad) instead of Bb7 as used on the book I read (this explanation about the "backdoor cadence"). Could you please explain your reasons? I'm asking because, for B7-Am (that's resolve to Am via tritone sub), I like to use Bb6 instead of Bb7, not to totally enclose the tone A chromatically. But in the case of Bb7-C, I totally need the tone Ab to take me to the tone G. Otherwise, if I want to highlight voice leading, my options are reduced to the tone F moving to the tone E.
Comment: I disagree that Fm7-Bb7-C is equivalent to Ab6-Bb-C. The former is used more commonly in swing and bebop (and connotes that feel), whereas the latter is more typical of rock or popular music.
Comment: @jdjazz, I said Fm7 (F,Ab,C,Eb) and Ab6 (Ab,C,Eb,F) are equivalent  (Ab6 is identical with Fm7 with the 3rd as bass tone!). And, yes, the Ab-Bb-C and Ab-Bb7-C sound differently, but both Bb chord are often Bb9 chords because the C is kept in the melody or as highest note.
Comment: Maybe I misread, but I see your answer saying that the two *progressions* are equivalent, not just the individual chords Fm7 and Ab6. To me, the statement "Fm7-Bb-C is equivalent with Ab6-Bb-C" suggests that the progressions are equivalent and both qualify as the back door cadence. To my knowledge, Ab6-Bb-C doesn't qualify as a back door cadence, and stating that these two progressions are equivalent seems like too strong a statement. Even though Fm7 and Ab6 have the same notes, the bass will play different things, which changes the quality of the progression.
Comment: I agree, there is a difference between the root chord Fm7 and its 1st inversion. Some of us will consider the bass note Ab as root of Ab6 some will say this is a passing note of the Fm7 chord.  It depends how long this Ab6 endures.

IVm6 or IVm7? (in major)


How to use figured bass over a stationary bass note

Question:
I am studying figured bass, and as a test I wanted to try and add figured bass symbols to the following passage marked with the pink arrow. I got stuck right at the beginning, because I am not sure what chord that is or how to number it.
The book I have says to first convert the chord into a close position triad, keeping the bass note the same, but I am not sure what triad DGE is. I assume it is part of a bigger triad but not sure. Maybe Em7 4/2?
For the word "show" I get a G6/4 chord and for the word "you" I get a D 5/3 chord. Then the word "The" seems to be a D5 chord so question 2 is? how would this D5 be notated in figured bass?
Answer: In terms of literal chords, your analysis is fine, except for the D5 chord, which should be Dsus4(omit 5) or something like that.
However, it misses the purpose of figured bass, which is to specify the intervals above the lowest voice. Figured bass does not attempt to identify chords, nor does it indicate the chord voicing, aside from specifying the lowest pitch (which would be notated explicitly).
For the measure in question, the figured bass would look like this:

I can show you the
5  4   6    5   8
3  2   4    3   4

And the 5-3 would typically be omitted as that figure is assumed if no other figure is given.

Roman Numeral Analysis includes figures but is distinct from figured bass. RNA is an analytical tool for understanding harmony, but, unlike chord symbols, it isn't intended as a literal description.
An RNA in this case might look like

I can show you the
             ---4
I  --DN--   I

where DN = Double Neighbor
Comment: @Aaron: You said "There is no chord with just a root and a fifth". Then you said: "It (8/4) refers to a chord with with an octave and a fourth above the bass" Can you explain please?
Comment: Thanks Aaron, is 8/4 the usual way to write chords with just a root and 5th?
Comment: @armani There is no chord with just root and fifth.
Comment: @Aaron - there are thousands of guitarists who would *really* argue with your last comment..! But I agree.
Comment: @Aaron, so what is 8/4?
Comment: @armani It refers to a chord with an octave and a fourth above the bass.
Comment: @Tim To clarify: there is no chord with just root and fifth ... in the measure under analysis.
Comment: @armani the word "the" is accompanied by a D in the bass and a G and D in the piano. G is a fourth above the bass; D is an octave above the bass.
Comment: @armani in the common practice period, you would never have such a chord, since chords all have at least three notes, so the rules of notating figured bass don't provide for it.  If it were figured only with 4, there would be an implied 5, so the chord would also include an A.  If the third note were supposed to be a B, the figure would be 6 over 4.


"Access Denied" when trying to connect to remote IIS server from my local workstation

Question: I am currently writing an application that connects to IIS server and spiders through the virtual directory to collection information.  When I try to connect from a Windows XP SP3 with IIS 5.1 machine to a Windows Servers 2003 server with IIS 6.0 I get an "Access Denied" exception.
In the server's security event log it shows that I am trying to establish a connection as my local workstation's ASPNET account.  I am an administrator on both machines and it does not seem to play a factor with trouble shooting the issue.
I posted this SO question on 4/1 and did not get anywhere.  Maybe posting it on SF will provide better insight and trouble shooting.
Comment: What kind of application is it?
Comment: It is a web application that can not connect to the remote IIS server.
Answer: In the discussion on StackOverflow you mentioned that it works when you run it as a standalone C# application, but not when you run it as a web application.
That makes sense. When you run it as a standalone C# application, it is running with your identity. When you run it through a web application, it is running using whatever identity you have configured for anonymous web requests under IIS, in this case, that local workstation's ASPNET account.
Depending on the security situation, you either want to
(1) configure the local web server so that that application serves anonymous web requests using a different account, one that has appropriate permissions on the server, or
(2) configure the local web server to not allow anonymous web requests. You will have to log on to the web page through your web browser using the username-password associated with an account that has appropriate permissions on the server


Self-Binding with Castle Windsor in C#

Question: With the Ninject Dependency Injection Container, I can perform self-binding in a manner similar to the following:
MyClass mc = ninjectKernel.Get<MyClass>();

Is there an equivalent sort of operation in Castle Windsor?
Comment: @JamesWiseman if I recall correctly, you can save yourself a little typing: `container.Register(Component.For());` when the "for" type argument is a class, and there's no "implemented by" call, Windsor is smart enough to register the class as the implementer.
Comment: I'm unsure what feature you're referring to, but Windsor's `MyClass mc = container.Resolve();` would on the surface seem to do the same thing.
Comment: Doh, obvious. Thanks. That looks suspiciosly like an answer to me if you want to post it. To get it to work I had to register it against itself. `container.Register(Component.For().ImplementedBy());`
Answer: In accordance with  Joachim Isaksson comments, this is what I had to do:
In the installer:
container.Register(Component.For<MyClass>().ImplementedBy<MyClass>());

To resolve:
MyClass mc = container.Resolve<MyClass>();

Comment: You don't need the `.ImplementedBy()`.  You can just have the `.For()` and it will work.
Answer: Castle Windsor's corresponding call is (unless I'm missing some intricate functionality in NInject)
MyClass mc = container.Resolve<MyClass>();

and, as you point out in the comments, you'll need to register the class against itself to work in Windsor.
Comment: In order to avoid having to register each individual class against itself, you can register multiple classes in some assembly against themselves, based on their base class.  For example, I use the following to self-register all my MVC Controller-derived classes:
`container.Register(Classes.FromThisAssembly().BasedOn().WithServiceSelf());`

Self-Binding with Castle Windsor in C#


Cannot update during an existing state transition

Question: I am trying to set state value based on result of a promise method. For optimistic updates I am setting state value before an asynchronous operation. If operation fails state is reset
componentWillMount(){
    this.setState({notify: this.props.notif});
}

render(){
    return(
        <Switch
          onValueChange={(val) => this.toggleNotifications(val)}
          disabled={! this.props.connected}
          value={this.state.notify}
        />
    )
}

toggleNotifications(val: boolean){
    this.setState({notify: val});
    mmSetNotification(val).catch(() => this.setState({notify: !val}));
}

I am using async method to set notification value using network call which will update user object
async function mmSetNotification(checked: boolean) : Promise {
    return new Promise((resolve, reject) => {
        Meteor.call('setNotification', checked, (error, result) => {
           if(error){
               reject(error);
           }else{
               resolve();
           }
        });
    });
}

Answer: Use this.setState instead mutating this.state
DOCS:

NEVER mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

toggleNotifications(val: boolean){
  this.setState({notify: val});
  mmSetNotification(val).catch(() => this.setState({notify: !val});
}

Comment: Same behaviour observed with this.setState also ```mmSetNotification(val).catch(() => this.setState({notify: !val}));```
Comment: Added to original question description
Comment: Are you sure that your network call returns an error? you can see this [example](https://babeljs.io/repl/#?evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&code=p().catch(err%20%3D%3E%20console.log(err))%0A%0Aasync%20function%20p()%20%3A%20Promise%20%7B%0A%20%20return%20new%20Promise((resolve%2C%20reject)%20%3D%3E%20%7B%0A%20%20%20%20reject('error')%0A%20%20%7D)%0A%7D%0A) and it works fine
Comment: Yea, It can return an error. The example shown above is a simple one. A complex method can reject methods if a specific criteria is not met
Comment: Can you log the value of `val` before you call `mmSetNotification` and in `catch` body?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118874/discussion-between-sergeybaranyuk-and-reku).


Analytical Badge still showing "FAQ"

Question: I just noticed that the FAQ link at the top of the page is replaced with "help". However, the description of the Analytical Badge is still "Visited every section of the FAQ". Shouldn't this also be changed to "Visited every section of the helpcenter" or something like that?
Also how will this badge be awarded now? Do you have to click on every link in the helpcenter to get this badge or do you just have to take the tour now?
Answer: Notice the description of the analytical badge.

Visited every section of the FAQ (retired)

There is a 'retired' in there. This means that the badge cannot be awarded anymore.
This applies to all stackexchange sites, including stackoverflow.

Analytical Badge still showing “FAQ”


How do I stop View/Edit tabs appearing on Taxonomy driven Pages when I am not logged in?

Question: I have a View and Edit button appearing on pages that are Taxonomy driven, even when I am not logged in (and in Incognito Mode).
These pages use the URL /taxonomy/term/%taxonomy_term and Views, using info from the URL, are used to display certain data on these pages. For example, with /cars/honda/civic 'cars', 'honda' and 'civic' would be used in the Views to show relevant information about Honda Civics.
The issue is that whilst there is no View and Edit buttons appearing on the base /cars page, they are appearing on every sub page (/cars/honda, /cars/toyota/camry, etc).
I can't find anything out of the ordinary in Permissions.
Would any one know what I could do to stop this?
(PS clicking the Edit button whilst not logged in does nothing - just takes you to 403 page).
Answer: This was due to someone not surrounding this code with a permissions checker, eg:
 if (!user_access('administer nodes')) {
    return;
  }


Views slideshow without jQuery Cycle

Question: I have a view slideshow that I managed to set up by following these instructions.
I want to use a responsive slider plugin instead of the jQuery Cycle plugin in Views Style Settings. How can I use this JavaScript code to create the slideshow.
Answer: This isn't exactly what you asked for, however:
I have tried a bunch of slideshows that claim various degrees of responsiveness and the best out of the box solution I have found that works as expected, is easy to set up, and is properly responsive, is the flexslider module, which can either be used by itself, or can be used with the views slideshow module.
If you haven't tried it it is definitely worth trying.
Answer: Not sure why my question was downvoted but here is the answer.
I created a views block for my custom content type "Slider Images" and called it "Home Page Slider". I set the "Slider Images" Link and Image as Fields in the view and formatted it as an HTML list.
In my template.php file I used this function
<code>function THEMENAME_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // if Home Page Slider View add the appropriate js and css
   if($view->name == 'home_page_slider') {
     // add needed javascript
     drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/js/responsiveslides.min.js');
     // add needed stylesheet
     drupal_add_css(drupal_get_path('theme', 'THEMENAME') .'/css/responsiveslides.css');
   }
}
</code>
to add my JS and CSS needed for the responsive slider plugin I wanted to use

Views slideshow without jQuery Cycle


How can I pick up vsftpd logins with auditd and its prelude plugin?

Question: I have a server running auditd and prelude with the audisdp-prelude plugin.  Currently I get events for several types of logins, like sshd and gdm.  However I don't seem to ever get login info for vsftpd.  I know that I can change vsftpd's configuration and make it output to a file and then parse that with prelude-lml, but I really would prefer that auditd send me the event so that I don't have to do that.  I can see that auditd is actually auditing the logins, but for some reason it doesn't forward them like it does for everything else.  I am running a separate prelude-manager server that I'm trying to use to collect all my note worthy events.
Answer: Sorry for the delay. Did you fix it ?
If not, http://www.sriramrajan.com/mw/index.php/Linux-Auditd may be useful.
and generally ...
In order to use audit facility you need to use following utilities
=> auditctl - a command to assist controlling the kernel's audit system. You can get status, and add or delete rules into kernel audit system. Setting a watch on a file is accomplished using this command:
=> ausearch - a command that can query the audit daemon logs based for events based on different search criteria.
It says .... export your vsftpd logs via syslog into a file and make the filtering from auditd. It's something similar to what you was thinking about prelude-lml.
Comment: I actually wound up modifying auditd slightly so that it produced an actual event.  The change I added only generated them for vsftpd anything else would still function as normal.


success function not being executed

Question: I am making a ajax call to get a record from the database I have seen in the console that it is successfully returning the record but success is function is not being executed.
function ajaxForParent() {
    var search = document.getElementById("resourceId").value;
    var folderId = document.getElementById("folderId").value;

    $.ajax({
        type : "GET",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : "/admin/content/changeParent",
        data : {search : search, folderId : folderId}, // Note it is important
        success : function(folder) {
            alert(folder);
            if (folder.id == document.getElementById("folderId").value) {
                $("#parentAvailable").html("Children Limit exceeding you cannot add more than 9 levels children");
                return false;
            }

            console.log(folder.id);
            console.log(document.getElementById("folderId").value);

            if (folder.id != document.getElementById("folderId").value) {
                console.log("I am coming here " +folder.id);
                var s = document.getElementById("folderId");
                s.value = folder.id;
            }
            $("#parentAvailable").html("Parent Found Successfully!");
        },
        error : function(content) {
            $("#parentAvailable").html("Parent Not available");
        }
    });
}

I have tried with the above it always entering the error function even though record is successfully return from server side. can anyone tell me what I am doing wrong here ?
when I throw the error I am getting this
SyntaxError: JSON.parse: end of data after property value in object at line 1 column 1587309 of the JSON data
Comment: the error suggests that the returned JSON is not valid.
Comment: check the html status code, make sure the response has a `200 OK` status
Comment: @UriGoren - Yeah I am getting 200 OK status
Comment: @GabyakaG.Petrioli is right, could you attach the server's response to the question ?
Comment: @UriGoren - I have tested the data that is coming in it is not the correct JSON format.
Comment: That error indicates bad json format, you can run `JSON.parse()` on it with a console, and verify that. from my experience it is usually a quoting issue
Answer: You cannot send json data via GET.
You need to use POST:
$.ajax({
    type : "POST", // <------ Use POST
    contentType : 'application/json; charset=utf-8',
    dataType : 'json',
    url : "/admin/content/changeParent",
    data : {search : search, folderId : folderId},

If your app /admin/content/changeParent accepts only GET, you may need to consider changing it to accept POST. Otherwise, your app cannot receive the JSON data you send to the server correctly via GET.
Comment: what ? offcourse you can use the `json` format with get, there is even a shorthand for that `$.getJSON()`
Comment: @Tao  - If I use the Post then how can I get the data which is coming back from the server ?
Comment: The response from the server can be of any format including JSON. No matter which HTTP verb you use, you will receive the response back from the server.
Comment: @UriGoren what you mentioned was getting a JSON response, not "sending JSON".
Comment: @TaoP.R. run this script in your console `jQuery.get('/',{'q':'r'})`, it is automatically translated to a `GET` request for `/?q=r`, `jQuery` can handle these kind of conversions automatically
Answer: It looks like the response contains improperly formatted json data. Try copying the response into a json linter such as http://jsonlint.com/ to find the problem.
Answer: take your server answer and paste it into some json linter (like http://jsonlint.com/) to make sure jquery can transform it to a valid response.
you can also put a breakpoint into your error callback and check for the error and value returned at that moment. While you're there, if the data received is a string and not an object, try to call JSON.parse(/* your server response */) to test if it's working at all and if you get any additional error.
Comment: this should be a comment, not a solution
Comment: only 41 reputation, can't comment ;)

success function not being executed


Is there a highest note representable on sheet music without using an octave higher notation?

Question: Is there a highest and lowest note that can be written on sheet music without using the one or more octave higher/lower notation? In my case for the piano specifically.
I want to learn to sight read and my first goal is to be able to name any note that appears on sheet music so that I don't have to count from a known position. Therefore I need to know all notes that could appear. Are there any rules about that? Can the highest and lowest notes on the piano be written without using the octave higher/lower notation?
Is there no standard for sheet music notation? I'm creating some very simple software to generate notes to help me practice but I don't want it to generate total nonsense which I'll never see in the real world. Are there any standards I could look up?
Comment: For the notation part you could generate Lilypond-notation, and then generate your practice sheets from that. Then you will get standard notation. See http://en.wikipedia.org/wiki/Lilypond.
Comment: There aren't any hard and fast notations. I own sheet music that goes 3 octaves above the staff.  As a longtime (suffering :-) ) musician, I would certainly ask that you limit your layout to maybe a 12th above or below, and after that use "8va" notation, or switch clefs for those instruments for which multiple clefs are in common use.
Comment: One thing to consider is the limitation of the human brain.  We break the staff up into five lines and can differentiate pitch based on where they fall. The ability to determine the pitch often has to do with how many ledger lines above or below the staff it is. Once you get to a certain point, the brain cannot automatically group the ledger lines into discernible numbers/distance. Think about tally marks. Once you get past 4, we add a slash through the group to make 5. This allows us to not have to count the marks. The brain can recognize groups of 4 but it gets harder as you move above that.
Comment: Once you think you've mastered it, may I suggest you test yourself on [this excerpt from *Trance and Dental Etudes* by P.D.Q. Bach](http://books.google.com/books?id=3hmSAgAAQBAJ&lpg=PT166&dq=%22trance%20and%20dental%20etudes%22&pg=PT167#v=onepage&q=%22trance%20and%20dental%20etudes%22&f=false). (You may need to broaden your definition of "piano" to include the *Überklavier*).
Answer: There is no absolute limit. The highest C on the piano, written 3 octaves above the staff, is perfectly legitimate. However, practically speaking, notes that far from the staff will almost always be written in a musical phrase containing other nearby notes, so the 8Va notation is used. Music that high is nearly impossible to sightread if not written using 8va notation, both because the distance from the staff is so great, and because the notes are so seldom read in that position.
If you are just starting out with sight reading, start out with a two octave range centered around the C in the center of the staff, and gradually increase it in both directions as you need it.
Comment: A bit off track but for completeness I'd just like to add that [the 15ma notation](http://music.stackexchange.com/a/15297/2245) can be used when 8va isn't enough.
Comment: I've seen handbell music use seven ledger lines above the staff. Since one pair of treble/bass clefs may have notes spread throughout a seven-octave range, and different notes of a chord may be played in different octaves, 8va notation would be inapplicable (beyond the fact that handbells are essentially always played an octave above what's written). I've sometimes wondered why there's no standard for a "super-treble" staff two octaves above the treble clef (with two ledger lines separating it from a treble clef). At  least for handbell music I think that would make things much easier to read.
Answer: As others have said, no there isn't a real limit, but there is a practical limit. If I am sightreading something and there are lots of ledger lines, there's no way you'll figure it out in time, so you might as well just skip it.
However, sometimes you'll know if you've worked your way up there gradually, or are playing octaves or something. A lot of sightreading isn't seeing each note, but recognizing patterns, so if you see an octave (and you'll get used to the distance between intervals on the sheet music), you only have to look at one of the notes. The same goes if you're playing individual notes really high or low - if you know where you are, you just read intervals instead of pitches.
I wouldn't recommend practicing more than maybe 3-4 ledger lines though if you're going for sightreading. It's just not common enough to worry about, and there are just too many other things to focus on, like getting the gist of a measure and filling the rest in yourself.
Comment: "filling in the rest" should also entail learning to actually see and count the rests -- much more important than > 4 ledger lines
Answer: The hard-and-fast rule for written sheet music is READABILITY.  Anything that makes it easier to read is "more correct" than some markup that makes it harder to read.
In the example given in the question, you'd rarely use ledger lines to annotate a note that's more than an octave above the staff, because it just gets too swampy to read all those ledger lines.  Use the 8va notation.  However, it's generally not seen to have an 8va marking on anything shorter than a bar or a complete phrase.  Think about that on a piano or guitar:  a single note or three written up 7 ledger lines tells you to "grab a quick high note" while the notation 8va tells you "move your whole hand position up there for a bit."
However, it isn't uncommon to have single bass clef notes annotated 8vb.
Answer: One point that has not been pointed out here, is that I was taught when sight reading a new piece of music, it should be looked over beforehand and analyzed to spot the hard to read notes so that they don't catch you by surprise as you attempt your performance. Doing so allows the time needed to count and determine ledger lines and notes.
Comment: I do this, but it was once pointed out to me that it's arguably no longer sight reading at that point.  A truly crack sight reader can look far enough ahead to be able to process the hard-to-read bits while playing.
Answer: As a point of comparison, I play Alto Recorder, and often see music that reaches the g four ledger lines above the treble staff (our highest note). Flutes, I think, can go even higher without using 8va.
Soprano and Sopranino recorders, as well as piccolos, can all go higher, but are typically notated an octave lower than sounding.
Comment: Former flautist here.  It's easily possible to go to the C five lines above and commonly taught.  It's possible to play every note up to A7, which as far as I'm aware doesn't have a known fingering.  This note is on the 8th line above the staff.  The highest note that I know is possible to play is C8 which sits on the 9th line above the staff.
Comment: That being said, the fingerings become somewhat of a complete mess after C#6.
Comment: What, your alto won't play the a natural above that g? Tsk! Admittedly, I've only ever played one piece that needed it...
Answer: For practicality, it very much depends on the context. A major scale played upwards through 5 octaves is perfectly readable, using as many ledger lines as needed. However, playing some huge complex interval like a 39th out of nowhere is never going to be sight-read at full speed. Context usually will determine whether ledger lines are appropriate or not.
Of course, theoretically, there is no limit to how many ledger lines can be used in sheet music, as frequency exists on an infinite and continuous spectrum. As the question asks about the case of the piano, the de facto limit would be C8 (or whatever the highest key on the board happens to be), which clocks in at 9 ledger lines above the treble staff.

In essence, any method of making a written note sound lower than normal would allow for a higher maximum ledger line cap.

It is technically possible to increase this limit by using bass clef to represent a stratospheric piano note, which would move the position of middle C even higher on the staff and force the highest note of the piano up onto six more ledger lines for a total of 15 (different low-pitched clefs also work).

It is also possible to go further by using not 8va, but 8vb. This would technically be outside the purview of the question, but it is a possible way to write even more ledger lines above the staff by moving middle C even higher than before.

Going further is also possible by detuning the piano. Place a mark at the beginning of the piece that states "A=220Hz", for a quick example, and you can squeeze another octave's worth of ledger lines out.

As a final absurd example, consider extreme accidentals: C duodecuple-flat 9 (C9 written with twelve flats attached to it) is a pitch written a full octave above C8 and uses an additional three ledger lines, but Cbbbbbbbbbbbb9 is still enharmonic to C8 and therefore a playable note!


Error submitting app via XCode

Question: I'm trying to submit an app tonight and I can validate the app find but when I go to submit, get the following errors:
Apple's web service operation was not successful
Unable to Authenticate the package
exception occurred when creating MZContentProviderUpload
Has anyone else seen this error?
Comment: I just got the same error.  Maybe their servers are experiencing temporary issues?
Comment: Now I am facing the same problem... https://discussions.apple.com/thread/3822193?start=0&tstart=0
Comment: https://discussions.apple.com/thread/3822193?start=0&tstart=0 Check this out.
Comment: for me worked resubmitting immediately after had this error
Comment: This is Apple's phone number for iTunesConnect, they are happy to listen to you vent over any frustrations that you might have with this program: +1 (800) 633-2152
Answer: Just had this happen on Xcode 7. Quit Xcode, opened it back up, resubmitted and it worked fine.
EDIT: I agree with @arlomedia in the comments, this is a problem on Apple's side. Just had it happen again and restarting did not fix it. Maybe I just got lucky the first time :)
Comment: It might be a problem on Apple's end, because I had the problem at exactly the same time as you. Anyway, it also worked for me after restarting Xcode.
Comment: Same issue for me happening 2 hours after you guys posted.  I restarted Xcode, but the problem is still there.  Guess I have to wait for Apple to fix on their side.
Comment: Definitely apple server issue. Same error here for the past an hour
Comment: Mine actually didn't go through before ... it got past the point where the error occurred, but then ran for a long time and timed out. Then when I tried again I kept getting the error. However, I just tried a few minutes ago and it finally submitted.
Answer: That seems like a temporary issue from Apple's side. It should have been fixed by now. Try uploading again.
Comment: Correct.  It works this morning!
Comment: I got this error in the morning before rushing out the door. Came home later and clicked Upload to App Store... again and it worked. No restart needed.
Answer: I saw a slightly different error message, six times in a row:
Exception occurred when creating MZContentProviderUpload for provider. (1004)

Restarted my mac, resubmitted and boom - worked.
Can't say for sure if it was the restart, could have just been something on Apple's servers as the other answers point out.
Comment: Just restart the Application Loader will help
Answer: I kept getting it for several days until I changed Deployment Target from 3.1.3 to 4.3.
My error also said "The bundle does not contain icon for iPad exactly '72x72' pixels". I checked the icon and updated it like 5 times :)

Error submitting app via XCode