How do you know when a key name needs an accidental?

Question: Take the following example from musictheory.net. If we go by the "cheat" rule where you can take the last sharp, then go one half note up, it will tell us that the major key is A.
Next, if we use the "cheat" rule of counting down a minor 3rd to find the relative minor key, we get F. That's okay, but how do I know when the key name needs an accidental? I would have guessed F here, not F#.
Comment: F is not a minor third below A, F♯ is a minor third below A. It looks like you need a better "cheat" rule: what will you do with the flat keys? Just learn the major key signatures first, then the relative minor is a minor third below (or a major sixth above) the major key: 3 sharps --> A Major; down a minor third --> F♯ Minor.
Comment: It really is worth learning the key sigs - at least to 4 or 5 # and b.
Comment: This is one of the many times when theory on its own is greatly helped with an instrument. Playing the A chord, followed by FM will probably tell the payer that they aren't relative at all. Playing A then F#m, the similarity should be heard. Not an answer, merely a comment, constructive, I hope.
Comment: You might find [this question about naming intervals useful](https://music.stackexchange.com/questions/60771/defining-intervals)
Comment: @DavidBowling - relative minor is a m3 below the major root, but that also makes it M6 above, rather than M3. Scary that 3 people agree with what's there!
Comment: @Tim -- Oops. Yes, a little scary that my typo got 3 consenters!
Comment: _the key name needs an accidental_  **Note:** When a **#** or **b** is part of the key signature, it's not called an _accidental_ . An _accidental_ is just that: An 'accident' - it really 'shouldn't' be there it that key.
Comment: I'm noticing a possible flaw in the counting down. Are you using inclusive counting (including the root as the first number)?
Answer: You know because you have to count down a minor third.
A minor third interval consists of one whole tone and one half tone.
Between A and G there is one whole tone.
Between G and F there is another whole tone. To make the interval between G and F a half tone you have to raise the F by a half tone by putting a sharp in front of it.
You also have an important hint by seeing that the F# is already in the key signature. Which probably is a faster way of getting it right.
Comment: Note that A♭ Minor is the relative minor to C♭ Major; not a common key, but a real key all the same.
Comment: Because Ab isn't technically a minor third below B. It's an augmented second.
Comment: @miniHessel - not sure that 'accented' is a good or accurate term to use here. It sounds like 'accented notes' are the main ones in a key, which they're not. If there was a word 'accidentalised', that may do!
Comment: Thank you for explaining. I messed up on intervals, at least I learned something new! So if you can see the note of the signature accented, that's what it is for the relative minor? If the minor was an A, and in the major the A was flat, that would make the relative minor an A flat?
Comment: Yes, it would (except that A flat minor isn't used). The shortcut works because in the major and the natural (!) minor scales all the accidentals are already in the key signature.
Comment: I have another question then, how do you know when to use for example G# instead of Ab? Take  for example B major, the relative minor key to B major is G#, but why not Ab?
Comment: Could one identify which notes are accented in a key, just by looking at the key signature? That's probably not normal, but if I looked at the key signature of B major, I can see that  C♯, D♯, E, F♯, G♯, and A♯ are all sharps. That would also mean, that if you know your scales, you could just check which notes are sharps, then you would immediately see that this is a B major key "signature"?
Comment: @miniHessel -- that method is not going to work for, e.g. F Major, which has one flat: B♭. You just need to know the key signatures; the easiest way is to memorize the number of sharps and flats for each key. A useful tool is the [Circle of Fifths](https://en.wikipedia.org/wiki/Circle_of_fifths). Learn this (it has other applications, too) and note that C at the top has no sharps or flats, G to the right has one sharp, next D has two sharps, ..., to the left of C, F has one flat, B♭ has two flats, and so on.
Comment: Still, looking at the key signature of F major, would tell you that the only note that is accented, is the Bb. So you can use a key signature to check which notes is accented in a key, I guess.
Comment: Then we agree. I just think it's awesome to see how everything connects.
Comment: @miniHessel - as Tim mentioned above : Learn about intervals and learn the circle of 5ths and how key signatures work, (or at least memorize them) . Shortcuts without fundamental understanding end up causing you more confusion. The basics are not hard at all, and once you understand them, you will never be confused - it's worth the effort if you have a sincere interest.
Comment: I am reading The Complete Musician, so I have touched upon circle of 5ths and intervals. It's a journey though, so far away from understanding everything.
Answer: Because it tells you right there that the key has 3 sharps and which notes are sharp. F, G, AND C are sharp.
When you do your "cheat" you land on F which you can see needs to be sharp by the key signature. But also if you knew your intervals you'd know a minor third below A is F# and a major third below A is F
Answer: I don't think the other answers caught on to your mistake. The minor 3rd is from the Major key name (A), not the last accidental (G#) which is what you did.
Comment: A minor third below G♯ is E♯, not F. If this is what OP did (and I am not sure that they did), they got it wrong two ways.


How can I restrict various roles with limit in creating nodes of a particular content type

Question: How can I restrict various roles with limit in creating nodes of a particular content type?
Answer: you can use node limit module to restrict nodes for various roles.
For each roles you can create a node limit condition with certain limit for nodes for tat particular content type.


Menu is missing under Resources - XAMARIN

Question: I am trying to implement a menu on my app bar but why I can't find it under Resource? As you can see, it has color red under it's name. I tried to right click on it but it only says generate menu method. I can't rebuild and deploy it since it gives me that kind of weird error. Also what happen after that is my VS can't read even the Resource itself. I can only solve it if I add another activity or delete it or to restart the VS.

Here is my Menu folder.
]2
Here is my full code for activity
using System;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using SupportToolbar = Android.Support.V7.Widget.Toolbar;
using Entities;

namespace RBankCI
{
    [Activity(Label = "PDRN", MainLauncher = true, Theme = "@style/Theme.FullScreenBaseDesign")]
    public class Activity_PDRN : AppCompatActivity, IActivityInterface
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Layout_PDRNForm);
            Title = string.Empty;
            i1_setupActionBar();
        }

        public void i1_setupActionBar()
        {
            // Initialize Support ToolBar
            SupportToolbar toolBar = FindViewById<SupportToolbar>(Resource.Id.toolBar);
            toolBar.SetBackgroundResource(Resource.Drawable.AppBarBackgrounWithTitle);
            SetSupportActionBar(toolBar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
        }

        public void i2_initialization()
        {
            throw new NotImplementedException();
        }

        public void i3_deserializeIntentExtras()
        {
            throw new NotImplementedException();
        }

        public void i4_setUpAllClickable()
        {
            throw new NotImplementedException();
        }

        public void i5_setTextChangeBehaviour()
        {
            throw new NotImplementedException();
        }

        public void i6_setTextFieldValues()
        {
            throw new NotImplementedException();
        }

        #region Override OnCreateOptionsMenu()
        ///
        /// Create a menu setting
        ///
        /// <param name="menu">Menu</param>
        /// <returns></returns>
        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            //Here is the problem. My VS can't read the Menu after Resource

            // Create Menu Action
            MenuInflater.Inflate(Resource.Menu.menu_form, menu);

            return true;
        }
        #endregion

        #region Override OnOptionsItemSelected()
        ///
        /// Event when a user clicks one of the ActionBar Icons
        ///
        /// <param name="item">Action Item</param>
        /// <returns></returns>
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            // Open Navigation Drawer
            switch (item.ItemId)
            {
                // User click menu icon
                case Android.Resource.Id.Home:
                    OnBackPressed();
                    return true;
                case Android.Resource.Id.menu_clear: //here, I can see and error a constant value is expected. This id is under the menu_form.xml
                    Toast.MakeText(this, "Clear All Fields", ToastLength.Short).Show();
                    return true;
                case Resource.Id.menu_attach: //here, I can see and error a constant value is expected. This id is under the menu_form.xml
                    Toast.MakeText(this, "Attach Photo", ToastLength.Short).Show();
                    return true;
                default:
                    return base.OnOptionsItemSelected(item);
            }
        }
        #endregion

        #region Override OnBackPressed()
        ///
        /// Override OnBackPressed
        ///
        public override void OnBackPressed()
        {
            try
            {
                Finish();
            }
            catch (Exception e)
            {
                Toast.MakeText(this, ENT_NegativeResponse.somethingWentWrong, 0).Show();
            }
        }
        #endregion
    }
}

Here is my menu_form.xml
<?xml version="1.0" encoding="utf-8" ?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

  <item
  android:id="@+id/menu_clear"
  android:title="Clear All Fields"
  android:icon="@drawable/ic_clear_fields_png_x3"
  app:showAsAction="ifRoom"/>

  <item
  android:id="@+id/menu_attach"
  android:title="Attach Photo"
  android:icon="@drawable/ic_attach_image_png_x3"
  app:showAsAction="ifRoom"/>

</menu>

Comment: and What Is Resource.Menu.. Please Don't Copy Screen Shot. Instead Post Your code
Comment: post your menu_form.xml
Comment: I take screenshots since we can't see the red line under Menu if I just copy the code .
Comment: Can someone explain about the downvote?
Answer: Use this-:
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_form, menu);

In this case Import R file that is of your current package
Comment: still nothing. I think it just instantiate the MenuInflater to variable inflater .
Comment: Try changing Resource to R file and try importing that as popupMenu.inflate(R.menu.medication_list_more_option);
Comment: No I can't. R is for android and Resource is for xamarin . Camel Casing and Some codes are slightly different like what you mentioned getMenuInflater is MenuInflater in xamarin.
Answer:
Menu is missing under Resources - XAMARIN

Check if the resource id has been generated in Resource.designer.cs.

In my project, the resource id is :
public partial class Id
{
    ...
    // aapt resource value: 0x7f0b007b
    public const int menu_attach = 2131427451;

    // aapt resource value: 0x7f0b007a
    public const int menu_clear = 2131427450;
    ...
}

...

public partial class Menu
{

    // aapt resource value: 0x7f0d0000
    public const int menu_form = 2131558400;

    static Menu()
    {
        global::Android.Runtime.ResourceIdManager.UpdateIdValues();
    }

    private Menu()
    {
    }
}

