What guitar effects pedals are important to get according to genre?

Question: I was wondering what guitar effects pedals are important to get. What are the typical pedals that one might need in order to get started? What is the bare minimum and what would be the ultimate ideal setup for each one according to these genres:
Rock
What pedals are important here? List each one on a scale of 1 to 10. What applies best out of these: Overdrive, Distortion, Fuzz?
Metal
What fits in here?  I assume a lot of Fuzz.
Blues
I assume some overdrive belongs here. :)
Worship
I have a pedalboard situated for this and was wondering what would be best.
I may add more genres later but for now this is it! Any answers are much appreciated!
Comment: @Dr, I think that this is a valuable question for performing musicians.  How about suggesting a rewording of the question that would pass muster?  I'd take a shot but I'm notorious for getting my questions downvoted. :-)
Comment: I'm certainly not going to close it if it gets reopened, but like this one I answered in 2012, I think it is opinion/consensus based: http://music.stackexchange.com/a/6604/104 - in fact it was specifically because of that one that I feel these are unanswerable in any useful way.
Comment: @DrMayhem A genre is a collection of patterns. Those patterns can be observed and analyzed objectively. It's not about right or wrong, but about the most common causes of the timbre dynamics of a genre or style. It's not about preference, but about means of achieving the common timbres that a genre or style carries.
Comment: @DrMayhem All those effect pedals (fuzz, distortion, and overdrive) can be generalized as distortion effects, and attached to the metal genre as such. "Distortion inducing pedals are the core of the metal guitar sound. Some common examples are fuzz, distortion, and overdrive; but it can also be achieved through FM, AM, waveshaping, etc". Again, it is not about what is preferred, but about what is needed. Also, that bit that isn't opinion based is what the question is about.
Comment: @DrMayhem I was not asking the question merely for opinions, I was asking to see the Industry standards and such, I was wondering what is specifically used.
Comment: @DrMayhem You keep missing the point. When I say "needed" I'm not referring to a requirement or a contract. When I say "needed" I'm referring to the common guitar timbre that is carved in the metal genre, and what is needed to achieve that particular timbre. Asker wants to know what is needed to get the characteristic sound of a genre, not what is used in 100% of the songs of a genre. We can't even agree to disagree here, the asker and you are talking about different things. We are not talking about opinions, or preferences. The closing reason makes no sense.
Comment: @DrMayhem I don't mean to offend you, but all I mean to say is there is two ways to look at it. If someones response had this link in it then it wouldn't exactly be "opinion based" it would be a recommendation, as the answers to many questions are. http://en.wikipedia.org/wiki/Distortion_(music) Also, here is a question of your own that is primarily "opinion based" http://music.stackexchange.com/questions/9525/how-can-i-easily-manage-different-tunings
Comment: @DrMayhem My argument is directed to all the closers, not just you.
Answer: Effects are usually a relatively personal topic among guitar players, so you will probably get a lot of variation among answers to this question. I can give my opinion on the matter but it's always best to experiment yourself and figure out what you like the sound of.
Generally I use an overdrive/distortion, a fuzz pedal, and a delay pedal for my bare-minimum setup. The fuzz is a personal thing, as it was my first pedal and I have always found uses for it, but it's not absolutely necessary for all genres. Basically you want to start with a good distortion or overdrive pedal, and your choice is going to depend on what styles of music you play.
For classic rock or blues if you have a decent tube amp with good built in distortion, you can use something like a Tube Screamer to get both light overdrive or push it harder for a heavier distortion when combined with the dirty channel on your amp.
For heavier rock/metal a fuzz might be useful, but you are also probably going to want a heavier distortion pedal. Boss makes some decent heavier "metal" type distortions, or again if you have the right amp sometimes a Tube Screamer might be enough to push the amp into heavier territories. The Proco rat and OCD pedals are a couple classic choices for heavier distorted sounds.
A delay pedal is usually the next most important pedal in my setup, and I'd say most guitarists are going to have one somewhere on their board. I don't usually use a reverb pedal because I will just use the amp's reverb, but delay is pretty important to me. You can get short slap-back delay which works great for country or blues, or you can push the delay time a bit and get a heavier, thicker sound that works well for rock or metal solos or interesting arpeggio based clean licks.
After a good OD/distortion and delay pedal, you can go any number of different directions. For classic rock or even metal I might get a wah pedal, but for more modern rock I would probably move towards modulation like a chorus or phaser pedal. A good compression or EQ pedal can also come in handy at this point, so you really have to do some experimenting to figure out what works with your sound. This is where personal preference and the music you are playing enters more into the decision process. Everyone needs distortion and delay (for the most part), but beyond that it becomes a little more complicated.
Also it's worth mentioning that if you are unsure of what pedals you will be able to find uses for, it might make sense to get a multi-effects pedal to do some experimentation with. They usually don't sound quite as good as individual pedals, but they are really useful for trying out different effects in different combinations to see what works best for you.
One last thing, you asked also for the "ultimate setup." If I had plenty of space (and money) my ideal board would probably look something like this:
tuner > volume > compression > fuzz > overdrive > distortion > EQ > wah > tremolo > chorus > flanger > phaser > octave > reverb > delay
That would pretty much cover you for any genre, from blues to rock to metal to worship, but it would also probably be overkill for a lot of situations. Again, experiment on your own with the basic elements and see what you like the best.
Edit: I forgot about the tuner. Very useful for playing live. Also a volume pedal can be helpful for easy volume control and swells if you want them.
Comment: +1 for the great answer. For experimenting and performing I'd recommend a multi-effect. I personally use Axe-Fx for everything. An equally important fact; very much is done with your hands, your picking technique and the settings on your guitar.
Comment: Also, the routing of the pedals can achieve very interesting things - you may want different setups for different genres. (I.e [volume > effects vs effects > volume], [reverb > delay vs delay > reverb], [distortion > EQ vs EQ > distortion] etc)
Comment: Yeah, you could write books about pedal order alone. It's all subjective so experimentation is usually the best route. I've never tried Axe-Fx, but heard good things. For me I need buttons and knobs to tweak, I can't deal with menus. For multi-effects I like the [Line 6 M13](http://line6.com/m13/). It's got a ton of effects with the simplicity of a stompbox.
Answer: The line between Blues, Rock and Metal can be "fuzz"ier than you'd think.
Effects can be broken up into three classes: Gain, Modulation and Time (GMT), and roughly, they are placed in the chain in this order.
(If you place things out of this order and like the sound, you are under no requirement to change.)
In the Gain section, Distortion occurs when the smooth wave of the signal gets "clipped" because the circuit cannot handle the signal. You can do this by using higher-output pickups, putting a pedal before the amp that forces it, boost the signal with a pedal going into the preamp, boosting the preamp to get the power amp distorting, and pushing the speakers to where they break.
Also involved is compression, where the volume difference between playing hard and playing soft. One big benefit from compression that you don't get from fuzz is sustain. The longer the note goes, the more voice-like or violin-like a note can be, and part of why guitar has been so popular in the last 50 years is that electricity has allowed it to sustain and sing.
(Far more about these points can be found elsewhere here, and also all around the Internet. Distortion and compression are much of what guitarists want to talk about.)
With pedals, the distortion and fuzz pedals give that square wave without necessarily adding signal, and overdrive and boost pedals amplify the signal without necessarily altering the wave.
There are great guitarists who use pedals to get their distortion. There are great guitarists who essentially plug right into the amp.
Modulation is changing the characteristics of the sound. Tremolo, vibrato, chorus, phase and flange are prime examples, as is the wah, although generally, the wah is placed as the first pedal after the guitar. I think you'd categorize pitch shifters and octave splitters here, too, but I'm not sure if you'd generally put octave splitters before or after fuzz...
Time effects are generally reverb and echo/delay. If you have a volume pedal or kill switch, you generally put it before the time effects, so that swells and repeats are not stopped when you silence the signal.
There are certain artists who are known for certain classes of effect. I associate Jimi Hendrix with the wah, U2's the Edge with delays, Dick Dale with excessive amounts of reverb, Tom Morello and Jack White with the Whammy Pedal pitch shifter, and Andy Summers of the Police and lots of fusion players with chorus. I don't associate metal with time effects much, as this would tend to muddy up the fast rhythms.
Specifically with worship, there was a point where the CCM/Worship guitar sound was Journey, followed by U2. Lately I'm hearing and playing lots of pop-punk influence -- basically crunchy guitar without much modulation or reverb/delay --  plus some folky bleedover from Mumford and Sons, but your congregation may vary.
But, given any effect, there is likely a player in any genre that uses it to great effect.
Comment: "...benefit from compression that you don't get from fuzz is sustain..." – actually you do get a bit of sustain from fuzz. Most distortion/overdrive etc. actually compress the signal quite a lot, in addition to the more obvious effect of adding of harmonic/intermodulation overtones (_that's_ what compressors don't do, at least not a lot).
Comment: Not all grit is fuzz. I was trying to specify a specific class of pedals. Otherwise, granted
Answer: Best advise I can give is to think about which artist exemplifies any given genre in your mind and research his setup.
An often overlooked item is a graphic equalizer placed after a run of the mill distortion box. By cutting or boosting certain frequencies post distortion you can traverse between many classic rock and metal sounds.
As an aside, the term Fuzz is usually reserved for that late sixties Jimi Hendrix, or more rrecently Queens of the Stone Age type of sound. Not metal. At all.
Comment: Fuzz is nowadays perhaps more common on bass than on guitar (unlike distortion/overdrive, it doesn't alter the _frequency response_ very much, so works well in frequency domains unintended for).
Answer: Generic pedals that are useful for all electric guitar genres are:

Volume boost and Volume rocker pedal for solos and for adjusting volume on the fly.
Overdrive for solos, tone coloration and sustain
Chorus for shimmering effects and to soften the harshness of the overdrive
Answer: This is a subjective question, but my opinion is that there is only one essential pedal for a gigging musician: a tuner. Obviously, tuners keep you in tune, and they also serve as a kill switch so you can put your guitar down without worrying about feedback.
I feel the best overdriven or distorted sounds are generated by tube amps, not pedals, for any genre. For blues and classic rock you can use your guitar's volume control to adjust the amount gain. For rock and metal, an amp with at least two foot-switchable channels is ideal. If the guitar's volume control doesn't give you the range of gain you desire, use a boost or overdrive pedal (such a tube screamer) to help push the tubes.
Here is a nice example of the diversity of tones you can get without pedals.


Problems aligning a Youtube clip centrally in an Android WebView

Question: I am trying to display a YouTube clip embedded in a WebView in Android with the size of the web view as large as 640x360 dip and in the center of a tablet's screen. I've managed to do this, however the YouTube clip seems to be cut off and a white background gets displayed as in the screenshot below:

Here is the Java code:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class VideoWebViewActivity extends Activity {

    private static final int VIDEO_WIDTH = 640;
    private static final int VIDEO_HEIGHT = 360;
    private WebView webView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.weblink_webview);

        webView.getSettings().setPluginsEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebChromeClient(new WebChromeClient());

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);

            }

            @Override
            public void onPageFinished(WebView view, String url) {

            }
        });

        String youtubeUrl = "http://www.youtube.com/embed/O1N2rENXq_Y";

        String embedCode = "<!DOCTYPE html>" + " "
                        + "

