Question on jointly distributed uniform random variables (deriving density function)

Question: I am looking at a simple example of choosing a point at random on a disk (circle) of radius $1$. The text book states simply:
$f(x,y) = \frac{1}{\pi}$ if $x^2 + y^2 \leq 1$ and $0$ otherwise. Now, when thinking in terms of single variable integrals, I understand that to find the pdf of a uniform random variable $X \in [a,b]$ we simply have the pdf equal to $\frac{1}{b-a}$ and this function integrates to $1$ over the range $[a,b]$. I know a similar version is at work here in the multivariate case but can't as easily see the justification or how to set-up the double integral to integrate over the circle using the pdf $\frac{1}{\pi}$ to get $1$.
I assume that for any area $A$ we simply have $\frac{1}{A}$ as our pdf. Can someone give me the generic double integral that we would use for an arbitrary area $A$? I suppose for a square or rectangle it seems straightforward $[a,b]\times[c,d]$ would imply a double integral of the form$\int_{a}^{b} \int_{c}^{d}$ but for a circle or a more complex area I am a bit lost.
Can someone shine some light on ways to think about the multivariate case of deriving the pdf and also provide guidance on how to set-up the double integral that would integrate $\frac{1}{\pi}$ to $1$? I am having a hard time figuring out the limits of integration.
Comment: Hint: The disk of support has radius $r = 1$ and area $A = \pi r^2 = \pi,$ so for the volume beneath the uniform density $f(x,y) = c$ and above the disk to be unity, you must have $c = 1/\pi.$ Of course the volume can be expressed by the double integral of $f(x,y)$ over the disk, but now you already know the answer by geometry.
Answer: To integrate over a unit circle, $y$ should range from $-\sqrt{1-x^2}$ to $\sqrt{1-x^2}$ while $x$ stays inside $[-1,1]$ (look at the circle to see this). This is a slightly annoying integral to do directly, but can be done using trig substitutions:
$$ \int_{-1}^1\int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}}\dfrac{1}{\pi}dydx = 1$$
Otherwise, it'll be easier to convert to polar coordinates:
$$ \int_0^{2\pi}\int_0^1\dfrac{1}{\pi}rdrd\theta = 1$$


Como criar uma pasta para cada usuário em PHP?

Question: Gostaria de um exemplo de como criar uma pasta para armazenar os dados de cada usuário em php, por exemplo www.facebook.com/nomedeusuario
Imagino que na sequencia é salvo um index dentro dessa pasta e esse index é criado no momento do cadastro, com as informações do usuário como no Facebook. Alguém poderia me dar um exemplo de como fazer isso?
Comment: Isso não é pasta. Isso pode ser melhor chamado de URL Amigável. O Facebook pode usar o `/qualquercoisa` para `profile.php?id=qualquercoisa`. Sim, ambos são acessíveis! Pode ver sobre isso aqui: http://pt.stackoverflow.com/questions/25985/url-amig%c3%a1vel-com-htaccess, mas complexo, ou aqui: http://pt.stackoverflow.com/questions/75963/url-amig%c3%a1vel-utilizando-htaccess/75970#75970.
Comment: Uma outra maneira de fazer reescrita, sem usar `mod_rewrire` é passar as variáveis após o arquivo index.php, exemplo: `www.seusite.com.br/index.php/pergunta/resposta` e captutar a URL e separar tudo `explode()`  `"index.php/"`.
Comment: @IvanFerrer inclusive, se configurar o Apache (ou equivalente) para isso, não precisa nem ser index.php. Pode muito bem ser `http://example.com/noticias/esporte` - é o que eu faço normalmente. Não uso htaccess e simplifico o processo todo.
Comment: Não é pasta é url amigável, [olha esse exemplo](http://codigofonte.uol.com.br/codigos/criando-url-amigaveis-com-um-codigo-simples-e-funcional). E [leia mais aqui](http://wbruno.com.br/php/desmistificando-urls-amigaveis-com-php-e-htaccessapache/)
Comment: to ligado @Bacco!
Answer: Se você quiser criar pasta, terá que definir um caminho ou um diretório onde as pastas serão criada e salvar em uma constante ou variável e depois pegar o nome da pessoa e para a criação da pasta, antes de qualquer ação verifique se a pasta já existe. Veja um exemplo abaixo:
$pathName = "C:\\php\\www\\pastas_user\\" . $nome_user;

if(!file_exists($pathName )){
   mkdir($pathName); //aqui ele irá criar a pasta
} else {
   $pathName .= time(); //concatena a pasta para gerar com um nome diferente
   mkdir($pathName); //aqui ele irá criar a pasta
}

Após isso é só gravar o diretório da pasta no banco de dados no registro do usuário.
Comment: +1, pois apesar de aparentemente o autor quer ser outra coisa, respondeu a pergunta. Afinal, ele pode estar querendo o URL para mil usos diferentes, inclusive salvar arquivos de cada um em separado. (e se não for isso, outra pessoa que está precisando disso pode procurar por "pasta" e achar exatamente sua resposta)
Comment: Acho que ele se refere a pasta como sendo a "URL", como ele disse, igual ao facebook.
Comment: Sim Bacco, na verdade eu procurava por essa "url amigavel" criada através do .htacess, mas aprender a criar a pasta também será útil para futuros projetos! Obrigado a todos!


Slack slash command response_type ephemeral are sent to the entire channel

Question: Ephemeral messages are supposed to be only visible to the user that issued the command. However, in my experience, it's sent to the entire channel.
Am I missing anything?

According to Slack Slash commands documentation, the only attribute needed is to set response_type to ephemeral in the response of Node.js app.
The code in my app looks like this:
<code>  var t = {
    "response_type": "ephemeral",
    "text": "How to use /please"
  }
    request({
    uri: uri,
    headers: {
      'content-type': 'application/json',
    },
    method: 'POST',
    body: JSON.stringify(t)
  }, function (error, response, body) {

    return res.status(200).end();
  });
</code>
Comment: Is this actually a response from a slash command? I ask because the screenshot has a bot named "incoming-webhook," which, well, sounds like an incoming webhook. :-) Incoming webhooks don't have a concept of ephemeral messages. (Which user would even see the message?)
Comment: Thanks @smarx. That's correct. The tutorial that I was using had an incoming webhook posting to a channel from the slack slash command. There was no need of the incoming webhook. It took me a while to figure that out. The incoming webhook is always public. The slash command can be either ephemeral or in_channel.
Comment: Here's the tutorial that I was talking about. http://www.sitepoint.com/getting-started-slack-bots/
Comment: So is your issue resolved? (Are you able to get ephemeral messages working from the slash command?)
Comment: Yes @smarx. Thanks for your help. Sorry, for the late response. For whatever reason, I didn't see it.
Answer: Ephemeral messages are only supported in slash commands currently. From your screen capture it looks like you're sending your payload to an incoming webhook. Unfortunately, I can't find the wiki that backs this up, but here's another post with a similar answer: Slack API "attachments" not showing


Setting width of progress-bar (countdown) before first "tick" (no additional libraries)

Question: I'd like to set the width of a countdown progress-bar before the first tick gets triggered (without additional libraries, only with javascript, html and css in one code file)
I've tried to change the code (esp. the html code) many times and tested many examples from different references and this site as well, but it didn't work.
Can you give me some hints where to look in order to solve this problem.  You can copy my example code into a txt file and simply run it as html in your browser and you will see the problem. It's only about the bar width before the first tick, after that everything looks as intended.
I know that I've got to set the width somehow (normally in css or in the div line), but don't know how to make this work in this special case.

    <progress value="10" max="10" id="pageBeginCountdown"></progress>

 Time up in 10  seconds

</html

Answer: Add the following lines in your .css file:
progress[10] {
  width: 200px;
}

Modify width with your desired size.
Regards.
Comment: It works, but only with "progress". progress[value] didn't work.


Puppeteer: how to store a session (including cookies, page state, local storage, etc) and continue later?