Solution :
If it has not been generated, usually clean and rebuilding the project will generate it again, unless there is a syntax error somewhere.
Comment: Nah it's not generating Menu, menu_form or even the menu_clear and menu_attach. If I comment the MenuInflater, my program works. But not if I try to initialize it.
Comment: @jace, delete your project bin and obj files and rebuild again, then you should `Menu` resource in your project.
Comment: I did that once, even the file under xamarin folder on appdata. restarted and done anything I could but I don't know why.
Comment: I already found the solution. Thanks to your comment. I'll just post is as an answer if ever others will have same situation as mine
Answer: UPDATE
Updating Xamarin for Visual Studio solved the issue for missing Menu under Resource . Got the blue-green color after

I found it back from my Resource.Designer.cs although it still have a message under it: 'Resource' does not contain a definition for 'Menu' and for the buttons they have "A constant value is required". But still it is working with redlines.
For reference of others, this is what I did.
My VS.Xamarin is good with my menu before until it prompts me with message that it is not recognizable. Here are my steps that I tried:
1. Restarted the VS
2. Removed bin and obj under project
3. Removed xamarin folder content under user/appdata/local/xamarin
4. Clean and Rebuild as many as I can
5. Create new menu folder under resource
6. Create menu file from add button but I think this is also a problem
Part of Soution
menu under add button generates menu_form.xml file while xamarin read an .axml format. So my solution is to create a layout, copy what my menu_form.xml have and clean then rebuild. Menu, menu_form and it's elements showed up to Resource.Designer.cs after that.
It's actually a problem for me since it is working before but suddenly stopped and gave me an error.
Still I have an error regarding Resource.Menu the same from the beginning with a red line yet it's working well. I don't know why my VS gives me that error.
Answer: Make sure you've edit it:

(Change BuildAction to AndroidResource)


iOS can i build an app or service to keep bluetooth discover device

Question: if discover a new device then push notification to the user.
how to start and any resources/sample code?
Answer: All three previous answers are incorrect. iOS5 introduced Core Bluetooth framework.
However, this framework is BT 4.0 LE only; none-the-less Bluetooth.
Here also is the PDF reference: http://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CoreBluetooth_Framework/CoreBluetooth_Framework.pdf
Example
Your class must conform to the CBCentralManagerDelegate and CBPeripheralDelegate protocols.
CBCentralManager * btCentral = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

/* Create an array of services from a CBUUID to scan for */
[btCentral scanForPeripheralsWithServices:nil options:nil];

That's basically to get you started on scanning for peripherals. You will also need to implement the CBCentralManagerDelegate methods and a few others, I suggest reading the docs:
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

- (void)centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals

Comment: How about build it as a service, can i trigger the bluetooth discovery  in background at the iphone normal state (not enter the app). I can discovery device now, mainly i would like the bluetooth running all the time, even it is back to HOME (not in app inside)
Comment: After some time, your app may become inactive, at which point, no.


If $\sum_{n=0}^\infty|a_n|<\infty$, prove that $\sum_{n=0}^\infty a_nx^n$ converges uniformly for $x\in[0,1]$.

Question:
If $\sum_{n=0}^\infty|a_n|<\infty$, prove that $\sum_{n=0}^\infty a_nx^n$ converges uniformly for $x\in[0,1]$.

Here's my attempt: Let $x\in[0,1]$. Then,
$$\begin{align}\sum_{n=0}^\infty a_nx^n
& \le\sum_{n=0}^\infty|a_nx^n|\\
& = \sum_{n=0}^\infty|a_n||x^n|\\
&\le \sum_{n=0}^\infty|a_n||1|^n \\
& = \sum_{n=0}^\infty|a_n| <\infty, \tag{$*$}\end{align}$$ which by the Weierstrass $M$-test, we have that $\displaystyle \sum_{n=0}^\infty a_nx^n$ converges uniformly on $[0,1]$.
Here's my question: Have I correctly used the Weierstrass $M$-test? The conditions of the Weierstrass $M$-test are:

Let $\sum_{k=1}^\infty u_k$ be a series of real-valued functions on $E$. If there exists positive $M_1,M_2,\ldots$ with $\sum_{k=0}^\infty M_k <\infty $ such that $\sum_{k=0}^\infty u_k \ll \sum_{k=0}^\infty M_k$, then $\sum_{k=0}^\infty u_k$ converges uniformly on $E$.

I don't necessarily know that the $|a_n|$ are necessarily positive. However, I do know that they are non-negative. Thus, can I not use the Weierstrass $M$-test here? And I'm not entirely sure that I showed the dominated part entirely, but I've shown that the series $\displaystyle \sum_{n=0}^\infty a_nx^n$ converges for all $x\in[0,1]$. I suppose I just have a hard time distinguishing between pointwise convergence and uniform convergence.
Comment: I don't know if you know this theorem, but I think you should : if a series of real-valued functions converges normally, then it converges uniformly. But here $||x\to a_n x^n||_{\infty, [0;1]} = |a_n|$
Answer: You should not use any theorem. For $|x| \le 1$ : $$f_k(x) = \sum_{n=0}^k a_n x^n, \qquad f(x) = \sum_{n=0}^\infty a_n x^n$$ Since $\sum_{n=0}^\infty |a_n| < \infty$, the series for $f(x)$ converges absolutely and is well-defined.
Also, again for $|x| \le 1$ : $$|f(x)-f_k(x)| =| \sum_{n=k+1}^\infty a_n x^n| \le \sum_{n=k+1}^\infty |a_n x^n| \le \sum_{n=k+1}^\infty |a_n |$$
where $\lim_{k \to \infty}\sum_{n=k+1}^\infty |a_n | =0$.
Q.e.d. this is the definition of the uniform convergence.
Comment: Sarcasm, maybe, but that's exactly what you did here. Also, you did use a theorem or two along the way.
Comment: In other words, don't use Weierstrass M, reprove Weierstrass M whenever you want to use it.
Comment: @zhw.  Sarcasm ? :D Well yes, at least the first few months you are studying real/complex/functional analysis (I wanted to show to the OP there is nothing difficult here, just need to look at the good things)
Answer: You aren't really using WM correctly. What you wrote was, essentially, if $M_n\ge 0$ for each $n,$ with $\sum_n M_n < \infty,$ and if $\sum |f_n(x)| \le \sum_n M_n$ on $E,$ then $\sum_n f_n$ converges uniformly on $E.$ That is false (and indeed it is a mistake I see on MSE often, even by skilled people of high reputation).
WM actually says: If for each $n$ we have $|f_n(x)|\le M_n$ for $x \in E,$ and if $\sum_n M_n <\infty,$ then $\sum_n f_n$ converges uniformly on $E.$ In your problem, you would take $E=[0,1],$ $f_n(x) = a_nx^n,$ and $M_n= |a_n|.$ That should lead to a correct proof for you.


Apache Storm: This script is deprecated. when run storm nimbus, supervisor, ui

Question: I am fresh on Apache Storm. I just install Storm and ZooKeeper on my laptop. The ZooKeeper is going well but use the command: storm nimbus, it shows that "This script is deprecated". Please see the snapshot

Same problems when run the commands of storm supervisor and ui.
Anyone knows what is going wrong? Appreciated if anyone can help me to figure out that. Thanks~
Comment: Please include the error message in a text form
Comment: Sure, when I run "storm nimbus" command in cmd, it returns "This script is deprecated. Please use the Powershell storm.ps1 script instead". Same for supervisor and ui command. However, it can recognize "storm version" command
Comment: Do you know what is going wrong? Is the problem of storm.yaml? :)
Answer: The error message is telling you what's wrong. The script is deprecated, and you should use the Powershell script instead. In the storm/bin directory, there's a storm.cmd and a storm.ps1 script. You should use the storm.ps1 script instead of storm.cmd.
You can run the script from the normal Windows terminal with e.g. "powershell -file storm.ps1 nimbus", or if you want plain "storm nimbus" to work you can delete the storm.cmd file and Windows should automatically use the powershell script.
The background for this is that the storm.cmd script has not kept up with the Bash+Python scripts which are used in Linux, so we decided to deprecate it and replace it with a shorter Powershell script that delegates to the same Python script used in Linux. https://issues.apache.org/jira/browse/STORM-2558
Comment: Thank you very much


What would be the ideal dataset to train a model to detect advertisements in an image?

Question: I am thinking of the requirements for training a model that would be able to detect if there is any kind of ad in an image.
I know that this sound too broad not just for a question on CV but for the model itself.
There are numerous problems like:

The non-standard format of advertisements.
The fact that ads can also contain pictures apart from plain text, which apparently will display some objects.
Also the fact that in most cases are part of other objects, for example the frontpage of a magazine, the picture of a tv for a given moment, the contents of a billboard, a leaflet on the front windshield of a car, etc...

Still I'd like to make an attempt, so I am thinking what should be the ideal dataset to train a model for this task.
What I've come up with is to use a dataset of company logos and train a model to detect logos in picture.
Yet this strategy would eventually lead to more problems like

The false positive due to the fact that company logos exist also on the products sold apart from the product advertisements. This particular problem could be solved if there was a way to configuring the model to mark an object(a logo in this case) only if it occupied a portion of the picture larger than X%, since for example a logo on a car is relatively small compared to the car in contrast to the proportions of a car and a company logo in a magazine advertisement.