";

        webView.loadData(embedCode, "text/html", null);
    }

    @Override
    public void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}

And here is the layout xml:
<?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/weblink"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:visibility="visible" >

    <WebView
        android:id="@+id/weblink_webview"
        android:layout_width="640dip"
        android:layout_height="wrap_content"
         />

</RelativeLayout>

Edit: The strangest thing about this, is that on a 7 inch tablet with Android 3.2 it works fine, however on a 10 inch tablet with 4.0.3 (ICS) it looks like in the screen shot.Same issue on a 10 inch tablet with Honeycomb 3.1. This leads me to believe that there is some kind of a setting/problem within the web view itself that causes this behaviour.
Edit 2: While trying various ideas to solve the problem, we noticed that the white rectangle over the right side of the clip seems to have it's size in direct link with the amount of left margin you add to the web view. For example, if we would give up centering the view and add an 100dip margin, we would get an approximately 100dip wide white strip on the clip's right.
Any suggestions are welcomed.
Thanks,
Mihai
Comment: have you tried setting: layout_width="wrap_content" ?
Comment: yep, I tried that, however I get 2 white horizontal rectangles to the right and left of the clip that reach to the screen edges and I don't want that.
Answer: this post is a bit old, but if you are still looking for a solution:
Webview on the ICS are very buggy, and your problem is the same with a google map in a WebView with a left margin.
To resolve this problem, in the manifest, I changed
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />

by
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="11" />

This allows not to activate the new features of ICS and solve the problem
Cheers
Comment: Indeed, there seems to be a bug with the WebView (confirmed that at Google I/O this year) in ICS, and it also seems to be fixed in Jelly Bean. Thanks for the answer, I am going to try it out, however we'll need to support newer APIs in our app, so this limitation may not work for us.


Batch - Extract string before the specified character

Question: How to get the string before the character hyphen? The following code gets the string after the hyphen. How can I reverse this?
<code>set string=1.0.10-SNAPSHOT

echo %string:*-=%

SNAPSHOT
</code>
But I want the 1.0.10 instead of SNAPSHOT of if the string is RELEASE
Comment: You want extract 1.0.10?
Comment: yes that's right
Answer: for extract string before hyphen (special charcter) you need used for
<code>@echo off
set string=1.0.10-SNAPSHOT
echo %string%
for /f "tokens=1 delims=-" %%a in ("%string%") do (
  echo %%a
  )
</code>


Getting an error in Xcode that I do not understand

Question: I am brand new to SWIFT/Xcode and I am trying to create a collection view but I keep getting an error when I run my code. The app appears to build successfully but when I select a button that is suppose to take me to a suggested videos screen the app crashes and I get the following error messages. I have seen several SO posts with the same error message but none of the suggested fixes have worked for my implementation. What am I doing wrong and how can I fix it?
Error Messages:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController
  collectionView:numberOfItemsInSection:]: unrecognized selector sent to
  instance 0x7fd6468165e0'
Thread 1: Exception: "-[UIViewController
  collectionView:numberOfItemsInSection:]: unrecognized selector sent to
  instance 0x7fd6468165e0"

My Code:
import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let videoThumbnail = [UIImage(named: "img1"), UIImage(named: "img2"), UIImage(named: "img3"), UIImage(named: "img4"), UIImage(named: "img5"), UIImage(named: "img6")]

    let videoDescription = ["Lorem ipsum 1", "Lorem ipsum 2", "Lorem ipsum 3", "Lorem ipsum 4", "Lorem ipsum 5", "Lorem ipsum 6"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return videoThumbnail.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let VideoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! VideoCell

        VideoCell.videoThumbnail.image = videoThumbnail[indexPath.row]
        VideoCell.videoDescription.text = videoDescription[indexPath.row]

        return VideoCell
    }
}

Comment: Most likely the class of the view controller is not set to `ViewController` but `dataSource` is connected in Interface Builder. The evidence is the base class `UIViewController` in the error message.
Answer: The variable names you create with UICollectionViewCell (VideoCell) are the same.
try this;
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! VideoCell

        videoCell.videoThumbnail.image = videoThumbnail[indexPath.row]
        videoCell.videoDescription.text = videoDescription[indexPath.row]

        return videoCell
    }


Multi Country and Language Site

Question: I'm trying to build a single global website that houses multiple countries, each with their own set of language translations. There is also a global overview site that also has its own language options. The global site will live on global.domain.com and function the same as a country site, and the countries will be at domain.com/langcode-countrycode/ (domain.com/en-us/). From anywhere on any site, the user will have a menu to navigate to another country/language. There will only be a dozen countries or so. There will also be company sites, but they are identical to the country sites. Each country/company will have its own management team that should only be able to edit their section. Each also needs the option to swap the logo and maybe some colors, but that's it.
From what I've found, Domain Access and Organic Groups, coupled with i18n, seems like the best option, but I just can't seem to get it set up in the right way. Is there a better approach to that?
Some countries want to be able to use another domain to access their country site, which I'm guessing would just be an alias to the main domain in Domain Access.
I can mostly picture how I would build this in WordPress, or even from scratch, but I'm new to Drupal, so I might be missing something obvious...
Answer: It sounds to me like you need a multi-site Drupal installation and each of those sites needs something like organic groups and also i18n.
Unless I am misunderstanding... what you're describing only makes sense if all the content across all sites is the exact same,  just translated versions.
Comment: The majority of the content is going to be the same. The main company offers services in each country. Each country site will consist of a homepage, about (which will mostly be about the company in general), services, contact. The services will only vary slightly by country. Does that make sense? A multi-site installation seemed too separate, and difficult for the client to add to later. Also, it seemed like it wouldn't work well with the required URL structure...

Multi Country and Language Site


How to make fields appear required (by colouring)

Question: Suppose, I have some required module attributes that cannot be made required for reasons that would conflict with certain actions such as duplicate. That these attributes are required, can be easily overcome during creation by raising ValidationErrors.
However, I would like to adjust the field parameters in the xml files form view to make these fields appear to the user in blue (as if they were required).
PS
I have tried all of the following
<field name="name" bgcolor="blue" fgcolor="red" color="black" colors="purple"/>

just to see if any of them would work.
I have also reset the local server and updated the module itself, thinking that maybe the xml files are not always reloaded on server-reset.
Any ideas on custom colouring fields in form-view would be very helpful.
Answer: You could add them as classes like this:
<field name="name" class="red"/>

.red {
    background:red;
    /* additional css here */
}

Comment: I like that this actually made something happen, although this background made it appear a little differently than I was hoping for. It kind made the entire field excluding the actual selection box a different colour
Comment: This was definitely the correct approach. Although required a much deeper understanding of css.
Answer: XML attributes on "official nodes" are validated, you cannot add them as you like. When developing web_field_style for v6 I had to patch .rng validation. I don't think that module has been ported to v8 or v9 (see OCA web repo), so I think you have 2 options:

port the module
use a wrapper div with a custom class  (yes, you can write HTML into form views), see example below

    <field name="start_date" colspan="2" class="foo" />

In this example the class "foo" on the field will be stripped out but the wrapping div with class "bla" will stay there ;)
Comment: Alright, this is the closest I've been so far. However, with this wrapper                                       the name of the field has disappeared and left me only with a selection box...
Comment: labels appear only if the field is contained into a  element. Still, you can add it explicitly with  tag
Comment: Again closer (let me clarify that this field is/was already contained in a ), but now the label's font appears differently from the rest **and** (more importantly) it has destroyed the formatting (i.e. the selection box is now below the label).
Answer: You should write those attributes to tree tag like this:
<tree colors="black" bgcolor="yellow:name == other" string="Invoice">
    <field name="name" />
    <field name="other" />
</tree>

Example from odoo source

In .xml side <, >, <=, >=, & is not supported. So we need to use <, >, <= >=, and &
Comment: I like this approach although, I was hoping to do something like this in the form view...


Doubt in finding volume and setting up the limits?

Question: I am currently confused in how to find volume enclosed between two surfaces $z_1=f_1(x,y),z_2(x,y)=f_2(x,y)$
After going through some online resources, I thought the general way of doing this is:
$\iint_{D} (z_2-z_1) dxdy$ where it will be $(z_2-z_1)$ or $(z_1-z_2)$ depending on the surfaces.
$D=\{(x,y)\in \mathbb{R}^2:  f_1(x,y)=f_2(x,y)$ (eliminating $z$ from the two equation)$\}$
However I got stuck while solving the problem .

Find the volume between the surfaces $x+y+2z=2,2x+y+z=4$
in the first octent.

I could figure out that it would be of the form
$$\iint _D \left\{(4-(2x+y))-\frac{(2-(x+y))}{2}\right\}\,dxdy$$
However how do I figure out $D$?
Should I take the projection of the two surfaces on the $xy$ plane and then find out the limits as we did in double integration?
Or should I equate the two surfaces and then find out the limit?
Comment: The volume between the two planes is infinite. Could you check the equations of the surfaces?
Comment: @RobertZ    Sorry I missed out first octent. Could you tell me when do we take the region $D=\{f_1(x,y)=f_2(x,y)\} $ and when do we just take the projection of the surfaces on the $xy$ plane and figure out the $x,y$
Comment: Yes I do understand but in this case if we take $f_1(x,y)=f_2(x,y)$ we get $3x+y=6,x=0,y=0$ which gives me a different answer if we take $x+y=2,2x+y=4,x=0,y=0$. Where is the mistake?
Comment: I added a picture. Here also the surface $z=0$ is crucial.
Answer: The first octant cut by the plane $x+y+2z=2$ is the tetrahedron
$$T_1=\{(x,y,z):x+y+2z\leq 2, x\geq 0, y\geq0, z\geq 0\}.$$
The first octant cut by the plane $2x+y+z=4$ is the tetrahedron
$$T_2=\{(x,y,z):2x+y+z\leq 4, x\geq 0, y\geq0, z\geq 0\}.$$
Notice that $T_1\subset T_2$: if $x+y+2z\leq 2$ and  $x,y,z\geq 0$ then
$$2x+y+z\leq 2(2-y-2z)+y+z=4-y-3z\leq 4.$$
$\hspace{4cm}$
Hence the desired volume is
$$\begin{align}\text{vol}(T_2)-\text{vol}(T_1)&=
\iint_{D_2}\Big(4-2x-y\Big)dxdy
-\iint_{D_1}\Big(1-\frac{x+y}{2}\Big)dxdy\\
&=\frac{16}{3}-\frac{2}{3}=\frac{14}{3}
\end{align}
$$
where
$$D_1=\{(x,y):x+y\leq 2, x\geq 0, y\geq0\}\;\text{and}\;
D_2=\{(x,y):2x+y\leq 4, x\geq 0, y\geq0\}.$$