Question: Is it possible to have a Puppeteer script that opens and interacts with a page, and then saves that browser sessions as-is, and have another script load that and continue from there?
By "browser session" I mean the currently loaded page including the page state (DOM space and javascript variables etc), cookies, local storage, the whole shebang. Basically everything it needs to continue exactly where the previous script left off.
If not, then is it possible to at least export and import cookies and local storage? So I can reload a particular page and continue processing, keeping any login or session data intact.
Comment: about the cookies: [link](https://stackoverflow.com/questions/56514877/how-to-save-cookies-and-load-it-in-another-puppeteer-session)
Comment: See also [How to manage log in session through headless chrome?](https://stackoverflow.com/questions/48608971/how-to-manage-log-in-session-through-headless-chrome)
Answer: I can't say for sure, but since Puppeteer is "just" a wrapper for Chrome DevTools Protocol (cdp), and cpd doesn't have a native "command" that does what you are asking for, it's not possible to do it for the whole shebang.
But you have options. One good option is to reutilize the same browser for the next script. You just need to pass the "userDataDir" option to puppeteer.launch command. Example: puppeteer.launch({ userDataDir: '/tmp/myChromeSession' });. Every puppeteer script that use this will use the same browser, so they will share the "permanent" cookies. The "session" cookies (or the ones that have an expiration time) sure get deleted, but this is the way that cookies are supposed to work.
Excerpt about User Data Directory:

The user data directory contains profile data such as history,
  bookmarks, and cookies, as well as other per-installation local state.

Despite this reference don't write nothing about Web Storage, it is preserved on the User Data Directory too. So, using this option you are good to go. I think is the best option for your case.
You have other options too, like copy just the cookies and Storage (localStorage and sessionStorage).
Copying cookies using puppeteer
With puppeteer, this process is very painful: you have to specify every origin you want to coope the cookies from. For example, if your site embed third-party things, like google signin or tracking, you have to copy cookies from "google.com", ".google.com", "www.google.com", etc. It's very very dumb and painful. Anyway, to copy cookies origin https://a.b.c, issue: const abcCookies = await page.cookies('https://a.b.c');
To restore them: await page.setCookie(...abcCookies);. Since they are json, you can serialize them and save to disk, to restore later.
Copying cookies using CDP
let { cookies } = await page._client.send('Network.getAllCookies');

Reference: Network.getAllCookies
To restore them, you use the Network.setCookies cdp method. Again, you can serialize those cookies and save to disk to restore later.
Copying Storage (localStorage and sessionStorage)
You can transfer you own origin Storage via const ls = await page.evaluate(() => JSON.stringify(localStorage)); and const ss = await page.evaluate(() => JSON.stringify(sessionStorage));. However you can't access other origins Storages for security reasons. Don't know CDP equivalent and think it doesn't exist yet.
Web Cache
If your site has a service worker, chances are that it save things on Web Cache API. I don't know if it make any sense to save this cached data, but if is important to you, you can transfer these cache too, but not using puppeteer apis or cdp. You have to use the Cache api by yourself and transfer the cache using page.evaluate.
IndexedDB
If you want to copy IndexedDB contents, you can use the cdp IndexedDB domain methods (like "IndexedDB.requestData") to get the data for any origin, but you can't set/restore this data. :)  You can however, in your own origin, restore the data programatically using page.evaluate.
Answer: The answer of Icrespilho is very valuable. He leaves two exercises for the reader and I have done one: IndexedDB.
Copying IndexedDB
He writes:

If you want to copy IndexedDB contents, you can use the cdp IndexedDB domain methods (like "IndexedDB.requestData") to get the data for any origin, but you can't set/restore this data. :) You can however, in your own origin, restore the data programatically using page.evaluate.

I have worked out reading the data as:
const indexedDB = await page.evaluate(async () => {
  const result = {};
  const databases = await window.indexedDB.databases();

  const connect = (database) => new Promise(function (resolve, _) {
    const request = window.indexedDB.open(database.name, database.version);
    request.onsuccess = _ => resolve(request.result);
  });

  const getAll = (db, objectStoreName) => new Promise(function (resolve, _) {
    const request = db.transaction([objectStoreName]).objectStore(objectStoreName).getAll();
    request.onsuccess = _ => resolve(request.result);
  });

  for (i = 0; i < databases.length; i++) {
    const db = await connect(databases[i])
    const dbName = db.name;
    result[dbName] = {}
    for (j = 0; j < db.objectStoreNames.length; j++) {
      const objectStoreName = db.objectStoreNames[j];
      result[dbName][objectStoreName] = []
      const values = await getAll(db, objectStoreName);
      result[dbName][objectStoreName] = values;
    }

  }
  return result;
});

I hope this helps anyone.
Comment: Here you are reading the IndexedDB, right? How do you set it?


How can I find an element of a particular type in a list, and also smart cast the result?

Question: Suppose I have a List<Animal>, and I want to find the first Dog in it. I then want to access some Dog-specific properties of the found Dog.
find doesn't really work:
val dog = animals.find { it is Dog }
// dog is of type "Animal?", but I want "Dog?"

I could use filterIsInstance:
val dog = animals.filterIsInstance<Dog>().firstOrNull()

But that goes through the whole animal list. I want it to stop when it finds the first dog. What is a built in method that does this?
Answer: You can use firstNotNullOfOrNull (which is a mouthful to say :D), with as? instead of is.
val dog = animals.firstNotNullOfOrNull { it as? Dog }

It applies the transformation to each element, and returns the first not-null transformation result, or null if there is no such result.
There is also the counterpart firstNotNullOf that throws an exception when there are no not-null results.
Answer: You can use sequences for lazy evaluations
Compare following code samples:
Eager
val firstString = listOf(1, "2", 3, "4", 5, "6")
        // following operations are applied to List
        .filterIsInstance<String>()
        .onEach { println(it) }
        .firstOrNull()

println("Result: $firstString")

Output:
2
4
6
Result: 2

Lazy
val firstString = listOf(1, "2", 3, "4", 5, "6")
        .asSequence()
        // following operations are applied to Sequence
        .filterIsInstance<String>()
        .onEach { println(it) }
        .firstOrNull()

println("Result: $firstString")

Output:
2
Result: 2

In both cases result is the same, but for lazy case no further steps are made after first match is found.


Can i use an other language instead of english for default django translation

Question: Can I use another language instead of english(say, french) for default django translation.
For example, instead for doing this:
messages.error(request, _('My message in english'))

I do this:
messages.error(request, _('Mon message en francais'))

Answer: Yeah, you could do that, and it would mostly work, but better would be to write them in English and then provide French translations (via the standard i18n approach), and to set the project's LANGUAGE_CODE to 'fr' as well.
That way, your code will be more easily reusable in other languages, and - perhaps more usefully to you if you're not worried about that - you'll be able to cleanly use French/other language translations already available in any third-party apps you want to add to your site, else you'll be mixing what Django thinks is default English (but is French) and thinks is French (and is French)
Allez! ;o)


Who is awarded the goal?

Question: If a footballer plays a free kick and the footballer intention is to play the free kick direct to the goal post, but it touches the footballer team mate before entering the goal post, who is awarded the goal? Is it the free kick player or his team mate who the ball touches?
Answer: Intention is irrelevant. The last attacker to play the ball will be considered the goalscorer, unless the goal is caused by the direct action of a defender and would probably not have scored otherwise.
Comment: @Nij, I believe, the extremely low **visitor number** is just a bug (we usually have a decent 6000-8000 here), it suddenly went down in [other communities](https://area51.stackexchange.com/proposals/7551/chess) as well. **Question rate** is an eternal problem of Beta sites, there's nothing much we can do. But the answer ratio is something that we the answerers can improve and I think it's something that frequent users should keep in mind.
Comment: The issue for us is that sports questions often have a single reasonable and correct answer - who did this, what is the rule, when or where did this happen, what is the number - unlike the science or technology or personal sites where multiple perspectives and explanations can be provided in the same space largely without repetition. I think on balance, if a question has more than two different answers here, the correct ones are all the same, or the question is OT/TB/UC/POB.
Comment: This way or another, we need more answers on questions. If studro summarized his comments within a separate answer, we would have had 2 useful answers with the same conclusion but with different approaches: yours (based on personal experience) and studro's (based on references).
Comment: This is generally correct. You won't be likely to find a source, because there are none. In most competitions, either the competition administrator, a committee or the referee makes the final decision, and how they do that is usually a matter for them.
Comment: [Here is some information](https://www.theguardian.com/football/2006/aug/23/theknowledge.sport) - potentially outdated now [2006] -  on the committee that decides in the Premier League.
Comment: [FIFA Magazine](http://www.fifa.com/news/y=1997/m=4/news=fifa-magazine-when-own-goal-not-own-goal-70226.html) also included an article about the topic in 1997 that may or may not be relevant anymore for their competitions.
Comment: @studro, these comments qualify to be a decent answer. Please keep in mind that we need to improve our [answer ratio](https://area51.stackexchange.com/proposals/27135/sports). It would be awesome if you could post a new answer with all these links.
Comment: If our answer ratio is a problem, our visitor numbers and question rate is a disaster. Having more answers for what is already here won't help a huge amount. @gdrt
Comment: I didn't add an answer as I thought both of these sources were somewhat outdated. They were added as comments in case Nij wanted to add them to the answer to provide background on what football governing bodies thought about deciding the goalscorer 10 - 20 years ago.
Answer: Touching the ball alone doesn't make the player the goal scorer. Usually there are a few points that have to be considered...

Would the ball go in without the player touching the ball?

If no the player who deflected the ball scored the goal. If yes it's up to the officials to decide (see below).

How far did he deflect the ball and did he distract the keeper or defenders enough? Would the keeper have saved it without that player interfering?

If the ball went far enough off the original direction it's usually the deflecting player getting the credit for the goal. There's no written rule about how far the ball has to be deflected into another direction, so it's up to the officials to decide. But again, touching the ball alone doesn't make that player the scorer. Deflecting the ball by a few inches doesn't do that either (usually).
For example:
The kick would land right next to the post and it would be a goal either way....

The ball rebounds off the leg of another player and the ball goes in at the other side of the goal. The deflecting player gets the credit (or an own goal if it was a defender).
The ball is only lightly touched by that player and doesn't change it's direction. The player who took the free kick gets the credit for the goal.

Who is awarded the goal?


Need more context for the Grafanalib Python3 library

Question: I'm building a project using python and grafana where I'd like to generate a certain number of copies of certain grafana dashboards based on certain criteria.  I've downloaded the grafanalib library to help me out with that, and I've read through the Generating Dashboards From Code section of the grafanalib website, but I feel like I still need more context to understand how to use this library.
So my first question is, how do I convert a grafana dashboard JSON model into a python friendly format?  What method of organization do I use?  I saw the dashboard generation function written in the grafanalib documentation, but it looked quite a bit different from how my JSON data is organized.  I'd just like some further description of how to do the conversion.
My second question is, once I've converted my grafana JSON into a python format, how do I then get the proper information to send that generated dashboard to my grafana server?  I see in the grafanalib documentation the "upload_to_grafana" function used to send the information and it takes in the three parameters (json, server, api_key), and I understand where its getting the json parameter from, but I dont get where the server information or API key are coming from or where that information is found to be input.
This is all being developed on a raspberry pi 4 just to put that out there.  I'm working on a personal smart agriculture project as a way to develop my coding abilities further, as I'm self taught.  Any help that can be provided to help me in my understanding is most appreciated.  Thank you.
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: create an API key in Grafana configuration ..The secret key that u get while creating is the API key ..Server is localhost:3000 in case of installed grafana
Comment: Welcome! Please read https://stackoverflow.com/help/how-to-answer and improve your answer (add link to docs, for example).


Is Clustering really = High Availability?

Question: These days clustering is becoming synonymous to high availability. As an enterprise architect I have to shake my head in disbelief. IMHO, clustering can be a component of HA but is far from being HA in itself. I'm always used to approaching HA as a solution involving multiple components from replication to mirroring to DR.
Does anyone else feel the same on this topic? Or am i just an grumpy old architect!
Answer: No, you are obviously right. HA is a goal, and clustering is one technology that helps you reach it.
Clustering will not get you HA if for example everything goes via a single switch...
Answer: Depends on your definitions I've always felt - I've always thought integrity of data is key component of HA and clustering doesn't give you this given the shared storage it employs.  Any cluster needs to be backed up by a robust backup strategy that would include a blend of mirrors, replication and off-line backups as appropriate to the requirements of the system you're protecting. I've seen first hand examples of a cluster breaking down and there being no other plans in place.
Answer: Clustering IMO is just like you thought, just a part of HA. It adds redundancy to prevent single system failure. However, just like any good HA environment, you should remove any single point of failure. Just because the servers are clustered, that doesn't assume multi-pathing to your storage, redundant switches in your network, or even redundant power circuits and PDUs in your rack. Replication is huge too, site failure can kill even the best HA solution unless data goes offsite (tape or otherwise).


Using rules, how do I assign an action to a vbo list item based on its position in the list?

Question: I'm using rules and conditional rules. I have an action set that is using a vbo list (4 node titles sorted by post date desc) to flag nodes on the list.  This works fine. However, I need to make the first item on the list sticky and the 2nd item on the list promoted.  Then I need to remove sticky and promoted from the 3rd item.
Do I need to be using alert_entity_list:0 and alert_entity_list:1 or should I be looking for alert-list-item:0, etc. ... or am I way off base?
Comment: I figured it out.  For any who are looking for same information, the data selector would be the entity-list:0 for the 1st item in the list.
Answer: I should have posted this as my answer and not as a comment to my question.  As stated above, the answer would be entity-list:0 token.


Which type of singularity does this complex function have at z = ∞?

Question: I'm trying to classify the type of singularity at z = ∞ (the point at infinity) of the complex function:
click to see the equation
Up to now, I've just been able to prove that ∞ is not a pole. So I would like to prove that it is either an essential singularity or a removable singularity. Thank you for your suggestions!
Comment: See what happens when you put $z=n \ge 2$ and then $z=in$
Answer: At , $z=n$ for each $1\neq n\in\mathbb{N}$ , $f(z)$ have zeros.
As, limit point of zeros is a isolated essential singularity.
So, $z=\infty$ is a isolated essential singularity of $f(z)$.
Comment: I don't understand what are you saying? And by the way, the given function is undefined at $z=\infty$. Also, one thing , a complex function is well defined at $\infty$ only if function is constant.


How to write a Declaration File for a Library that exports an already typed Library

Question: I want to write an index.d.ts for a library, that puts a thin abstraction layer over some exports of an already typed library. The rest is a 1:1 export from the original library. How would I write the index.d.ts declaration file ?
Situation: Exporting of already typed library
The library imports everything from React-Router-Dom (which is very well typed) in its index.js, sugars a few exports, than exports everything in its own index.js.
    import * as ReactRouterDom from 'react-router-dom'

    // (...modification on some ReactRouterDom props)

    module.exports = {
      ...ReactRouterDom,
    }

Question: Declaration File
I'd PR the index.d.ts (with eventual type dependencies) to this new library which would be gladly merged. So it does not have to live on Definitely Typed.
Due to a lack of experience, I am not sure if I need to copy all the definitions for ReactRouterDom or rather, how such a problem is approach in general.
Thanks alot
Dino
Answer: You can re-export the declarations:
// your-lib/index.d.ts
export * from 'react-router-dom'
export const Prompt = 42

Would be a declaration file which is identical to react-router-dom except Prompt is now a number instead of what it was before.


Doubt in a particular condition of Laurent series

Question: I was reading about Laurent series from the wikipedia and in one of the conditions of Laurent series it is mentioned that

On the boundary of the annulus, one cannot make a general statement, except to say that there is at least one point on the inner boundary and one point on the outer boundary such that f(z) cannot be holomorphically continued to those points.

as I don't know much about complex analysis other than some basic stuff
Is "holomorphically continued" used there is same as analyticity at the boundary? or it is something else and if it is then please anyone explain it in layman's terms.
Answer: "Holomorphically continued" means that if you have your Laurent series $f(z)$ in the annulus $|z-z_0| < R$, you can define a function $\tilde{f}(z)$ on some set $S$ that intersects the annulus, such that $\tilde{f}(z)$ is holomorphic.
It is a similar idea to how you can treat the (shifted) gamma function as an analytic continuation of the factorial function - the factorial is defined only on the natural numbers, but the gamma function is analytic on (most of) the complex numbers.
Comment: The annulus is defined as being the maximum extent where the Laurent series is guaranteed to converge, so there is always going to be a point on that annulus where it breaks down.
Comment: Thanks for answer! although it is not that easy for me to understand everything u wrote, can u please tell is it necessary that there should be atleast one singularity at the both boundaries of annulus in Laurent series expansion"?


Trying to increase file upload limit for phpmyadmin

Question: I'm having an issue with phpmyadmin where the max file upload size stays constant at 128MiB. I have read other issues extensively and have already run phpinfo() to make sure i'm loading the right file. The ini files it is loading are:
Configuration File (php.ini) Path = C:\Windows
Loaded Configuration File = C:\wamp\bin\apache\apache2.4.9\bin\php.ini
These files have been updated so that the following parameters are as follows:

memory_limit = 1500M
upload_max_filesize = 1028M
post_max_size = 1028M
max_execution_time = 500

Further more the phpinfo() function returns these values for both local and master values. Additonally, I am using wamp server and have not only restarted all the services as well as restarted my computer. Despite this the phpmyadmin file upload function stays at 128MiB.
The reason this is an issue is due to the fact the data I need to import is an extremely large .csv the current one is 350MB however I expect to have to import one that is at least 3GB. I'm completely at a loss as to how I should continue with this.
Comment: Might be a phpmyadmin limitation,try another client like http://www.heidisql.com/
Comment: possible duplicate of [Import file size limit in PHPMyAdmin](http://stackoverflow.com/questions/3958615/import-file-size-limit-in-phpmyadmin)
Comment: Using phpmyadmin to import multi-gigabyte csv files will likely fail, and will definitely be hard to verify. Split up those huge files into 50MiB chunks or load them another way. See this https://stackoverflow.com/questions/33944872/import-big-csv-file-into-mysql
Comment: https://youtu.be/LKEZPVujTgI see here
Answer: Find the php.ini file.
Find this and change it:
post_max_size = 128M

Change the values of theese like this
memory_limit = 2000M
post_max_size = 4000M
upload_max_filesize = 5000M

Restart apache, and you are good to go.
EDIT:
As you can see, memory_limit is lower than post_max_size that is lower than upload_max_filesize. You need to put values like these in order to workaround upload.
Comment: Values. As you can see, memory limit is lower than post_max_size that is lower than upload_max_filesize. You need to put values like these in order to workaround upload.
Comment: If you upload a file of size `5000M` will you get it in `$_FILES` and if you want to read this file can you with the above limits?
Comment: He needs to import file that is more than 3GB. So, draw conclusion from this.


getline skipping first input character c++

Question: So I have been making this program for a while now. I have looked all over the internet and none of the solutions I have found work. Every time I put in my input in the arr[i].question and arr[i].answer, it says that my question is wrong without me giving a answer to the question. I have tried using cin.ignore(), cin.clear(), and cin.sync(). I might have been using them in the wrong places but i'm not sure. I might be confusing, so just look at the code.
Here is the input format.
    cin >> count;
cin.ignore();

for(int i =0; i < count; i++){
    cout << "Enter the question.\n" << endl;
    //enter the question

    getline(cin, arr[i].question);
    cin.ignore();

    cout << "Enter the answer.\n" << endl;
    //enter the answer

    getline (cin, arr[i].answer);
    cin.ignore();

}

and here is the out put format to quiz you.
    for(int j =0; j < count; j++){
    cout << "\n" << arr[j].question << endl;
    getline(cin, userguess);

    if(arr[j].answer.compare(userguess) !=0){
        cout << "Wrong. Keep trying!\n";
        incorrect++;
        total++;
    }
    if(arr[j].answer.compare(userguess) ==0){
        cout << "Nice job. Keep it up!\n";
        correct++;
        total++;
    }

Whenever I put in my question it doesn't output a question in the console or let me put in an answer. It just says wrong.
A little help please?
edit: here is the whole code:
// final PROJECT.cpp : Defines the entry point for the console application.

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include <cstdio>
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <cstdlib>

using namespace std;

struct flashcards{
string question;
string answer;
}FC1, FC2, FC3, FC4, FC5, FC6, FC7, FC8, FC9, FC10, FC11, FC12, FC13, FC14, FC15, FC16, FC17, FC18, FC19, FC20;

int _tmain(int argc, _TCHAR* argv[])

{
system ("color 4B");
string userguess;
string again;
flashcards arr[10000];
int count;
float correct=0;
float incorrect=0;
float total=0;
//one major problem, wont accept spaces.
cout<< "Flash Card Runner\n";
cout<< "This program was made by Jacob Malcy\n";
cout<< "Beta 3.8\n";
cout<< "IN ORDER FOR YOU TO HAVE MULTIPLE WORD FLASH CARDS,\n";
cout << "SKIP NUMBER ONE FLASHCARD QUESTION AND ANSWER!\n";
cout<< "This bug is currently being worked on.\n";
cout << "If you happen to have problems conntact Jacob.\n";
int choice;

cout<< "Would you like to create or test? Enter 0 for create and 1 for test.\n";
cin >> choice;
if(choice==0){
    //Creating new deck of cards
cout<< "How many flashcards do you want?\n";
cin >> count;
cin.clear();

for(int i =0; i < count; i++){
    cout << "Enter the question.\n" << endl;
    //enter the question

    getline(cin, arr[i].question);
    cin.ignore();

    cout << "Enter the answer.\n" << endl;
    //enter the answer

    getline (cin, arr[i].answer);
    cin.ignore();

}
}
else if(choice==1){
    //Reading in new file
    cout << "Reading file...\n";

    string line;
    ifstream myfile ("Save.txt");
    if (myfile.is_open())
    {
        count = 0;

        while ( myfile.good () )
        {
            getline (myfile,line);
            arr[count].question = line;
            cout << line << endl;

        getline (myfile,line);
        arr[count].answer = line;
        cout << line << endl;
        count++;

        }

        myfile.close();
    }

    else cout << "Unable to open the file";
}

do
{

for(int j =0; j < count; j++){
    cout << "\n" << arr[j].question << endl;
    getline(cin, userguess);

    if(arr[j].answer.compare(userguess) !=0){
        cout << "Wrong. Keep trying!\n";
        incorrect++;
        total++;
    }
    if(arr[j].answer.compare(userguess) ==0){
        cout << "Nice job. Keep it up!\n";
        correct++;
        total++;
    }

}
cout<< "The number of correct questions answered was: \n" << correct << endl;
cout<<"The number of total questions answered was: " << total <<"\n";
    cout<< "The number of incorrect questions answered was: \n" << incorrect << endl;
    //cout<< total;
    float percent = (correct/total)*100;
    cout<< "The total percent you got right is: \n" << percent << "% correct" << endl;
    system("pause");
    cout << "Would you like to run the quiz again?\n"
    << "Type y or Y to run this again. If not, enter any other letter.\n";
    cin >> again;
    if((again == "y") || (again == "Y")){
    correct=0;
    incorrect=0;
    total=0;
    }

}while((again == "y") || (again == "Y"));

ofstream myfile ("Save.txt");
if (myfile.is_open())
{

    for(int i =0; i <count; i++){

        myfile << arr[i].question << "\n";
        myfile << arr[i].answer << "\n";
    }
    myfile.close();

    }
else cout << "Unable to save file";

cout << "Your finished with the quiz. Goodbye!\n";

system("PAUSE");
return 0;
}

When I run it, it comes out like this
    Flash Card Runner
This program was made by Jacob Malcy
Beta 3.8
IN ORDER FOR YOU TO HAVE MULTIPLE WORD FLASH CARDS,
SKIP NUMBER ONE FLASH CARD QUESTION AND ANSWER!
This is a bug is currently being worked on.
if you happen to have problems, conntact Jacob.
Would you like to create or test? Enter 0 for create and 1 for test.

If i enter zero:
How many flashcards do you want?

say I enter two 2
Enter the question.

Hi ho
Enter the answer.

Merry oh

enter the question.

fi fa
enter the answer.

fo fum

then it just skips to:
Wrong. Keep trying!

erry oh

Before wrong, it should display the first question, and give me the oppertunity to answer.
It just says wrong before i can. then it displays the answer with the first character missing. There you go.
Comment: `cin.sync` is not guaranteed to do what it says, so I wouldn't rely on that behaviour.
Comment: It's not at all to me clear what you are saying. Could be post a complete program and state clearly what you input and what you see in the console. Just cut and paste the whole program, and the whole console session. And jrok is correct, cin.ignore() is either incorrect or sub-optimal on all the occasions you are using it. cin.sync() and cin.clear() are irrelevant. I guess you read all those posts on the internet without gaining an understanding of the issue.
Comment: Alright here is the whole code.
Comment: Jrok, when I get rid of any cin.ignore();, it simply skips all of the input and only states the output. And yeah i'm trying to get rid of the newline. I just cant figure out why it skips.
Answer: I presume you're calling ignore right after getline to get rid of the trailing newline character.
Do not do that. std::getline already extracts the newline character from the stream (and discards it), so you're ignoring the first character of the next line.


Is there any online tutorial explains how can I map the requested URL to actions' code in drupal 7?

Question: I'm beginner to Drupal 7. As I know, when the user request for example the URL: (www.example.com/node/123) then the Node module will responsible on responding to this request. How can I create a simple php function in my custom module so that it can respond to a specific request generated from my custom page or my custom form submission? for example: www.example.com/mymodule/blablabla?
Comment: did you try pathauto mmodule ?
Comment: Actually no. but I believe that redirecting the http request to php function to handle the request is the functionality of the core/bootstrap of Drupal, right?
Answer: You are looking for hook_menu(), you will need to implement this hook on your custom module to register path in drupal.

Define menu items and page callbacks.
This hook enables modules to register paths in order to define how URL
  requests are handled. Paths may be registered for URL handling only,
  or they can register a link to be placed in a menu (usually the
  Navigation menu). A path and its associated information is commonly
  called a "menu router item". This hook is rarely called (for example,
  when modules are enabled), and its results are cached in the database.

Since you are beginner, First I would suggest you to learn about hook system for drupal.
Checkout this answer for detailed use of hook_menu.
Comment: No, making a single page request will not invoke the callback function of every single router path. That would be insane
Comment: You mean that any requested URL or form data submission to Drupal will be handled by invoking all functions in all modules that implements hook_menu()? even if it is form data submission?
Comment: short answer will be yes.. you will need to explore more on `hook_menu` and the options available.


what is the difference between Metropolis-Hastings and my approach? Will my approach's distribution be different from that of MH?

Question: Problem Statement, suppose I want to sample from a distribution p(x) =  f(x)/NC, where NC is a normalizing constant. It's hard to sample from p(x). So one way is to use MH algorithm. But it's computationally expensive. So I plan to do the following: generate X randomly, X is an array containing all xs, pass to f to get f(X), array of fs, and then the discrete PDF is given by p(xi) = f(xi)/sum(f(X)), and then choose points from this discrete PDF.
Comment: It is unclear what you mean by "generate X randomly". Is it uniformly over a certain (necessarily bounded) set? From another distribution?
Answer: Your approach is called importance sampling (specifically, I think, self-normalised importance sampling).  It can be used for Bayesian inference
The difficulty with this approach is that the number of points you need can be very large when the space is high-dimensional.  In particular, if $f$ is a posterior distribution (as is most often the case in MCMC), it is likely to be concentrated on a small volume of the parameter space. If you sample $X$ from some other unrelated distribution, you will need a very large sample space to get any points where the posterior density is high.
Also, if you have an unbounded space you can't even sample uniformly from it. You need to rescale your $p(x)$ by the density you're actually sampling the $X$s from, and it's important that this density goes to zero no faster than $f$ does in the tails, otherwise you get very influential points in the tails.
The point of MH and other MCMC methods is that they can sample preferentially from areas where $f$ is large, and so you end up needing fewer points than if you just sampled and reweighted. The improved targeting can compensate for any extra computation per point.
Comment: Thank, this really helps. Btw, do you have any reference for faster implementation of MH?


Calcular média em C utilizando vetores

Question: iniciei minha jornada no C há dois dias atrás. Fui tentar desenvolver uma função que calculava a média de determinados números de um vetor. A função está com algum problema já que era para retornar o valor de 4,5 e está retornando o valor de 4.00. Será que alguém poderia me ajudar?
#include <stdio.h>

int mediaVetor(float vet[], int tam){
  float media, soma = 0;
  int i;

  for(i =0; i<tam; i++){
    soma = soma + vet[i];
  }
  media = (float) soma/tam;

  return media;
}

int main(){
  float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
  float resultado;

  resultado = mediaVetor(vetor, 6);
  printf("A media dos vetores e de %.2f\n", resultado);
}

Comment: O tipo de sua função deveria ser float e não int. float mediaVetor(float vet[], int tam){
Comment: Nossa, não tinha reparado nisso. Obrigado.
Answer: O tipo de retorno da função deve ser float. O cast em media = (float) soma / tam é desnecessário, pois o valor da operação já é um float.
#include <stdio.h>

float mediaVetor(float vet[], int tam) {
    float media, soma = 0;
    int i;

    for(i = 0; i < tam; i++){
        soma += vet[i];
    }

    media = soma / tam;

    return media;
}

int main(){
    float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
    float resultado;

    resultado = mediaVetor(vetor, 6);
    printf("A media dos vetores e de %.2f\n", resultado);
}

Answer: O problema está na declaração do mediaVetor. Ao invés de int, usa float. Como abaixo:
#include <stdio.h>

float mediaVetor(float vet[], int tam){
  float media, soma = 0;
  int i;

  for(i =0; i<tam; i++){
    soma = soma + vet[i];
  }
  media = (float) soma/tam;

  return media;
}

int main(){
  float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
  float resultado;

  resultado = mediaVetor(vetor, 6);
  printf("A media dos vetores e de %.2f\n", resultado);
}

Calcular média em C utilizando vetores


Why semaphore table is not using MEMORY as storage engine?

Question: Drupal's table "semaphore" is using MyISAM (Drupal 6). I was wondering why it's not using MEMORY as storage engine?
The only thing that I could think of is that Drupal needs locking/semaphore data after MySQL restart. But the point with semaphore is that it should not have important data...
Am I missing something?
Answer: Drupal supports multiple database backends, but both MEMORY and the concept of storage engines as a whole is MySQL specific. Therefore, the Schema API has no support for specifying the storage engine.


On an exact sequence of complex vector spaces

Question: Let us consider the following  exact sequence of complex vector spaces:
$0 \to A \to B \to C \to D \to E \to.....\to 0$, where $E$ and the later vector spaces are not necessarily zero.
By rank nullity theorem one can say $\text{dim}(B) \leq \text{dim}(A) +\text{dim}(C)$, can we extend this inequality involving $A,B,C,D$ as something like $\text{dim}(B)+ \text{dim}(D)\leq \text{dim}(A) +\text{dim}(C)$?
I know that one can equate the complete sequence with alternating signs, but I'm looking for an inequality only involving first $4$ spaces.
Any remark from anyone is welcome.
Comment: I suspect that it's the reverse, i.e. $\dim(B) + \dim(D) \geq \dim(A) + \dim(C)$
Answer: We are given the following information:

There is an injective map $f:A \to B$ (so that $\dim f(A) = \dim A$),
There is a map $g:B \to C$ whose kernel is $f(A)$,
There is a map $h:C \to D$ whose kernel is $g(B)$.

Applying the rank-nullity theorem to $g,h$ yields
$$
\dim(B) = \dim \ker g + \dim g(B) = \dim(A) + \dim g(B)\\
\dim(C) = \dim \ker h + \dim h(C) = \dim g(B) + \dim h(C).
$$
Subtracting these equations yields
$$
\dim(B) - \dim(C) = \dim(A) - \dim h(C) \geq \dim(A) - \dim(D) \implies\\
\dim(B) + \dim(D) \geq \dim(A) + \dim(C).
$$

In general, we can extend this result as follows. As you have correctly noted, the long exact sequence $0\to A_1 \to A_2 \to \cdots \to A_n \to 0$ yields the equality
$$
\dim(A_1) - \dim(A_2) + \cdots + (-1)^{n-1} \dim(A_n) = 0
$$
Let $f_i$ denote the map from $A_i \to A_{i+1}$. Truncating this sequence yields the "left exact" sequence $0\to A_1 \to A_2 \to \cdots \to A_k$. With this, we have the equality
$$
\dim(A_1) - \dim(A_2) + \cdots + (-1)^{k-1}\dim f_{k-1}(A_{k-1}) = 0.
$$
Using the fact that $\dim f_{k-1}(A_{k-1}) \leq \dim(A_k)$ yields the kind of inequality that you're after. For $k = 2p+1$, we get
$$
\sum_{i=1}^p \dim A_{2i} \leq \sum_{i=0}^p \dim A_{2i+1}.
$$
For $k = 2p$, we get
$$
\sum_{i=1}^p \dim A_{2i} \geq \sum_{i=0}^{p-1} \dim A_{2i+1}.
$$
Comment: @HARRY What about $\dim(B) \leq [\dim(A) - \dim(D)] + \dim(C) + \dim(E)$?
Comment: @HARRY I get that, but I'm suggesting that introducing this one other term could be a way to salvage whatever it is that you were trying to do
Comment: thanks. I was looking for an upperbound of $\text{dim}(B)$ interms of $\text{dim}(A)-\text{dim}(D)$ and $\text{dim}(C)$. But it seems that it is not possible.
Comment: I meant upperbound only involving $A,C,D$ not the other terms.
Comment: @Benn Grosmann, My point of asking this question involving the first four terms was that I wanted to avoid the fifth terms onwards, involving them the picture becomes more difficult to compute.


Question about fixed effects, and state-by -time fixed effects

Question: I have seen papers at the US level where they include county fixed effects, and state-by-year fixed effects, i.e.:
$y_{c,t}$ = $\beta$$x_{c,t}$ + $\lambda_c$ + $\mu_{s,t}$ + $\eta_{c,t}$
where c indexes county, t time, and s states, opposed to a more typical county and just year fixed effect.  $\lambda_c$ are county fixed effects, $\mu_{s,t}$ are state-year fixed effects, and $\eta_{c,t}$ is the error term.  They referred to this as 'comparing counties within states'. How does this accomplish that goal? so is this estimator of $\beta$ than estimating $dy/dx$ within a state, and then averaging the state effects over each state?
Comment: You also have a county x time FE here, but don't mention this in the text. Or is that meant to be the error term?
Comment: Sorry yes $\eta_c,t$ is the error term.  I will edit that into the question
Answer: Consider first the simpler regression:
$$
y_c = \beta x_c + \mu_s + \eta_c
$$
In this regression, the idea is to use the variability of $x$ across counties within states to identify $\beta$. Why would you want that? Maybe because other policies are implemented at the state level that might influence both $x$ and $y$. In this case, omitting the state fixed effects $\mu$ would allow one to use both the cross-county and the cross-state variability of $x$, which might cause a bias.
Running this fixed-effect regression is exactly equivalent to centering your $y$ and your $x$ by removing the state average to each county-level measure and run the simple regression of the centered $y$ on the centered $x$. Or, as you put it, running one regression per state, and then average all state-specific estimates.
Now, let's go back to your specification:
$$
y_{ct} = \beta x_{ct} + \lambda_{c} + \mu_{st} + \eta_{ct}
$$
We are not only using the within-state variability in this case. For instance, if $x$ was varying across counties but constant over time, we could not identify $\beta$. The presence of $\lambda_c$ means that we are identifying $\beta$ from the variability of $x$ over time and across counties within states.
This is a very flexible specification because it allows the different states to have arbitrarily different time evolutions in $y$, and counties to have arbitrarily different levels of $y$. For this reason, it is also quite demanding on the data, and you end up throwing away a lot of the variability in $x$, leading to less precise estimators.
Note that differentiating this equation over time leads to:
$$
\Delta y_{ct} = \beta \Delta x_{ct} + \Delta \mu_{st} + \Delta \eta_{ct}
$$
with $\Delta X_t$ defined as $X_t - X_{t-1}$.
In differences, this model is therefore close to the first one: we rely on the within-state cross-county variability of the time difference of $x$.
Comment: Thank you! I think this is making a lot of sense to me, particularly thinking of the logic in the differenced specification


Unable to set field collection field value on form validation

Question: The question might look similar to How to form_alter fields attached to an unlimited field collection? but I am more concerned about "values not saved after custom validation"
I have a field collection "field_assignments" consists of:

field_check_user: A user reference field
field_assigned_booklets: An integer field
field_total_cost: A hidden field (used in validation handler for calculation)

I have content type "marking" having this field collection (unlimited values) along with a field_rate. I have alter node editing form and defined a custom validation which is working fine. The problem is that I cannot update the field collection item "field_total_cost" value in custom validation function. The validation function is
function _additional_validate($form, &$form_state) {
   // If rate is set to 100 and assigned booklets are 5; this should result 500
   $tc = $form_state['values']['field_assignments']['und'][0]
         ['field_assigned_booklets']['und'][0]['value'] * $form_state['values']['field_rate']['und'][0]['value'];

   $form_state['values']['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'] = $tc;
}

If I dpm $form_state, I can see that the ['field_total_cost']['und'][0]['value'] is updated (see image below) but when the node is submitted, it does not show that value in node view and does not save that value in the database. How can I save a value in field collection field?

I tried form_set_value() but couldn't understand how to set value for compounded fields (field collection in this case, I'll be thankful if someone can show how can I construct that "#parent" stuff with these fields). The code with form_set_value() I tried:
 // testing on a single field - works perfectly
 form_set_value($form['field_rate']['und'][0]['value'], $tc, $form_state);

 // does not update the value
 form_set_value($form['field_assignments']['und'][0]['field_total_cost']['und'][0]['value'], $tc, $form_state);

P.S: I have written 'und' instead LANGUAGE_NONE for ease
Answer: Use Computed field instead of doing it yourself! Don't use _validate, just use _compute.

Change field_total_cost to a computed field, saving as decimal.
Create a custom module and add the following (much clearer than using Computed Fields settings inputs - yuk)

Do something like the following :
/**
 * Computed field for - field_total_cost
 */
function computed_field_field_total_cost_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $tot   = 0;
  $books = 0;
  $rate  = 0;
  if (isset($entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'])) {
    $books = $entity->field_assigned_booklets[LANGUAGE_NONE][0]['value'];
  }
  if (isset($entity->field_rate[LANGUAGE_NONE][0]['value'])) {
    $rate = $entity->field_rate[LANGUAGE_NONE][0]['value'];
  }
  $tot = $books * $rate;
  $entity_field[0]['value'] = number_format((float) $tot, 2, '.', '');
}

/**
 * Display for - field_total_cost
 */
function computed_field_field_total_cost_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return '£' . number_format($entity_field_item['value'], 2);
}

I obviously don't know what your calculations are like but you get the idea.
This will calculate and populate the Total Cost field per field collection.
OR
If you still want to do it on validate you (afaict) can't do it on node_validate but you can on a field validate. So you need to add a custom validate function to your Field Collection field, then it should work as you think.
Add a custom validate callback on hook_field_widget_form_alter
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add custom validation hooks for Field Collections.
  if ($context['field']['field_name'] == 'field_assignments') {
    array_unshift($element['#element_validate'], 'MYMODULE_field_assignments_validate');
  }
}

Create the custom validate function and set the value similar to how you suggested
/**
 * Custom validate function for field_assignments.
 *
 *  @see MYMODULE_field_widget_form_alter()
 */
function MYMODULE_field_assignments_validate($element, &$form_state, $form) {
  form_set_value($form["field_assignments"][LANGUAGE_NONE][0]['field_total_cost'], array(LANGUAGE_NONE => array(0 => array('value' => 123.456))), $form_state);
}

I obliviously left out any logic in this example, but you get the idea :)


alinhar e centralizar imagem e titulo

Question: Olá.
Eu queria centralizar e alinhar o me H1 e H2 com a Imagem

Vermelha

100

Comment: Isto responde à sua pergunta? [Como centralizar a imagem?](https://pt.stackoverflow.com/questions/270520/como-centralizar-a-imagem)
Comment: É interessante mostrar sua tentativa.
Answer: Adicione o css
.bike {display: flex; justify-content: center}
.cor {display: flex; justify-content: center; width: 100%}
.preco {display: flex; justify-content: center; width: 100%}

O código completo ficaria
<!DOCTYPE html>

Vermelha

100

Ou você poderia ainda de forma mais simples colocar o css
li {display: flex; flex-direction: column; align-items: center}

alinhar e centralizar imagem e titulo


How does Drupal determine the context in which to display the admin theme?

Question: One of the great things about Drupal 7 is the inclusion of an administration theme, Seven.
How does Drupal determine whether to display the administration theme or the site's theme?
Is it path-based (everything under /admin), or something else?
Answer: There is now a hook for this: hook_admin_paths(). As usual, the default configuration is in system_admin_paths() but there are many other implementations in core, search for _admin_paths.
Comment: Oh that is awesome: if Drupal 6's motto was "there's a module for that", Drupal 7's should be "there's a hook for that". I was also interested in how I could check if the page I'm on is an admin path, but using your info I was able to find it:  [`path_is_admin()`](http://api.drupal.org/api/drupal/includes--path.inc/function/path_is_admin/7)
Answer: Here is an example for using hook_admin_paths to display the advance help + user login pages in the admin theme.
<code>/**
 * Implement hook_admin_paths(),
 * to define which paths will be displayed in the admin theme.
 */
function objet_admin_paths() {
  $paths = array(
    'help*' => TRUE, // the advanced help module
    'user*' => TRUE, // User login screens
  );

  return $paths;
}
</code>


Visual Basic 2010 String Containing a Speech Mark

Question: How can I make a speech mark in a string? The following shows the whole of the line and all code after that (With the Express IDE) to be a comment as well:
Variable = "\""

Comment: possible duplicate of [What is the Visual Basic (VB) equivalent of \ in C#?](http://stackoverflow.com/questions/1274079/what-is-the-visual-basic-vb-equivalent-of-in-c)
Answer: Try
Variable = """"

Comment: its basically a bit like everything is a literal string @"""" in c# = """" in vb.net
Answer: I prefer Chr(34) or Convert.ToChar(34)


Using multiple if else statements and why they loop?

Question: When I type in this code it gives me a return that once I use yes for the first time, on the name, it uses that return for all of them for example: if I said my name is Justin, and I said that "Yes" it is, then say I mistyped my age, then it would not give me a chance to change it, it would say "Great!". How do I fix this? I am in 9th grade so I don't know too much about programming, sorry for the noob question. Thanks in advance!
import java.util.Scanner;
public class helloworld_main {
private static Scanner scan;

public static void main(String args[])
{

    scan = new Scanner(System.in);
    String name, age, year, yes, no, no1, no2;

    System.out.print("Please enter your name --> "); // user prompt
    name = scan.nextLine();

    System.out.print("Please enter your age --> "); // user prompt
    age = scan.nextLine();

    System.out.print("Please enter the year you were born --> "); // user prompt
    year = scan.nextLine();

    // Their Name
    System.out.println("So your name is... " + name + ". Right?"); // correction if name is not correct
    yes = scan.nextLine();

        if ("Yes".equals(yes))
        {
                System.out.println("Great!");
         } else {
                    System.out.println("Oh. Please retype it.");
                    no = scan.nextLine();
    System.out.println("Hello, " + no);
         }

        // The Age
    System.out.println("The age you entered is..." + age + ". Right?");

        if ("Yes".equals(yes))
        {
            System.out.println("Great!");
        } else {
                System.out.println("OK. Please reenter your age.");
                no1 = scan.nextLine();
        System.out.println("OK, I love " + no1 + " year olds!");
        }

        // Year Born
    System.out.println("The year you were born is... " + year + ". Right?");

        if ("Yes".equals(yes))
        {
            System.out.println("Fantastic!");
        } else {
                System.out.println("Ok then, please tell me what year you were born again.");
                no2 = scan.nextLine();
        System.out.println("Cool! I know someone else born in " + no2);
        }
    scan.close();

}

}
Comment: In eclipse you can debug your app and step each line of code so you can see exactly what's happening.  Here is a [tutorial](http://www.vogella.com/tutorials/EclipseDebugging/article.html) on debugging java in eclipse.
Answer: You need to read the user input again after you prompt for it again. Add:
yes = scan.nextLine();

after:
System.out.println("The age you entered is..." + age + ". Right?");

and:
System.out.println("The year you were born is... " + year + ". Right?");

Comment: Personally I think learning how to debug would be more useful than giving them an answer.  As you can see [here](http://stackoverflow.com/questions/28590089/how-to-only-print-else-and-not-the-if), they are going to ask a question anytime there's a problem and not know how to find the problem themselves.


AngularJS - Filter view by month with ng-click

Question: I would like to filter my view with a simple link. I have several objects which all contain a date. Eg. If I click March only data with "Startdate" March should be displayed. I searched the web but found nothing which worked for me. This is my json object and the criteria should be "Startdate".
trips.son
[{
  "Startdate": "Thu Jan 02 2014 00:00:00 +0100",
  "DAYS": [{
    "DATE": "Thu Jan 02 2014 00:00:00 +0100",
    "IATA": "TXL",
    "DUTY": "6:10"
  }]
}, {
  "Startdate": "Sun Jan 05 2014 00:00:00 +0100",
  "DAYS": [{
    "DATE": "Sun Jan 05 2014 00:00:00 +0100",
    "IATA": "CBTH",
    "DUTY": "8:07"
  }]
}, {
  "Startdate": "Wed Sep 24 2014 00:00:00 +0200",
  "DAYS": [{
    "DATE": "Wed Sep 24 2014 00:00:00 +0200",
    "IATA": "BCN",
    "DUTY": "9:35"
  }, {
    "DATE": "Thu Sep 25 2014 00:00:00 +0200",
    "IATA": "BCN",
    "DUTY": "15:34"
  }]
}, {
  "Startdate": "Sat Sep 27 2014 00:00:00 +0200",
  "DAYS": [{
    "DATE": "Sat Sep 27 2014 00:00:00 +0200",
    "IATA": "CPH",
    "DUTY": "4:44"
  }]
}]

Here you can see what I mean:
UPDATED: plnkr
By default only January should by displayed - changing the view when each link is clicked !
Comment: I'm confused, the dropdown filter appears to be working correctly in the plnkr that you posted.  did you find the problem or are you having some other issue?
Comment: there is a problem with my plunker ! it won't show up the actual version ! nevertheless I just found a way of doing what I want ! I will post it soon
Answer: I found a way which works for me ! Maybe not the best but it will do the job.
Added StartdateMonth as the name of the month to my scope:
var date = new Date($scope.trips[i].Startdate);
            $scope.trips[i].Startdate = date;
            var names = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
            $scope.trips[i].StartdateMonth = names[date.getMonth()];

create ng-click for tab:

Januar

Februar

finally add the filter:


Looking for a "nice" Recurrence relation....

Question: I'm want to build a game (with steps) that the solution have a Recurrence relation, i.e. - to solve the game you have to move from point A to point B, from point B to point C...(kind of a maze).
Of course that will be a few ways to each point, and the player should choose the way with the amount of the steps by the Recurrence relation...
What I need?
I need few Recurrence relations (something like 4) that all the first 15 elements (it can be less the 15) are between $3-50$
I try to find few, but there was problems:
$x(n)= 2*x(n-1)$ - if I choose $x(0)>0$ the numbers are getting higher too much fast...
$x(n)=2*x(n-1)-x(n-2)$ - Too much easy to solve (from few examples...).
(I took those examples from a site...)
Can you help me and give me few examples?
Thank you!
Comment: Consider prime modules and primitive roots $a$, $x_n=ax_{n-1}\pmod{p}$ for no-repeat.
Comment: Perhaps you might try using modular arithmetic to force numbers to fall into a specific range.  For example, using $x_n = 2x_{n-1}\mod{30}$ with $x_0 = 3$ you get the sequence $3,6,12,24,18,6,12,24,18,6,\dots$  (18 instead of 48 because 18=48-30).
Comment: To expand on what Alexey suggests, by taking different seed values for $x_0$ and $a$, interesting patterns can occur.  For example, with $x_0=1$, $a=2$, and $p=13$, the same recursive definition generates the sequence: $1,2,4,8,3,6,12,11,9,5,10,7,1,2,4,8,\dots$.  You might become more adventurous by using non-linear recursive definitions (e.g.by taking the square of the previous number) or by using more than just the previous number (like fibonacci $f_n = f_{n-1} + f_{n-2}$), etc.  Whatever you use though can always be forced into a specific range by considering modular arithmetic is my point.
Comment: Thank you @JMoravitz!! If you have more ideas like that it will be great!! :-). And if it can be with no-repeat it will be better! Thank you so much!! :-)
Answer: This python script tests relations in the form $x_{n+1}=ax_n+bn+c$.
An example:
1 -1 8 3 [3, 9, 14, 18, 21, 23, 24, 24, 23, 21, 18, 14, 9, 3]
$x_n=x_{n-1}-n+8,\ x_1=3$ yields the above sequence (in bracets).
Or this 1 1 -5 11 [11, 8, 6, 5, 5, 6, 8, 11, 15, 20, 26, 33, 41, 50]


Counterexample for the logical argument

Question: Give a counter example to show the argument is not valid by using formulas from a particular structure interpreting the language.
$\forall x\exists y (r_1xy)$
$\forall y \exists x (r_2xy)$
then, $\forall x \exists y ((r_1xy)\wedge (r_2xy))$
Answer: Let the universe be $\mathbb{N}$, $r_1$ denotes $=$, and $r_2$ denotes $\neq$.
Comment: Hard to beat that for simplicity!

Counterexample for the logical argument


How to guess notes of the song once I have the chords?

Question: I am new to Piano / Keyboard. Recently, I came across this app called Chord AI, and it beautifully recognises chord of any song !
Now, I have the chords available. But, it is not enough right ? I have to play the notes along with it.
Is there any procedure to help me guess the notes ?
Thanks in advance !
Comment: Do you mean the melody or the full arrangement?
Answer: Just play the songs of which you find the sheet music: e.g. search for the title among images.There are 1000s of melodies - also with chords. Start with the most popular like folksongs and children songs, even baby songs, or simplified tunes of symphonies. So you will train reading melodies and sight reading and get  an idea of chords and fitting melodies. Then you can look for songs on youtube tutorials with or without chords and play along. You will train your ear and sens for harmony and melodies.  Finally you will be able to play along every song you like and accompany it with chords.
But there is now way to find the melody of chords, if you have only the chords and don't know the tune.
And you will have to study a lot about triads, chord notation, inversions, progressions etc.
example images:
searching for Joyful in images


Select data from one table & then rename the columns based on another table in SQL server

Question: I have two tables. TableOne which contains two columns (name & value). TableTwo can contain N no. of columns. Number of rows in TableOne will be equal to number of columns in TableTwo.
see the below image for more information.

What I want:
When I run select query on TableTwo, the result-set should pick the column names based on value column of TableOne. We need to match column name of TableTwo with rows available in TableOne and perform transform.
So the output should look like this:
ColumnOne | ColumnTwo | columnThree | ColumnFour

 1           1            1             2015-05-08 15:28:22.630
 2           2            2             2015-05-07 15:28:22.630
 ................
 ................

Comment: I won't attempt to answer this question, simply because it's a really bad example of database design. You should explore the fundamentals of the relational database model and re-design it based on what you have learned. Keeping data in 1NF (First Normal Form), is paramount to a good database design. This will cause all kinds of headaches in the future.
Comment: Don't tag products not involved... Are you really using MySQL and SQL Server and Oracle?
Comment: You need `Dynamic SQL`; code that reads one table, to create a new SQL statement to read from the next table.  This can not be done using a single query.
Comment: I didnt understand on what base you get your output ? you have column 3 and 4 .. what is unique in col 1 and col 2 ?
Comment: @JohnnyBell - Actually, *First* Normal Form is a flat file format with large scale repetition.  I think you mean *Fifth* Normal Form, usually...
Comment: @MatBailie Yes agreed, but it's dependent on the product. For example, consumer information would be better stored in 1NF, but an application model would be split down further to support the "MVC" architecture. I was simply pointing the OP in the right direction.
Answer: You can use dynamic sql to generate the query to execute based on the values in the first table. Here is an example:
Declare @dynamicSQL nvarchar(200)

SET @dynamicSQL = 'SELECT ' + (SELECT stuff((select ',' + name + ' AS ' + value
     from Table1
     for xml path('')),1,1,'')) + ' FROM Table2'
EXECUTE sp_executesql @dynamicSQL

SQL Fiddle: http://sqlfiddle.com/#!6/768f9/10
Comment: I couldn't edit my original answer so I added a new one. I have added the column name changing based on the contents of the 'Value" field


Scaling Problem

Question: Clara wanted to enlarge a figure on the photocopy machine. She set the enlargement factor to $1.25$. If the area of the figure was $10$ square inches before it was enlarged, what will the area be after it is run through the machine enlarged?
Comment: [Similar figures](http://en.wikipedia.org/wiki/Similar_figures)
Comment: Interesting question. Please, provide the context and doubts next time!
Answer: Answer is 10 × 1.252 or 15.625.How? The photocopy machine will increase the length of every side of the figure 1.25 times. So if there is square with side measuring 1cm. Its length will increase to 1.25cm. Now, you can see that its area will be 1.252 or 1.5625. Similarly, if there is a rectangle with length  l  and breadth b its sides will increase to 1.25 × l and 1.25 × b. So, the new area will be 1.25 × l × 1.25 × b or 1.252 × l ×  b or 1.252 × (OLD AREA).
This is because area is 2-dimensional. If this was the case with volume (maybe there was a 3-d printer instead), the figure's volume would have been increased by 1.253.
You an also try this with circles, polygons and other shapes. The results will be the same.
P.S. Area of a circle is πr2 where π = 3.141 and r = radius of the circle
Comment: So, enlargement factor always applies into the 'linear dimension' (sides in this case), I mean, how did you know that the enlargement factor did not apply to the area, that could becames directly $10\times 1.25$ ? Many thanks.
Comment: More specifically, if I say: enlarge the figure by an $100\%$ enlargement, can a people answer if we should multiply the area by $2$, instead of the lenghts? If not, there is some paper or statement about it? Many thanks.

Scaling Problem


How can I collect only the elements of the greatest length with Java Streams?

Question: I am trying to use Java Streams to collects all the Strings of the greatest length from my list:
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");

List<String> longest = strings.stream()
            .sorted(Comparator.comparingInt(String::length).reversed())
            .takeWhile(???)
            .collect(Collectors.toList());

I would like my longest to contain {"long word", "long wwww", "llll wwww"}, because those are the Strings that have the greatest lengths. In case of only having one of the Strings with greatest length, I am obviously expecting the resulting List to contain only that element.
I tried to first sort them in order to have the greatest length appear in the first element, but I am unable to retrieve the length of the first element in the stream. I could try something like peek():
static class IntWrapper {
    int value;
}

public static void main(String[] args) throws IOException {
    List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");

    IntWrapper wrapper = new IntWrapper();

    List<String> longest = strings.stream()
            .sorted(Comparator.comparingInt(String::length).reversed())
            .peek(s -> {
                if (wrapper.value < s.length()) wrapper.value = s.length();
            })
            .takeWhile(s -> s.length() == wrapper.value)
            .collect(Collectors.toList());

    System.out.println(longest);
}

but it's... ugly? I don't like the introduction of dummy wrapper (thank you, effectively final requirement) or the peek() hack.
Is there any more elegant way to achieve this?
Answer: Try this:
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");

List<String> longest = strings.stream()
        .collect(groupingBy(String::length, TreeMap::new, toList()))
        .lastEntry()
        .getValue();

System.out.println(longest);

Output:
[long word, long wwww, llll wwww]

Comment: Shorter and elegant but this explodes if the `strings` list is empty.
Comment: Made a trivial edit for formatting and TreeMap, not that your answer was incorrect though. Its the cleanest with the existing capabilities in my opinion.
Comment: @Naman, I've rolled it back. Please make a separate answer with that version. Because it uses not only streams.
Comment: You can take a look again, it does use `Stream` with an initialization of the `TreeMap` using a constructor instead. There is no value add in making another answer for that edit. This still keeps up with OP's expectation and is good with the rollback as well.
Answer: Well, I don't know if this will be more elegant but it should do what you want:
List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");

List<String> longest = strings.stream()
        .collect(Collectors.groupingBy(String::length))     // Build Map<Length, List<Strings>>
        .entrySet().stream()                                // EntrySet stream of said map
        .max(Map.Entry.comparingByKey())                    // Keep max length
        .map(Map.Entry::getValue)                           // Get value of max length
        .orElse(Collections.emptyList());                   // Or return an empty list if there's none

System.out.println(longest);

Output:

[long word, long wwww, llll wwww]
Comment: The answer from @IlyaLysenko using `TreeMap` is a more elegant version of this.
Comment: @Fureeish But overly complicated for something as simple as [this answer](https://stackoverflow.com/a/60765407/1746118) or else there is never a harm in defining a custom collector.
Answer: You may consider it uglier, but a custom collector is definitely correct, more efficient, and even parallelizes nicely:
Collector<String, List<String>, List<String>> collector = Collector.of(
   ArrayList::new,
   (list, elem) -> {
     if (list.isEmpty() || elem.length() == list.get(0).length()) {
       list.add(elem);
     } else if (elem.length() > list.get(0).length()) {
       list.clear();
       list.add(elem);
     }
   },
   (list1, list2) -> {
     int len1 = list1.isEmpty() ? -1 : list1.get(0).length();
     int len2 = list2.isEmpty() ? -1 : list2.get(0).length();
     if (len1 < len2) {
       return list2;
     } else if (len1 > len2) {
       return list1;
     } else {
       list1.addAll(list2);
       return list1;
     }
   });

return strings.stream().collect(collector);

Comment: I do consider correctness as a part of elegance and, in this case, I believe this is not only superior, but surely an eleganet solution. Thank you. I would like to wait for other approaches though, if any appear. If not, I will happily accept your answer!
Comment: You might have meant `list1.get(0).length()` instead of `list1.get(0).size()`. Made an edit, feel free to revert.
Answer: I don't know if you find it more elegant, but it is succinct:
       List<String> strings = Arrays.asList("long word", "short", "long wwww", "llll wwww", "shr");

       TreeMap<Integer, List<String>> collect = strings.stream().collect(
                Collectors.groupingBy(
                        String::length,
                        TreeMap::new,
                        mapping(Function.identity(), toList())));

       System.out.println(collect.lastEntry().getValue());


Why can we assume that there is no constant value when doing a "reverse derivative" by going from a $v(t)$ equation to a $d(t)$ equation?

Question: I'm trying to solve this question for my calculus homework on derivatives:
A car whose position is given by the equation $d(t) = 25t + t^2$ passes a police car that is traveling at 20 m/s. The police officer turns on the siren and begins to accelerate at 1.5 m/s^2 to chase the speeding car.
a) At what time is the speeding car moving at 31 m/s?
The derivative of $d(t)$ is $v(t) = 25 + 2t$, so the time is 3 seconds for the speeding car.
b) How fast is the police car moving at that time?
The police car's $v(t)$ equation is $v(t) = 20 + 1.5t$, so subbing in 3 seconds gives us 24.5 m/s.
c) How far apart are the vehicles at that time?
Here, I assumed the "reverse derivative" of the police car's $v(t)$ equation was $d(t) = 20t + (3/4)t^2$, and then I used the other speeding car distance equation as well. I plugged in 3 seconds into both of these and then I found that the distance between them is 17.25m which is right.
For part c), when we are going from the velocity-time equation to the distance-time equation for the police car, why can we assume that there is no constant value? If there was a constant value, how would we know what it is? Like what I mean by that is with this equation that models the distance of the police car, $d(t) = 20t + (3/4)t^2$, how do I know if it's not like $d(t) = 10 + 20t + (3/4)t^2$? But mainly, when and why can we assume that there is no constant value?
Answer: The problem is actually ill-posed, it doesn't say at which time the speeding car passed the police car and from what point the displacements are calculated. Your (and their!) solution apparently assumes that they passed each other at $t=0$ and all the displacements were taken from the place where they met. The problem statement should've been a lot more explicit about that.
With that assumption, the displacement of the police car is indeed:
$$d(t)=\int 20+\frac{3}{2}t\,dt=20t+\frac{3}{4}t^2+C$$
however the assumption that at $t=0$ (when they met) it was $d(t)=0$ yields:
$$20\cdot 0+\frac{3}{4}\cdot 0^2+C=0$$
i.e.
$$C=0$$
Comment: Yes, and I also have an issue with how "begins to accelerate" apparently means "undergoes constant acceleration".
Comment: @ryang True, although "begins to accelerate at $1.5\frac{m}{s^2}$", sort of, does imply constant acceleration. We also seem to be invited to imagine that the speeding car passed the police car, the police officer saw that, and began accelerating - all at the same time. These are also things which were not stated pedantically enough.
Comment: My own pet peeve is about *dimensionality*. How can it be $d(t)=25t+t^2$ when the left side is in metres and we add seconds and seconds squared on the right side? The correct writing is $d(t)=25\frac{m}{s}t+1\frac{m}{s^2}t^2$. However, this kind of sloppiness is so usual in the problems of this type that I have given up.
Comment: Eeeeps! (Hadn't noticed that till you pointed out.) And you're totally right; I retract my complaint: "at t=0, I start running at 8m/s", although technically consistent with "1 min later, I am running at 5m/s", is more reasonably construed as "t=0 is the start of my 8m/s constant-speed run". hehe


reference books for self study of basics of mathematics

Question: I am a computer science graduate and slacked my way through high school and college and don't have a solid understanding of the basic concepts in mathematics
I also don't have the mathematical way of thinking.
I am trying to build a product which requires understanding loads of theory, on the subject at hand. But whenever mathematics comes into the picture
it goes above and over my head. This question will hopefully be useful to people like me in similar situations. I am willing to invest years to learn
the basics right.
From the top of my head, i can think of the following areas that i have no familiarity

Harmonic Numbers
Infinite series
Probability
Combinatorics,permutation and combination
Set theory
Discrete mathematics
Trigonometry
Calculus
Logarithms
Matrices and determinants
Vectors

If you know of any more fundamental areas that i missed out please do add it along with reference books for the same.
Comment: See my answer here: http://math.stackexchange.com/questions/427868/relearning-from-the-basics-to-calculus-and-beyond?lq=1 and search out others on MSE like: http://math.stackexchange.com/questions/69060/what-is-a-good-book-for-learning-math-from-the-ground-up?rq=1, http://math.stackexchange.com/questions/39427/a-good-book-for-learning-mathematical-trickery?rq=1, http://math.stackexchange.com/questions/38854/basic-book-about-mathematical-proofs?rq=1
Comment: A lot of these might be well grouped together. For instance, trigonometry, infinite series, and logarithms are typically covered in a basic pre-calculus/calculus class. You also often see set theory, basic combinatorics and probability appear in discrete mathematics classes. If you could get a good calculus text and a good discrete mathematics text, you could cover a lot of ground here.
Comment: Does this answer your question? [Learning mathematics as if an absolute beginner?](https://math.stackexchange.com/questions/22513/learning-mathematics-as-if-an-absolute-beginner)
Answer: Probability - Introduction to Probability Theory William Feller
Linear Algebra - Gilbert Strang
Calculus - Apostol Calculus Vol 1 and 2
Number theory - Hardy and Wright Theory of numbers
These books will give you a basic idea of these topics. These are comparitively easy to understand even for a high school student with a strong mathematical foundation. All the areas you have mentioned are included in these books.
Answer: Concrete Mathematics: A Foundation for Computer Science would be my suggestion for a book to consider in covering the basics of most of the areas you mention at least in terms of getting an understanding of the Abstract Algebra along with Calculus, Analysis and other areas of Mathematics.


PySpark query performance - join vs when

Question: I have a query where I want to change the content of two dataframes (purDf ~432.8 MiB  & ticDf ~9.3 GiB) based on some conditions and then join them.
I've tried doing it in two different ways with different performances. Alternative 1 relies on a lot of when satements while Alternative 2 is using joins instead to minimize then number of when statements in the query.
Alternative 1
purDf
.select(col('id').alias('TicketEventId'),
    col('ticketId').alias('TicketId'),
    col('ticketEventType').alias('TicketEventType'),
    when( col('ticketEventType') == 'ticketRefunded', col('amountInclVat')*-1)
    .otherwise(col('amountInclVat'))
    .alias('AmountInclVAT'),
    col('created_datetime').alias('CreatedAtLocal')
)
.join(ticDf
  .select(
          when( substring(col('saleschannel_id'),0,2) ==  'Af', 'Ombud').
          when( substring(col('saleschannel_id'),0,2) ==  'Kc', 'Kundcenter').
          when( substring(col('saleschannel_id'),0,2) ==  'Rb', 'Regionbuss').
          when( substring(col('saleschannel_id'),0,2) ==  'Do', 'Do').
          when( substring(col('saleschannel_id'),0,2) ==  'MK', 'Mitt konto').
          when( col('saleschannel_id') ==  'tvm', 'Biljettautomater').
          when( col('saleschannel_id') ==  'washington', 'appen').
          when( col('saleschannel_id') ==  'EComPublic', 'Köp & Skicka').
          when( col('saleschannel_id') ==  'tapnride', 'Blippa').
          when( col('saleschannel_id') ==  'Senior', 'Seniorresor').
          when( col('saleschannel_id') ==  'Skola', 'Skola').
          when( col('saleschannel_id') ==  'Service', 'Serviceresor').
          when( col('saleschannel_id') ==  '2', 'FrontOffice').
          otherwise('Övrigt').
          alias('SalesChannel'),
          col('ticketId').alias('TicketId')),
  'TicketId', how = 'inner'

Using Alternative 1 completed the command in ~ 40 seconds
Alternative 2
stringCodesSubstr = spark.createDataFrame([{'saleschannel_id_substr' : 'Af', 'tempId1' :'Ombud'},
                                             {'saleschannel_id_substr' : 'Kc', 'tempId1' :'Kundcenter'},
                                             {'saleschannel_id_substr' : 'Rb', 'tempId1' :'Regionbuss'},
                                             {'saleschannel_id_substr' : 'Do', 'tempId1' :'Do'},
                                             {'saleschannel_id_substr' : 'MK', 'tempId1' :'Mitt konto'}]
                                         )

stringCodes = spark.createDataFrame([{'saleschannel_id' : 'tvm', 'tempId2' :'Biljettautomater'},
                                      {'saleschannel_id' : 'washington', 'tempId2' :'appen'},
                                      {'saleschannel_id' : 'EComPublic', 'tempId2' :'Köp & Skicka'},
                                      {'saleschannel_id' : 'tapnride', 'tempId2' :'Blippa'},
                                      {'saleschannel_id' : 'Senior', 'tempId2' :'Seniorresor'},
                                      {'saleschannel_id' : 'Skola', 'tempId2' :'Skola'},
                                      {'saleschannel_id' : 'Service', 'tempId2' :'Serviceresor'},
                                      {'saleschannel_id' : '2', 'tempId2' :'FrontOffice'}]
                                   )

ticketsPreProcess = (ticDf
           .select(substring(col('saleschannel_id'),0,2).alias('saleschannel_id_substr'),
                   col('saleschannel_id'),
                   col('ticketId')
           )
          )

tickets = (ticketsPreProcess.join(stringCodesSubstr, ['saleschannel_id_substr'] , how = 'left')
                                       .join(stringCodes, ['saleschannel_id'], how = 'left')
                                       .select(coalesce( col('tempId1'), col('tempId2'), lit('Övrigt') ).alias('SalesChannel'),
                                              col('ticketId')
                                              )
           )

purchaseTemp = purDf.join(tickets, ['ticketId'], how = 'inner')

purchaseView = (purchaseTemp.select(
                                      col('id').alias('TicketEventId'),
                                      col('ticketId').alias('TicketId'),
                                      col('ticketEventType').alias('TicketEventType'),
                                      when( col('ticketEventType') == 'ticketRefunded', col('amountInclVat')*-1)
                                        .otherwise(col('amountInclVat'))
                                        .alias('AmountInclVAT'),
                                      col('created_datetime').alias('CreatedAtLocal'),
                                      col('SalesChannel'))
                                      )

Using Alternative 2 completed the command in ~ 22 seconds.
I'm using Databrick Runtime Version 10.3 (includes Apache Spark 3.2.1, Scala 2.12) and a cluster of 4 nodes with 32gb memory and 4 cores each.
My question is, what is the reason for this drastic difference in performance? I can see in the Spark UI that Alternative 2 seem to be able to run more things in parallel, but I don't understand why.
I've tried reading the physical plan but since I'm new to spark I cant make any sense of it. If anyone can help me with that, see the plans below.
Alternative 1
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [TicketId#234, TicketEventId#233, TicketEventType#235, AmountInclVAT#236, CreatedAtLocal#237, SalesChannel#243]
   +- SortMergeJoin [TicketId#234], [TicketId#244], Inner
      :- Sort [TicketId#234 ASC NULLS FIRST], false, 0
      :  +- Exchange hashpartitioning(TicketId#234, 200), ENSURE_REQUIREMENTS, [id=#416]
      :     +- Project [id#90 AS TicketEventId#233, ticketId#91 AS TicketId#234, ticketEventType#92 AS TicketEventType#235, CASE WHEN (ticketEventType#92 = ticketRefunded) THEN (amountInclVat#94 * -1.0) ELSE amountInclVat#94 END AS AmountInclVAT#236, created_datetime#95 AS CreatedAtLocal#237]
      :        +- Filter ((isnotnull(created_datetime#95) AND (created_datetime#95 >= 2022-04-01 00:00:00)) AND isnotnull(ticketId#91))
      :           +- FileScan parquet [id#90,ticketid#91,ticketEventType#92,amountInclVat#94,created_datetime#95] Batched: true, DataFilters: [isnotnull(created_datetime#95), (created_datetime#95 >= 2022-04-01 00:00:00), isnotnull(ticketid..., Format: Parquet, Location: PreparedDeltaFileIndex(1 paths)[dbfs:/mnt/datalake/gold/purchases], PartitionFilters: [], PushedFilters: [IsNotNull(created_datetime), GreaterThanOrEqual(created_datetime,2022-04-01 00:00:00.0), IsNotNu..., ReadSchema: struct<id:string,ticketid:string,ticketEventType:string,amountInclVat:double,created_datetime:tim...
      +- Sort [TicketId#244 ASC NULLS FIRST], false, 0
         +- Exchange hashpartitioning(TicketId#244, 200), ENSURE_REQUIREMENTS, [id=#417]
            +- Project [CASE WHEN (ephemeralsubstring(saleschannel_id#170, 0, 2) = Af) THEN Ombud WHEN (ephemeralsubstring(saleschannel_id#170, 0, 2) = Kc) THEN Kundcenter WHEN (ephemeralsubstring(saleschannel_id#170, 0, 2) = Rb) THEN Regionbuss WHEN (ephemeralsubstring(saleschannel_id#170, 0, 2) = Do) THEN Do WHEN (ephemeralsubstring(saleschannel_id#170, 0, 2) = MK) THEN Mitt konto WHEN (saleschannel_id#170 = tvm) THEN Biljettautomater WHEN (saleschannel_id#170 = washington) THEN SKÅ-appen WHEN (saleschannel_id#170 = EComPublic) THEN Köp & Skicka WHEN (saleschannel_id#170 = tapnride) THEN Blippa WHEN (saleschannel_id#170 = Senior) THEN Seniorresor WHEN (saleschannel_id#170 = Skola) THEN Skola WHEN (saleschannel_id#170 = Service) THEN Serviceresor WHEN (saleschannel_id#170 = 2) THEN Singapore FrontOffice ELSE Övrigt END AS SalesChannel#243, ticketId#154 AS TicketId#244]
               +- Filter ((isnotnull(created_datetime#159) AND (created_datetime#159 >= 2022-04-01 00:00:00)) AND isnotnull(ticketId#154))
                  +- FileScan parquet [ticketId#154,created_datetime#159,saleschannel_id#170] Batched: true, DataFilters: [isnotnull(created_datetime#159), (created_datetime#159 >= 2022-04-01 00:00:00), isnotnull(ticket..., Format: Parquet, Location: PreparedDeltaFileIndex(1 paths)[dbfs:/mnt/datalake/gold/tickets], PartitionFilters: [], PushedFilters: [IsNotNull(created_datetime), GreaterThanOrEqual(created_datetime,2022-04-01 00:00:00.0), IsNotNu..., ReadSchema: struct<ticketId:string,created_datetime:timestamp,saleschannel_id:string>

Alternative 2
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [id#90 AS TicketEventId#1132, ticketId#91 AS TicketId#1133, ticketEventType#92 AS TicketEventType#1134, CASE WHEN (ticketEventType#92 = ticketRefunded) THEN (amountInclVat#94 * -1.0) ELSE amountInclVat#94 END AS AmountInclVAT#1135, created_datetime#95 AS CreatedAtLocal#1136, SalesChannel#1122]
   +- SortMergeJoin [ticketid#91], [ticketId#154], Inner
      :- Sort [ticketid#91 ASC NULLS FIRST], false, 0
      :  +- Exchange hashpartitioning(ticketid#91, 200), ENSURE_REQUIREMENTS, [id=#785]
      :     +- Filter ((isnotnull(created_datetime#95) AND (created_datetime#95 >= 2022-04-01 00:00:00)) AND isnotnull(ticketid#91))
      :        +- FileScan parquet [id#90,ticketid#91,ticketEventType#92,amountInclVat#94,created_datetime#95] Batched: true, DataFilters: [isnotnull(created_datetime#95), (created_datetime#95 >= 2022-04-01 00:00:00), isnotnull(ticketid..., Format: Parquet, Location: PreparedDeltaFileIndex(1 paths)[dbfs:/mnt/datalake/gold/purchases], PartitionFilters: [], PushedFilters: [IsNotNull(created_datetime), GreaterThanOrEqual(created_datetime,2022-04-01 00:00:00.0), IsNotNu..., ReadSchema: struct<id:string,ticketid:string,ticketEventType:string,amountInclVat:double,created_datetime:tim...
      +- Sort [ticketId#154 ASC NULLS FIRST], false, 0
         +- Exchange hashpartitioning(ticketId#154, 200), ENSURE_REQUIREMENTS, [id=#786]
            +- Project [coalesce(tempId1#1102, tempId2#1106, Övrigt) AS SalesChannel#1122, ticketId#154]
               +- SortMergeJoin [saleschannel_id#170], [saleschannel_id#1105], LeftOuter
                  :- Sort [saleschannel_id#170 ASC NULLS FIRST], false, 0
                  :  +- Exchange hashpartitioning(saleschannel_id#170, 200), ENSURE_REQUIREMENTS, [id=#777]
                  :     +- Project [saleschannel_id#170, ticketId#154, tempId1#1102]
                  :        +- SortMergeJoin [saleschannel_id_substr#1109], [saleschannel_id_substr#1101], LeftOuter
                  :           :- Sort [saleschannel_id_substr#1109 ASC NULLS FIRST], false, 0
                  :           :  +- Exchange hashpartitioning(saleschannel_id_substr#1109, 200), ENSURE_REQUIREMENTS, [id=#769]
                  :           :     +- Project [substring(saleschannel_id#170, 0, 2) AS saleschannel_id_substr#1109, saleschannel_id#170, ticketId#154]
                  :           :        +- Filter ((isnotnull(created_datetime#159) AND (created_datetime#159 >= 2022-04-01 00:00:00)) AND isnotnull(ticketId#154))
                  :           :           +- FileScan parquet [ticketId#154,created_datetime#159,saleschannel_id#170] Batched: true, DataFilters: [isnotnull(created_datetime#159), (created_datetime#159 >= 2022-04-01 00:00:00), isnotnull(ticket..., Format: Parquet, Location: PreparedDeltaFileIndex(1 paths)[dbfs:/mnt/datalake/gold/tickets], PartitionFilters: [], PushedFilters: [IsNotNull(created_datetime), GreaterThanOrEqual(created_datetime,2022-04-01 00:00:00.0), IsNotNu..., ReadSchema: struct<ticketId:string,created_datetime:timestamp,saleschannel_id:string>
                  :           +- Sort [saleschannel_id_substr#1101 ASC NULLS FIRST], false, 0
                  :              +- Exchange hashpartitioning(saleschannel_id_substr#1101, 200), ENSURE_REQUIREMENTS, [id=#770]
                  :                 +- Filter isnotnull(saleschannel_id_substr#1101)
                  :                    +- Scan ExistingRDD[saleschannel_id_substr#1101,tempId1#1102]
                  +- Sort [saleschannel_id#1105 ASC NULLS FIRST], false, 0
                     +- Exchange hashpartitioning(saleschannel_id#1105, 200), ENSURE_REQUIREMENTS, [id=#778]
                        +- Filter isnotnull(saleschannel_id#1105)
                           +- Scan ExistingRDD[saleschannel_id#1105,tempId2#1106]

Comment: when you say *completed the command*, do you mean an action (e.g. `show()`, `write`, etc.)? performance will come into the picture once the action is executed.
Comment: Yes. After each query i displayed the result using display() and printed the physical plan using explain().
Answer: After some further testing I found the reason why Alternative 1 was slower than Alternative 2.
Before I ran the code shown above I defined the dataframes purDf and ticDf without actually using them. Due to sparks Lazy Evaluation, the dataframes were not actually loaded until I needed them for the first time. Since I always ran Atlernative 1 before Alternative 2, Alternative 1 seemed slower since it also needed to load the data for the dataframes.
After re-running the tests where I made sure that the dataframes had been loaded and cached before the test, I found that it was actually Alternative 1 that was the best performing one. That makes sense to me since the when statements can be computed on several different partitions independently but the joins requires some amount of shuffling and sorting that needs to be performed before the join can be made.
I managed to improve the performance of Alternative 2 slightly be using broadcast join when creating the dataframe called tickets. But Alternative 1 was still the best performing one.


Select 2 not populating options, but return data is correct format?

Question: I have this jQuery
$('#document').ready(function(){
        $('#page_posts_select').select2({
            ajax: {
                url: "admin/pages/get_posts_for_select",
                type: "GET",
                success: function(data){
                    console.log(data);
                }
            }
        });
    })

And the data logged in the console is like this:
{"results":[{"id":"1","text":"Option1"},{"id":"2","text":"Option2"}]}

My server side function looks like this:
$results = $this->posts_model->get_all_posts_for_dropdown();
    $select_results = array();
    foreach($results as $result){
        $select_results[] = array('id'=>$result->post_id, 'text'=>$result->title);
    }
    $output = new stdClass();
    $output->results = $select_results;
    echo json_encode($output);

Why does my select list not display any options, shouldn't it display the Option1 and Option2 in the dropdown? Is there some extra attribute that the ajax needs?
According to the research I have done all I should need is the correct returned format, being the object with the "results" attribute holding the array of "id" and "text" fields.
Please help, thanks!
Answer: I think I have solved this, I did not include dataType: 'json' for the ajax attributes.


Access Denied when Menu CallBack Function is Called

Question: I am trying to call a function after the user clicks on an ajaxified link below.
$form['link'] = array(
  '#type' => 'item',
  '#markup' => l(t($record->studid),'myid_print/callback', array('attributes' => array('class' => 'use-ajax'))),
);

Below is my hook_menu function:
function myid_print_menu()
{
    $items = array();
    $items['myid_print/callback'] = array(
        'page callback' => 'myid_print_user_page_callback',
        'access callback'    => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function myid_print_user_access()
{
    return TRUE;
}

myid_print.pages.inc file:
function myid_print_user_page_callback()
{
    return 'Successful';
}

The above code throws the error below:

Where am I missing?
Answer: Your AJAX request is calling the path /drupal-7.34/myid_print/callback on the server. The path registered on your Drupal instance (assuming you're running under the drupal-7.34 directory) is /drupal-7.34/print/callback. Hence, the error you're seeing.
If you want to pass an argument to your print callback, you should do this.
$items['print/%/callback'] = array(
    'page callback' => 'print_user_page_callback',
    'page arguments' => array(1),
    'access callback'    => 'print_user_access',
    'file' => 'print.pages.inc',
    'type' => MENU_CALLBACK,
);

function print_user_page_callback($id)
{
    return 'Successful printing '.$id;
}

Read more on hook_menu() if you'd like to understand more how module's can register paths.
Comment: Im sorry , but I just edited my code in the post to(print*) from (myid_print*). It was my mistake, sorry for not being consistent in my post but in my real code, it was really myid_print*
Answer: I tried uninstalling my Jquery Update Module and suddenly the error disappears. I don't know why it works. Still thankful though.