So, any ideas on which criteria should I take into consideration to create a useful dataset for this task are welcome.
Answer: I will limit my answer to web page ads to start.
You could build a dataset by modifying an ad-blocker browser extension like uBlock Origin not to block the ads, but highlight them (say, with a colored border that you could later detect) and then take a screenshot of the page. Then go browse around the web for a few days or weeks, that should allow you to build up a considerable dataset. For an computer vision task like this one, solved through deep convolutional networks, a big dataset (I'd say 10^5 samples at least) is necessary.
Of course, this would only label ads that the ad-blocker already knows how to block. But this isn't as useless as it sounds - I'd expect the model trained on this dataset to generalize at least a bit to out-of-sample ads that the ad-blocker doesn't know how to block yet. Then you'd go through cycles of correcting the model's mistakes to build an improved dataset to train new generations of the model - which I expect to do better and better. You could do this by using the browser extension to display your model's predictions while you browse the web and allow predictions to be corrected by you. In a few weeks, you'd improve the dataset and model a lot.
The ultimate ads to block would be the type embedded by Facebook in a user's newsfeed - those are unblockable by current ad-blockers AFAIK, because Facebook works hard to defeat their regex-like rules. If you inspect FB's HTML, there are no nicely labelled CSS classes and ids, they're all obfuscated. The "Sponsored" title FB puts near ads is made up of many separate divs.
You could train a model to detect the specific apprearance of the chrome (UI-element) frame and "Sponsored" title Facebook puts around these ads, then use that to label images you capture, then use this new dataset to train a more sophisticated model.
Hope all this helps, have fun, this is a fascinating topic.
FWIW, I do not expect the logo detector to work well, for the same reasons you state. At least, not by applying a simple rule like "everything in a rectangle around a logo is an ad". A logo detector's output could serve as input for an ad detector CV model though.
Comment: Would a model trained with this strategy have at least descent performance if you tried to feed it with images from the street? My guess is that it would perform good for the ads which would use similar design for the outdoors and the internet advertisement, but I have no idea if the model could learn generally common characteristics from ads just by looking internet ads and still perform sufficient for the rest kind of ads. Please share your thought on that. Thank you!


java drawing rectangle with nested loop

Question: I have a homework for college. I have to draw a rectangle with nested for loop that looks like this:
    1
   234
  34567
 4567890
567890123

for now I managed to do this:
public class DN2 {
    public static void main(String[] args){
        trikotnik(8);

    }
    static void trikotnik(int n){
        for (int i = 1; i <= n; i++) {
            for (int j = n; j > i; j--) {
                System.out.print("  ");
            }
            for (int j = 1; j > 1; j--) {
                System.out.print(j + " ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
        System.out.println();
        }
    }
}

Comment: isn't this a triangle? Also, if this is homework you should figure it out yourself.
Comment: What does your program currently print?
Comment: It prints this:

      1
    2 1 2
  3 2 1 2 3  etc...
  1
Comment: sorry I don' know how to make it go in new line here
Comment: @user3378249 just [edit] your original post if you have additional information you need to include.
Comment: Yes I agree it is a homework :D but I need just some advice.
Comment: I think there's a bug in `for (int j = 1; j > 1; j--)` - it seems to me that this loop would never be iterated, because if `j = 1`, it's not `> 1`.
Answer: To draw a triangle, at most you need two nested loops, one to deal with rows and another to deal with columns.
 for (int y=0; y<5; y++)
 {
   for (int x=0; x<9; x++)
   {
      //write character that should be at (x,y), i.e. (column, row)
   }
 }

You haven't specified anything about which numbers to should be printed where so I'm not going to guess at an algorithm but
for (int j = 1; j > 1; j--)

is saying, set j to 1 and while it is greater than one, decrement it. As you've set it to one, it can never be greater than one so this loop is skipped completely
Comment: It seems that the number printed in position `i` in row `j` is `( i + j - 1 ) % 10`.  Also, your code draws a rectangle, not a triangle.
Comment: yeah, I thought about my downvote and retracted it.  It's a bit ambiguous whether the OP is after a rectangle or a triangle.  If I didn't happen to know that "trikotnik" means "triangle", I also wouldn't know what to answer.
Comment: I'll let you know how it goes.

java drawing rectangle with nested loop


regex grep/egrep problems

Question: Based on searches on stackoverflow, I found out the difference between grep/egrep, but I still can't determine why this doesn't work.  I've even check it at https://regex101.com/ and it shows it checked out right.
Regex:
.*ping[\/] or ping\D

searching against (text.txt):
path=/bin/ping6
path=/bin/ping

I'm trying to skip the first and only find the 2nd.
If I would do grep ping text.txt it finds both which isn't what I want.
grep -e ".*ping[\/]" text.txt [doesn't work]
egrep ".*ping[\/]" text.txt [doesn't work]
grep -P ".*ping[\/]" text.txt [doesn't work]

I did get this to work but not sure why:
grep -P "ping\D" text.txt [worked]
grep -e "ping\D" text.txt [doesn't work]

What am I failing to understand with grep -e/egrep/grep -p/regex?
When I man grep -P it said it's highly experimental and not to use it.
Answer: \D is the letter "D" for extended regular expressions. For perl regexes, \D is a non-digit and \d is a digit.
To search for "ping" followed optionally by a digit followed by a slash, you want:
grep 'ping[[:digit:]]\?/'
grep -E 'ping[[:digit:]]?/'

To search for "ping" not followed by a digit:
grep -E 'ping($|[^[:digit:]])'   # ping then end-of-line or non-digit
grep -P 'ping(?!\d)'

GNU extended regular expressions  documented here.
Comment: Well that explains why it works for grep -P and not grep -e.  I actually don't want the 6 so i only want the word ping but ping 6 is first and it matches.
Comment: Isn't `grep -E 'ping($|[^[:digit:]])'` the same as `grep -E 'ping[^[:digit:]]'`? Since the `$` anchor is a non digit?
Comment: if the string is `/bin/ping`, then the pattern `'ping[^[:digit:]]'` **will not match** because there is no character following "ping" and `[^[:digit:]]` must match one character. The `$` anchor matches the empty string after "ping".
Comment: i saw there are several that are [[::]] and have something inside of them.  Why does it have double [[]] instead of just []?
Comment: Because `[:digit:]` is special syntax *inside* the `[...]` brackets. See the [regex(7)](http://manpages.ubuntu.com/manpages/trusty/en/man7/regex.7.html) man page.
Comment: @glenn you made me realize i had a typo in the question.  I wrote the trailing slash where it doesn't actually have one. so its just /bin/ping
Comment: Did you try that? What happened? What does the documentation say about that regex?
Comment: ping [^[:digit:]] worked for ping.  But why doesn't that match /usr/bin/at  if that is changed to "$f"[^[:digit:]]? I know I only asked for ping and I don't know if I need to start a new question, but I added it back in to my bigger script and it works for 99% of what is read it except for one.  So if its path=/usr/bin/at or path=/bin/ping both next characters are a space it should work.
Comment: is `"$f"[^[:digit:]]` inside single quotes?
Comment: `grep '/usr/bin/at[^[:digit:]]' test.txt` works fine but my script doesn't.

`VALUE1=$(my find command it returns several /usr/bin or /usr/sbin paths)

find command again -print | while read f; do

 #this just is checking to see if it is already in the file
 VALUE2=$(grep -e '"$f"[^[:digit:]]' test.txt

 if [ -z "$VALUE2" ]; then
  do something
 else
  do something
 fi

done`

if i take the ' ' away it works for everyone except /usr/bin/at why?
Comment: variables are not expanded within single quotes. Please search for similar problems, there are plenty of answers
Comment: @glennjackman grep -e ''"$f"'[^[:digit:]]' worked.  I found someone suggested using set -x to see exactly what was happening.  It works exactly as it should now.

regex grep/egrep problems


Animation doesn't start at the expected position center instead of leading top

Question: I am trying to implement an animation to symbolize the "swipe down". It's basically a circle scaling and moving down. I've done it but it only works with a tap gesture to start the animation and I want to run the animation right after the content appear using onAppear.
So, this works fine (starts in the middle):
Circle()
    .foregroundColor(.gray)
    .frame(width: 60, height: 60)
    .shadow(radius: 10)
    .offset(y: self.animated ? 350 : 0)
    .scaleEffect(self.animated ? 0.33 : 1)
    .onTapGesture {
        withAnimation(Animation.linear(duration: 1).delay(0.8).repeatForever(autoreverses: false)) {
            self.animated.toggle()
        }
    }

This doesn't work:
Circle()
    .foregroundColor(.gray)
    .frame(width: 60, height: 60)
    .shadow(radius: 10)
    .offset(y: self.animated ? 350 : 0)
    .scaleEffect(self.animated ? 0.33 : 1)
    .onAppear {
        withAnimation(Animation.linear(duration: 1).delay(0.8).repeatForever(autoreverses: false)) {
            self.animated.toggle()
        }
    }

The animation start from the leading top but I thought using onAppear that every element was already in place.

Any clue why the animation doesn't start where it should start?
UPDATE
Full content view code:
struct ContentView: View {

    @State var animated = false

    var body: some View {
        NavigationView {
            ZStack {
                Circle()
                    .foregroundColor(.gray)
                    .frame(width: 60, height: 60)
                    .shadow(radius: 10)
                    .offset(y: self.animated ? 350 : 0)
                    .scaleEffect(self.animated ? 0.33 : 1)
                    .onAppear {
                        withAnimation(Animation.linear(duration: 1).delay(0.8).repeatForever(autoreverses: false)) {
                            self.animated.toggle()
                        }
                    }
            }
        }
    }

}

Answer: Just found out what was the issue. For some reason NavigationView was messing with the initial layout of the Circle. I just removed it and things started working as expected.

Final code:
struct ContentView: View {

    @State var animated = false

    var body: some View {
        ZStack {
            Circle()
                .foregroundColor(.gray)
                .frame(width: 60, height: 60)
                .shadow(radius: 10)
                .offset(y: self.animated ? 350 : 0)
                .scaleEffect(self.animated ? 0.33 : 1)
                .onAppear {
                    withAnimation(Animation.linear(duration: 1).delay(0.8).repeatForever(autoreverses: false)) {
                        self.animated.toggle()
                    }
                }
        }
    }

}


como pegar um elemento Pai a partir de um filho com id?

Question: tenho o seguinte codigo:

hhaushdus

    <input name='profile_id' />

Preciso pegar essa div:

hhaushdus

  <input name='profile_id' />

Tentei desta maneira:
let element = document.getElementsByName('profile_id')[0].parentNode;

isso me retornou o pai:

hhaushdus

    <input name='profile_id' />

Basicamente são duas perguntas, como eu pego esta div com a classe 'minhaClasse' e se tem como fazer um getElement de um getElement tipo:
document.getElementsByName('profile_id')[0].parentNode.getElementByClassName('minhaClasse'));

Comment: Mas o objetivo é apanhar um elemento pai com a classe `minhaClasse` ou um irmão ? No exemplo dado `minhaClasse` é pai de `profile_id`
Answer: Eu recomendo dar uma olhada em https://www.w3schools.com/jsref/prop_node_childnodes.asp
Não lembro qual a sintaxe correta mas acho que esse código especifico pode te ajudar https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_childnodes2
EDIT
Esqueci de por alguns detalhes para referenciar um div especifico vc deve mostrar pro código qual div vc quer, recomendo colocar um id na div pai e dps executar os comandos e códigos que vc quer,
Exemplo:

function myFunction() {
    var c = document.getElementById("myDIV").childNodes;
    c[1].style.backgroundColor = "yellow";
}

PAI

FILHO

hhaushdus

    <input name='profile_id' />

<button onclick="myFunction()">Try it</button>
Comment: Eu editei dando um exemplo... Mas agora vou realmente escrever e colocar fontes
Comment: Eu só queria entender pq dão negativo se estou tentando ajudar ... E se a resposta não está errada por si só
Comment: Recomendo não colocar o link do artigo, em vez disso, transcreva-o.
Answer: você pode fazer o seguinte:
x = document.getElementsByClassName("minhaClasse");
isto vai retornar todos os elementos que possuem esta classe, depois basta você iterar e realizar o processo que você deseja:
for (var i = 0; i < x.length; i++) {
    //seu código aqui
}


Random variable $X$ has uniform distribution on section $[0,2]$. What's the expected value of variable $Y=\frac{X^{4}}{2}$

Question: Random variable $X$ has uniform distribution on section $[0,2]$. What's the expected value of variable $Y=\frac{X^{4}}{2}$
I don't know how to start this task.
I know formula for density of this distribution:
$f(x))\left\{\begin{matrix}
\frac{1}{b-a} &,x\in [a,b] \\
0 & ,x\notin [a,b]\
\end{matrix}\right.$
If I put values from section I will get:
$f(x))\left\{\begin{matrix}
\frac{1}{2} &,x\in [0,2] \\
0 & ,x\notin [0,2]\
\end{matrix}\right.$
Can I use this to solve this task or should I take a go at it with different method?
Comment: Do you know how to determine the expected value of a (function of a) random variable, from a PDF?  For instance, if you wanted to find the expected value of $X$, you would write $E(X) = \int_{x=0}^2 x f(x)\, dx$.  If you want to find the expected value of $Y$, you would write $E(Y) = \int_{x=0}^2 y(x) f(x) \, dx$, where $y(x) = \ldots$?
Comment: Do you have a definition for expected value (given a continuous random variable and probability density function)?
Comment: @BrianTung so $y(x)=\frac{x^{4}}{2}$, what should I do about $f(x)$?
$f(x)=\frac{x^{1}}{2}$ based on density?
Comment: Answer would be $\frac{{8}}{5}$ in this case, is this right?
Comment: You already have $f(x)$ in your problem statement.  Only look at the interval $[0, 2]$.  ETA: Incidentally, the usual term for a closed interval is a **segment**.
Comment: https://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician
Comment: @BrianTung Are you sure $8/5$ is not correct? I got the same result, and I also numerically checked it.
Comment: @VarunVejalla: You're right.  That's what I get for doing it in my head.
Answer: There's probably a shortcut somewhere, so you can find $\mathbf{E}Y$ without the pdf, but I don't know it. So first, it's the easiest to find CDF of $Y$:
$$
P(Y<y) = P(X^4<2y) = P(0<X<(2y)^{\frac{1}{4}})
$$
Since $X$ is positive, and $X^4$ is a strictly increasing funciton, it's easy enough to find it. From that, take a derivative to get pdf. Now, follow @BrianTung's suggestion by using the definition of $\mathbf{E}X$
Answer: The expected value of a probability distribution, $g(x)$, is defined as $\int_{\mathbb{R}}x g(x) dx$. In your case, $g(x)$ is the distribution of $\frac{X^4}{2}$, where $X \in U(0, 2)$. Using the substitution $x = \frac{u^4}{2}$, which is equivalent to the law of the unconscious statistician, the integral becomes  $$\int_{0}^{2} \frac{u^4}{2} \cdot\frac{1}{2-0} \  \mathrm d u$$
Can you finish from here?


Como fazer rolagem automatica

Question: estou desenvolvendo uma aplicação onde o usuário faz uma pergunta e o servidor entrega uma resposta, estou com o problema em fazer com que a barra de rolagem vá acompanhando a conversa, até o momento estou tendo o histórico da conversa na tela porém tenho que arrastar com o mouse para ver as novas mensagens.
Estou utilizando JSF com AJAX .

                    <h:panelGroup id="dialogo">
                        <ui:repeat var="conversa" value="#{chat.conversas}">
                            <h:panelGroup rendered="#{conversa.usuario == 1}">

                                        <h:outputText value="#{conversa.intereacaoFala}" />

                            </h:panelGroup>
                            <h:panelGroup rendered="#{conversa.usuario == 2}">

                                        <h:outputText value="#{conversa.intereacaoFala}"/>

                            </h:panelGroup>
                        </ui:repeat>
                    </h:panelGroup>

Answer: Testei dessa forma aqui e deu certo, tenta pra ver.

É importante lembrar que tem que ter um height inicial, o overflow-y, é para exibir apenas barra na vertical, auto seria para não aparecer se não precisa-se, caso não der certo tenta também overflow:scroll
Comment: Obrigado pela ajuda Marcos, mas não deu certo :/

Como fazer rolagem automatica


Is it typically assumed that functions are bijective?

Question: That is, if I'm reading a textbook, or perhaps even lecture notes, and there are theorems or definitions regarding functions, is it typically assumed that functions are bijective or if nothing is specified is it taken to mean that they are not bijective (or perhaps they can be either bijective or not, depending on context?)
For example, the definition of a function being measurable at the wiki page here. The definition says "A function $f:X\to Y \dots$. Can $f$ be assumed to be bijective?
Comment: Definitely not.  Bijective functions are very special.
Comment: No, typically it will not be bijective.
Answer: No. Every single time a function is bijective, it will be said so, either explicitly or by using a qualifier that implies it, like isomorphism or automorphism.
Comment: I would consider that "isomorphism" says "bijective" explicitly, as it is a direct part of what isomorphism means. But yes, I  will edit my answer.
Comment: I still gave you a +1, but it's perhaps worth pointing out that, arguably, statements like "suppose $\theta:G\to H$ is an isomorphism" only *implicitly* say that $\theta$ is bijective.
Comment: Alright, Thank you. I accepted your answer (it answered my questions perfectly fine), but perhaps edit your answer to reflect Will R's point, if you have time.


Split DF string column and add it as new column

Question: I want to take a DF column and build new column based on str splitting.
Column values looks like that:
abcd <> 1234
In order to split i'm using the following:
df['user_id'] = df['Customer User Id'].str.split('<>').str.get(1)

This action works but i'm getting red window saying:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
Tried to replace the code with loc:
df['user_id'] = df.loc[:,['Customer User Id']]['Customer User Id'].str.split('<>|<').str.get(1)

but the error still shows
Any suggestions..
Comment: can you show what is your data? so that we can help you
Comment: Is `df` already a slice of another *DataFrame*? Either way, it is only a warning.
Comment: @pacholik Yes, df is already slice from raw_df
Comment: @RohanAmrute Not sure what data you want to see, the data in this column is strings looks like "abcd <> 1234" and i want to create new column with only the numbers on the right side
Comment: I tried  your code, there is no error or warning of such kind
Comment: Possible duplicate of [How to deal with this Pandas warning?](http://stackoverflow.com/questions/20625582/how-to-deal-with-this-pandas-warning)
Comment: Take look at http://pandas-docs.github.io/pandas-docs-travis/indexing.html#returning-a-view-versus-a-copy and http://stackoverflow.com/q/20625582/1028589 .
Comment: Added screenshot with the message [link](https://goo.gl/XoSJNl)
Answer: I am using this kind of data:
key1  key2
22    abcd <> 1234
34    abcd <> 1234
12    abcd <> 1234
55    abcd <> 1234

And the code is:
my_df["key3"] = my_df['key2'].str.split('<>').str.get(1)

Output is :
key1    key2    key3
22  abcd <> 1234    1234
34  abcd <> 1234    1234
12  abcd <> 1234    1234
55  abcd <> 1234    1234


How do you open a LUA file that is most likely a binary?

Question: I have a .lua file I am triying to access to edit the code. But when I open it in VS Code the next text appears:

"The file is not displayed in the editor because it is either binary
  or uses an unsupported text encoding".

If I open it anyway it opens with some characters like this:

Is this file encrypted or compiled as binary? and if so is there any way I can decompile it so I can see the code?
Answer: It looks like you have some Lua bytecode
There are a variety of tools to convert this to readable text, depending on what version of Lua is in use.
Comment: @KeithThompson - `.luac`
Comment: Both `.lua` and `.luac` file extensions are just a convention, not a standard.  Lua files could have arbitrary file extensions.  This is because of Lua was born in Linux world, where file extension means nothing.
Comment: You should use the `.lua` extension only for Lua source code. (There doesn't seem to be a convention for naming Lua byte code files.)
Comment: @EgorSkriptunoff: That makes sense. It would be nice of the `luac` man page mentioned it.
Comment: And a Lua binary file is functionally equivalent to a Lua source file, except of course for reading and editing by humans. So, it is somewhat reasonable to use the same naming convention.


Is there a "natural" / "categorical" definition of the "parity" of a permutation?

Question: Given a permutation $\sigma$ on $n$ elements (i.e. $\sigma \in S_n$), there is a notion of "parity" (or "sign" or "signature") of $\sigma$, which can be defined in several equivalent ways (look here). This  produces a homomorphism $S_n \to \{\pm 1\}$.
I've known the various definitions, the proof of their equivalences and the various applications of them for quite a while, and yet something seems missing. I can't convince myself that any of those definitions is really "natural". Of course "natural" is something rather subjective, but for me at least, it is close in meaning to "categorical". For example, a "natural" presentation of the definition (and basic properties) of addition/multiplication of natural numbers, can be achieved by considering the category of finite sets, where these operations are categorical sum/product.
Since $S_n$ is the automorphism group of a set with $n$ elements, I would say that the (horizontal?) categorification of it is the groupoid of all sets with $n$-elements. This is arguably a more "natural" object. Of course, this groupoid is equivalent to $S_n$ so it is just a matter of perspective. Now, we can define the quotient groupoid for which the hom-sets are the two element sets of equivalence classes of isomorphisms, where two are equivalent if there quotient is an even permutation. This is cheating of course. The question is, can we define this quotient in a "natural" way? I find it very surprising that this kind of structure associated with plain finite sets, is so well hidden.
I heard that the K-theory of finite sets encodes some information of this sort. If this is so, I would be very happy to hear more about it.
As a final note, one famous neat application of the notion of parity of a permutation is the proof of the impossibility of the 14-15 puzzle. The proof is beautiful, but it applies group-theory techniques to something which is most naturally viewed as a groupoid. This might be completely unrelated to the main question, but it seems that a more natural/groupoidal definition of parity might be applicable to this situation as well.
Comment: I probably should have explained more. I meant that the objects are the possible states of the puzzle and the arrows are the legal moves. Since at each stage you can apply only a subset of permutations (depending on where the hole is), it is not an $S_n$-set in an obvious way, but rather a more complicated groupoid.
Comment: What you describe is only a graph: to get a category you have to throw in composites of legal moves too.
Comment: Why is 14-15 more naturally a groupoid? Are you thinking of reinterpreting the notion of $G$-set as a groupoid, where you add arrows $x \xrightarrow{g} gx$ for all set elements $x$ and group elements $g$?
Comment: (Somewhat) related: [What structure does the alternating group preserve?](http://math.stackexchange.com/questions/5191/)
Comment: @Hurkyl, Of course. Thank you for the correction. I only described a "generating set", but you should include all compositions of these.
Comment: An other direction, can we characterise the parity map $S_n\to \{0,1\}$ by some universal property?
Answer:
Now, we can define the quotient groupoid for which the hom-sets are the two element sets of equivalence classes of isomorphisms, where two are equivalent if there quotient is an even permutation. This is cheating of course. The question is, can we define this quotient in a «natural» way?

Fix a field $k$ (of $\operatorname{char}\ne2$). There is a functor $\det\colon S\mapsto\Lambda^{top}(k[S])$ from our groupoid to the category of vector spaces. Now we can define the quotient groupoid ($f\sim g\iff\det f=\det g$).
Whether this definition is natural enough, can be debated, of course.
At least it's natural in the sense that one doesn't have to identify a set with $\{1,\ldots,n\}$ etc.
P.S. The exterior algebra can be defined w/o permutations (as the quotient of the free algebra by relations $v\wedge v=0$).
Answer: Here's an answer that might be more like what you were expecting. The collection of all symmetric groups together organize into a symmetric monoidal groupoid, namely the symmetric monoidal groupoid $S$ of finite sets and bijections. This is the free symmetric monoidal groupoid on a point.
Now, given any symmetric monoidal category you can ask what it looks like when you freely adjoin inverses to it, at various levels of sophistication. First, you can just ask for its Grothendieck group; that is, you look at the commutative monoid of isomorphism classes, then adjoin inverses. This gives you $\mathbb{Z}$.
Second, you can ask for a symmetric monoidal groupoid rather than just a group, but one where every object is invertible (I think this is sometimes called a "Picard groupoid"). This gives you a groupoid with $\pi_0 \cong \mathbb{Z}$ and $\pi_1 \cong \mathbb{Z}_2$: that is, the objects under the symmetric monoidal product are just $\mathbb{Z}$ again, but now they have automorphisms of order $2$. The induced map from $S$ sends each permutation to its sign, but also assigns data to isomorphisms between finite sets which we haven't necessarily identified. This Picard groupoid is the free Picard groupoid on a point.
Continuing in this way, you can ask for a symmetric monoidal $n$-groupoid rather than just a groupoid, or in other words a connective $n$-truncated spectrum. The spectrum you get in this way is the $n$-truncation $\tau_{\le n}(\mathbb{S})$ of the sphere spectrum (which is the free spectrum on a point). This is a version of the Barratt-Priddy-Quillen theorem, and it reveals that the $\mathbb{Z}$ above was the zeroth stable homotopy group of spheres, while the $\mathbb{Z}_2$ above was the first. These $n$-truncations, and the natural map from $S$ into them, are candidates for "higher sign characters" as in Ganter-Kapranov.
Answer: This is the abelianization map $S_n \to S_n/[S_n, S_n]$. It's universal with respect to maps from $S_n$ to abelian groups.
Comment: @Kotel: you cannot define the parity of a map, even a bijection, between finite sets. The only maps which have well-defined parity are automorphisms of a fixed finite set, so there's very little difference between talking about the group and talking about the category here.
Comment: Good point. But still, I was hoping for something a bit different. Namely, that all this should be something about maps between finite sets and not just group theoretic properties of $S_n$. Or rather, *why* the abelianization of $S_n$ is the group of order two for all $n$.
Answer: I am not sure at what level of sophistication you are looking for such a "natural" definition but a good candidate is orientability. Thinking of the permutation as permuting vectors in a basis for a finite-dimensional vector space, one can characterize parity of the permutation in terms of preserving or reversing the orientation.  The orientation itself can be formalized in terms of the determinant bundle (in this case over a single point) of the vector space. Namely, the orientation is an element of this line bundle, and the permutation induces an action either by $+1$ or by $-1$ on this bundle, corresponding respectively to a even or odd permutation.
Comment: I am aware of this idea, but it is somewhat unsatisfactory in my opinion. The geometric notion of orientation gives a nice intuition, but to formally extract the notion of parity from it requires some technical work. For example, you can define the parity as the determinant of the associated permutation matrix. This is possible (and non-circular), but it is a bit mysterious. Note that I am not looking for something elementary, or simple in any way. I am hoping for a construction that will say something like "parity is the universal 'blah' of the category of finite sets".
Comment: What I tried to point out in my answer is that one does not need to resort to matrices here. The determinant bundle is a fairly canonical construction, and the induced action is similarly "natural" in a categorical sense. Thus we are reduced to a $Z_2$ action on a line bundle, all coordinate-free.
Comment: You are right. I wasn't paying attention enough. This is similar to Grigory's answer. It still seems strange that you have to pass through vector spaces (whether you call it geometry or algebra).
Comment: Just to elaborate a bit, when passing through vector spaces, there is an arbitrary choice of the scalar field. Since the construction does not depend on it, it seems artificial. Perhaps there is something general to say about the connection to $GL_n$ as a group scheme. Or maybe even $\mathbb{F}_1$ (though I really know nothing about that, so maybe I shouldn't through big words...)
Comment: I would suggest $\mathbb{F}_3$. That seems more natural.


Twig e Namespaces

Question: Olá, estou com uma dificuldade em implementar o Twig no meu projeto MVC, estou usando namespaces, autoloader toda aquela coisa do PSR-0.
Gostaria da juda de vocês para implementar por que já estou quase surtando. rs
public function render($file, $data = null){
    require_once LIB . '/Twig/Autoloader.php';
    \Twig_Autoloader::register();

    $loader = new \Lib\Twig_Loader_Filesystem('/path/to/templates');
    $twig = new Twig_Environment($loader, array(
        'cache' => '/path/to/compilation_cache',
    ));
}

Essa é meu método que irá renderizar o template, até o momento possuo o seguinte erro:
Exception: Controller Twig_Autoloader not found. in C:\UwAmp\www\system\engine\autoload.php
Comment: Se você está usando PSR-0 por que não simplesmente inclui o vendor/autoload.php e dá um use na classe do Twig ?
Comment: Tentei fazer isso, mas ele começa da erro em outras classes dentro do Twig, sei lá o que interface blá blá blá. rs
Answer: Mais fácil vc usar o composer pra fazer o autoload, é só rodar

composer require "twig/twig:1.*"

e depois incluir o autoload gerado pelo composer:

require_once '/path/to/vendor/autoload.php';

O twig tem uma documentação bem completa que explica como fazer a instalação pelo composer

Twig e Namespaces


iEquation in Rudin's 1.1.3 (Principles of Mathematical Analysis)

Question: So I've been working on Rudin's 1.1.3 for a while and I think I'm close to a figuring it out.
In the set $A$ there are positive rationals $p$ such that $p^2<2$ and we can find a rational $q$ in $A$ such that $p<q$. So we can also say $q^2<2$.
I want to say that $q=p+x$ where $x$ is very small so that I can say $p^2<q^2$ because $q^2=(p+x)^2=p^2+2px+x^2$ and that's bigger than just $p^2$
Now $p^2<q^2<2$ and I can move things around so that I get $0<q<p+(2-p^2)/(q+p)$ which I can then rearrange into what I have below.
So, unless I'm doing things wrong, I can get $p<q<p-(p^2-2)/(p+q)$
The latter part of that relation is somewhat close to what Rudin has in 1.1.3 but I still have inequalities and my denominator still has a $q$.
=Update=
So reading a helpful reply, I've simplified by attempts:
We know that $q^2<2$ and if $q=p+x$ then we have $(p+x)^2<2$. We can then the $x$ on one side and get this; $x(2p+x)<2-p^2$
But still not sure completely clear what the next methodological step is.
=Update 2=
For some reason I still can't make the connection from $2p+x = p + p +x$ and the $p +2 $. I understand that the latter expression is probably chosen due to elegance in how it will nicely simplify eventually.
For this last stage, I understand that
$0<p^2<q^2=(p+x)^2<2$ and because $(p+x)^2<2$ then either $p$ or $x$ is positive and less than $sqrt(2)$. I suppose we can think of it as $p+x<sqrt(2)$ even though we shouldn't be using sqrt(2). Like, sure, $p+x<sqrt(2)<2$ but then how do we get rid of that inequality when we're replacing that $p+x$ with $2$.
I'm pretty sure I understand the theory of what Rudin's doing and your replies, but the actual computation with the inequalities is messing me up.
Comment: Are you talking about Equation (3) in Section 1.1 of Rudin's *Principles of Mathematical Analysis*?
Comment: Yes, on page 2. Sorry, should have mentioned the book since he has multiple ones.
Comment: You already know that there are infinite many $q$ that can be selected, So there are two focused questions you might ask: Can someone help me show that Rudin's formula for $q$ works?  How was Rudin motivated to come up with his formula for $q$?
Comment: Guess you spent enough time on this. If you would like to see a proof that Rudin's $q$ works, see https://math.stackexchange.com/a/2217492/432081 Bunch of further info and proofs there.
Comment: You can't get a rational number that is "infinitely close" to $\sqrt{2}$. That statement is not meaningful. You can get a rational number as close as you like to it, but depending on how close you say you want it, you have to pick a different number. Also, it's not that you "know that $p + x < 2$, it's that you're looking at what the consequences are *if* this is true, and then at the end you're picking $x$ so that it is true. Then you say that for a number to be in the set $A$, it has to be less that $2 - p^2$. That's not true.
Answer: I don't think it's necessarily easy to go from what you're doing to what he does.
You are basically looking for some small, positive number $x$ that satisfies the inequality
$$x(2p + x) < 2 - p^2.$$
At this point, there are many ways to pick $x$. For example, you could pick $x$ to be any number that is both less than $p$ and less than $(2-p^2)/3p$.
But if you want to get Rudin's result, you first impose the condition $x < 2 - p$. Now it is sufficient for the inequality
$$x(p+2) \leq 2 - p^2$$ to be satisfied.
So it's enough to take
$$x =  \frac{2-p^2}{p + 2}$$
and to check that this value of $x$ satisfies $x < 2-p$. This is straightforward to check.
What I think Rudin is really doing is this. Draw the parabola $y = x^2 - 2$. You already know a point $(p,p^2 - 2)$ on the parabola, and you want to find a better approximation than $p$ to $\sqrt{2}$, the new approximation being on the same side of $\sqrt{2}$ as $p$ is.
To do this you draw a line of positive (rational) slope $m$ through the point $(p,p^2 - 2)$ you know, and take the intersection $(q,0)$ with the $x$-axis. The fact that $m > 0$ guarantees that $q$ and $\sqrt{2}$ are on the same side of $p$. To be certain that you don't overshoot $\sqrt{2}$, all you need to do is make sure that the slope $m$ of the line is larger than that of the secant line from $(p,p^2 - 2)$ to $(\sqrt{2},0)$, which is $p + \sqrt{2}$. For convenience, Rudin takes $m = p + 2$, but he could have taken $p + 3/2$ or a lot of other things.
Addendum
When you reach $x(2p + x) < 2 - p^2$, you have a lot of freedom in how to pick $x$. In this problem, all we need to do is find one positive value of $x$ that works. The condition is equivalent to
$$x < \frac{2-p^2}{2p + x}.$$
Because $x$ appears on the right side, it wouldn't make sense to simply say "Pick $x$ to be less than $(2-p^2)/(2p + x)$." Nonetheless, since $x$ can be picked as small as we like (clearly, if $(p + x)^2 < 2$, this will remain true if $x$ is replaced with a smaller positive number), we can simplify things by assuming that $x$ is less than some convenient value. In particular, $2p + x$ will be much simpler if we replace $x$ with $p$, since $x$ will no longer appear in the expression.
Consider the following chain of inequalities, which may or may not be true for a given value of $x$.
$$x(2p + x) < x(3p) \leq 2 - p^2.$$
The first inequality will be true if $x < p$. The second will be true if $x \leq (2-p^2)/3p$. So any choice of $x$ that is less than the minimum of $p$ and $(2 - p^2)/3p$ will necessarily be a solution of the original inequality.
Addendum 2
In response to a comment, I will add details about the part of the answer that explains Rudin's expression for $q$.
This is very much like what I explained above for $3p$, but with $p + 2$ instead. Essentially, in order for the inequality $x(2p + x) < 2 - p^2$ to hold, it is sufficient for the following two inequalities to hold:
$$x(2p + x) < x(p + 2) \leq 2 - p^2.$$
I have not written $p + 2$ here for any reason other than that it's the particular expression Rudin chose. Other expressions would also work, including $p + 3/2$, or more generally $p + a$ where $a$ is any rational number larger than $\sqrt{2}$.
When does the double inequality hold? The first part holds when $2p + x < p + 2$ or, equivalently, when $x < 2 - p$. The second part holds when $x \leq (2 - p^2)/(p + 2)$. As I mentioned in my answer, the second inequality actually implies the first, because we certainly have $(2-p^2)/(p + 2) < 2 - p$. Therefore it is enough to take $x = (2 - p^2)/(p + 2)$, or any smaller rational number.
Comment: Thanks for the help.

That first inequality of yours is great because I see that I was going down a too complicated path. I went a step back and simplified my question.

I'm not sure what prompts the condition other than something like if q^2 < 2 then q <2 and so p+x < 2. But even then, I'm also sure where your second inequality comes from.
Comment: I've added a clarification of what I said about how you can select $x$.
Comment: Yes, it's getting more clear. I still have to think about it more but this will be good to consider in the meantime. Thanks.
Comment: I like the geometric description of what Rudin might be doing. Makes me want to develop the theory of linear quadratic systems over the rational numbers.
Comment: You know, I think I get it now because of similar asked questions. I've got to where I have "x (2p + x) < 2 - p^2" and I know we have to d something about the terms in the brackets so we can have x only on the left side. Apparently we have "2p + x" becoming "p+2" but that's because we somehow know that "p + x < 2". Without knowing the answer, how do you get from "2p+x" to "p+2"? I understand the "p+p+x" part but what's the intuition about the "p+x<2" to make the magic happen? the 2 seems arbitrary to me, unless Rudin wanted a number which could perhaps relate to both A and B simultaneously?
Comment: At the end of my answer I gave what I think is a more plausible path to get to Rudin's $p + 2$, which as I've explained is only one of many choices possible. There is not really an automatic and natural path that I see to get from your approach to his, so what I did was force things to work out with his expression for $q$. I'll add more details about this to my answer.
Comment: Thanks for the clarification. I've updated my original question with my second update. I think it's trouble with inequalities at this point. I understand your theory of forcing things to work out for his expression for q, but when I do it I still can't seem to justify my actions going from "2p+x" to "p+2" even when I know that p+x<2 is one of the many numbers he could have chosen.
Comment: What I'm saying is that if the double inequality is true, then the original inequality is true. The solution of the inequality $2p + x < p + 2$ is $x < 2 - p$. So at least the first half of the double inequality will be true if we pick $x$ in any way that is $< 2 - p$. Then we look at the second half of the inequality, and point out that if the second half is true, then the first half is automatically true.
Comment: Okay I'm pretty sure I got it now. I've updated for a third time with my notes. Even though it's my rough notes, do you think what I have is a solid explanation for Rudin's equations?


Quais as principais diferenças entre Kotlin e Scala?

Question: Já estão bem claras as diferenças entre Kotlin e Java, tais como:

Mais conciso (redução de até 40% do código)
Null Safety
Inferência de tipos
Data class
Interoperável com Java

Porém, todas estas características já existem no Scala, uma linguagem que também roda na JVM.
Assim, quais as principais diferenças entre Kotlin e Scala? Quais são as lacunas existentes no Scala que motivaram o Kotlin?
Comment: `Porém, todas estas características já existem no Scala, uma linguagem que também roda na JVM (...) Quais são as lacunas existentes no Scala que motivaram o Kotlin?` Não, não é por existirem lacunas que as coisas são criadas. O ecossistema das linguagens funciona a maior parte do tempo assim: https://xkcd.com/927/
Comment: Sucintamente, as principais diferenças entre Kotlin e Scala é que Kotlin é mais rápido e mais fácil de ler.
Comment: Uma delas: https://pt.stackoverflow.com/q/139839/101
Comment: @acklay porque?
Comment: @bigown eu li algumas comparações e essa foi uma conclusão que tirei em relação ao funcionamento das duas. Esse [projeto no Github](https://github.com/SidneyXu/AndroidDemoIn4Languages) possui um uma comparação usando 4 formas diferentes. Java, Groovy, Scala e Kotlin. Não acredito que teve alguma tendenciosidade nesta análise.
Answer: Imagino que está querendo saber porque criaram Kotlin se Scala já resolve esses problemas, ou seja, por que criaram um Java melhor que o Java se Scala já faz isso? Se não for isso imagino que a pergunta é duplicata.
Talvez o maior motivo seja porque Scala até é interessante, mas não é exatamente um Java melhor que o Java. Ela pendeu muito para o lado funcional e cria dificuldades para o programador médio acostumado com uma linguagem essencialmente imperativa. Kotlin mantém o espírito imperativo do Java muito mais que Scala fez. Os problemas mais típicos que o Java resolve são resolvidos de forma mais adequada em Kotlin.
Verdade seja dita que Kotlin começou ser desenvolvida quando Scala estava em um estágio menos avançado e tinha mais problemas do que tem hoje para o programador médio. Scala está mais palatável.
Para atender os requisitos da linguagem um compilador Scala não conseguiu ser tão eficiente. Já Kotlin foi pensada para ter uma sintaxe que favorecesse a compilação. Podemos dizer que esse é um motivo oficial. Embora pra falar a verdade acho o compilador de Kotlin bem lento (talvez Scala seja trágico, acontece muito em linguagens que oferecem facilidades demais).
Ali fala também que o conjunto de características não agradava. E este geralmente é o motivo para se criar uma nova linguagem. Raramente se cria algo novo em, linguagens de mercado, apenas se faz o já existente de uma forma diferente com um conjunto e intersecções específicas diferente do que já existe, e isso faz diferença.
Especificamente Kotlin:

é um pouco mais explícita que Scala. Linguagens funcionais tendem a ser muito concisas sacrificando um pouco a legibilidade. Kotlin optou por ser mais verbosa onde pode acrescentar algo importante para o código, não tanto quanto Java.
é um pouco mais voltada para OOP que Scala.
interopera com Java melhor.
compila para e interopera com JavaScript.
possui Extensions.
é segura para uso de valores nulos na própria linguagem.
tem smart casts.
usa inline functions para eficiência onde é possível.
trata a delegação como primeira classe.
pode chamar uma função pelo seu nome como uma referência.

Por outro lado ela não tem:

o modelo Actor implementado na linguagem.
geradores (yield).
tipos por valor, mas terá quando Java 10 implementar, o que deve ser mais compatível com Java.
tipagem estrutural.
XML na linguagem.
criação de novos operadores
tipos existenciais.
tipagem dependente do caminho.
macros

Certamente tem outras coisas que eu não lembro ou não achei. Obviamente tem pequenas diferenças de sintaxe. Tem diferenças pequenas em cada mecanismo, por exemplo Qual e a diferenca entre Kotlin data class e Scala case class?. E isso pode ter ficado defasado ao longo do tempo, tem coisas que a linguagem não tem agora, mas é uma questão de tempo.
Coloquei no GitHub para referência futura.


Amount of Possible Bootstrap Samples

Question: I know that the total possible amount of distinct bootstrap resamples of size $n$ is $\binom{2n-1}{n-1}$. Is there any way to prove or justify this?
Comment: Proof is by induction. Start with n=2, then show that for any arbitrary dataset, you can create "new" datasets by replacing one or more observations from the existing unique bootstrapped datasets with the new observation, deduplicating
Answer: A standard technique is the "stars and bars" construction.
By "distinct bootstrap resample" what you mean is a sequence of $N$ elements of a set of size $N$ without paying attention to their order.  Enumerate this set as $\{x_1, x_2, \ldots, x_N\}.$  Corresponding to any such sequence is the unique ordered sequence in which all of the $x_1$ in the bootstrap sample (if any) precede all the $x_2$ in the sample, which precede all the $x_3$ in the sample, etc.  This sequence, in turn, is determined by the counts $n_j$ of each $x_j.$
Draw a diagram of this sequence by placing $n_1$ stars * (representing the $n_1$ copies of $x_1$ in the sample) followed by a bar | to their right, then $n_2$ stars (representing the $n_2$ copies of $x_2$ in the sample) followed by another bar, and so on, until placing the last $n_N$ stars (but not followed by any bar).
For instance, in a set of $N=5$ elements suppose the bootstrap sample is $(x_1,x_5,x_3,x_4,x_3).$  Its ordered version is $(x_1,x_3,x_3,x_4,x_5),$ for which the counts are $(n_i) = (1,0,2,1,1).$  Its stars-and-bars diagram therefore is

* | | * * | * | *

Clearly such a diagram always has $N$ stars (because the bootstrap sample has $N$ elements) and $N-1$ bars (because they separate $N$ groups of stars).  Numbering the $N+N-1$ symbols left to right as $1,2,\ldots, 2N-1,$ note that the bars in this example have the numbers $\{2,3,6,8\}\subset\{1,2,\ldots,9\}.$
Conversely, corresponding to any diagram of $N$ stars and $N-1$ bars and an enumeration of $N$ observations we can recover the bootstrap sample.  E.g., the diagram

| | | * * * | | * * | * * * |

with $N=8$ stars and $7$ bars corresponds to the (sorted) bootstrap sample $(x_4,x_4,x_4,\,x_6,x_6,\,x_7,x_7,x_7)$ of an eight-element set.  The bars appear at positions $\{1,2,3,7,8,11,15\}\subset\{1,2,\ldots,15\}.$
To count the distinct bootstrap samples, then, it suffices to count the distinct stars and bars diagrams.  But each such diagram corresponds to an $N-1$-element subset of $N+N-1=2N-1$ positions: namely, the positions in which the bars are located.  By definition, this count is the binomial coefficient $\binom{2N-1}{N-1},$ QED.

Application
There are very efficient methods to sample without replacement and to return that result in order.  Thus, you can create bootstrap samples very efficiently with stars and bars.
To illustrate, here is an R implementation.  Given a dataset x, it generates an array, samples, whose columns represent all possible bootstrap resamples of x in terms of the positions of the bars.  (This makes it impractical to apply to real problems, where $\binom{2N-1}{N-1}$ is so large that samples cannot be stored or even computed in reasonable time.)  Because the relative chance of a resample with counts $(n_i)$ is $1/\prod (n_i!),$ columns cannot be selected uniformly from this array: the draws must be weighted by these relative chances.  A caller-specified number N of resamples is returned in an array, one column per resample.
sample.boot <- function(N=1, x) {
  n <- length(x)
  samples <- combn(2*n-1, n-1)                         # Columns represent possible bootstrap samples
  counts <- apply(rbind(0, samples, 2*n), 2, diff) - 1 # Counts the stars between the bars
  p <- exp(-colSums(lfactorial(counts)))               # Relative chances of the samples
  p <- p / sum(p)
  j <- sample.int(ncol(samples), N, replace=TRUE, prob=p)
  apply(counts[, j, drop=FALSE], 2, function(i) rep(x, i))  # Replicates each `x[i]` `n.i[i]` times
}

E.g., the commands
X <- sample.boot(1e5, c("a", "b", "c"))
table(apply(X, 2, paste0, collapse=""))

produce the output

  aaa   aab   aac   abb   abc   acc   bbb   bbc   bcc   ccc
 3655 11171 11127 11031 22145 11224  3725 11148 11105  3669

The first line is the ordered bootstrap resample and beneath it are the counts of how many times each resample appeared among $10^5$ draws.  For instance, the chances of aaa, bbb, and ccc are all $1/3^3,$ for expected frequencies of $10^5/3^3 \approx 3704.$  The actual frequencies in this experiment were $3655,$ $3725,$ and $3669,$ differing from their expectations by small amounts attributable to the randomness of the drawing.

References

Richard Stanley, Enumerative Combinatorics (Volume I), Second Edition.  Available at http://www-math.mit.edu/~rstan/ec/.

Almost any resource on mathematical problem solving at an elementary level ("elementary" does not mean "easy" or "unsophisticated"!).  See https://brilliant.org/wiki/integer-equations-star-and-bars/ for instance.
Comment: @Christian You are absolutely right.  I am grateful for your attention to this (and wish the system allowed me to award you reputation for your efforts).  I have fixed the example so it generates bootstrap resamples with the correct probabilities.
Comment: If I understand things correctly, your sample.boot function will produce bootstrap samples that have a different distribution than straight i.i.d. sampling from the empirical distribution, because the latter produces a uniform distribution of ordered samples, whereas yours produces a uniform distribution over distinct samples ignoring the order. Not sure how much of a problem that is and what implications it has?
Comment: @Christian To what problem are you referring?  The distinction between sampling with and without replacement from the bootstrap distribution, perhaps?
Comment: According to Efron's original paper (and probably most literature), standard nonparametric bootstrap is defined as i.i.d. sampling from the empirical distribution. Are you claiming that your sample.boot function produces the same distribution over bootstrap samples than that? I doubt it.
Comment: Example $N=4$. Probability under i.i.d. sampling to obtain four times the first sample element is $(1/4)^4$. What you do seems to produce a uniform distribution over the possible distinct bootstrap samples. There are, if I'm not mistaken, 35 of these, so the probability for the bootstrap sample above under your scheme will be 1/35, which is different. Am I wrong?

Amount of Possible Bootstrap Samples


Bayesian logistic regression: mixed categorical and continuous predictors

Question: I'm trying to model the probability of an event Y based on three independant variables, one (X) is continuous (a log count) and the others (A and B) are categorical (nominal). B is a subcategory of A. A has 4 levels, most of all are well populated, B has 3 to 15 levels, depending of level of A, and about half are well populated.
I could take all my three variables and do a Bayesian logistic regression (one-hot encoding for A and B, ending up with 1+4+15 columns). I could also proceed by steps: four distinct models/logistic regressions of Y based on X, one for each level of A. Then using the coefficients of each as priors on X, do logistic regressions Y ~ X on each level of B (if levelBj of B belongs to levelAi of A then I use the priors of model i above).
Does it make sense to proceed that way? Are there advantages/disadvantages doing that? Are there alternatives? Any links/tutorials on the problem of mixing categorical and continuous variables for bayesian logistic regression are also appreciated (particularly for PyMC3).
Answer: Short answer: Your second proposal seems strange to me, go for the simpler first proposal. There is no problem in principle with mixing different kinds of variables as predictors in a regression. If the range of the continuous variable is not small, consider to spline it (or simpler, a quadratic polynomial model).  For the categorical variable with some sparse levels, maybe regularization, see Principled way of collapsing categorical variables with many levels?


Fatal error allowed memory exhausted when looping with conditional statement

Question: <?php
$array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
$result = [];
for ($i=0; $i < count($array) ; $i++) {
    if (($i >=3 AND $i <= 6) OR $i=8){
        array_push($result, $array[$i]*2);
    } else {
        array_push($result, $array[$i]*10);
    }
}
var_dump($result);
?>

I want to multiply value in array that have key 3, 4, 5, 6, and 8 by 2, other than that key I want to multiply it by 10.
Tried change memory limit even to -1 (unlimited) but still give same error.
Answer: It seems the only problem is: you are changing the value of $i inside the if clause because of a missing =, it should be $i==8 instead of $i=8, a working script with some minor changes would be:
<?php
    $array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
    $result = [];
    $length = count($array);
    for($i=0; $i < $length ; $i++) {
        if (($i >=3 AND $i <= 6) OR $i==8){
            $val = $array[$i] * 2;
        } else {
            $val = $array[$i] * 10;
        }
        array_push($result, $val);
    }
    // output
    echo "
";
    print_r($result);
    echo "
";
?>

This outputs:
Array
(
    [0] => 100
    [1] => 200
    [2] => 300
    [3] => 80
    [4] => 100
    [5] => 120
    [6] => 140
    [7] => 800
    [8] => 180
    [9] => 1000
)

Answer: change your if condition from: if (($i >=3 AND $i <= 6) OR $i=8){
to : if (($i >=3 AND $i <= 6) OR $i==8){
***You are not assigning a value to $i. You are checking its value. That's why you must use ==.


How to wait under UITests in Xcode until some view will be visible for tap?

Question: Sometimes under UITests in Xcode the compiler try to tap the button before it is loaded and presented. Then arise a problem like no matched found for....
But the simple solution for this is:
sleep(1) //wait 1 second and give `mybutton` time to load and be accessible for uitests
mybutton.tap()

But this is horrible since I cannot put there 0.1 as a parameter. And it makes me annoying to wait 1 second before a lot of buttons.
Is there a way to wait until it is visible for uitests?
Answer: You should create an XCTestExpectation and wait for it to be fulfilled
expectationForPredicate(NSPredicate(format: "hittable == true"), evaluatedWithObject: mybutton, handler: nil)
waitForExpectationsWithTimeout(10.0, handler: nil)

mybutton.tap()

Comment: For Swift 3 you can leave `handler` parameters.


How to convert a link that has javascript:__doPostBack in href to normal url which wget/curl/lynx can understand?

Question: I searched in SO first, and found this question. How to click a link that has javascript:__doPostBack in href? but it gives the answer in python only.
What I need is, when go through a website, some pages (2,3,4, etc) with links like below:
javascript:__doPostBack('AspNetPager1','2')
javascript:__doPostBack('AspNetPager1','3')
javascript:__doPostBack('AspNetPager1','4')

If I click it, and it will display the next page, but the real url isn't displayed in browser.
So my questions is, how can I convert the javascript link into traceable real url and feed to wget/curl/lynx?
My purpose is to use the tools (wget/curl/lynx) to download these pages one by one by scripting. But because of these javascript:__doPostBack, I can't find a good way to do it.
Answer: You can't really do it analytically.  __doPostBack could be arbitrarily complex.
What you should do instead is install Firebug (assuming you are using Firefox), activate the Network tab, press "Persist", and then click that button.  The Network tab will show you the actual network traffic, and you can deduce the real URLs from that.  In fact, you can just right-click on the particular network request that interests you and select "Copy as cURL" and it will put the  curl instructions -- complete with things like cookies and headers -- in your paste buffer.
There is a similar function built-in to Chrome.
Comment: Thanks, I have firefox (of course), and have install two add-ons: `httpfox`, and `Live HTTP Headers`. Let me try `firebug`.
Comment: @Malvolio Can you help elaborate more? I'm having exactly the same problem, but I'm not sure how to deduce the real URL from the network traffic.
Comment: @song0089 -- are you looking at the Network _panel_ of the debugger?  Both Chrome and Firebug have on option (by clicking on the request) of "copy as cURL".  If you are looking at the network traffic directly (e.g. with Wireshark), look for a line reading "Host: xxxxx" and another with "GET yyyy" -- xxxx/yyyy is the URL.


At what nps a note could be considered as just continuous hum?

Question: I am just curious to know the limit of our ear to distinguish time between two notes played. For example: A person playing quarter note at 60 bpm(4/4) is easily distinguishable because the delay between notes is 1 second, but if we keep increasing the BPM the frequency of notes increases and I believe it reaches some point  where it sounds constant.
I did my research but I didn't found anything useful. (Perhaps I am phrasing the question wrong or something). It will be better if you provide with some reference.
Answer: If the note is played percussively (e.g. with a pick, as opposed to e.g. a violin bow), at somewhere around 30 nps the attack of the note itself will be heard as a low note.
Why? Simply because around 30 Hz (give or take, depending on person, age, ear conditions, etc.) is the lowest frequency audible by humans.
In other words, when the percussive attack of the note is repeated fast enough, at a frequency within human hearing range, you'll start to hear that sequence of attacks as a frequency of its own.
If somehow the frequency of the original note manages to still get out (1) you will then probably hear two notes: the frequency of the original note played, and a second low frequency, a low pitched buzz caused by the hitting of the notes, if that happens at a frequency within human hearing range, which starts at around 25-30 Hz. In fact, this low pitched frequency will be the dominant sound, and the frequency of the original note will only be partially heard under special circumstances (1).
Sometimes we hear a buzz from electrical appliances, caused by the AC frequency (50 or 60 Hz, depending on the country), this might be something similar to that, starting to be audible at around 25-30 Hz.
(1) It depends on the note you play and the physics if the instrument. If you play, for example, an E5 note on a guitar (High E string at 12th fret) 30 times a second with a pick, that E5 note may still be heard, albeit in a broken and irregular way, because its frequency is about 660 Hz, i.e. much higher than the 30 Hz frequency of the picking itself. So there may be some time, about 33 msec, between one picking motion an the next, for that E5 frequency to come out somehow. On the other hand, if you pick a low E note on the bass (E1 = 41 Hz) 30 times a second, there is not enough time between pickings for that string to vibrate at least a few times and produce a distinct frequency.
Bottom line, if you start hitting a note very fast, 30 times a second or more, then the frequency of that hitting becomes the note you hear.


Erro ao implementar compartilhamento para o facebook

Question: Segue o código que tenho:

Em seguida mais algum código:
<meta property="og:title" content="<?php echo $titulorowimvtopo ?>" />
<meta property="og:description" content="<?php echo $descricaorowimvtopo ?>" />
<meta property="og:image" content="http://www.roteirodoimovel.com.br/cp/clientes/<?php echo $cliente ?>/<?php echo $idimovel ?>/<?php echo $idfototopoid; ?>" />
<meta property="fb:app_id" content="966242223397117" />

E por fim  a implementação para a exibição do botão compartilhar e curtir:
<div class="fb-like" data-href="http://www.<?php echo $_SERVER["HTTP_HOST"]; ?>/detalhes.php?cliente=1&idimovel=6" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true">

Como podem ver o código tem implementações PHP para dinamizar o processo, porém em todas as páginas a imagem, titulo e descrição são as mesmas. O que não deveria acontecer, uma vez que cada página possui seu próprio título, imagem e descrição.
Como resolver isso?
Comment: De onde está vindo `$titulorowimvtopo` e `$descricaorowimvtopo`? Tem certeza que estão corretos a cada página?
Answer: Ao exibir o código fonte da página os dados estão corretos?
você pode usar as ferramentas do próprio facebook para verificar os erros em um determinado URL.
https://developers.facebook.com/tools/debug/
Answer: Na hora de compartilhar que aparece sempre os mesmos dados certo? Se for, deve ser porque na div os dados estão estáticos, e não dinâmicos como na tag meta. Será que não é isso?
<div class="fb-like" data-href="http://www.<?php echo $_SERVER["HTTP_HOST"]; ?>/detalhes.php?cliente=<?php echo $cliente ?>&idimovel=<?php echo $idimovel ?>" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true">


Displaying Database on Listview

Question: I'm trying to create a ListView which displays the contents of my database on an activity in an android application. The method I have attempted crashes the app before it can run. Below is my code for my main activity and sqlhelper class. If anyone could tell me why that would be great thanks.
Main Activity
    package com.mcclure.hannah.books;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.List;
import com.mcclure.hannah.books.MySQLiteHelper;
import com.mcclure.hannah.books.Book;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
private ListView lv ;
private String TAG="Hannah";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView) findViewById(R.id.lv);
    MySQLiteHelper db = new MySQLiteHelper(this);

    /**
     * CRUD Operations
     * */
    // add Books
    db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));
    db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
    db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));

    // get all books
    List<Book> list = db.getAllBooks();

    // delete one book
    db.deleteBook(list.get(0));

    // get all books
    db.getAllBooks();

    String[] array = list.toArray(new String[list.size()]);

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
             this,
             android.R.layout.simple_list_item_1, array );
    Log.d(TAG,"**************************");
     lv.setAdapter(arrayAdapter);

}

}
MySQLiteHelper Classs
package com.mcclure.hannah.books;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mcclure.hannah.books.Book;
public class MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create book table
    String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "title TEXT, "+
            "author TEXT )";

    // create books table
    db.execSQL(CREATE_BOOK_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older books table if existed
    db.execSQL("DROP TABLE IF EXISTS books");

    // create fresh books table
    this.onCreate(db);
}
//---------------------------------------------------------------------

/**
 * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books
 */

// Books table name
private static final String TABLE_BOOKS = "books";

// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";

private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

public void addBook(Book book){
    Log.d("addBook", book.toString());
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, book.getTitle()); // get title
    values.put(KEY_AUTHOR, book.getAuthor()); // get author

    // 3. insert
    db.insert(TABLE_BOOKS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close();
}

public Book getBook(int id){

    // 1. get reference to readable DB
    SQLiteDatabase db = this.getReadableDatabase();

    // 2. build query
    Cursor cursor =
            db.query(TABLE_BOOKS, // a. table
                    COLUMNS, // b. column names
                    " id = ?", // c. selections
                    new String[] { String.valueOf(id) }, // d. selections args
                    null, // e. group by
                    null, // f. having
                    null, // g. order by
                    null); // h. limit

    // 3. if we got results get the first one
    if (cursor != null)
        cursor.moveToFirst();

    // 4. build book object
    Book book = new Book();
    book.setId(Integer.parseInt(cursor.getString(0)));
    book.setTitle(cursor.getString(1));
    book.setAuthor(cursor.getString(2));

    Log.d("getBook("+id+")", book.toString());

    // 5. return book
    return book;
}

// Get All Books
public List<Book> getAllBooks() {
    List<Book> books = new LinkedList<Book>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_BOOKS;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    Book book = null;
    if (cursor.moveToFirst()) {
        do {
            book = new Book();
            book.setId(Integer.parseInt(cursor.getString(0)));
            book.setTitle(cursor.getString(1));
            book.setAuthor(cursor.getString(2));

            // Add book to books
            books.add(book);
        } while (cursor.moveToNext());
    }

    Log.d("getAllBooks()", books.toString());

    // return books
    return books;
}

// Updating single book
public int updateBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("title", book.getTitle()); // get title
    values.put("author", book.getAuthor()); // get author

    // 3. updating row
    int i = db.update(TABLE_BOOKS, //table
            values, // column/value
            KEY_ID+" = ?", // selections
            new String[] { String.valueOf(book.getId()) }); //selection args

    // 4. close
    db.close();

    return i;

}

// Deleting single book
public void deleteBook(Book book) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. delete
    db.delete(TABLE_BOOKS,
            KEY_ID+" = ?",
            new String[] { String.valueOf(book.getId()) });

    // 3. close
    db.close();

    Log.d("deleteBook", book.toString());

}

The error message (stacktrace) diplayed is :
04-21 16:12:09.364 6896-6896/com.mcclure.hannah.books E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mcclure.hannah.books, PID: 6896
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mcclure.hannah.books/com.mcclure.hannah.books.MainActivity}: java.lang.ArrayStoreException: com.mcclure.hannah.books.Book cannot be stored in an array of type java.lang.String[]
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2808)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
        at android.app.ActivityThread.access$900(ActivityThread.java:181)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:6145)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.ArrayStoreException: com.mcclure.hannah.books.Book cannot be stored in an array of type java.lang.String[]
        at java.util.LinkedList.toArray(LinkedList.java:958)
        at com.mcclure.hannah.books.MainActivity.onCreate(MainActivity.java:43)
        at android.app.Activity.performCreate(Activity.java:6374)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
        at android.app.ActivityThread.access$900(ActivityThread.java:181)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:6145)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Comment: "Crashes the app" implies that there must be a stacktrace or some error message available. Pleas do always post error details.
Comment: The logcat doesn't show the error it says to much output to process most times.
Comment: Filter your logcat output by app to display only relevant lines.
Comment: Thank you I have added  the error message displayed
Comment: `Caused by: java.lang.ArrayStoreException: com.mcclure.hannah.books.Book cannot be stored in an array of type java.lang.String[]`
Answer: You are trying to add a Book in a list of String:
 String[] array = list.toArray(new String[list.size()]);

Displaying Database on Listview