How do I print a custom menu?

Question: There are lot of tutorials on Internet about how to display menu, but no one works for me.
I have tried:
$menu_array = menu_navigation_links('menu_menu-login-menu');
print theme('links__menu_login_menu', array('links' => $menu_array));

print drupal_render(menu_tree_output(menu_tree_all_data('menu-login-menu')));

Both don't work.
My menu looks like this.
Comment: By Default all the menus are available as block under Blocks section. You can assign it in to required region. Are you trying to do something different?
Answer: Have you tried using the Menu Block module (D7)?
Disable the main menu in the theme settings and create one or multiple menu blocks with a lot of options for the menus. The module can render submenu items with the main navigation and/or in a separate menu-block. The Menu block module can render a custom menu as well.
You can also add an extra region to your theme that renders a menu-block-menu inside a nav-tag:
yourtheme.info file add:
regions[nav_custom] = Nav Custom

In page.tpl.php add:
<?php if ($page['nav_custom']): ?>

      <?php print render($page['nav_custom']); ?>

<?php endif; ?>

Comment: YES, thanks. I have already fixed this problem in the almost same way, you write here...

How do I print a custom menu?


How to send server metrics data to statsd?

Question: Our monitoring stack is Grafana + InluxDB + statsD.
We use it for application monitoring.
We need to add server metrics (CPU, memory, network connections, etc...) to Grafana, so I'm guessing we'll need some agent to collect server metrics and pass to statsD.
Do you know of any agent that can do that? or any other way to implement this?
Answer: You can use collectd deamon for system metrics. Use the provided plugins to collect the information you need. To feed into Influx use the network plugin and configure your InfluxDB Server Params.
On the InfluxDB side you will need to create a database for collectd.
[collectd]
enabled = true
port = YOURPORT where COLLECTD is sending the data.
database = "collectd_db"
typesdb = "/opt/collectd/share/collectd/types.db"

restart Influxdb with that config.toml.
Step by STEP can be found here https://anomaly.io/collectd-metrics-to-influxdb/
Answer: I've decided to write my own agent to solve this problem.
It's ridiculously easy to deploy and connects to statsd instead of directly to Influx DB.
https://github.com/eranbetzalel/statsd-agent-js/


Trying to create a static page for my module using page callback in hook_menu

Question: I'm taking first steps in building a module for Drupal 7 and am trying to create a static page within hook_menu function. In the $items array, for 'page callback' I create an very simple function named 'semi_static_page'. This simple function returns some html. the code is below.
$items['admin/config/media/tsoundcloud/config/soundcloud_static'] =             array(
    'title' => t('Semi Static Page'),
    'description' => 'Temp page to show data',
    'page callback' => 'semi_static_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );

function semi_static_page(){
  $output = 'this is some output, etc…….';
  return $output;
}

But this page generate the following error.
Fatal error: Unsupported operand types in /Users/tomcarden/Sites/sweetteas/includes/form.inc on line 1079
How can this be resolved? Ultimately I want to load an .inc in the semi_static_page function.
thanks in advance!
Answer: $output = 'this is some output, etc…….';
If you see in the above line, you are using wrong sign, which I have  highlighted after ...... That is wrong. It should be '
Above isuue is for sure!!!!

Other just my suggestion, As I am also learning Hooks, may be TOTALLY WRONG but for your attention.
I have changed code as below and after that, I have written my point..
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['admin/config/media/tsoundcloud/config/soundcloud_static'] = array(
    'title' => 'Semi Static Page',
    'description' => 'Temp page to show data',
    'page callback' => 'mymodule_semistaticpage',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    );
    return $items;
 }

/**
 * Page callback
 */
function mymodule_semistaticpage(){
  $output = 'this is some output, etc…….';
  return $output;
}

The following points are for code which you have posted in main-question, and I have corrected those in above code,

See function name, it should start with module name.
The _page(), may creating confusion as some hook has _page() part..so I did change function name to mymodule_semistaticpage()
where is return $items;?
I think title do not need, t()?
Answer: Your current problem is very clearly mentioned in error statement , you need to replace (') with (') without parentheses of-course.
other suggestions:
1: Title field do not require t() function
2: Description field should be written in t() function
3: Never ever forget to return $items array.
4: It is customary to start call back function names with your module name.
5: Always document your code for future purposes.
6: Your call back function should return content in a theme-able formate for example ('#type' => 'markup') etc


theme taxonomy term object

Question: I created a module that looks up some taxonomy terms using taxonomy_get_tree() does some stuff with it and then passes it to a template file.
In that template file i want to display them sorted according to some parameters.
The sorting stuff and all works fine but in the end i would just like to display the term using its standard template. But i can't get this to work, i have the entire term object and what i thought i had to do was something like:
theme('node', array('elements' => array('#view_mode' => 'teaser', '#node' => $term)));

but the array needs a lot more items then i can provide, so isn't there an easier way?
Answer: You are passing 'node' as the $hook value, although your data is for a taxonomy term rather than a node. Trying using the hook 'taxonomy_term' instead of 'node'. I'm not sure what the proper structure for the $variables array is, but if you have the full term object, I would try just passing $term as the second parameter.
documentation for theme()
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7
documentation for theme_taxonomy_term()
http://api.drupal.org/api/drupal/developer--theme.php/function/theme_taxonomy_term/7

theme taxonomy term object


Python does deepcopy of an object duplicate its static variables?

Question: I'm used to code in C and Java and I just got into Python.
I have a Class Obj that has 2 static class variables a and b and has 2 instance variables x and y. I have an instance of Obj obj. During the program I need to make copies of obj (i.e. obj2) so that obj.x and obj2.x are not the same object, but obj.a and obj2.a are the same object (same pointer).
If I make something like obj.a = foo, then obj2.a == foo should be true.
I'm creating obj2 by making obj2 = copy.deepcopy(obj), but they are not sharing the pointer, it's creating another instance obj2.a and using more memory then needed.
I need them to work exactly like static variables in Java. How can I do this?
Comment: Please update your question with a minimal code snippet which shows what you have so far, the problem that ensues and the expected behaviour.
Comment: Why would you end up on `deepcopy` when you want them to share memory, when it's the exact opposite of what you want?
Comment: Unless I'm missing something, the basic OOP of Python supports what you want to do. I think you need a [mcve] to demonstrate the issue you have
Answer: Python has a specific way of working with static fields of classes. If you change the static field of class accessing through an object you will change the value only for this object.
obj.a = foo # changes the field a only for obj

But if you change field accessing through the class it will change values for all instances of this class.
Obj.a = foo # changes the field a for all instances

Also if you want to compare references you should use is keyword
class Dog:
    type="Dog"

a = Dog()
from copy import deepcopy
b = deepcopy(a)
a.type is b.type
>>True
a.type == b.type
>>True
a.type = "Cat"
a.type is b.type
>>False
b.type is Dog.type
>>True

Comment: When you call `b = deepcopy(a)`, is there a copy of `type` being created in memory or is the variable `b` just pointing to the same position in the memory as `a`? I don't want to use unnecessary memory.
Comment: will be created new instance but reference to a static field in a and b will be the same


Can I use one Log4Net config file for multiple (related) solutions?

Question: I have executable projects A and B in solutions sA and sB. Both of these solutions reference projects C, D, etc... as they are similar in functionality and so share a lot of common code.
I've happily implemented Log4Net into sA by keeping the dll and config file in a parent folder of the two solutions and referencing them from sA. The config file was added to project A so that during the build it is copied into the bin\Debug or Release folder and available during run-time.
My problem is this - since C, D, etc are common projects, they are referencing the original golden source file and not any project-specific config. However, when I added the config file to A, it was copied into the project folder, so I am no longer editing the original. If I add the file to B then I now have three files, which will undoubtedly fall out of sync.
Is there a way I can have the projects reference the original and copy that into the appropriate bin folder, effectively having one config file across sA and sB? Is there another solution I'm overlooking?
Answer: Do you look for Add an existing file to a project as link?

Hope this helps
Comment: This is perfect - I'd completely forgotten about that feature! This way I can maintain a single source but edit it transparently from each solution. Thanks.


Why is this Haxe try-catch block still crashing, when using Release mode for C++ target

Question: I have a HaxeFlixel project, that is working OK in Debug mode for misc targets, including flash, neko and windows. But Targeting Windows in Release mode, I'm having an unexpected crash, and surprisingly it's happening inside a try-catch block. Here's the crashing function:
/**
 * Will safely scan a parent node's children, search for a child by name, and return it's text.
 * @param   parent an Fast object that is parent of the `nodeNamed` node
 * @param   nodeName the node's name or a comma-separated path to the child (will scan recursively)
 * @return node's text as String, or null if child is not there
 */
public static function getNodeText(parent:Fast, nodeName:String):String {

    try {
        var _node : Fast = getNodeNamed(parent, nodeName);

        //if (_node == null)
        //  return null;

        // next line will crash if _node is null
        var it :Iterator<Xml> = _node.x.iterator();
        if ( it == null || !it.hasNext() )
            return null;
        var v = it.next();
        var n = it.next();
        if( n != null ) {
            if( v.nodeType == Xml.PCData && n.nodeType == Xml.CData && StringTools.trim(v.nodeValue) == "" ) {
                var n2 = it.next();
                if( n2 == null || (n2.nodeType == Xml.PCData && StringTools.trim(n2.nodeValue) == "" && it.next() == null) )
                    return n.nodeValue;
            }
            //does not only have data (has children)
            return null;
        }
        if( v.nodeType != Xml.PCData && v.nodeType != Xml.CData )
            //does not have data";
            return null;
        return v.nodeValue;
    }catch (err:Dynamic) {
        trace("Failed parsing node Text [" + nodeName+"] " + err );
        return null;
    }
}

By enabling if (_node == null) return null; line, It's working safely again. By catching errors as Dynamic I thought I was supposed to catch every possible error type! Why is this happening? And why is it appearing in release mode?
My IDE is FlashDevelop, and I'm using HaxeFlixel 3.3.6, lime 0.9.7 and openFL 1.4.0,  if that makes any difference
EDIT: I suspect this has to do with how the translated C++ code missed the Dynamic Exception. The equivalent generated C++ code is:
STATIC_HX_DEFINE_DYNAMIC_FUNC2(BaxXML_obj,_getNodeNamed,return )

::String BaxXML_obj::getNodeText( ::haxe::xml::Fast parent,::String nodeName){
    HX_STACK_FRAME("bax.utils.BaxXML","getNodeText",0x4a152f07,"bax.utils.BaxXML.getNodeText","bax/utils/BaxXML.hx",56,0xf6e2d3cc)
    HX_STACK_ARG(parent,"parent")
    HX_STACK_ARG(nodeName,"nodeName")
    HX_STACK_LINE(56)
    try
    {
    HX_STACK_CATCHABLE(Dynamic, 0);
    {
        HX_STACK_LINE(57)
        ::haxe::xml::Fast _node = ::bax::utils::BaxXML_obj::getNodeNamed(parent,nodeName);      HX_STACK_VAR(_node,"_node");
        HX_STACK_LINE(63)
        Dynamic it = _node->x->iterator();      HX_STACK_VAR(it,"it");
        // ...  Let's skip the irrelevant code
    }
    catch(Dynamic __e){
        {
            HX_STACK_BEGIN_CATCH
            Dynamic err = __e;{
                HX_STACK_LINE(82)
                ::String _g5 = ::Std_obj::string(err);      HX_STACK_VAR(_g5,"_g5");
                HX_STACK_LINE(82)
                ::String _g6 = (((HX_CSTRING("Failed parsing node Text [") + nodeName) + HX_CSTRING("] ")) + _g5);      HX_STACK_VAR(_g6,"_g6");
                HX_STACK_LINE(82)
                ::haxe::Log_obj::trace(_g6,hx::SourceInfo(HX_CSTRING("BaxXML.hx"),82,HX_CSTRING("bax.utils.BaxXML"),HX_CSTRING("getNodeText")));
                HX_STACK_LINE(83)
                return null();
            }
        }
    }
    HX_STACK_LINE(56)
    return null();
}

Answer: What haxedefs do you have defined?
Adding these to your project.xml might help:
<haxedef name="HXCPP_CHECK_POINTER"/>
<haxedef name="HXCPP_STACK_LINE" />
<haxedef name="HXCPP_STACK_TRACE"/>

You might also try the crashdumper library:
https://github.com/larsiusprime/crashdumper
(Crashdumper will turn on HXCPP_CHECK_POINTER by default as part of it's include.xml, and will set up hooks for both hxcpp's errors and openfl/lime's uncaught error events)
Comment: I didn't try the crashdumper, but the haxedefs worked for me just fine, I think this is the way to work with Haxe: It will still crash with a nullPointer Exception, but it provides the stack to track the Exception. Thanx again!
Comment: Thanks! Did you ever find the final cause of the crash?
Comment: Sure, check my answer. C++ cannot dereference null-pointer Exceptions, leading to app Crash. I still don't know why it happens on release mode, and not in debug. Tracing down the null pointer exceptions, and putting null checks before accessing null Fast nodes, I solved my crashes
Answer: I guess this boils down to how C++ handles null-pointer Exceptions. It doesn't!
More info here or here
Comment: More precisely, it doesn't have null pointer dereference exceptions at all. However, on Windows you can [catch system signals as exceptions](https://msdn.microsoft.com/en-us/library/windows/desktop/ms681409%28v=vs.85%29.aspx). Whether this is a good idea is left to the reader's discretion (hint : no.)
Answer: That seems odd, some questions that may help solving it.

It looks like you are doing quite some assumptions on how the xml looks (doing some manual it.next()), why is that?
Why are you using this big-ass try-catch block?
How does getNodeNamed look, it seems it can return null.
Do you have an example xml to test with?
Comment: Thanx for your time. This is a part of a generic XML Parser (Utility Class) I've made for myself, that is safely parsing misc types of xml data, where the structure model is loose. E.g, it should handle a missing optional child, returning null instead of crashing (Fast would crash). The getNodeNamed is supposed to return null if the child is not there, and in this case it does, that's why I've put it in a try-catch, I think that the XML is irrelevant. The main issue in this question, is why a NullPointer in `_node.x.iterator();` breaks the try-catch block
Comment: What I'm trying to explain is that the code is irrelevant since I've narroewd down the exact line where the code is crashing. I've provided some documentation for the function, to help you understand how the 'big-ass-try' works, but honestly I don't think that the function's logic is the issue here.


Virtualize GridView inside ScrollViewer in Windows Store App

Question: I have the following application:
I am developing a Windows Store app in which I need to show a big grid filled with buttons. The content of the buttons are some numbers and when I click any of them, I open a Popup with editor, where I edit those numbers. For that purpose I use a GridView, I put an ItemsWrapGrid as ItemsPanel. This makes the grid look exactly as I need it to look. I put the GridView inside a ScrollViewer, because I need to scroll the grid in both directions, since it has a lot of elements. Also I need to have the pinch-to-zoom effect that the ScrollViewer gives out of the box. I need to change the ItemsSource for that GridView when the user chooses different source in a ListView next to the GridView.
The problem:
Putting the GridView inside the ScrollViewer breaks the Virtualization inside and this has a major impact on my performance. When I switch the ItemsSource of the GridView, it takes more than 3-4 seconds for the rendering and during that time, the UI is frozen.
My question:
How can I keep the awesome stuff that the ScrollViewer gives me and also keep the virtualization? Because when I remove the ScrollViewer, changing between the ItemsSources happens almost instantly.
Any idea?
Comment: I know I am late, but did you ever find/implement a solution that you could put here as an answer to yourself? Thanks.
Comment: Nope, sorry. The project died and I stopped looking for a solution. ♂
Answer: You'll be best off implementing virtualization yourself since you're trying to use the GridView far from the use cases it was designed for.
Put a Canvas in a ScrollViewer that does both pan and zoom and handle view change events on the ScrollViewer by laying out item containers inside and around the viewport. Avoid unnecessary changes too, so keep containers in place if they are to stay realized between view change events and recycle containers that are leaving the viewport neighborhood.
Comment: Yes, I thought about doing my own virtualization, but that seemed like an overkill for the situation. My experience with custom virtualization scenarios shows that there is a ton of cases that you can screw up.
Comment: What I am now trying to do is make a copy of the template of the GridView. It has an internal ScrollViewer, which I am trying to take advantage of. When I set all the needed parameters there, the virtualization still seems to work, which is nice. But now I can't break off the ItemsWrapGrid at the element count that I want. It always goes to the next row just before it goes out the viewport. I am guessing some internal code does that in order to keep the virtualization working.
Comment: Like I said - it wasn't designed for your use case so sooner or later you'll hit a brick wall. I'd recommend either rolling your own virtualization or changing the design.


What is Statistics?

Question: In Mathematics, what is Statistics? For myself I just want to know what Statistics mean in it's purest form? also I need a much simpler definition or explanation for kids aged 4-10. Need to explain probability to kids, so I have to explain Statistics first.
Comment: Educated guessing.
Comment: Statistics is all about quantifying uncertainty in events with a certain degree of belief with all of the information that is on hand. I usually play the 'Monthy Hall Problem' with people that don't have any knowledge in statistics. This usually helps a lot! https://en.wikipedia.org/wiki/Monty_Hall_problem . Using paradoxes like 'the birthday paradox' or 'the gambler fallacy', often helps!
Comment: @Matthew Daly you know, using the same word in the explanation which you are trying to define can be confusing to a kid... Thanks for the comment though...
Comment: Thanks @FromTheoryToPractice. So "quatifying uncertainity" means quantifying the unquantifiable, within acceptable limits...
Comment: uncertainty can be defined as 'that that we don't know'. So you want to quantify the amount you don't know about a specific event. This could be due to incomplete information, inherent stochasticity in the system, or other reasons. Edit: it's early in the morning here, so I confused statistics with probability theory (in the field where I work in, it often gets used interchangeable)
Comment: @FromTheoryToPractice I think Uncertainity is something that you Cannot know...
Comment: @Ashish...well, if you look at the Monthy Hall Problem: in essence, the outcome is deterministic. But for the contestant, because he has limited information, the outcome is uncertain. Einstein once said: 'God doesn't play dice', meaning that uncertainty is just something we cannot observe and not something you cannot know.
Comment: @FromTheoryToPractice yes within math uncertainity is something we cannot Observe but otherwise uncertainity is something we cannot Know. IMHO
Comment: @Ashish Shukla yes, or something you just cannot know for certain
Comment: @WilliamElliot Hi Thanks. So can I say that our Mind aided by Math using formulas, allows us to make "educated guess" over much more data than our unaided mind alone? If that is so than can you please tell me how do logs and exponents help in it...
Comment: How old are the kids? Their age can vary quite a lot and from the sample I observed, what they can understand and what they enjoy is strongly related to their age.
Comment: This might be a better fit for matheducators.se.
Comment: @Taladris from 4 to 8, I am one of them. I was explaining probability vs. belief to them. They want to make a remote controlled drone and we live in a village in India. So from that explanation I wanted to make them also understand difference between Mind and Heart(Intuition), so I stumbled upon Statistics and wanted to know what it is...
Comment: One way to describe it is, "The study of how to make valid conclusions based on limited data." To be a bit more concrete, but slightly less general, you can say that a major goal of statistics is to make conclusions about a population based on a small sample from that population. For example, we might want to figure out what fraction of the population supports a particular political candidate, based on the results of a survey.
Comment: Did you do any research?
Comment: Statistics is basically (lossy) data-compression ... Don't tell that to your kids, but it does show that it is effectively summarizing sets of data points in such a way that they become more meaningful to our feeble mind (if we were infinitely smart, there would be no need for statistics: we could just look at the data set and see everything that's there). If this is for young kids, I would illustrate it with something simple like taking an average: have them count how many times they hear/see [something] every day for several days, take that average, and say: "we're doing statistics, kids!"
Comment: Hey @gen-zreadytoperish I don't understand the problem. This is the kind of well meaning objection which doesn't add any value in terms of resolution of the question. Maybe you don't have anything to say but that does not mean others don't have either. Pleanty people commented and answered, and maybe I am not looking for a precise answer. I don't know WHAT to change that question to. One of my young students asked and it seemed legitimate question to me. I cannot even appeal don't like the way disagreements are handled at stackexchange...
Comment: @Bram28 Today I read your comment(Carefully) and realised that you are saying the exact same thing I have been shouting at people for so many years. Thank you. Our minds are tools which are equipped to handle a finite set of information, excluding both the extremes, meaning our minds cannot handle Zero or INFINITY. To say that I "Intellectually understand" Zero and Infinity, IS WRONG. We ALWAYS "INTUITIVELY UNDERSTAND" Zero and Infinity. Well this question has been meaningful in so many ways. Thanks... By the Way, today I am tackling/learning multiplication in school...
Answer: In the simplest context, a statistic (small 's') is a function whose input is a data set and whose output is some real number.  We then define Statistics (big 'S') to be the study of these types of functions.  (this is what one of the comments initially said)
Of course, we try to avoid any ounce of formality when introducing a topic, especially to children, so to them, I think a more appropriate definition (even if it's imprecise) would be:
"Statistics is the study of how to summarize large data sets and how meaningful those summaries are."
For instance, the mean, median, and mode provide numbers which summarize "where" the data generally is.  Likewise, the variance or standard deviation provide numbers which summarize how close together the data generally is.  We can even talk about much more complicated values that summarize a data set, but these are the ones that are most likely to be seen in the real world.
Comment: So would you say that a fairly small set of "what and how to" of summarization describes most datasets found in Nature? And where can I find a list of statistic(s) and what they say about a dataset?
Comment: Great answer, especially the distinction between semi-formal definition and children-friendly definition. What you defined is actually 'descriptive statistics'. Do you have similar definitions for 'inferential statistics'?
Comment: @Taladris I'm not a statistician by any means, but I'm pretty sure the definition I gave is broad enough to encompass both descriptive and inferential statistics (and maybe more...).  Feel free to correct me if I'm grossly inaccurate here, but afaik the main difference between the two at the level of theory is how they interpret the undefined terms "large" and "data set" --- with very divergent results --- and since I don't even try to define either, it's ambiguous enough to encompass both.  (That said, I do agree that my last paragraph is interpreted in the context of descriptive statistics.)
Comment: Hypothesis testing also gives us a summary of a data set and how meaningful that summary is, in the sense that a significance level is "meaningful." So I would say this covers more than just descriptive statistics.
Comment: "We can even talk about much more complicated values that summarize a data set, but these are the ones that are most likely to be seen in the real world." I would Love to have that kind of mastery over the subject... @BrianMoehring Thanks for the answer...
Answer: To understand what statistics is, you need to contrast it with probability.
Probability deduces how likely events are based on certain assumptions. If I asked you how likely you were to get exactly two heads when tossing a coin five times, you'd probably assume each toss is independent, with a probability of $\frac12$ of giving heads.
Statistics is how we test such assumptions by looking at events that really happened. If all five tosses gave heads, that might not prove anything's amiss, since in theory it has a $1$ in $32$ chance. By "in theory", I mean on our assumptions, which in this context we call a null hypothesis. We might call the null hypothesis into question, however, if $70$ of $100$ tosses gave heads.
Answer: Mathematics is the abstract science of numbers, quantity and space. Mathematics may be studied in its own right (pure mathematics), or as it is applied to other disciplines such as physics and engineering (applied mathematics).
Statistics is the science of collecting and analyzing numerical data in large quantities, especially for the purpose of inferring proportions as a whole from those in a representative sample. It can be considered as a branch of applied mathematics concerned with collecting, organizing, and interpreting data. The data are represented by means of graphs.
Mathematicians solve problems. Problems they work on range from pure mathematical problems to applied problems. Mathematicians try to find common features in seemingly distinct problems. That is, they look for patterns. They classify what behaviors can result from certain systems.
Statisticians develop techniques to overcome problems in data collection and analysis. They use statistical methods to collect and analyze data and to help solve real-world problems in business, engineering, healthcare and other fields.
${}$
Ref.: https://scse.d.umn.edu/about/departments-and-programs/mathematics-statistics-department/what-math
Comment: "Statistics is the science of collecting and analyzing data" without "numerical" would be more comprehensive. Certainly, the kids should be introduced to the categorical and numerical types of data first.
Comment: @farruhota I was able to make them understand what 1 is, so they know numerical data type. Categorical I will do as and when opportunity arises. Thanks
Comment: Apparently, you explained what $1$ is with objects like apple, pen, car, etc. So, you can have several kids have different objects (say, one has 4 apples, another has 3 pears, etc) and show their possessions by bar graph, so the graph is a summary (representation of the data, i.e. facts and figures).
Comment: Statistics is a branch of mathematics, and statisticians are mathematicians too, as they also find common features in seemingly distinct problems and look for patterns. Statisticians deal with problems concerning data, using mathematics to solve them.
Comment: Yes, @bing-nagata-smirnov, infact, it was mentioned in my discussion.

What is Statistics?


Prove $|G_1| \cdot |G_2| = |G_1G_2| \cdot |G_1 \cap G_2|$.

Question: Let $G_1, G_2$ be subgroups of a group $G$ and $G_1G_2 = \{g_1g_2: g_1 \in G_1, g_2 \in G_2\}$. Prove that $|G_1| \cdot |G_2| = |G_1G_2| \cdot |G_1 \cap G_2|$.
I've thought about cosets and considered sets $g_1G_2$ for all $g_1 \in G_1$. Sum of all these sets is equal to $G_1G_2$ and each element is counted the same number of times, $|G_1 \cap G_2|$ presumably, but I can't seem to prove this fact nor see a connection.
Answer: Define $\varphi: G_1\times G_2\to G_1G_2$ by $\varphi(g_1,g_2)=g_1g_2$. The map $\varphi$ is obviously surjective. Now let $g_1\in G_1,g_2\in G_2$. For all $x\in G_1\cap G_2$ have $\varphi(g_1x,x^{-1}g_2)=g_1g_2$. The other direction is also correct: if $\varphi(h_1,h_2)=g_1g_2$ then there must be some $x\in G_1\cap G_2$ such that $(h_1,h_2)=(g_1x,x^{-1}g_2)$. Why is it true? Well, assume that $\varphi(h_1,h_2)=g_1g_2$. It means that $h_1h_2=g_1g_2$, and hence $g_1^{-1}h_1=g_2h_2^{-1}$. So now let $x=g_1^{-1}h_1=g_2h_2^{-1}$. This element is in $G_1\cap G_2$ (because $g_1^{-1}h_1\in G_1$ and $g_2h_2^{-1}\in G_2$), and indeed $h_1=g_1x, h_2=x^{-1}g_2$. Alright, so this proves that $|\varphi^{-1}(g_1g_2)|=|G_1\cap G_2|$. In other words, for all $y\in G_1G_2$ we have $|\varphi^{-1}(y)|=|G_1\cap G_2|$. The result follows.
Answer: Hint: Given $g_1g_2\in G_1G_2$, the same element is counted as all different possible $(g_1g)(g^{-1}g_2)$ for each distinct $g\in G_1\cap G_2$. That's the connection.


How it was decided that year's first grand slam will be Australian Open?

Question: In tennis sport, all 4 grand slams are played in a specific order in a year. First we Australian Open, then French, Wimbledon and in the last we have US Open.
Can anyone explain the exact reason why this order is fixed and how it was decided when first time these championships came into play.
Comment: I imagine it has to do with Australia being in the southern hemisphere (And therefore January being a summer month)?
Comment: Also you have to have Wimbledon in June/July, since it rains almost all year in England ;)
Comment: Hehe @Fatalize , but yeah seriously it came in mind while writing something about these grand slams that what is the reason behind such an order. On which basis, tennis sport authority decide the time period for these tournaments to organize..
Answer: The Australian Open didn't really become one of the 4 majors that all the top players competed in until the early 1980's. In fact, the tournament wasn't even held in 1986 because of a reshuffling of the schedule that year. As with most tournaments on the ATP and WTA tours, they are held during a time of year that has the best weather. For the Australian Open, that means during the summer time in the southern hemisphere, so, late January/early February. If you go back far enough in the history of the Australian Open you'll see the dates for it being in December, so it's moved around on the calendar a little bit over the years before it finally settled into the same two weeks over the past 25 years or so.
As for the other majors - it's really the same reason. Paris has good weather in late May/early June. Wimbledon has - typically - the best weather for tennis in late June/early July. The US Open could really be played anytime from June through September but Wimbledon and the French Open already had the calendar during the earlier summer months so it's been played in late August.
Also keep in mind that the French-Wimbledon-US Open are three different surfaces so the tour tries to allow for some time in between each event for players to play in warm up tournaments on the respective surfaces to allow players to adjust.
Comment: However, each year, players complain of the excessive Australian heat & many retirement happens due to heat strokes.
Answer: The Australian open is always first for many reasons:

In Australia, January is in summer and suits the surface,
The whole of January are school holidays allowing people to travel with their kids to the Open.
Most tradespeople in Australia don't work in January, thus suiting them.
Both the NRL (Rugby league) and the AFL are in their off-season.
January attracts extremely large crowds with around 720,899 people as the total attendance figure (compared to around 650,000 for the US Open, 600,000 for Wimbledon and around 450,000 for Roland-Garros)
Comment: Hi Luje, I feel that some of these points are correct, but not all of them. I can assure you that the vast majority of people are working in Australia again by the end of the first week of January. This answer would be stronger if you could add some sources to support each claim.


Trouble including jquery in page

Question: I'm working my way through http://www.packtpub.com/article/data-tables-datatables-plugin-jquery-1.3-with-php, to try to utilize the datatables jquery plugin.

  <base href="http://localhost/projectname/">

When I run this and check chrome developer tools console I see:
GET http://localhost/datatables/media/css/demo_table.css 404 (Not Found) myview:10
Uncaught ReferenceError: $ is not defined masterlist:12
GET http://localhost/myproject/datatables/media/css/demo_table.css 404 (Not Found)

I want to include jquery ( which I have locally in myproject/js/jquery.js ) in the project, byt this does not seem to be working. I thought:

would do it. Can someone explain why this is not working
Addendum: Following Orangepill's directions my code is now:

  <base href="<?=base_url();?>">

   # LINE 8

should be

I believe the data-original notation was a copy paste error from somewhere that had some lazy loading processing happening.
for the issue with your css try to change from a import to a head link
<link rel='stylesheet' href='js/datatables/media/css/demo_table.css'/>

it appears as though import is not respecting your base tag
Comment: view source and see what the base href is being set to... it's almost like it's nixing the `://` from there and trying to load it from a path relative to that
Comment:  -- which is what I thought it should be
Comment: You were right again :  worked. Thank you!

Trouble including jquery in page


Derivative of real vector fields according to Koszul formula

Question: I'm trying to understand covariant derivative in the simplest case of $\mathbb{R}^n$ here.
On a Riemannian manifold $(M,g)$, for a connection $\nabla$ which is compatible and torsion-free, I have been shown that the Koszul formula
$$ 2g(\nabla_XY, Z) = \partial_X (g(Y,Z)) + \partial_Y (g(X,Z)) - \partial_Z (g(X,Y))+ g([X,Y],Z) - g([X,Z],Y) - g([Y,Z],X)$$
holds.
I have just started studying these thing, but I'm pretty sure $\mathbb{R}^n$ and the usuals operators have all the good properties (compatibility of the connection, etc...).
1) Is it true that for $\textbf{X, Y}: \mathbb{R}^n\rightarrow\mathbb{R}^n$ smooth vector fields, I can think of $\nabla_\textbf{X}\textbf{Y}$ as the field $\space p\mapsto\frac{\partial{\textbf{Y}}}{\partial\textbf{X}(p)}|_p$ ?
(derivative of the field $\mathbf{Y}$ along the direction $\mathbf{X}(p)$ )
2) In demostrating the Koszul formula, I've written
$$ ...\space g(\nabla_XY,Z) = g([X,Y],Z)+g(\nabla_YX,Z) \space ... $$
Now with interpretation 1), since $[X,Y]=0$ in euclidean space, this piece should become
$$ \langle \frac{\partial\textbf{y}}{\partial\textbf{x}},\textbf{z}\rangle = \frac{\partial\textbf{x}}{\partial\textbf{y}},\textbf{z}\rangle $$
that is to say
$$ \frac{\partial\textbf{y}}{\partial\textbf{x}} = \frac{\partial\textbf{x}}{\partial\textbf{y}} $$
which is false.
I guess 1) is false then, but I was pretty sure about this interpretation (since the Leibniz rule for connection seems to work perfectly).
Do I have to throw away all this intuition?
Answer: You are right with one, but why should the Lie bracket of general vector fields be zero on $\mathbb R^n$. This is true for coordinate vector fields (and doesn't lead to a contradiction in this case) but not for general vector fields.
Comment: I afraid that the notation you use carries a big danger of cofusion. If you view $X$ as a function to $\mathbb R^n$, then $X(f)(x)=Df(x)(X(x))$. So if you differentiate this again, you also differentiate the function $X$ and not only $f$. In fact, on $\mathbb R^n$, you can realize (in this language) the Lie bracket as $[X,Y](x)=DY(x)(X(x))-DX(x)(Y(x))$ without involving the action on a function $f$. But in any case the notation as kind of a partial derivative looks very dangerous to me.
Comment: There are two different descriptions here. Either you expand $X(Y(f))-Y(X)(f))$. This needs differentiating $Df(_))(Y(_))$ in direction $X$, which gives $D^2f(x)(X(x),Y(x))+Df(x)(DY(x)(X(x))$. The first summand is symmetric in $X$ and $Y$, and thus does not contribute to the difference. This computation basically also proves the fomula in my comment, in which one only differentiates the vector fields as functions with values in $\mathbb R^n$.
Comment: Ok, that's it. So, being $[X,Y]=XY-YX$, I interpret $XY$ as the operator $f\mapsto (X\circ Y)(f)$ where in euclidean space $(X\circ Y)(f)=X(Y(f))=\frac{\partial^2}{\partial X\partial Y}(f)$. This must be the point I get wrong, right?
Comment: I mean, if $X\circ Y=\frac{\partial^2}{\partial X \partial Y}$ then the Lie brackets would be $0$ for Schwartz's theorem. But I was sure $X(f)$ meant $\frac{\partial f}{\partial X}$
Comment: This is definitely what's misleading me. Still, I don't grasp the right idea. Let me think about it a bit more, and thank you for your time!
Comment: So for the purpose of writing the Lie brackets, I'll try to write down $XY$: $$Y(f,p)=Df(p)(X(p))$$ according to your notation. Then
$$(XY)(f,p)=X(Y(f,⋅),p)=X(Df(⋅)(Y(⋅)),p)=X(Df(Y),p)=D(Df(Y)(p)(X(p))$$
$$\space$$
In short: $$ XY=D(D⋅Y)(X) $$ where $f$ goes at the place "⋅ ".

Does this mean your formula for $[⋅,⋅]$ lacks a $D$?
Comment: I think the answer is yes. You were right, I also have to differentiate the vector field. I also think I can understand now: thank you, this was very helpful! :) Could you confirm me that a double $D$ is right, because indeed I have to differentiate twice? I'll mark this as an answer then.


Como eu faço para colocar um controle ao lado do outro com bootstrap

Question: Tenho esse html com bootstrap. Preciso colocar uns textbox um ao lado do outro. Usei um controle horizontal e não funcionou. No controle Produtor eu coloquei dois textbox e não funcionou.
<form class="form-horizontal">

                Produtor

                    <input type="text" class="form-control form-white">

                    <input type="text" class="form-control form-white">

                CNPJ

                    <input type="text" class="form-control form-white">

                Tipo Produtor

                    <input type="text" class="form-control form-white">

                Filial

                    <input type="text" class="form-control form-white">

                Data de Inclusão

                    <input type="text" name="timepicker" class="b-datepicker form-control form-white" placeholder="Informe a data" data-orientation="top">

</form>

Comment: você tem duas divs após a label produtor, coloque "col-sm-3" e teste, se quiser você pode usar o site [ http://www.bootply.com/ ] que é ótimo para isso.
Comment: Visita esta página ela te ajudará a perceber melhor essas situações. https://getbootstrap.com/examples/grid/
Answer: Você pode colunar os dados conforme você fez, veja o exemplo: https://jsfiddle.net/ivanteles/fhoznrzt/
Comment: @IvanTeles, prefira colocar o código e o link, invés de colocar só o link.
Comment: Podes explicar na resposta o que esse jsFiddle tem e que ajuda ao perguntado? Assim a resposta ficaria ainda melhor :)
Comment: Entendi, sempre dentro do mesmo grupo. Mudou de grupo, ela vai para a linha de baixo.


IllegalArgumentException using Random.nextInt()

Question: I wrote trivia math application. It is start normally but after 10-20 question i got the mesage "the application has stopped unexpectedly".
This is the code. I know it is long but maybe you can help
package com.example.learn2;

public class Learn extends Activity {
private Button option_1;
private Button option_2;
private Button option_3;
private Button option_4;
private Button next;
private Button question;

private LinearLayout layout1;
private int[] arrayOf4Cell;

private TextView textScore;
private LinearLayout.LayoutParams params;
private int score=0;

///////////////////
private String xString;
private String yString;
private String ques;
private String correctAnswerTHE_ANSWERString;

private String a;
private String b;
private String c;
private String d;

/////////////////
private Random r;
private Random theQuestion;
private Random oneTOfour;

//////////////
private int correctAnswer;
private int correctAnswerTHE_ANSWER;

private int x;
private int y;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

     r= new Random();
     theQuestion= new Random();
     oneTOfour= new Random();

    option_1= new Button(this);
    option_2= new Button(this);
    option_3= new Button(this);
    option_4= new Button(this);
    question= new Button(this);
    next= new Button(this);
    next.setText("שאלה הבאה");

    params = new LinearLayout.LayoutParams(
            500, LayoutParams.WRAP_CONTENT);

    textScore= new TextView(this);
    arrayOf4Cell= new int[4];

    layout1 = new LinearLayout(this);

    option_1.setTextSize(10);
    option_2.setTextSize(10);
    option_3.setTextSize(10);
    option_4.setTextSize(10);

    question.setWidth(10);

    next.setTextSize(20);
    next.setGravity(Gravity.RIGHT);

    option_1.setGravity(Gravity.CENTER);
    option_2.setGravity(Gravity.CENTER);
    option_3.setGravity(Gravity.CENTER);
    option_4.setGravity(Gravity.CENTER);

    question.setGravity((Gravity.CENTER));
    question.setTextSize(20);
    question.setBackgroundColor(Color.CYAN);
    String scoreString=Integer.toString(score);
    textScore.setText(scoreString);

    ////////////////listener for each button
    option_1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String text=(String) option_1.getText();
            if(text.equals(correctAnswerTHE_ANSWERString)){
                Toast.makeText(Learn.this,"נכון!!", Toast.LENGTH_LONG).show();
                score++;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
                createAllLauout2();
            }
            else{
                Toast.makeText(Learn.this,"טעות. נסה שוב.", Toast.LENGTH_LONG).show();
                score--;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);

            }

        }
    });

    option_2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String text=(String) option_2.getText();
            if(text.equals(correctAnswerTHE_ANSWERString)){
                Toast.makeText(Learn.this,"נכון!!", Toast.LENGTH_LONG).show();
                score++;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
                createAllLauout2();

            }
            else{
                Toast.makeText(Learn.this,"טעות. נסה שוב.", Toast.LENGTH_LONG).show();
                score--;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
            }

        }
    });

    option_3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String text=(String) option_3.getText();
            if(text.equals(correctAnswerTHE_ANSWERString)){
                Toast.makeText(Learn.this,"נכון!!", Toast.LENGTH_LONG).show();
                score++;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
                createAllLauout2();
            }
            else{
                Toast.makeText(Learn.this,"טעות. נסה שוב.", Toast.LENGTH_LONG).show();
                score--;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
            }

        }
    });

    option_4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String text=(String) option_4.getText();
            if(text.equals(correctAnswerTHE_ANSWERString)){
                Toast.makeText(Learn.this,"נכון!!", Toast.LENGTH_LONG).show();
                score++;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);
                createAllLauout2();
            }
            else{
                Toast.makeText(Learn.this,"טעות. נסה שוב.", Toast.LENGTH_LONG).show();
                score--;
                String scoreString=Integer.toString(score);
                textScore.setText(scoreString);

            }

        }
    });

    layout1.setGravity(Gravity.CENTER_VERTICAL);
    layout1.setOrientation(LinearLayout.VERTICAL);
    layout1.setBackgroundColor(Color.argb(5, 102, 102, 204));
    layout1.addView(textScore);
    layout1.addView(question);
    layout1.addView( option_1);
    layout1.addView(option_2);
    layout1.addView(option_3);
    layout1.addView(option_4);
    layout1.addView(next);

    createAllLauout2();

    setContentView(layout1);

    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            createAllLauout2();

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_learn, menu);
    return true;
}

public void  createAllLauout2(){

    correctAnswer=oneTOfour.nextInt(4);
     correctAnswerTHE_ANSWER = r.nextInt(10);
    correctAnswerTHE_ANSWERString=Integer.toString(correctAnswerTHE_ANSWER);
     x=theQuestion.nextInt(correctAnswerTHE_ANSWER); // x in x+y
     y=correctAnswerTHE_ANSWER-x; //y in x+y

    xString=Integer.toString(x);
    yString=Integer.toString(y);
    ques=xString + "+" + yString;
    question.setText(ques);

    arrayOf4Cell[0]=correctAnswerTHE_ANSWER+3;
    arrayOf4Cell[1]=correctAnswerTHE_ANSWER*6;
    arrayOf4Cell[2]=correctAnswerTHE_ANSWER*2+4;
    arrayOf4Cell[3]=correctAnswerTHE_ANSWER*5+1;

    arrayOf4Cell[correctAnswer]=correctAnswerTHE_ANSWER; //one of the cell get the right answer

     a=Integer.toString(arrayOf4Cell[0]);
     b=Integer.toString(arrayOf4Cell[1]);
     c=Integer.toString(arrayOf4Cell[2]);
     d=Integer.toString(arrayOf4Cell[3]);

    option_1.setText(a);
    option_2.setText(b);
    option_3.setText(c);
    option_4.setText(d);

    layout1.updateViewLayout(question, params);
    layout1.updateViewLayout(option_1, params);
    layout1.updateViewLayout(option_2, params);
    layout1.updateViewLayout(option_3, params);
    layout1.updateViewLayout(option_4, params);
    layout1.updateViewLayout(textScore, params);

}

}
This is logcat:
09-27 16:59:06.142: D/AndroidRuntime(2314): Shutting down VM
09-27 16:59:06.152: W/dalvikvm(2314): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-27 16:59:06.152: E/AndroidRuntime(2314): FATAL EXCEPTION: main
09-27 16:59:06.152: E/AndroidRuntime(2314): java.lang.IllegalArgumentException
09-27 16:59:06.152: E/AndroidRuntime(2314):     at java.util.Random.nextInt(Random.java:225)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at com.example.learn2.Learn.createAllLauout2(Learn.java:246)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at com.example.learn2.Learn$4.onClick(Learn.java:183)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.view.View.performClick(View.java:2408)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.view.View$PerformClick.run(View.java:8816)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.os.Handler.handleCallback(Handler.java:587)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.os.Looper.loop(Looper.java:123)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at java.lang.reflect.Method.invokeNative(Native Method)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at java.lang.reflect.Method.invoke(Method.java:521)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-27 16:59:06.152: E/AndroidRuntime(2314):     at dalvik.system.NativeStart.main(Native Method)

Comment: Those are some of the least useful variable names I've ever seen. >.> *What is Learn.java line 246?*
Answer: The problem is here:
x=theQuestion.nextInt(correctAnswerTHE_ANSWER);

when correctAnswerTHE_ANSWER is 0.
You cannot call nextInt(0).  Check out Random#nextInt()`.

A quick fix is to check:
if(correctAnswerTHE_ANSWER == 0)
    x = 0;
else
    x=theQuestion.nextInt(correctAnswerTHE_ANSWER);

But I'm not certain what you are doing so hopefully you will find a better solution.


Problem with Infinite number of iterated integrals

Question: I have been working on a problem from a past high school Math Competition and I have been stumped. I am asked to compute
$$\lim_{n\rightarrow\infty} \int_{0}^{1}\int_{0}^{1}\cdot\cdot\cdot\int_{0}^{1}\frac{x_{1}^{505}+x_{2}^{505}+...+x_{n}^{505}}{x_{1}^{2020}+x_{2}^{2020}+...+x_{n}^{2020}}\,dx_{1}\,dx_{2}\,...\,dx_{n}$$ At first I tried a lot of direct evaluations of the integral to find a simplification i.e. solving the general integrals
$$\int_{0}^{1}\frac{x^{505}+a}{x^{2020}+b}\,dx$$ but this really only complicated the matter, so I began to look for more clever manipulations. I noticed for $x_i \in [0,1]$ that we would have the integrand
$$ f(x_1,x_2,...,x_n) = \frac{\frac{1}{n}}{\frac{1}{n}}\cdot\frac{\sum_{i=1}^{n}x_{i}^{505}}{\sum_{i=1}^{n}x_{i}^{2020}}$$ which can be seen as a Riemann sum so at infinity,
$$\lim_{n\rightarrow\infty}f(x_1,x_2,...,x_n)=\frac{\int_{0}^{1}x^{505}\,dx}{\int_{0}^{1}x^{2020}\,dx}=\frac{2021}{506}$$ My thought process was that the region in $\mathbb{R}^n$ being integrated over is the unit cube, so I could try to view the integral as the product of the volume of the region by some average value of the function in the region, which would maybe approach a constant value because of the Riemann sum? I was just unsure if any of this can be justified, especially when the number of integrals approaches infinity. Any help or advice is appreciated.
Comment: @Mr.Miso yes still cant figure it out haha
Comment: https://math.stackexchange.com/q/3681872/321264
Answer: Here's a solution that's entirely analytical.
Let $I_n=\int_{0}^{1}\int_{0}^{1}\cdot\cdot\cdot\int_{0}^{1}\frac{x_{1}^{505}+x_{2}^{505}+...+x_{n}^{505}}{x_{1}^{2020}+x_{2}^{2020}+...+x_{n}^{2020}}\,dx_{1}\,dx_{2}\,...\,dx_{n}$
Then
$$\begin{split}
I_n &= \int_{0}^{1}\cdot\cdot\cdot\int_{0}^{1}\left(x_{1}^{505}+...+x_{n}^{505}\right)\int_0^{+\infty}e^{-(x_1^{2020}+...+x_n^{2020})t}\,dt\,dx_{1}\,...\,dx_{n}\\
&=\int_0^{+\infty}\int_{0}^{1}\cdot\cdot\cdot\int_{0}^{1}\left(x_{1}^{505}+...+x_{n}^{505}\right)e^{-(x_1^{2020}+...+x_n^{2020})t}\,dx_{1}\,...\,dx_{n}\,dt\\
&=\int_0^{+\infty}\int_{0}^{1}\cdot\cdot\cdot\int_{0}^{1}\left(x_{1}^{505}+...+x_{n}^{505}\right)e^{-tx_1^{2020}}...e^{-tx_n^{2020}}\,dx_{1}\,...\,dx_{n}\,dt\\
&= n\int_0^{+\infty}\int_0^1x_1^{505}e^{-x_1^{2020}t}dx_1\left( \int_0^1 e^{-ty^{2020}}dy\right)^{n-1}dt \,\,\text{(by symmetry)}\\
&= \int_0^{+\infty}\int_0^1 x^{505}e^{-\frac u n x^{2020}}dx\left( \int_0^1 e^{-\frac u n y^{2020}}dy\right)^{n-1} du\,\,\text{ (with }u=nt\text{)}\\
&= \int_0^{+\infty}\frac{\int_0^1 x^{505}e^{-\frac u n x^{2020}}dx}{\int_0^1 e^{-\frac u n y^{2020}}dy}\left( \int_0^1 e^{-\frac u n y^{2020}}dy\right)^n du
\end{split}$$
Now, for a given $u>0$
$$\begin{split}
\left( \int_0^1 e^{-\frac u n y^{2020}}dy\right)^n &= \exp\left( n\ln \int_0^1e^{-\frac u n y^{2020}}dy\right)\\
&= \exp\left( n\ln \int_0^1\left(1-\frac u n y^{2020}+\mathcal O(\frac 1 {n^2})\right)dy\right)\\
&=\exp\left( n\ln \left(1 - \frac u {2021n} + \mathcal O(\frac 1 {n^2})
 \right)\right)\\
&=e^{-\frac u {2021}}+o(1)
\end{split}$$
and the same integral is dominated by 1. Therefore by the Dominated Convergence Theorem:
$$
\lim_{n\rightarrow+\infty}I_n = \int_0^{+\infty}\frac{\int_0^1 x^{505}dx}{\int_0^1 1dy}e^{-\frac u {2021}} du = \frac{2021}{506}
$$
Answer: I was the author of this question! Glad to see it is still engaging minds ~1 year after the initial contest. :)
Your answer is correct, but as you noted your reasoning is not really rigorous, although you are on the right track.
To give you a pointer, see if you can find a statistical interpretation of that integral instead of geometric.
Comment: That is so cool haha! Yes I think I get what you mean I was thinking along Riemann Sum lines but I think it simplifies nicer using expected value. Thanks for the integral


Java robot does not stop

Question: I have a problem with the operation of the JNativeHook library and Java Robot. My robot should run when I press F9 and it should stop when I click F6, but it is not working. I don't know what I am doing wrong here. Every time I tried to stop the robot it just does not stop. The code says that when I press F6 the work value should change to false and the while loop should stop calling the robot.
import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeHookException;
import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent;
import com.github.kwhat.jnativehook.keyboard.NativeKeyListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main extends JFrame implements NativeKeyListener {

    static int szerokosc = 2;
    static int dlugosc = 10;
    static boolean work = false;
    static Robot robot;
    static JTextField t1;
    static JTextField t3;
    static JTextField p1;
    JFrame jf;
    JLabel label, label2, label4;

    public Main() {
        try {
            robot = new Robot();
            jf = new JFrame();
            ImageIcon img = new ImageIcon("pickaxe.png");
            JTextPane tp = new JTextPane();
            jf.setLocation(800, 300);
            tp.setFont(new Font("Arial", 0, 32));
            jf.setTitle("Kopacz by Macijke");
            jf.setIconImage(img.getImage());
            jf.setPreferredSize(new Dimension(350, 350));
            jf.setLayout(new FlowLayout());
            label = new JLabel("Kliknij F9, aby włączyć kopanie na 6/3/3!");
            label.setBounds(50, 10, 250, 20);
            jf.add(label);

            label2 = new JLabel("Komenda nr 1");
            label2.setBounds(10, 20, 250, 90);
            t1 = new JTextField("/repair");
            t1.setBounds(100, 50, 150, 30);
            label2.setVisible(true);

            label4 = new JLabel("Długość");
            label4.setBounds(10, 240, 250, 90);
            t3 = new JTextField("10");
            t3.setBounds(65, 270, 50, 30);

            // ============
            p1 = new JTextField("11");
            p1.setBounds(255, 50, 30, 30);

            // ============

            jf.setDefaultCloseOperation(3);
            jf.setLayout(null);
            jf.add(t1);
            jf.add(t3);
            jf.add(label2);
            jf.add(label4);
            jf.add(p1);
            jf.pack();
            jf.setVisible(true);
        } catch (AWTException var3) {
            var3.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
            Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
        } catch (NativeHookException e) {
            e.printStackTrace();
        }

        GlobalScreen.addNativeKeyListener(new Main());
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        //
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
        if (e.getKeyCode() == NativeKeyEvent.VC_F6) {
            work = false;
        }

        if (e.getKeyCode() == NativeKeyEvent.VC_F9) {
            dlugosc = Integer.parseInt(t3.getText());
            work = true;
            int i = 1;
            while (work) {
                robot.mousePress(InputEvent.BUTTON1_MASK);
                for (int z = 0; z < dlugosc; z++) {
                    robot.keyPress(KeyEvent.VK_W);
                    robot.delay(210);
                    robot.keyRelease(KeyEvent.VK_W);

                }

                for (int a = 0; a < szerokosc; a++) {
                    robot.keyPress(KeyEvent.VK_A);
                    robot.delay(150);
                    robot.keyRelease(KeyEvent.VK_A);
                }

                for (int z = 0; z < dlugosc; z++) {
                    robot.keyPress(KeyEvent.VK_S);
                    robot.delay(210);
                    robot.keyRelease(KeyEvent.VK_S);

                }

                for (int z = 0; z < szerokosc; z++) {
                    robot.keyPress(KeyEvent.VK_D);
                    robot.delay(150);
                    robot.keyRelease(KeyEvent.VK_D);
                }
                robot.mouseRelease(InputEvent.BUTTON1_MASK);

                if (i % 25 == 0) {
                    robot.delay(100);
                    robot.keyPress(KeyEvent.VK_2);
                    robot.keyRelease(KeyEvent.VK_2);
                    robot.delay(250);
                    robot.mousePress(InputEvent.BUTTON3_MASK);
                    robot.delay(4000);
                    robot.mouseRelease(InputEvent.BUTTON3_MASK);
                    robot.delay(250);
                    robot.keyPress(KeyEvent.VK_1);
                    robot.keyRelease(KeyEvent.VK_1);
                    robot.delay(100);
                }
                i++;
            }
        }

    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
        //
    }

}

Answer: Try declaring work as volatile:
static volatile boolean work = false;
The problem is probrably due to synchronization
When your method nativeKeyReleased is invoked, it is going to run on a different thread, and all variables visible to a thread are instead copies.
Your code does not work because when you set work as true, this change will not propagate to the copy your while loop is looking at.
The volatile keyword will ensure that this variable is written to the main memory as well, instead of the CPU cache. thus achieving synchronization among different threads.
This article describes well how volatile works in Java.
Side Note
If you need to set the value of work in different locations, you should use synchronized setter method instead of a volatile field, as stated here
The rule of thumb is:

Use Volatile when you variables are going to get read by multiple
threads, but written to by only one thread
Use Synchronized when your variables will get read and written to by
multiple threads
Comment: That volatile flushes to main memory is common misconception. Modern CPUs have coherent caches due to cache coherence protocols like MESI. Forcing to read and write to main memory would make concurrent programs extremely slow.
Comment: The article posted suffers from the 'flushing to main' memory fallacy as well.

Java robot does not stop


I need help reading Xcode's error console

Question: I'm an Xcode beginner and am having trouble reading the error console to fix whatever has been making my app crash.  My code (Swift) compiles, but I get the SIGABRT error that I've seen so many other threads about. It seems like the solution is pretty different for each problem.
2017-05-08 20:57:32.821 ChordGenerator[6335:422217] -[ChordGenerator.ViewController newChordButton:]: unrecognized selector sent to instance 0x7f9ec6407fd0
2017-05-08 20:57:32.825 ChordGenerator[6335:422217] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ChordGenerator.ViewController newChordButton:]: unrecognized selector sent to instance 0x7f9ec6407fd0'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010b0beb0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010828b141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010b12e134 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x000000010b045840 ___forwarding___ + 1024
    4   CoreFoundation                      0x000000010b0453b8 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x0000000108f87d22 -[UIApplication sendAction:to:from:forEvent:] + 83
    6   UIKit                               0x000000010910c25c -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x000000010910c577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    8   UIKit                               0x000000010910b4b2 -[UIControl touchesEnded:withEvent:] + 618
    9   UIKit                               0x0000000108ff549a -[UIWindow _sendTouchesForEvent:] + 2707
    10  UIKit                               0x0000000108ff6bb0 -[UIWindow sendEvent:] + 4114
    11  UIKit                               0x0000000108fa37b0 -[UIApplication sendEvent:] + 352
    12  UIKit                               0x0000000109786adc __dispatchPreprocessedEventFromEventQueue + 2926
    13  UIKit                               0x000000010977ea3a __handleEventQueue + 1122
    14  CoreFoundation                      0x000000010b064c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    15  CoreFoundation                      0x000000010b04a0cf __CFRunLoopDoSources0 + 527
    16  CoreFoundation                      0x000000010b0495ff __CFRunLoopRun + 911
    17  CoreFoundation                      0x000000010b049016 CFRunLoopRunSpecific + 406
    18  GraphicsServices                    0x000000010cf7ba24 GSEventRunModal + 62
    19  UIKit                               0x0000000108f860d4 UIApplicationMain + 159
    20  ChordGenerator                      0x0000000107cb06a7 main + 55
    21  libdyld.dylib                       0x000000010c01065d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Comment: `SIGABRT` only means that it is a `SIG`nal for the process to `AB`o`RT`. Look at the first two lines of the error, maybe that will give some hints to the source of the error?
Comment: Here is the issue `reason: '-[ChordGenerator.ViewController newChordButton:]:`. Either the method `newChordButton` doesn't exist or the class doesn't conform to this method.
Comment: Fix your button action so it points to a valid method in your view controller.
Answer: 2017-05-08 20:57:32.821 ChordGenerator[6335:422217] -[ChordGenerator.ViewController newChordButton:]: unrecognized selector sent to instance 0x7f9ec6407fd0
This is the line you need to focus on. According to this, your project "ChordGenerator" which has a file "ViewController" has some function to which you are passing a selector "newChordButton". Currently, the system is unable to find that function. All in all, pass a function name that exists in the scope of the target i.e. if target=self, then the function newChordButton must be there in the current ViewController.swift class.
If you are testing, simply make an empty function:
func newChordButton(){
  print("Entered newChordButton function")
}


images not displaying with squid proxy page

Question: We are using a Red Hat 6 squid server to redirect HTTP request for custom notifications. Squid provides several built in splash pages however we are using a slightly customized one taken from a built in and just renamed it. When our splash page appears our custom image does not. The image on the web page is just a square with an x through it. The image file is on the squid server but the squid logs I think it tells the story. I just don't know how to fix. For example, there is a GET HTTP function that seems to want to append the name of whatever site the end user is going to, to the actual image location:
1457051968.734     14 192.168.150.125 TCP_DENIED/403 2881 GET http://www.google.com/images/image.png - NONE/- text/html

Problem is my image is not at Google but on the squid server. How can I override this? I have tried setting an absolute path in the splash page but that did not work. Here is what I have now:

The images folder is under /var/www/html/ and squid has rights to that folder. Any help is appreciated.
Answer: This depends on your static resource path set in the squid config.
Relevant directives for this are set in
error_directory # path to message files
icon_directory # path to icon/image files

The path to the embedded image should be like this:
/squid-internal-static/icons/SN.png

squid-internal-static points to your icon_directory.
Comment: ok I added "icon_directory /usr/local/squid/share/icons" to my squid.conf. How should it be referenced in my splash page HTML? Currently I have  . And this is still not working.
Comment: Logs still show Logs still show TCP_DENIED/403 2897 GET http://www.google.com/usr/share/squid/icons/image.png - NONE/- text/html
Comment: you have to create an image URI that starts with "/squid-internal-static" like i've written above. So your uri would be "/squid-internal-static/image.png". /squid-internal-static/image.png points to /usr/local/squid/share/icons/image.png
Comment: That's what I did. Here is what I have now. Squid conf = "icon_directory /usr/local/squid/share/icons". HTML splash page img tag =  = Now in the logs it shows TCP_DENIED/403 3051 GET http://localhost:3128/squid-internal-static/image.png - NONE/- text/html and still no image displayed.
Comment: we're using a similar setup with current build of squid - it's working with this setup. maybe there's a policy that rejects the request to the proxy itself and therefore the image cannot be delivered. URI looks good.
Comment: Its possible. What version of squid are you running? We are on 3.1. I saw where there was a bug fix for icon serving in 3.2. That may be what we need to do. ftp://ftp.arnes.si/packages/squid/squid-3.3-ChangeLog.txt. Or I may be able to whitelist one of our other servers and host the image there.
Comment: We're running current dev build in out test environment - currently 4.0.7. Offloading to a trusted source is also possible - and may be required if you'll add some additional features like AV scanning with custom reporting via redirection.
Comment: I'm going to have to post a new question. Its still not working with the image relocated to a white-listed server. Damn this is frustrating.  Hey on a side note- do you know of a directive I can use that will allow the page to come up after X number of seconds? For instance site A gets captured and the splash screen is shown. I want it to automatically go to the site the user originally intended after X number of seconds.
Comment: Of course - that's simple HTML and some lines of JS. I think you'll find the desired answer on google quite easily :-)
Comment: I have no idea how that would work using squid. You mean put the html and JS for the release in the splash page HTML?
Comment: That's how this works. It's just like any other website - you just shouldn't use any additional libs and more complex stuff - that's not what a proxy is made for.
Comment: I don't get what you are saying. Everything I see online whether is JS or in the meta tag - can you do a meta tag refresh without declaring the URL?
Comment: No. Just embed a small script of javascript that sets a timeout after x seconds and triggers redirection of the page. That's all.
Comment: Actually a meta tag worked!!