Is there a default web user group on CentOS Linux?

Question: I am used to Ubuntu and now have CentOS.  For my other web servers (on ubuntu) there is a user and/or group call "www-data" Is this something specific to Ubuntu or the LAMP appliance that I installed?
On my CentOS account it looks like the owner is 6226? How does this relate to www-data?
Answer: In Centos:

Apache Webserver, it runs as forks off to the apache user, apache group
MySQL runs as a mysql user, mysql group
Comment: Are you saying that 6226 is Apache User or the Apache group?
Comment: Default apache id for user is 48
Default apache id for group is 48

ID 6226, not sure what this. How did you determine that ID?  that could the the PID that the apache service was running at
Comment: OK, well I found that by checking the permissions via WinSCP.
Comment: OK, so 6226 is NOT a user group.
Comment: OK, so 6226 is listed as the owner of the files in the HTML folder.  I'm a bit clueless. Doing research.  Consulting my pocket linux book for guidance.
Comment: I had some luck changing permissions to apache when I needed to.
Answer: Same issue here, on a development server.
<code># ls -la
drwxr-xr-x 5 root root    4096 2011-01-23 00:14 .
drwxr-xr-x 7 root root    4096 2011-02-03 10:11 ..
drwxr-xr-x 9 6226 6226    4096 2010-12-15 14:17 d
drwxr-xr-x 8 root root    4096 2011-01-23 13:51 htdocs
</code>
"d" is a drupal installation, and the directory was created with:
<code># tar -xzvf drupal.tar.gz
</code>
Using tar to directly examine its archive:
<code># gunzip drupal.tar.gz
# tar -tvf drupal.tar

-rw-r--r-- bender/bender    765 2007-09-10 13:29 drupal-6.20/themes/pushbutton/forum-link-rtl.png
</code>
Only one line is included because they all show the same owner/group. A quick Google search shows a few similar cases. Mystery solved?
Comment: You have 6226 because whoever packages the Drupal tarballs does so when logged in with a user whose uid and gid are 6226 on their system.


$.when apply for single request

Question: I am trying to use $.when apply  in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
    for (var i = 0; i < arguments.length; i++) {
       var value = arguments[0];
    }
});

This is what i do not want to do.
if (apiRequestList.length === 1) {
    $.ajax({

    });
} else {
    $.when.apply(null, apiRequestList).then(function () {
        for (var i = 0; i < arguments.length; i++) {
           var value = arguments[0];
        }
    });

}

Comment: It's unclear what the difference is that you're concerned about.  The object returned from `$.when()` does vary depending on whether single or multiple promises are passed, but AFAIK the resulting parameters passed to the subsequent `.then` callback will always just be a list of the promises' resolved values.
Comment: Just drop `$.when` and use `Promise.all` instead.
Answer: You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {

    var _arguments = Array.prototype.slice.call(arguments);
    if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
        _arguments = [arguments];

    for (var i = 0; i < _arguments.length; i++) {
        var value = _arguments[i][0];
        console.log(value);
    }
});

Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
  return $.post("/echo/html/", {
    html: "a = " + a,
    delay: Math.random()
  });
}
function doIt(apiRequestList) {
  $.when.apply(null, apiRequestList).then(function() {

      var _arguments = arguments;
      if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
          _arguments = [arguments];

      for (var i = 0; i < _arguments.length; i++) {
          var value = _arguments[i][0];
          console.log(value);
      }
      console.log("----");
  });
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);

Example output (it'll vary because of the Math.random()):

a = 4
----
a = 1
a = 2
a = 3
----
Comment: Wouldn't it better: `_arguments = Array.prototype.slice.call(arguments);`?
Comment: @A.Wolff Not necessary, you can iterate over `arguments` just fine

$.when apply for single request


buggy JQuery .animation()

Question: here i have 6 divs (.sticker) inside a single div, onClicking one of them i would like to fadeOut the others keeping the clicked one in it position (that's why i do the postop/posleft thing) then i want to move it on the middle of the bigger div while it grows by height and width, showing a hided div (.info). The same for closing!
So, this code it's working but it's really laggy, it's not smooth as jQuery should be, am i doing something wrong?
Thanks to all the comunity!
<code>$("body").on('click', '.sticker', function () {

    if (!is_open) {
        postop = $(this).position().top;
        posleft = $(this).position().left;
        $('.sticker').not(this).fadeOut(350, function () {
            $(".sticker").css("position", "absolute").css("left", posleft + "px").css("top", postop + "px");
            $(".sticker").animate({
                'top': '0px',
                'left': '300px',
                'height': '480px',
                'width': '750px',
                'left': '90px'
            }, 350);
            $(".sticker").children(".wrap").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $(".sticker").find(".imgspace").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $(".sticker").find(".info").animate({
                'height': '100px'
            }, 350);
            $('.arrow-left').animate({
                'left': '-20px'
            }, 450);
            $('.arrow-right').animate({
                'left': '880px'
            }, 450);
            is_open = true;

        });
    }
    if (is_open) {
        $(".sticker").children(".wrap").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $(".sticker").find(".imgspace").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $(".sticker").find(".info").animate({
            'height': '0px'
        }, 350);
        $(".sticker").animate({
            'height': '230px',
            'width': '300px',
            'top': postop,
            'left': posleft
        }, 350, function () {
            $(".sticker").css("position", "static");
            $(".sticker").not(this).fadeIn(300);
            is_open = false;
        });

    }

});
</code>
Comment: can you attach a jsFiddle or something like that?
Answer: You will want to use .siblings to hide all others when you click on one. I would do some research on the jQuery API document.  This is where I would start.
Answer: As Yotam has commented, difficult to debug without a jsFiddle. But things that stuck out to me (and in no way is this exhaustive and I am no JavaScript expert):

cache your jQuery objects rather than keep requerying the DOM (var $sticker = $('.sticker'))
Chain together your animations on the same objects
What is the difference between  $sticker.children(".wrap") and $sticker.find(".imgspace")? Can you not use $sticker.find(".wrap, .imgspace")?

You could further simplify the code by setting your values to variable objects rather than call the same method twice hard coded with different values.
<code>$("body").on('click', '.sticker', function () {

    if (!is_open) {
        var $position = $(this).position(),
            $sticker = $('.sticker');

        $sticker.not(this).fadeOut(350, function () {
            $sticker.css({
                        position: 'absolute',
                        left: $position.left+'px',
                        top: $position.top+'px'
                    })
                    .animate({
                        'top': '0px',
                        'left': '300px',
                        'height': '480px',
                        'width': '750px',
                        'left': '90px'
                    }, 350);
            $sticker.find(".wrap, .imgspace").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $sticker.find(".info").animate({ 'height': '100px' }, 350);
            $('.arrow-left').animate({ 'left': '-20px' }, 450)
                            .animate({ 'left': '880px' }, 450);
            is_open = true;

        });
    }
    if (is_open) {
        $sticker.find(".wrap, .imgspace").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $sticker.find(".info").animate({
            'height': '0px'
        }, 350);
        $sticker.animate({
            'height': '230px',
            'width': '300px',
            'top': $position.top,
            'left': $position.left
        }, 350, function () {
            $sticker.css("position", "static")
                    .not(this).fadeIn(300);
            is_open = false;
        });
    }
});
</code>

buggy JQuery .animation()


How to force angular material follow the ionic v5 dark mode switch

Question: im trying to develop my first App and i got stuck with this issue.
when the device is in dark mode ionic automatically switches to dark mode as well.
but the angular material doesn't change its color scheme which keeps the text dark.
Thanks is Advance.
Comment: In the scheme color in variables , change it from dark to light
Answer: if you use global variables for giving color through all the app it will change when you switch and there will be no problem. the problem is with using non-ionic variables to color them.
Comment: Touched it like at ionic 2  and now just starting to get back at it. I don't see how it's relevant to the wuestion
Comment: how do i set the ionic veriable to the angular material theme thats what i cant figure out
Comment: @AlexSkiba use `mode="md"` for material design and `color="variable-name"`
Comment: @AlexSkiba how long do you use ionic?
Comment: I don't understand your question
Comment: @AlexSkiba when do you started to use ionic? a month? a year?
Comment: @AlexSkiba I asked it to see how much you are familiar with ionic.
Comment: not that much i know the very basic things and trying to expand my knowledge. Should i try to set the material template with the ionic variables?
Comment: @AlexSkiba the material theme is a theme that is built-in in ionic. just add `mode='md'` to your tags. and then you can use attribute color (for example: `color='primary'`) to color them.
Comment: the problem is with ios i guess i will just over write the dark mode colors i guess


How can I catch event when a text field is exiting focus (on blur) in Flutter?

Question: I look into TextFormField, the fields here isn't what I need:

onChanged (called after each key pressed, I need when the user has already complete and exit the TextFormField focus)
onEditingComplete (called after user press on Done key or similar, but user may exit TextFormField focus without tapping those button)
onSave (called after calling form.save(). But I need to do this after user finish editing, to let user know that the app does "auto-correcting" to what the user entered)
validator (also called on form.validate(), right before form.save(). not what I needed)

I need that when user exit the focus (dismissing the keyboard or tapping into another text field), I do a processing to let user see that their input is being adjusted and processed to the "correct one". How can I catch such event?
Answer: By using FocusNode class,  you add a focus listener and can catch focus change.
By using Focus class, you just wrap TextField and add a onFocusChange parameter.
[Solution 1]

add a define FocusNode instance

FocusNode focusNode = FocusNode();

add a listener of FocusNode at initState.

focusNode.addListener(() {
      print('1:  ${focusNode.hasFocus}');
    });

add a FocusNode instance to TextField's focusNode parameter.

TextField(
      focusNode: focusNode,
    )

[Solution 2]

Wrap TextField by Focus widget

Focus(
  child: TextField(),
  onFocusChange: (hasFocus) {
    print('2:  $hasFocus');
  },
)

[Example Full Code]
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FocusNode focusNode = FocusNode();
  @override
  void initState() {
    super.initState();
    focusNode.addListener(() {
      print(focusNode.hasFocus);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    return TextField(
      focusNode: focusNode,
    );
  }
}

Comment: ouu. I just only ever heard the first solution, but never the second. I think the second solution is the best for me. Thanks!!
Comment: @appdev It works for TextFormField
Comment: second solution is not valid for textform filed


MvcSiteMap causes all my controllers to instantiate

Question: Trying to built menu from MenuHelperModel causes MvcSiteMap to construct all my controllers. That could be a big performance hit.
Is this only way to go when I rely on [Authorize] to set up security for controllers?
Answer: First of all, constructors should be simple. If creating your controllers on each request is slowing your application down, it is a sign that your constructors are doing too much work. The MVC framework creates one instance per request, anyway, so this is likely slowing down more than just MvcSiteMapProvider.
That said, there is another option. You can use the roles attribute/Roles property to set the same roles as you have in AuthorizeAttribute. The downsides of doing this are:

You have to duplicate your entire security scheme.
You won't be able to use a custom AuthorizeAttribute.

You might be able to work around the first limitation by making a dynamic node provider that scans your application using Reflection and sets up the roles from AuthorizeAttribute as the roles of the corresponding node. This code is only run once per cache timeout, so having some Reflection at that point probably won't cause a performance problem.
Comment: >The MVC framework creates one constructor instance per request, anyway.
One instance per request is not same as one instance per controller per request, but I understand your point.
Getting my constructors simpler was my first step.
Comment: True. But unfortunately, Microsoft didn't have the foresight for anyone who wants to use `AuthorizeAttribute` for checking security on anything that is *not* the current request - you are left with no choice but to mock up a `ControllerContext` object that represents the *would be* request, which requires a controller instance (or duplicate the whole security scheme as I mentioned).


How do you get that big 90s distorted guitar sound (Jawbreaker, Pixies, etc.)

Question: I've researched this question before but after not finding exact sounding examples of what I'm going after, I decided to post my question here with an audio example.
I'm looking to get this sound:
Jawbreaker - "West Bay Invitational"
I'm using software to emulate this sound but it ends up sounding flat and not punchy at all. I've tried layering the tracks, adding delays distortion and flanger, and while it all sounds nice in a wall of sound kind of way, it's not there yet.
I'm using Logic and the pedalboard audio effect.
I'll also take advice with physical equipment.
Thank you in advance!
Comment: Without even listening, I bet the original sound is not as distorted as you're trying to make it. The overall effect comes in the mix, as the track is comped. It was the early days of multi-band compressors & brick-wall limiting. Listen to Eels, Novocaine for the Soul for one of the very first examples.
Comment: I listened [& to some pixies]... my first comment stands. Don't over-push your amp sound, the effect comes afterwards, at the mix. Check this extract - more like Eels than your examples, but this is a single guitar, no overdubs, crunchy not high-gain, mastering comp makes the "wall" - https://soundcloud.com/graham-lee-15/norton-disney-weightless-excerpt
Comment: Thank you! I'll look into multi band compression and brick wall limiting. From a quick glance it seems like they are mostly used in the mastering stage rather than mixing/writing.
Comment: Yes - though if that's what you're aiming for from the start, you can strap one over the master bus earlier. You need to learn how it affects things, though, & not just go mad with it ;)
Comment: I would definitely advise against adding any effects to the mater track prior to completing your mix.  I would agree that the overall "wall of sound" approach to guitars has more to do with how it is mixed/mastered but you do have to get the right sound on the way in (or in the box if you're doing your effects there), so I think the best answer will talk more about that than mixing but it all has to be considered.
Comment: I'm looking at tutorials now for it! Do you believe software can approach this kind of sound? I do want to eventually learn the mastering process. I'm starting to realize writing, mixing and mastering are kind of linked into one process.
Comment: @Basstickler thank you so much for your input as well. I think I'd like to get the sound as close as possible out of the gate before fiddling with effects, specially because I'm mostly using software.
Comment: You're surely welcome.  The general rule that I've encountered when working with professional engineers is that you want to make everything sound as good and as close to your end goal as possible before you're even going into the computer, then use the plugins to get the rest of the way there.  Obviously this is a bit different when you're only using plugins for your effects but you can apply that thought process here again, but more broadly, that you want to get everything as close to your desired result as early in the process as possible.
Comment: I've also heard a lot of professionals talk about getting everything the way you want it in your mix and not leave any of it to the master.  Mastering should just be making small changes to allow everything to be the appropriate loudness and translate properly to different speakers.  If the mastering engineer is expected to change the overall sound/feel of a track, then the mix wasn't done properly.
Comment: I'll have to invest in some equipment then. Currently just have my home set up but I'll look into physical equipment to start the writing and recording process.
Comment: That's not a bad idea, however, you should definitely base your decisions in part on what you intend to do with your product and how realistic those goals are in the short term.  Basically, don't spend a bunch of money on hardware that you can come close to emulating with software if you're not going to actually get paid more because of it.  Hardware is great to have but if you're not actually making any money from music, the authenticity shouldn't be too much of a concern.  You can replicate pretty much anything with software.
Answer: The guitar sound on that track is clearly a fuzz pedal to me. Fuzz pedals include:

ProCo Rat (very popular in the 90s because of Kurt Cobain - it might be a Rat)
Big Muff Pi (this recording might be a Pi)
Dallas/Arbiter Fuzz Face - Maybe the most famous vintage fuzzes with many clones made over the years up through today
Sola Sound Tone Bender - Also vintage and many clones have been made

There are some fuzzes that have come out since the 90s that have been popular, most particularly the Zvex Fuzz Factory as made famous by Matt Bellamy of Muse. But that's not related to this question.
I would try some different fuzz sounds, and probably single coil pickups. Actually I find the guitar sound in the sample recording to be quite thin. It only is full in context because of the bass guitar. Fuzz doesn't usually have a setting that only applies a little bit of fuzz, but you can find the edge of fuzz by rolling off the guitar's volume a bit.
So I would say single coil bridge pickup into a fuzz pedal like a Rat or Pi or some cheap 90s fuzz (punk is all about cheap - usually). Make the amp pretty clean, maybe even a solid state amp - it doesn't have a rich midrange. Set the fuzz to middle settings and put all the tone controls on the amp all the way up. Roll off the volume knob on the guitar until it starts to sound about right.
That hopefully gets you close to the raw guitar sound. There are two guitar tracks on that recording both with the same sound. It's not exactly double tracked, because the parts are slightly different. One guitar is panned around 50% right and other about 50% left (meaning halfway between center and panned hard. Then there's the bass that helps with the low end.
I suggest working from time to time to recreate tones that you like, but limit yourself to just giving it a good attempt. Don't spend too much time chasing someone else's sound because you really want to find your own. You'll never nail another sound anyway.
When you're done, a look-ahead peak limiter on the whole mix was very popular (I guess actually mandatory) in the 90s, and just a bit of subtle reverb.
Comment: This is an incredibly helpful answer. Thank you so much. I'm hearing the bass a lot more now since you mentioned it. Your encouragement to find my own sound is inspiring, and freeing in many ways. Thank you also for pointing out the panning on the tracks, it helps me listen to songs closer to hear exactly what might be going on. Truly appreciate it!
Comment: Agree with this answer, this is bass, and also the drums are making it very punchy.  note how turned down the guitar really is, and as Todd said, panned heavily. when working the mix keep the guitar's bass down, work on higher treble/tone and blend with bass/kick.  NOTE:  if you are using a solid state amp, overdrive pedals do not come out pretty.   go for a "distortion" pedal.  take your amp and guitar into a music store, and ask to try out pedals.  maybe leave your stuff and go out for lunch lol they'll very likely have no problem with it if you're serious about buying.
Comment: note:  I know you mentioned software solutions, but also stated hardware.  I've used both extensively, and suggest getting ONE good, dedicated distortion pedal, and learning it well, will be a most valuable asset for years to come. (I say distortion, because I feel they're more robust, but that's personal opinion.  my pedal is reviled (ORIGINAL Grunge FX69, DOD, had since I was a kid) but with my trusty 90's Strat I pull a wild range of sounds


jQuery - make a DIV visible on the browser

Question: I have designed a long form around two pages. After the user submits the form, I need to force him/her to see the top of the form if the form contains any errors.
I have an error holder on top of the form.
My question is how to make the browser scrolls to the error holder so that the user can easily see it?
Thank you
/////////////////////////////////////////// follow Peter's comments
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>jQuery</title>

Hello world

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

    <button type="button" id="clearhere" name="clearhere">Click Me!</button>

///////////////////////////////////////////
Comment: `goToByScroll('#topbar2');` . Note the hash sign. You have to call the function using a literal jQuery selector. Here is your code working: http://jsfiddle.net/F4TQ5/
Answer: To scroll to the top an element simply make use of the jQuery .animate() and .offset() functions. For example to scroll to the top of an element with a particular selector (such as an id) passed in as an argument, use this:
  // This is a function that scrolls to the element that matches selector
function goToByScroll(selector){
      // Scroll
    $('html,body').animate({
        scrollTop: $(selector).offset().top},
        'slow');
};

For example, if you have only one form on the page, you can use: goToByScroll("form");. If you want to scroll to an element with a particular id use goToByScroll("#myId"); ... etc.
If you want to adjust the scroll time to an exact number of milliseconds, just replace 'slow' with the number of millisecond, for example 1000 (no quotes) for a scroll of 1 second.
Just trigger the above function when you want to scroll to the top of your form.
Here's a live jsFiddle example (as a 5 line jQuery plugin)
Comment: Hello Peter,

I have tried this method. However, it doesn't work for me.

The firebug reports:

Break on ErrorCopy
$(id).offset() is null

Thank you
Comment: @q0987 - What is id? How did you call the function? Sounds like a problem with that. Take a look at how I call the function in the jsFiddle examples.
Comment: Hello Peter,

I have posted my script following my original question. I have used firebug to debug and it reports the error as above.

Thank you
Comment: @q0987 `goToByScroll('#topbar2');` . Note the hash sign. You have to call the function using a literal jQuery selector. I got your code to work here: http://jsfiddle.net/F4TQ5/
Comment: Hello Peter,

Thank you so much for your helps.

Just curious, why you choose to use $('html, body').animate rather than just $('html').animate.

I found that $('body').animate doesn't work for me.

Thank you
Comment: @q0987 - Firefox and IE use `body` in quirks mode. So selecting both `html` and `body` covers all the bases.
Answer: You could use the jQuery ScrollTo plugin to smoothly scroll back up to the error holder:
// in your validation, on error
$(window).scrollTo($('#errorHolderId'), 500);

Sans plugin
If you don't want to use a plugin, you can do it with a combination of offset() or position() and scrollTop:
var errorHolderTop = $('#errorHolderId').offset().top;
$(window).scrollTop(errorHolderTop);

The reason I mentioned both offset and position is because they behave slightly differently.  Offset returns coordinates relative to the document whereas position is relative to your element's offset parent.
You could also animate the scrollTop property if you wanted to create the smooth scroll effect:
var errorHolderTop = $('#errorHolderId').offset().top;
$('html, body').animate({scrollTop: errorHolderTop});

In action here.
Comment: Hello Pat,

Is there way that I don't have to use a extra plugin?

Thank you
Comment: @q0987 sure, see my edits for a few different ways of doing it.
Comment: Hello Pat,

Interesting here. Both you and Peter use $('html, body') rather than just $('html'). any reason?

Thank you
Comment: @q0987 cross-browser compatibility my good man.  Some browsers want to scroll the `html` element, others want the `body`.


Proof of Delta System Lemma

Question: I'm reading my class notes on set theory. There is a proof of Delta system theorem, and there is something unclear about it.
Delta system lemma: Suppose $\{a_{\alpha}: \alpha<\aleph_1\}$ is a collection of finite subsets of $\aleph_1$. Then there exists an uncountable subset $I\subseteq\aleph_1$ such that $\{a_{\alpha}:\alpha\in I\}$ is a $\Delta$-system, i.e there is some set $a$ such that $a_{\alpha}\cap a_{\beta}=a$ for all $\alpha\ne\beta\in I$.
In the proof we use the following result:
Fodor's theorem: Asssume $\kappa$ is a regular uncountable cardinal, $S\subseteq\kappa$ is a stationary set and $f:S\to\kappa$ has the property $f(\alpha)<\alpha$ (which means $f$ is a regressive function) for all $\alpha\in S$. Then there is a stationary set $S^*\subseteq S$ such that $f$ is constant of $S^*$.
Proof of $\Delta$-system theorem: Let $S=\{\alpha<\aleph_1: \omega<\alpha \ is\ a\ limit \ ordinal\}$, this is a stationary subset of $\aleph_1$. We can define $f:S\to \aleph_1$ by $f(\alpha)=|a_{\alpha}|$. Since the sets $a_{\alpha}$ are finite this is a regressive function, so there are $n^*<\omega$ and a stationary subset $S^*\subseteq S$ such that $|a_{\alpha}|=n^*$ for all $\alpha\in S^*$.
Next we define $g:S^*\to \aleph_1$, $g(\alpha)=|a_{\alpha}\cap\alpha|$. Again, $g$ is regressive so there are $n^{**}<\omega$ and a stationary subset $S^{**}\subseteq S^*$ such that $|a_{\alpha}\cap\alpha|=n^{**}$ for all $\alpha\in S^{**}$. Now for each $\alpha\in S^{**}$ we will write the set $a_{\alpha}\cap\alpha$ as an increasing sequence:
$a_{\alpha}\cap\alpha=\{a_{\alpha}^0, a_{\alpha}^1,...,a_{\alpha}^{n^{**}-1}\}$
Now we keep defining regressive functions. Let $g_0: S^{**}\to\aleph_1$, $\alpha\to a_{\alpha}^0<\alpha$. There is a stationary subset $S_0\subseteq S^{**}$ and some $a^0$ such that $a_{\alpha}^0=a^0$ for all $\alpha\in S_0$. Now we define $g_1:S_0\to\aleph_1$, $\alpha\to a_{\alpha}^1<\alpha$. Again, there is a stationary subset $S_1\subseteq S_0$ and some $a^1$ such that $a_{\alpha}^1=a^1$ for all $\alpha\in S_1$. We continue this way and finally get a stationary set $S_{n^{**}-1}$ such that for all $\alpha$ in this set we have:
$a_{\alpha}\cap\alpha=\{a^0, a^1,...,a^{n^{**}-1}\}$
And finally we define the set $a=\{a^0, a^1,...,a^{n^{**}-1}\}$. It can be checked that $C=\{\delta<\aleph_1: a_\alpha\subseteq\delta \ \forall\alpha<\delta\}$ is a Club set, and hence if we define $I=C\cap S_{n^{**}-1}$ then this is a stationary set, hence uncountable. And $\{a_{\alpha}:\alpha\in I\}$ is a $\Delta$-system, because if $\alpha<\beta\in I$ then we have: ($I\subseteq C$, so $\alpha<\beta$ implies $a_{\alpha}\subseteq\beta$)
$a\subseteq a_{\alpha}\cap a_{\beta}\subseteq \beta\cap a_{\beta}=a$
And hence $a_{\alpha}\cap a_{\beta}=a$. So we got what we wanted.
My question is: do we really need the function $f$ and the natural number $n^*$ at the beginning of the proof? I just can't see where did we use it. We never used the size of the sets $a_{\alpha}$ in the proof, only the size of the sets $a_{\alpha}\cap\alpha$. Am I missing something or could we immediately start from the function $g$?
Comment: $f$ does seem superfluous. If you're interested there's also easy inductive proofs of the $\Delta$-system lemma that don't need Fodor's lemma. See thm 9.18 in Jech's book for example
Comment: Yes, I also think we don't use $f$ at all in that proof. Thanks. And yes, Jech's proof looks easier.
Comment: Ok, I found out that $f$ is really not needed in this proof. We can immediately start from $g$. Not sure if I should delete the question. Maybe some users will want to read this non-standard proof the the Delta System lemma.
Comment: You can also answer you own question, just to remove it from the unanswered list
Answer: Alright, I'll answer the question. Yes, I found out that we don't need $f$ in this proof. Also, the one thing I didn't explain in the question is why $C$ is a Club set. It follows from the fact that $C$ is the diagonal intersection of the sets $C_{\alpha}=\{\delta<\aleph_1: a_{\alpha}\subseteq\delta\}$ which are all obviously Club sets. This is not the shortest proof the $\Delta$-System lemma, but I think it's still a nice proof.

Proof of Delta System Lemma


is $f(x)= x^7+x-\frac{1}{n}$ injective?

Question: I want to prove that $f(x)= x^7+x-\frac{1}{n}$ is injective.
So, if I take two real values $x$ and $y$ and consider the values assumed by the function, they should be the same.
$f(x)=f(y) \rightarrow x^7+x-\frac{1}{n}=y^7+y-\frac{1}{n}\rightarrow x^7+x=y^7+y$
But I don't know how to continue
Comment: Is this a monotone function?
Answer: How about taking the derivative?   $f'(x)=7x^6+1\ne0$.
Thus $f$ is $1-1$.
Comment: @Botond if I want not to use derivatives?
Answer: If you don't want to use derivatives you were on the right track.
You already had that it had to hold $$x^7+x=y^7+y$$ so let's move forward with this one.
First consider that it follows from above that $x$ and $y$ have to have to same leading sign, wlog let's assume $x,y > 0$ (otherwise we multiply both sides with $(-1)$) and it follows:
$$\begin{align} &&x^7+x&=y^7+y \\ &\iff& (x^7 - y^7) + (x-y) &= 0 \\ &\iff& (x-y)\left(1 + \sum_{k=0}^6 x^ky^{6-k}\right) &= 0 \end{align}$$
but this only holds for $x=y$ because of $$\left(1 + \sum_{k=0}^6 x^ky^{1-k}\right) > 0$$ for $x,y>0$

is $f(x)= x^7+x-\frac{1}{n}$ injective?


trigonometric summation with arithmetic progression of angles and coefficients

Question: How can we sum up sin and cos series when the angles and also coefficients  are in arithmetic progression?
Such as cos(x)+2cos(2x)+3cos(3x)+.......+ncos(nx)
Comment: Can you specify a little bit, by writing an equation of the sum that you want to calculate?
Comment: related question: https://math.stackexchange.com/questions/1172449/find-formula-of-sum-sin-nx
Answer: Hint
Consider $$C_n=\sum_{k=1}^n k\, \cos(kx)\qquad \text{and}\qquad S_n=\sum_{k=1}^n k\, \sin(kx) $$ Integrate with respect to $x$
$$\int C_n\,dx=\sum_{k=1}^n  \sin(kx)\qquad \text{and}\qquad \int S_n\,dx=-\sum_{k=1}^n  \cos(kx)$$ which take you back to a much simpler and classical problem.
When done, differneiate with respect to $x$.
Answer: You can show that, using complex numbers, or using trigonometric identities:
$$\sum_{k=1}^{n} \sin(kx) = \frac{\sin(\frac{nx}{2})}{\sin(\frac{x}{2})} \sin(x+(n-1)\tfrac{x}{2})$$
Now differentiate wrt $x$ to get:
$$\sum_{k=1}^{n} k\cos(kx) = \frac{d}{dx}\left(\frac{\sin(\frac{nx}{2})}{\sin(\frac{x}{2})} \sin(x+(n-1)\tfrac{x}{2})\right) $$
Answer: $$\cos x+2\cos 2x+...+n\cos nx  = S\\ S=\sum_{k=1}^n \cos nx+\sum_{k=2}^n \cos nx... \\=\frac{\sin(n\frac{x}{2})}{\sin ( \frac{x}{2} )} \cos \biggl( \frac{ 2 x + (n-1)\cdot x}{2}\biggr) + \frac{\sin((n-1)\frac{x}{2})}{\sin ( \frac{x}{2} )} \times \cos \biggl( \frac{ 4x + (n-2)\cdot x}{2}\biggr) \\ +\frac{\sin((n-2) \frac{x}{2})}{\sin ( \frac{x}{2} )} \times \cos \biggl( \frac{ 6x + (n-3)\cdot x}{2}\biggr) \cdots \\ =\frac{1}{\sin\frac x2}\left[\sin(n\frac x2)\cos((n+1)\frac x2)+\sin((n-1)\frac x2)\cos((n+2)\frac x2)+\\ \sin((n-2)\frac x2)\cos((n+3)\frac x2) \cdots \right] \\
= \frac{1}{2\sin \frac x2}\left[\sin(nx+x/2)-\sin(x/2)+ \sin(nx+x/2)-\sin(x/2)\cdots\right] \\ =\frac{n\left[\sin(nx+x/2)-\sin(x/2) \right]}{2\sin \frac x2} = \frac{n\cos((n+1)x/2)\cos(nx/2)}{\sin \frac x2}$$


Proving that $D$ is dense in $(0,\infty)$

Question: Suppose $G \subset (0, \infty) $ and is not bounded. If we define set $D$ as below
$$ D = \Big\{x \in (0, \infty) : \exists A \subset \mathbb{N} \text{ not bounded s.t. } \forall n \in A, nx \in G \Big\} $$
Prove that $D$ is dense in $(0,\infty)$.
Comment: n is a natural number?
Comment: @polbos Yes, n is a natural number
Answer: First show that $ D = (0, \infty) $.
Then show that a set with no isolated points is dense in itself.
Hence $D$ is dense in $(0, \infty)$.
Comment: I have edited the question.
Comment: @FreeMind I have edited the answer accordingly and also suggested a rewording of the question to make it clearer.


Expectation of product of two inner products

Question: Suppose $a,w \sim \mathcal{N}(0,I_n)$ where the entries of $a$ and $w$ are independent. Define the following random vectors: $w_+$ and $w_-$ whose $i$-th entry is $$(w_+)_i = w_i 1_{\{w_i > 0\}}\ \text{and}\ (w_-)_i = |w_i| 1_{\{w_i < 0\}}.$$ That is, $w_+$ keeps the positive entries of $w$ and $w_-$ keeps the magnitude of the negative entries of $w$. I am interested in calculating $$\mathbb{E}|\langle a,w_+ \rangle \langle a,w_- \rangle|.$$ How could one go about this calculation? Since $a$ and $w$ are independent, is there a way to use conditional expectation to simplify this?
Answer: You might be able to simplify this:
Conditional on $w$ the random variables $U=\langle a,w_+\rangle$ and
$V=\langle a,w_-\rangle$ are independent mean $0$ gaussians with variances $\|w_+\|^2$ and $\|w_-\|^2$, respectively.  (Independent because $\langle w_+,w_-\rangle=0$.)  So your desired expectation is $(E|Z|)^2 E(\|w_+\| \|w_-\|)$,
where $Z\sim N(0,1)$, that is, $$\left( \frac2{\sqrt{2\pi}}\int_0^\infty z e^{-z^2/2}\,dz\right)^2 E(\|w_+\| \|w_-\|)=\frac 2 \pi \,E(\|w_+\| \|w_-\|).$$
We can write a formula for $E(\|w_+\| \|w_-\|)$ as follows:
$$E(\|w_+\| \|w_-\|) = \sum_{k=0}^n \binom n k 2^{-n} E\sqrt{X_k}\,E\sqrt{X_{n-k}}\tag{*}$$ where $X_k$ is a $\chi^2$ random variable with $k$ degrees of freedom, and $X_{n-k}$ is another, with $n-k$ degrees of freedom.  To see this, introduce $n$ iid Bernoulli random variables $b_1,\dots,b_n$ and note that the joint distribution of $(\|w_+\|^2, \|w_-\|^2)$ is the same as that of $$(R,S)=(\sum_{i=1}^n b_i w_i^2,\sum_{i=1}^n (1-b_i) w_i^2).$$  The idea here is that the $b_i$ decide for the $w_i$ whether they are positive or not.  Conditional on $\sum_i b_i = k$, $R$ and $S$ are independent $\chi^2$ rvs, with $k$ and $n-k$ degrees of freedom, respectively.
Finally, using the fact that the expectation of the square root of a $\chi^2$ rv with $\nu$ degrees of freedom is $0$ if $\nu=0$ and $$E\sqrt{X_\nu} = \sqrt 2 \frac{\Gamma(\frac{\nu+1}2)}{\Gamma(\frac \nu 2 )}$$ otherwise, we have an answer to the original question: $$
E|\langle a,w_+\rangle\langle a,w_-\rangle| = \frac {2^{2-n}} \pi \sum_{k=1}^{n-1}\binom n k \frac{\Gamma(\frac{k+1}2)}{\Gamma(\frac k 2 )}\frac{\Gamma(\frac{n-k+1}2)}{\Gamma(\frac {n-k} 2 )}.$$
Comment: Hey thank you for this. This is a really elegant solution. I had some numerical simulations for various sizes of $n$ and it matched up exactly with your calculation. I have a couple of questions for you:
Comment: 1) $U = \langle a,w_+ \rangle \sim \mathcal{N}(0,\|w_+\|^2 = \|w_+\| \mathcal{N}(0,1)$ so did you simply write $U = \langle a, w_+\rangle = \|w_+\| Z$ where $Z \sim \mathcal{N}(0,1)$ and similarly for $V$? Why exactly does the orthogonality of $w_+$ and $w_-$ give you independence?
Comment: Yes for the "simply write" bits.  For the "Why does...", work out the covariance  between $U$ and $V$: $EUV= Ea'w_+a'w_- = E w_+'aa'w_-= w_+ 'Eaa'w_-= w_+'IW_-=\langle w_+,w_-\rangle=0$. (Where $a'$ means $a$ transpose, etc.)
Comment: Wouldn't that only imply they are uncorrelated but not necessarily independent?
Comment: Conditional on $w$, $(U,V)$ are jointly gaussian, as they are linear forms in gaussian $a$.  Conditionally uncorrelated gaussians are conditionally independent.
Comment: Ah that's the critical part I was missing thank you. So the norm if $w_+$ and $w_-$ can essentially be expressed as a chi square random variable with bernoulli parameters $b_1,\dots,b_n$ which is why the pmf of the binomial distribution arises in the expectation?
Comment: This line of reasoning is really elegant! This particular problem is a specific case of an overarching problem I have: let $a,w,z \sim \mathcal{N}(0,I_n)$ be independent and fix $\theta \in [0,\pi]$. Define $w_+$ in the same way and define $y_+$ as $$(y_+)_i = (w_i \cos(\theta) + z_i \sin(\theta))1_{\{w_i \cos(\theta) + z_i \sin(\theta) > 0\}}.$$ Then I want to find $$\mathbb{E}|\langle a, w_+ \rangle \langle a,y_+ \rangle|.$$
Comment: Yes to "which is why" 2 comments back.  In effect, if $W\sim N(0,1)$ then $W$ and $(-1)^B|W|$ are equally distributed, where $B$ is independent Bernoulli.  Your revised problem with $y_+$ would  need something more complex than a Bernoulli, as there are 4 possible sign choices per coordinate, not 2.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/69884/discussion-between-xk3-and-kimchi-lover).


TypeScript: How to import all export functions from a JS file and then declare all those functions

Question: I'm trying to create a .d.ts file for a js package so I can have typescript import functions from that package. The package is using CommonJs style to define its exported functions. (Not an es6 file.)
The package's main property from its package.json is directed to file: index.js. The index.js file is displayed as:
'use strict'

const Plugins = require('./Plugins')

module.exports = {
  plugins: Plugins
}

From the Plugis.js file:
module.exports.function1 = function1() {// function1 content};

module.exports.function2 = function2() {// function2 content};

module.exports.function3 = function3() {// function3 content};

In pure JavaScript, this works, and I can use any of const Plugins exported functions.
I'm trying to create a typescript version index.d.ts with a similar make up:
'use strict'

import Plugins from './Plugins'

module.exports = {
  plugins: Plugins
}

However, I get errors when I import the js package and attempt to use the exported functions. For example, can use plugins.function1(). I've been researching this topic and followed several examples, but I keep getting errors, such as if I declare the function I want to use, and examples use imports from es6 style files. what is correct approach to import all file's functions?
Answer: Solved my problem. In addition to creating a index.d.ts I had to create a Plugins.d.ts file, then declare all the exported functions.
Plugins.d.ts:
declare export function1 = function1(): <Return value> {// function1 content};

declare export function2 = function2(): <Return value> {// function2 content};

declare export function3 = function3(): <Return value> {// function3 content};

For index.d.ts, my export and declare were off too, but I was able to correct it.
index.d.ts:
import * as Plugins from "./Plugins";

declare module "compatible-package-example" {
    export {Plugins}
}

Now when I import this package, I can use exported functions without issue.


Python Skcriteria Package, How do I get the similarity index for all cases and not just the top case with TOPSIS?

Question: Looking through the documentation:
https://scikit-criteria.readthedocs.io/en/latest/tutorial/quickstart.html
rank.e_.similarity shows the similarity index for the top case, but it does not specify how to get that value for other cases. My project seeks to show the index for top 10 cases of an experiment.
I tried simple indexing but without knowledge of how the object is set up I can not call the value for other cases. The values exist in the backend somewhere as it is needed to determine TOPSIS best case.
Answer: The vector stored in rank.e_.similarity contains the similarity values for each of the alternatives.
Thus rank.e_similarity[0] has the similarity index for the alternative rank.alternatives[0].
This value is calculated with the formula :
similarity = d_worst / (d_better + d_worst)

Where:

d_worstis the distance to the anti-ideal alternative
d_betteris the distance to the ideal alternative.

As of scikit-criteria 0.6 the distance metric is configurable. By default the Euclidean distance is used.
For more details regarding the ideal and anti-ideal points I recommend reading the TOPSIS wikipedia page https://en.wikipedia.org/wiki/TOPSIS


dynamically created labels are overridden

Question: i am working on one application in which i have added 5 labels dynamically in a function.when i recall the same function the labels are overridden on the previously created labels in spite of releasing the labels on each creation.
    for(int i = 1; i < [array count]; i++)
    {
        CGRect lblframe = CGRectMake(count, ycord, width, height);
        UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
        label.backgroundColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:17];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor colorWithRed:(188/255.f) green:(149/255.f) blue:(88/255.f) alpha:1.0];;
        label.text = [arr objectAtIndex:i];

        count = count + xcord;
        [subcatScroll addSubview:label];
        [label release];
   }

Comment: "when i recall the same function the labels are overridden on the previously created labels in spite of releasing the labels on each creation", can you explain more on your requirement?
Comment: I have some dynamically created labels in a scrollview. When I click on one value of labels lets say the first one in my horizontal scroll , another set of values appear in dynamically created labels just below the upper scrollview. Now When I click on second value of Main scrollview then the values on the lower scrollview are overwritten with the new values. I tried to release the previous labels but the issue was not solved.
Comment: Do you actually need to create new labels? can't you just replace the text of those already existing?
Answer: Write below code before for loop to get your requirement:
for (id object in [subcatScroll subviews]) {

    [object removeFromSuperview];
}

Answer: I'm not sure I completely follow, so correct me if I'm misunderstanding.
Every time you call this function, you are adding a number of new labels. So if you call this function the second time, assuming 'count', 'ycord', 'width', and 'height' correspond with the values that the first call had, you are obviously adding a second group of labels in the same place as the first ones which are now directly on top of one another. You are not "overriding" the old labels, you are placing a second group directly ontop of the old ones.
Calling "release" on each label, only means you are decreasing the retainCount by 1. This number is used for memory management only. This means if you now remove the labels from the view the memory is released.
CGRect lblframe = CGRectMake(10.0, ycord, 200.0, 20.0);
UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "1" since you called alloc
[self.view addSubview:label];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "2" since adding to subview increases retaincount by one
[label release];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "1" since you released
[label removeFromSuperview]; // will decrease retainCount of label to "0" and therefore free the memory

so say you wanted to remove the previously created labels from the view, you would have to do so. Either keep a reference to each of them and call "removeFromSuperview" on each of them.
If the only thing in the view where you're adding the labels, you can also just remove every subview that was added to it like so:
// remove old labels
for (UILabel *aLabel in [self.view subviews]) [aLabel removeFromSuperview];

NSArray *myArray = [NSArray arrayWithObjects:@"I", @"II", @"III", @"IV", nil];
for (int i=0; i<[myArray count]; i++) {
    float ycord = i*40.0;
    CGRect lblframe = CGRectMake(10.0, ycord, 200.0, 20.0);
    UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
    label.backgroundColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:17];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor colorWithRed:(188/255.f) green:(149/255.f) blue:(88/255.f) alpha:1.0];;
    label.text = [myArray objectAtIndex:i];

    [self.view addSubview:label];
    [label release];
}

I hope this helped, but providing further info on what you're trying to do may make it easier to help you.
Comment: for (UILabel *aLabel in [self.view subviews]) [aLabel removeFromSuperview];     yes it works thanks jan.


Content type Text field as Geolocation source field in View

Question: I have a text field(named as address) in my content type and I will store the address in that text field. Here I don't want to store the address in geolocation field so I have to use text field to store address.
I just created the View with page and have set Format as "Geolocation Google Maps API - CommonMap". In that Format settings I have to set Geolocation source field to display the Map. But I can't able to set Content type Text field as Geolocation source field.
Is there any way to set Content type Text field as Geolocation source field?
Answer: Map formatters usually only take geolocation data in order to display them (latitude and longitude for example). There is a way to "convert" a textual address into geolocation data with the help of a Geocoding service.
So you do have to create a geolocation field. You can set it to automatically take the address and convert it to points on a map, and you can hide this field from users. It's a problem though if the address someone enters isn't correct in some way.
With the geodata ready in that field you can set your views map to use that field as the source for geo points on a map.
Here's a comparison of modules that can help you with this: Comparison of Mapping modules.
It seems your best bet is Geofield Well Known Text and Geocoder.
Comment: So, Do I need to store the address in Geofield instead of Text field? Can you please explain in detail or let me know how to convert Text field address into Geolocation source field?
Comment: You need both fields, the usual text address for humans to enter information, and the other geofield that can be configured to automatically "read" the address and save the geo numbers, so users dont have to do anything except type the address. I'm not sure if you'll need to replace your text field with WKT field to make it work. WKT gives you suggestions as you type so it minimizes errors.
Comment: You can find configuration steps on Geocoder documentation page https://www.drupal.org/node/1355780
Comment: Actually users will not enters the address in that content type fields. The text address mapped with Salesforce field when cron run. Now I am getting the text address values. But getting the address in Text field in drupal instead of Geofield. So let me how to convert this to geofield source to display map in view.
Comment: Follow the steps from Geocoder doc to create a geofield with geocoder and configure it to use your text address as source. It should work if your Salesforce has correct addresses.
Comment: I just tried the same but when I save node after submitting the values then it shows HTTP 500 error. The node is not saving & also the value is not geocoding. Why?
Comment: Does the 500 error happen only after configuring the geocoder? Usually it's related to some other server configuration. It's difficult to know without more information. Can you include your configuration info in the question?
Comment: Its an Geocoder Error only. Here is the actual error : **Fatal error: Class 'Ivory\HttpAdapter\AbstractHttpAdapter' not found in /docroot/modules/contrib/geocoder/src/GeocoderHttpAdapter.php on line 12**
Comment: It seems to be a dependency issue. Have you used composer to install the module? Maybe you also need `egeloen/http-adapter`: [Ivory\\HttpAdapter\\AbstractHttpAdapter](https://www.drupal.org/project/geocoder/issues/2995941), [Package egeloen/http-adapter is abandoned, you should avoid using it. Use php-http/httplug instead](https://www.drupal.org/project/geocoder/issues/2772541).
Comment: Yes, I used composer to install the module. I referred that link as well but no luck.
Comment: Module installed after executing this `composer require drupal/geocoder` After that I added this in git by **git add modules/contrib/geocoder/, git add vendor/egeloen/, git add vendor/igorw/, git add vendor/willdurand/**. Finally I committed and push to the server. Is this right?
Comment: It seems that using the `composer require drupal/geocoder` is all you need to make it work (this is the usual way of installing modules in D8, it takes care of all the dependencies). Is this working now and no 500 server error? When it comes to versioning the modules and vendor folders aren't usually tracked, and it is just because that is all now managed with Composer, but if you don't use Composer on the server, then yes you need to copy/push all of those files up there so geocoder would work.
Comment: Still same error, I have installed the module using composer only. I am using acquia cloud & working in local after git clone
Comment: How can I directly install the module using composer directly on Acquia Cloud? Because I downloaded the module in local and then only I pushed it to server using Git
Comment: Acquia has documentation about this: https://docs.acquia.com/resource/composer/ you might also want to try contacting Acqui support and point them to that issue.


Restrict access of IAM user to delete Route53 hostedzone NS and SOA record sets

Question: I have written IAM Policy to restrict IAM users to just use a single hosted zone for testing but how can I restrict IAM users to delete this hosted zone's NS record and SOA record sets.
PFB my IAM policy:
<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "route53:GetChange",
                "route53:ListTrafficPolicyVersions",
                "route53:GetHostedZone",
                "route53:GetHealthCheck",
                "route53:DeleteHealthCheck",
                "route53:UpdateHealthCheck",
                "route53:ListQueryLoggingConfigs",
                "route53:ListResourceRecordSets",
                "route53:GetTrafficPolicyInstance",
                "route53:UpdateHostedZoneComment",
                "route53:GetQueryLoggingConfig",
                "route53:UpdateTrafficPolicyComment",
                "route53:UpdateTrafficPolicyInstance",
                "route53:GetHealthCheckLastFailureReason",
                "route53:GetHealthCheckStatus",
                "route53:ListTrafficPolicyInstancesByHostedZone",
                "route53:ListVPCAssociationAuthorizations",
                "route53:GetReusableDelegationSetLimit",
                "route53:ChangeResourceRecordSets",
                "route53:GetReusableDelegationSet",
                "route53:ListTagsForResource",
                "route53:ListTagsForResources",
                "route53:ListTrafficPolicyInstancesByPolicy",
                "route53:GetHostedZoneLimit",
                "route53:GetTrafficPolicy"
            ],
            "Resource": "arn:aws:route53:::hostedzone/Z03200001ZUWD7XXXXXXX"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "route53:ListReusableDelegationSets",
                "route53:ListTrafficPolicyInstances",
                "route53:GetTrafficPolicyInstanceCount",
                "route53:CreateReusableDelegationSet",
                "route53:CreateTrafficPolicy",
                "route53:TestDNSAnswer",
                "route53:ListHostedZones",
                "route53:ListHostedZonesByName",
                "route53:GetAccountLimit",
                "route53:GetCheckerIpRanges",
                "route53:ListHealthChecks",
                "route53:CreateHealthCheck",
                "route53:ListTrafficPolicies",
                "route53:GetGeoLocation",
                "route53:ListGeoLocations",
                "route53:GetHostedZoneCount",
                "route53:GetHealthCheckCount"
            ],
            "Resource": "*"
        }
    ]
}
</code>
Answer: SOA record can't be deleted in Route53. It's an integral part of any DNS zone. And I believe NS records can't be deleted either, they are managed by Route53. Regardless of your IAM permissions.
Comment: Let me try. Really appreciated your response.
Comment: Thanks for your answer. Can I try to delete and verify?
Comment: @Usman create a new dummy hosted zone in Route53 (it doesn't have to be officially registered) and play with it. That's the easiest way to find out.
Answer: If you have created a hosted zone with Route53, 2 recordsets created automatically and those are NS record and SOA record. No one deletes NS and SOA records can't be deleted.


Mutual information for markov chain identity qeustion

Question: given that:
$$A-B-C-D \space\space  markov \space chain$$
We know that:
$$ I(A;C|D) = H(C|D)-H(C|A,D)$$
but does it also say that:
$$ H(C|A,D)=H(C|D) \space \space from \space the \space markovian?$$
does this move legit?
thanks
Answer: No, it does not.
As you correctly pointed out,
$$ I(A;C|D) = H(C|D)-H(C|A,D),$$
and so
$$H(C|A,D)=H(C|D)$$ would imply that $$I(A;C|D) = 0.$$
It's easy to give a counterexample though.
Say that $A$ is a random fair heads/tails coin flip (with entropy 1 in bits), $B = A$, $C= B$, and $D = tails$. Note that this is indeed a Markov chain. In this case, clearly $D$ contains no information at all, and
$$
I(A;C|D) = I(A;C) = H(A) - H(A | C) = 1 - 0 \gneq 0.
$$.
Comment: Great!, thanks, I was thinking that given the markov chain, the uncertinty in $C$ would only be affected by the previous member of the chain which is $D$, which would imply that the entropy $H(C|,A,D)$ would not depend on $A$. what am I assuming wrong here?
Comment: "the previous member of the chain which is $D$" - not that it matters much (the question is symmetric in $A$ and $D$, and you don't need $B$ at all), but is $D$ the *previous* member? I thought it's the *next*. In any case, if $X \rightarrow Y \rightarrow Z$ form a MC, then the only thing to say is that $I(X; Z|Y) = 0$.
Comment: (continued) Think about the case of $X \rightarrow Y \rightarrow Z$, where $X$ is a dice roll, $Y$ is a pair of results of the previous dice roll and a new one, and $Z$ is a prize that is given if the sum of the rolls is greater than 7. Clearly, if you know $X$ (the first dice roll) and $Z$ (whether the prize was given), the uncertainty about the second dice roll decreases .
Comment: No problem. All the best.


PHP preg_match on text not working

Question: This php code is not catching numeric characters or symbols as it should.
$firstname = check_input($_POST['firstname'], "Please enter your first name");
$firstname = ucwords($firstname);
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
  show_error("Name should have only alpha characters and white space");
}

For example, the results should be Geronimo. If ge5on*mo is entered, that's what gets returned.
Any suggestions?
Comment: We need more info. "as it should" means nothing if you don't know what it *should* do!
Comment: Where is your test-cases with `real` and `expected` outcome ?
Comment: Your regular expression looks fine. What is the problem exactly? What is the value of `$firstname`?
Answer: Well, no full test cases in your example. So I will try to walk blindly in the dark. At first your expression is flawed, because it can capture just empty spaces without any name. Second - it doesn't captures unicode characters. I would start with such expression for name capture :
^(?:\p{Lu}\p{Ll}+[-\h]?){1,}$
Explanation:

^(?:
\p{Lu}    // first letter in name must be in upper-case
\p{Ll}+   // after that goes at least 1 non-upper case letter
[-\h]?    // we allow separators between names
){1,}     // human can have multiple names (at least 1)
$

PHP preg_match on text not working


Como publicar aplicativos para tablets na Play Store?

Question: Não consigo disponibilizar meu aplicativo para tablets de 7 e 10 polegadas, quando envio o APK no Developer Console, ele apresenta o seguinte erro:

Projete seu app para tablets
Seu APK não parece ter sido projetado para tablets

Pesquisei sobre como resolver na internet mas não achei uma resposta para minha duvida. Este link foi o mais próximo que encontrei do meu problema.
Critério utilizados pelo Google Play para determinar se um aplicativo é projetado para tablets
Como mostra a imagem, fiz o layout para todos tamanhos e os icones tambem:
Comment: Coloque o *AndroidManifest.xml*.
Answer: Da uma conferida, se você usa alguma permissão específica só pra smartphones, como por exemplo a de ligação:
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>

Pra que funcione nos tablets também, vc deve alterar essa permissão, para:
<uses-feature android:name="android.hardware.telephony" android:required="false" />

Esse é só um exemplo, existem várias permissões que se vc usar no seu projeto, vai torná-lo exclusivo para smartphones.
Answer: Apenas uma adição:
Criar Layouts para a menor largura como 600dp seria encorajado já que você planeja publicar para tablets. (layout-sw600dp)
xxhdpi às vezes ficam desconfortáveis em tablets de 10"


appending arrays into session variable php

Question: Im trying to add additional arrays into my session variable such as...
$_SESSION[cart] .= array($_POST[name],$_POST[price],$_POST[quantity]);

All i get when i do this 3 times and var_dump is string(15) "ArrayArrayArray"
Answer: Youre using .= "." is for string concat so youre arrays are getting converted to strings you should use one of the following:
$_SESSION['cart'][] = array($_POST[name],$_POST[price],$_POST[quantity]);

$_SESSION['cart'] += array($_POST[name],$_POST[price],$_POST[quantity]);

array_push(array($_POST[name],$_POST[price],$_POST[quantity]), (array) $_SESSION['cart'];

Answer: You can use print_r and see the content of the array.
i.e., print_r($_SESSION)
Comment: `Var_dump` often gives more information then `print_r`. I really don't see how or why this would be any help.


A curious way of generating series expansion for $\cos x$

Question: If we take the approximation $\sin x  \approx x$, then, using the trigonometric identity $1- \cos 2x = 2\sin^2 x$, and take $2\sin^2 x \approx 2x^2$, we get, after making the substitution $x \to x/2$, that
$$\cos x \approx 1 - \frac{x^2}{2}$$
Now, using the trigonometric identity
$$\cos(2x)=2\cos^2(x)-1$$
and using the last approximation  $\cos x \approx 1 - \frac{x^2}{2}$, then we get a new approximation for $\cos x$, namely
$$\cos(2x)\approx2\left(1-\frac{x^2}2\right)^2-1=1-2x^2+\frac{x^4}2$$
Then let $x\to\frac x2$ to get
$$\cos(x)\approx1-\frac{x^2}2+\frac{x^4}{32}$$
So, we repeat:
$$\cos(2x)=2\cos^2(x)-1\approx2\left(1-\frac{x^2}2+\frac{x^4}{32}\right)^2-1$$
and so on. This seems to generate a series expansion for $\cos x$, similar to Taylor's series, but with greater denominators.
The question is: Does the iterative procedure described above generates better and better approximations to $\cos x$, that is, a Taylor-like series one, or this iterative procedure doesn't converge to $\cos x$ to arbitrary accuraty for real $x$?
Comment: How exactly do you get $\sin x\approx x-x^3/8$?
Comment: $sin x = x$ is an estimate with some error, the error is small when $x$ is small.  The algebra you have done has indeed increased the precision of your estimate, but the Taylor polynomial $\sin x = x - \frac {x^3}{6}, \cos x = 1 - \frac{x^2}{2} + \frac {x^4}{24} $ is a better estimate for the same degree of polynomial.
Comment: My first thought would be to see if I could prove that $f(x) \mapsto 2 [f(x/2)]^2 - 1$ is a contraction on $C [-\epsilon, \epsilon]$ for some $\epsilon > 0$, which would then imply that iterating it would converge uniformly to a unique fixed point function on $[-\epsilon, \epsilon]$.
Comment: Repeatedly applying the double-angle formula to a Taylor or Padé approximation of the cosine is a known trick for numerics. See e.g. [this](https://doi.org/10.1137/0901013), where it is used for the *matrix* cosine.
Comment: @LordSharktheUnknown Use the second trigonometric identity, $\sin x \approx x$ and the approximation obtained for $\cos x$, and the map $ x  \mapsto x/2$
Comment: @DougM I know that Taylor's series are better, but what I want to see is a proof that the series generated by the above procedure indeed converges to the sine and cosine functions, if they do.
Comment: I'm guessing they don't converge to $\sin(x) $ and $\cos(x) $ , since from the first few terms $\dfrac{d}{dx}\sin(x) = \cos(x)$ isn't satisfied.
Comment: You should specify your iteration procedure more clearly because I get a different result at the second step: $\cos x = 1-x^2/2+x^4/32-x^6/8192$ and $\sin x = x-5x^3/32+x^5/256$
Comment: @Raskolnikov I have edited the question. Can you look at it?
Comment: [I found a related paper.](https://arxiv.org/pdf/cs/0406049.pdf)
Answer: You get weird coefficients for terms beyond $x^2$ because you re using an inaccurate input for the double angle formula.  If you have
$\cos x = 1-(x^2/2)+O(x^4)$,
you must accept
$\cos 2x = 1-(2x^2)+(x^4/2)+O(x^4)$;
and putting $x/2$ for $x$ then gives
$\cos x = 1-(x^2/2)+(x^4/32)+O(x^4)$
You did not make the error term any smaller in order of magnitude than the quartic term you added, so you cannot defend the quartic term.
How to get the right quartic term?  Assume
$\cos x = 1-(x^2/2)+(ax^4)+O(x^6)$.
Apply the double angle formula; after simplifying you get
$\cos 2x = 1-(2x^2)+((4a+(1/2))x^4)+O(x^6)$,
where everything that's a multiple of $x^6$ or a higher power is lost in the "noise" of the error term. Put $x/2$ for $x$ to then get
$\cos x = 1-(x^2/2)+((a/4+(1/32))x^4)+O(x^6)$.
This matches your original assumption if $a=(a/4)+(1/32)$; thus, properly, $a=(1/24)$.
Comment: Thanks for your answer! Just help me to understand this: 1) Your answer implies that, in fact, these weird coefficients makes this a non-convergent series for $\cos x$. 2) Also, with this correction, it is possible to obtain every correct term of the original series expansion. Is that right?
Comment: 1) the series might still converge but not to $\cos x$; 2) the corrected method will work for all terms.
Answer: I've written a little R program for your iteration. It represents the series as a sequence of their coefficients. I then define the effect of halving the input on the coefficients
halvearg<-function(x) ((1/2)^(0:(length(x)-1)))*x

and the multiplication of series
seriesprod<-function(x,y) {
    length(x)->n
    sprod<-rep(0,2*n-1)
    for (l in 1:(2*n-1)) {
        for (k in (max(l-n+1,1)):(min(l,n))) {
            sprod[l]<-sprod[l]+x[k]*y[l-k+1]
        }
    }
    return(sprod)
}

In principle, multiplication of series could be done by the convolve function in R, which uses the FFT. But it doesn't produce exactly the output I want, so I'll either have to write my own variant of convolve or try to adapt the existing one. For now, I just defined my own series multiplication.
Then, I apply your iteration scheme on the starting input
$$\cos x = 1-\frac{x^2}{2}$$
which is represented as
x<-c(1,0,-0.5)

Here's the iteration
unit<-c(1,0,0)

for (k in 1:10) {
    unit<-c(1,rep(0,2*length(x)-2))
    x<-halvearg(x)
    x<-2*seriesprod(x,x)-unit
}

Notice I don't evaluate many steps, because the sequence grows very fast, indeed the length grows according to the recursion
$$\ell_n=2\ell_{n-1}-1$$
which is exponentially fast.
Here are the first 10 terms of the series, after those 10 iterations
[1]  1.000000e+00  0.000000e+00 -5.000000e-01  0.000000e+00  4.166663e-02
[6]  0.000000e+00 -1.388882e-03  0.000000e+00  2.480126e-05  0.000000e+00

Here are the first ten terms of the actual Taylor series of $\cos$ for comparison
[1] 1.000000e+00  0.000000e+00 -5.000000e-01 0.000000e+00 4.166667e-02
[6] 0.000000e+00 -1.388889e-03  0.000000e+00 2.480159e-05 0.000000e+00

Not too bad. Here's a plot of the logarithm of the coefficients in blue at each step of the iteration. The red curve is the negative logarithm of the gamma or factorial function. You can see it converges pretty fast.


call a vector of names for grid.arrange

Question: lets say I have a list called ALL with 40 elements, each of which is a ggplot.
if i want to plot one of these i can do
ALL[[1]]

or
print(ALL)

if i want to plot them all together i can do
grid.arrange(ALL[[1]] ,ALL[[2]], ALL[[3]], ....  )

or
grid.arrange(ALL[[names(ALL)[1]]] ,ALL[[names(ALL)[2]]], ALL[[names(ALL)[3]]], ....  )

This is really tiring with many list elements. But i cannot figure out how to just call grid.arrange to plot all plots. I don't want to apply over the list because i want multiple plots on the same page.
Calling 40 plots to grid.arrange may seem a lot but they are small plots and even for 1:10 plots on a page this is a lot of typing!!!!
Comment: Try `do.call(grid.arrange, ALL)`.
Comment: Cheers Josh, would you like to make an answer so i can accept this may be useful for other SOers...
Answer: Whenever you've got a list (here your ALL) whose elements are the arguments you'd like passed in to a function (here grid.arrange), you can use do.call.
This should do the trick:
## Equivalent to grid.arrange(ALL[[1]], ALL[[2]], ..., ALL[[n]])
do.call(grid.arrange, ALL)

call a vector of names for grid.arrange


Achieving statistical significance in an A/B test

Question: Out of one pool, I've randomly selected a small group (group A) and put everyone else in group B. Then, I'm observing whether or not they take a desired action.
If I'm looking to test at a 95% confidence, what's the best methodology and stats test to use? I read that with a large enough sample, it's ok to use a standard t-test, but can someone tell me if that's accurate?
Assuming it is, I've applied it and come up with the result that group A has a much higher rate of the desired action than group B and applying the error bars, it's still showing that group A > group B (albeit a smaller rate). This is highly unlikely. At worst, the expectation was group A's actions would be more or less the same to group B.
Any comments on what would cause such an unlikely result even with a high confidence level?
Comment: I think I am missing something. If you *randomly* selected group A *from group B*, then the groups should not be different, right? So I assume that you in fact did not select at random, but based on some criterion. How large are your groups A and B? Apart from that, a t test is not appropriate for yes/no variables (take an action or not), a contingency table and a chi squared test would be better.
Comment: Think of a typical website A/B test. I put a percentage of visitors in A and everyone else in B. Group A sees one experience. Group B sees another experience. Then, I measure something like..do they click this button. I want to measure the rate at which they click the button and see what the difference is between those two groups. One group is much smaller than the other, like 1 in group A for every 20 in group B. But, the people who are selected to be in each group are selected randomly.
Answer: The appropriate methodology for statistically testing your data would be a chi squared test on a contingency table. First, put your data in tabular form, which could look like this (I am using R, but any statistics package can do this):
obs <- cbind(c(20,100),c(1000,10000))
rownames(obs) <- c("takes action","takes no action")
colnames(obs) <- c("A","B")
obs

Result:
                  A     B
takes action     20  1000
takes no action 100 10000

Then you do the test:
chisq.test(obs)

Result:
        Pearson's Chi-squared test with Yates' continuity correction

data:  obs
X-squared = 7.2933, df = 1, p-value = 0.006921

The p value is less than the conventional threshold of 0.05, so your data would be highly unlikely if the groups were in fact identical in their propensity to take the action. The group sizes should not matter for this test (unless there are less than five entries in some cell in the table above, in which case one should use Fisher's Exact Test). And we can calculate quickly that 20% in group A but only 10% in group B take the action.
Now, that is the standard statistical treatment of your data. As to why there is a difference between your groups, that is a question of interpretation, and statistics will only be of limited use here... You will need to look at the exact nature of the action people take or do not take, at the different experiences you expose groups A and B to and so on. After all, if you expose people to different experiences, I assume that you hope to elicit different responses, otherwise why use different experiences, right?
Good luck!


Why $\gcd(b,qb+r)=\gcd(b,r),\,$ so $\,\gcd(b,a) = \gcd(b,a\bmod b)$

Question: Given: $a = qb + r$. Then it holds that $\gcd(a,b)=\gcd(b,r)$. That doesn't sound logical to me. Why is this so?

Addendum by LePressentiment on 11/29/2013: (in the interest of http://meta.math.stackexchange.com/a/4110/53259 and averting a duplicate)
What's the intuition behind this result? I only recognise the proof and examples solely due to algebraic properties and formal definitions; I'd like to apprehend the result naturally.
Comment: $a$, $b$, $r$ are integers? (If yes, tagging the question [tag:elementary-number-theory] would be suitable.) Or are you looking for some greater generality, e.g. they are elements of some type of commutative ring? If yes, you should say so and you should also mention, what are the assumptions about this ring.
Comment: If you're asking about integers, then this question is very similar to yours: http://math.stackexchange.com/questions/59147/need-help-understanding-euclids-algorithm-to-find-greatest-common-divisor
Comment: see page 13 here http://www-groups.dcs.st-and.ac.uk/~martyn/teaching/1003/1003EuclideanAlgorithm.pdf
Comment: @Martin The result does not depend upon the underlying ring (assuming $\rm\:gcd(a,b)\:$ exists).
Comment: @BillDubuque I think that it would be better to close as a duplicate in the opposite direction ([706016](http://math.stackexchange.com/questions/706016/prove-that-gcda-b-gcda-b-ma) $\to$ [95799](http://math.stackexchange.com/questions/95799)
rather than 95799 $\to$ 706016). I think that the post which is the most useful should be left open, as [discussed on meta](http://meta.math.stackexchange.com/a/16418). And this question has more answers and some answers are more detailed.
I have also mentioned this [in chat](http://chat.stackexchange.com/transcript/message/30715294#30715294).
Comment: The statement $\gcd(qb+r,b)=\gcd(b,r)$ is actually a reformulation of a famous lemma, used repeatedly in what is known as the "Euclidean algorithm" to find the $\gcd$ of two integers not both zero. Specifically the lemma says $\gcd(a,b)= \gcd(b, r(a,b)) $ where $r(a,b)$ is the remainder of $a \div b $
Comment: But $GCD(20,25)$ is not equal to GCD$(20, 20+25 * 2)$, i.e. $GCD(20,70)$ right? how is this true then ?
Comment: First is giving $5$, and second is giving $10$. Sorry, I'm a bit confused, I had the same question so I came up here...
Comment: Also, I also read that GCD$(a,a-b)$=GCD$(a,b)$.... This is also wrong for numbers $30,32$ Please help.
Answer: Hint $  $ note if $\rm\, d\mid \color{#c00}b\ $ then $\rm\ d\,\mid\, q \color{#c00}b + r  \!\iff d\ |\ r, \ $ i.e. arithmetically in congruence language:
$\!\rm\bmod d^{\phantom{|^|}}\!\!\!\!:\ $  if $\rm\ \color{#c00}{b\equiv 0}\ $ then $\rm\ q\color{#c00}b+r\equiv 0 \!\iff\! r\equiv 0\ $ by  congruence sum & product rules.
By above $\rm\, \{qb+r,b\}\, $ and $\rm\, \{r,\, b\}\, $ have the same set $\,\rm S\,$ of common divisors $\rm\,d,\,$ which implies that they also have the same greatest common divisor $\rm(= \max S)$.
Thus $\rm \,\bbox[5px,border:1px solid #c00]{\gcd(a,b) = \gcd(r,b)\,\ {\rm  if}\,\ a\equiv r\pmod{\! b}} \,$ since then $\rm\, a = qb+r\,$ for $\,r\in\Bbb Z$
e.g. $\ \ \rm  \bbox[5px,border:1px solid #c00]{\gcd(a,b) = \gcd(a\bmod b,b)}\,\ $ by choosing $\rm \, r = a\bmod b,\, $ using the division algorithm. $ $ This gcd modular reduction is the descent (induction) step in the well-known classical recursive Euclidean algorithm for the gcd.
Also $\rm\, d\mid a\iff d\mid  r\ $ if $\rm \ a\equiv r\pmod{\! d},\,$ since then $\rm\,a = qd+r\,$ so the above applies.
So $\ \ \,\rm \bbox[5px,border:1px solid #c00]{\!d\mid a\iff d\mid (a\bmod d)}.\,$ This divisibility mod reduction often simplifies matters.
Generally the set of multiples of $\rm\,d\,$ are closed under integral linear combinations, and ditto for common multiples of any set of integers, which leads to the universal property of the lcm, using descent via the Euclidean division algorithm.
Many of the above properties also hold for ideals, and we can give unified proofs for both.
Remark $ $ The result holds true because $\rm\,\mathbb Z\,$ forms a subring of its fraction field $\rm\,\mathbb Q.\,$ More generally, given any subring $\rm\,Z\,$ of a field $\rm\,F\,$ we define divisibility relative to $\rm\ Z\ $ by  $\rm\ x\mid y \iff y/x\in Z.\,$ The above proof still works, since if $\rm\ q,\ b/d\ \in Z\, $ then  $\rm\, q\,(b/d) + r/d\in Z\iff r/d\in Z.\,$ Thus the common divisibility laws follow from the fact that (sub)rings are closed under subtraction and multiplication (subring test). Being so closed,  $\rm\,Z\,$ serves as a ring of "integers" for divisibility tests.
For example,  to focus on the prime $2$ we can ignore all odd primes and define a divisibility relation so that $\rm\ m\ |\ n\ $ if the power of $2$ in $\rm\,m\,$ is $\le$ that in $\rm\,n\,$ or, equivalently if $\rm\ n/m\ $ has odd denominator in lowest terms. The set of all such fractions forms a ring $\rm\,Z\,$ of $2$-integral fractions. Moreover, this ring enjoys parity, so arguments based upon even/odd arithmetic go through. Similar ideas lead to powerful local-global techniques of reducing divisibility problems from complicated "global" rings to simpler "local" rings, where divisibility is decided by simply comparing powers of a prime.
Comment: Thank you! Extremely clear explanation :)
Answer: If $d$ is a divisor of $a$ and of $b$, then
$$
\begin{align}
a & = dn, \\
b & = dm.
\end{align}
$$
So $$a-b= dn-dm=d(n-m)= (d\cdot\text{something}).$$
So $d$ is a divisor of $a-b$.
Thus: All divisors that $a$ and $b$ have in common are divisors of $a-b$.
If $d$ is a divisor of $a$ and of $a-b$, then
$$
\begin{align}
a & = dn, \\
a-b & = d\ell.
\end{align}
$$
So
$$
b=a-(a-b)=dn-d\ell=(d\cdot\text{something}).
$$
So $d$ is a divisor of $b$.
Thus: All divisors that $a$ and $a-b$ have in common are divisors of $b$.
Therefore, the set of all common divisors of $a$ and $b$ is the same as the set of all common divisors of $a$ and $a-b$.
Subtracting one member of a pair from the other never alters the set of all common divisors; therefore it never alters the $\gcd$.
Comment: @Kevin Beware that this fails if the ring is not $\rm\:\mathbb Z\:$ since then the remainder $\rm\:r\:$ generally cannot be obtained by *repeatedly subtracting* $\rm\:b\:$ from $\rm\ q\ b + r\:,\:$ as it can when $\rm\:q\in\mathbb N\:.\:$ In other words, in general Euclidean rings, e.g. the polynomial ring $\rm\:F[x]\:$ over a field $\rm\:F\:,\:$ the Euclidean algorithm generally requires division with remainder, not simply iterated subtraction, in order to effect descent to a "smaller" remainder. So this ad-hoc special-case doesn't generally reveal the essence of the matter.
Comment: Very clear answer! Little remark: $a-b \neq r$, but $a-qb = r$, but all your explanation will work using that :).
Comment: @Kevin : Thanks; I've fixed the typo.
Comment: To express Bill Dubuque's point in other way: Euclid's algorithm works for polynomials, but the argument I give in my answer doesn't work for polynomials unless you do some adaptations.
Comment: The top comment is important - this answer, although clear, seems to be answering a different question. I'd like to see a similar explanation that involves the remainder rather than just subtraction.
Comment: Also, why do we need both parts of this answer? is it not sufficient to show that an arbitrary factor of both (a, b) must also be a factor of (b, a-qb)? If not can you please explain why?
Answer: You can show that for any integer $d$, we have $d\; |\; a$ and $d\; |\; b$ if and only if $d\; |\; b$ and $d\; |\; r$. In other words, $a$ and $b$ have exactly the same common divisors as $b$ and $r$. Thus $\gcd(a,b)$ is the same as $\gcd(b,r)$.
Comment: @Kevin: If $d$ divides $a$ and $b$, then $d$ divides $-qb$ and thus divides the sum $a - qb = r$. This shows that any common divisor of $a$ and $b$ is a common divisor of $b$ and $r$. If $d$ divides $b$ and $r$, then $d$ divides $qb$ and thus divides the sum $qb + r$. This shows that any common divisor of $b$ and $r$ is a common divisor of $a$ and $b$.
Comment: excellent answer, +1 for it.
Comment: Thanks, but why do they have the same common divisors?
Answer: Since set of common divisors of $a-b$ and $b$ coincides with the set of common divisors of $a$ and $b$ then $\operatorname{gcd}(a,b)=\operatorname{gcd}(a-b,b)$. If $a=qb+r$, where $b>0$ and $0\leq r<b$, you can apply this equality $q$ times and obtain $\operatorname{gcd}(a,b)=\operatorname{gcd}(r,b)$
Comment: But $a-b$ and $b$ don't have the same set of divisors. They have the same set of common divisors with $a$.
Comment: @Norbert : what you must have meant is that $\{a,b\}$ and $\{a-b,b\}$ have the same set of common divisors.
Comment: Beware that this "repeated subtraction" implementation of division with remainder does not generally yield the Euclidean algorithm in other domains, e.g. for polynomials. See my comment to Hardy's answer.
Comment: Thanks, for this warning. I believed that this appraoch works in all cases.
Comment: Ok common divisors. I always miss some details.
Comment: Yes, this is what I meant.
Answer: I'm going to use the notation $(a,b)$ for the GCD of $a$ and $b$.
If $d|a$ and $d | b$ then $d|(a,b)$, by the definition of GCD. (Well, by one common definition... if that's not the definition you learned, then you probably learned it as a theorem).
Since $(a,b)|a$ and $(a,b)|b$, by the definition of $(a,b)$, it divides $r = a-qb$, so we have $(a,b)|r$. This gives us $(a,b)|b$ and $(a,b)|r$, hence $(a,b)|(b,r)$.
Now let's go the other way. $(b,r)|b$ and $(b,r)|r$, both by definition, so it also divides $r+qb$, giving us $(b,r)|a$. That gives is $(b,r)|(a,b)$.
From $(a,b)|(b,r)$ and $(b,r)|(a,b)$, we get $(a,b)=(b,r)$ or $(a,b)=-(b,r)$. The latter can be eliminated because GCD is by definition greater than zero.
Answer: Let $A$ be a commutative ring. For any $a_1,\dots,a_n$ in $A$ let $(a_1,\dots,a_n)$ the ideal generated by the $a_i$.
Then, for any $q,b,r$ in $A$, we have
$$
(qb+r,b)=(b,r).
$$
Indeed, $qb+r$ is in $(b,r)$, and $r$ is in $(qb+r,b)$.
EDIT. Dear Kevin: Your question, I think, would be better understood if put in a wider context, involving rings and ideals. The most basic fact behind the question is, I believe, the fact that, in any commutative ring, the elements $qb+r$ and $b$ generate the same ideal as the elements $b$ and $r$. If you make additional hypothesis, this fact can be interpreted in terms of divisibility. (See Bill's comment.) The simplest is to assume that your ring is a principal ideal domain.
I could try to explain this in greater details, but many mathematicians much better than I have already done that. So, my advice would be to take a look at at least one of the many Algebra textbooks written by great mathematicians. Here are some of these books:

Michael Artin, Algebra.
Nathan Jacobson, Basic Algebra.
Serge Lang, Algebra.
Saunders Mac Lane, Garret Birkhoff, Algebra.

In short, my advice is the classic: Read the masters!
Comment: *Divisor theory* gives one nice way to better understand the relations between ideals and gcds.  For a brief overview see Friedemann Lucius, [Rings with a theory of greatest common divisors](http://www.digizeitschriften.de/dms/img/?PPN=GDZPPN002239620) and for a longer exposition see Olaf Neumann, Was sollen und was sind Divisoren? (What are divisors and what are they good for?), Math. Semesterber, 48, 2, 139-192 (2001).
Comment: This seems to implicitly assume some relation between gcds and ideals, e.g. for Bezout domains $\rm\ (a,b) = (\gcd(a,b))\:.$
Comment: Dear @Bill: Thanks for your comment. I edited the answer. (Of course, I agree with you.)
Comment: Thank you for the neat explanation. Do you have a suggestion how I can update the question to involve rings and ideals?
Comment: @www.data-blogger.com - Thank *you*! It's better, I think, to leave the question as it is. It's a nice question, and it has several outstanding answers (mine is not one of them). Users having answered the question in its original formulation, readers might be confused if you changed this formulation.
Answer: Theorem:
Let $a > b > 0$ with $a = bq + r$, $0\leq{}r<b$ then $\gcd(a;b) = \gcd(b;r)$.

Proof:
Need to show that $C(a;b) = C(b;r)$ for then the result will hold. To show that the two sets are equal requires showing that $C(a;b) \subseteq C(b;r)$ and that $C(b;r) \subseteq C(a;b)$:

Let $y \in C(a;b)$ thus $y|a$ and $y|b$,
then $y|[a+(-q)b]$,
and so $y|r$, since $r=a-bq$,
but since $y|b$ is also true, we now have that $y \in C(b;r)$,
finally this means that $C(a;b) \subseteq C(b;r)$.

Now let $y \in C(b;r)$ thus $y|b$ and $y|r$,
then $y|[(q)b+r]$,
and so $y|a$, since $a=bq+r$,
but since $y|b$ is also true, we now have that $y \in C(a;b)$,
finally this means that $C(b;r) \subseteq C(a;b)$.

Therefore the required results have been proven.

Note:
Where $C(a;b)$ denotes the set of common divisors/factors of $a$ and $b$, that is: $C(a;b)=\{y: y|a \land y|b\}$
Answer: Let
$$a = qb + r \implies a\equiv r (\text{ mod }b)\implies r = a\text{ mod }b$$
Bey GCD recursion theorem we have:
$$\gcd\big(a, b\big) = \gcd\big(a, a\text{ mod } b\big)$$
Therefore

$$\gcd\big(a, b\big) = \gcd\big(a, a\text{ mod } b\big) = \gcd\big(a, r\big)$$

See reference

Bibliographic reference:
Thomas H. Cormen (2009). Introduction to Algorithms 3rd, 934.


Different permissions per log file when using rsyslog

Question: Is it feasible to define different permissions per log file, using rsyslog?
$FileCreateMode applies to all, but I want different permissions for a specific file.
Answer: According to the official documentation on Configuration,

FileCreateMode may be specified multiple times. If so, it specifies the creation mode for all selector lines that follow until the next $FileCreateMode directive. Order of lines is vitally important.


The Hardy–Littlewood maximal function is Borel measurable

Question: Let $f : \mathbb R^n \to \mathbb R$ be Lebesgue-integrable. We define the Hardy–Littlewood maximal function $Mf: \mathbb R^n \to [0, \infty]$ by
$$
M f(x) :=\sup _{r>0} \frac{1}{|B(x, r)|} \int_{B(x, r)} |f(t)| \mathrm d t
$$
where $B(x, r)$ is the open ball of radius $r$ centred at $x$, and $|E|$ denotes the $n$-dimensional Lebesgue measure of $E \subset \mathbb R^n$.

Theorem: $Mf$ is Borel measurable.

I'm trying to adapt the strategy in this thread to higher dimension. Could you have a check on my attempt?
Proof: Let
$$
g_r (x) := \frac{1}{|B(x, r)|} \quad \text{and} \quad h_r(x) := \int_{B(x, r)} |f(t)| \mathrm d t \quad \forall r>0, \forall x \in \mathbb R^n.
$$
Because Lebesgue measure is translation-invariant, we get $g_r (x) = g_r (y)$ for all $x, y \in \mathbb R^n$. This means $g_r$ is constant. Let's prove that $h_r$ is continuous. Let $x, x_n \in \mathbb R^n$ such that $x_n \to x$. Because the $n$-dimensional Lebesgue measure of a sphere is $0$, we have $1_{B(x_n, r)} \to 1_{B(x, r)}$ a.e. It follows that
$$
1_{B(x_n, r)} |f| \to 1_{B(x, r)} |f| \quad \text{a.e.}
$$
By dominated convergence theorem, we get $h_r (x_n) \to h_r (x)$ and thus $(g_rh_r) (x_n) \to (g_rh_r) (x)$. It follows that $g_rh_r$ is measurable. The supremum of a collection of measurable functions is measurable, so
$$
Mf = \sup_{r>0} g_rh_r
$$
is measurable.
Comment: Its almost correct. At the end, you have to say that the supremum of countably many measurable functions is measurable. The supremum can be taken over all positive rational numbers since $g_r(x)$ and $h_r(x)$ continuously depend on $r$.
Comment: @ChristopheLeuridan I actually missed that important subtlety. Thank you so much for your help!
Answer: Here is a little refinement of your sketch of proof.
A function $f$ on $\mathbb{R}^n$ is called locally integrable, denoted $f\in L^1_{loc}(\mathbb{R}^d,\lambda_d)$,  if $f\mathbb{1}_E\in\mathcal{L}_1(\mathbb{R}^d,\lambda_d)$ for all bounded measurable set $E$.
Claim:  For such function $f$ and fixed $r>0$, the map $$M_rf:x\mapsto \frac{1}{\lambda(B(x;r))}\int_{B(x;r)}f\,d\lambda=\frac{1}{\omega_n r^n}\int_{B(x;r)}f\,d\lambda$$
is continuous and hence measurable.
Indeed, for fixed $x\in\mathbb{R}^d$ we have $f\mathbb{1}_{B(x;2r)}\in L^1$. Since $\|\mathbb{1}_{B(y;r)}-\mathbb{1}_{B(x;r)}\|_1\xrightarrow{y\rightarrow x}0$, the conclsion follows from
\begin{align*}
    \Big|\int_{B(y;r)}f\,d\lambda-\int_{B(x;r)}f\,d\lambda\Big|\leq \int_{B(x;r)\triangle B(y;r)}|f\mathbb{1}_{B(x;2r)}|\,d\lambda.
  \end{align*}
for $|x-y|<r$. Continuity follows from the following basic result:

$f\in L_1(\mu)$ then for any $\varepsilon>0$, there is $\delta>0$ such that $\mu(A)<\delta$ implies that $\int_A|f|\,d\mu<\varepsilon$.

It follows that the map
$x\mapsto\sup_{r>0}\frac{1}{\lambda(B(x;r))}\int_{B(x;r)}\,d\lambda=\sup_{r>0}M_rf(x)$ is lower semicontinuous and so, measurable.
Answer: Here's another elementary approach $:$
Given $\alpha \in \mathbb R,$ consider the set $A_{\alpha} : = \left \{x \in \mathbb R^n\ |\ Mf(x) \gt \alpha \right \}.$ We claim that $A_{\alpha}$ is open and hence Borel measurable in particular.
Take $x \in A_{\alpha}$ arbitrarily. Then $M f(x) \gt \alpha$ i.e.
$$\sup\limits_{r \gt 0} \frac {1} {\left \lvert B(x,r) \right \rvert} \int_{B(x,r)} |f(t)|\ dt > \alpha.$$ So by the property of supremum there exists $r_0 \gt 0$ such that $$\frac {1} {\left \lvert B(x,r_0) \right \rvert} \int_{B(x,r_0)} |f(t)|\ dt > \alpha.$$ Choose $r' \gt r \gt 0$ such that $$\tag{*}\frac {1} {\left \lvert B(x,r') \right \rvert} \int_{B(x,r_0)} |f(t)|\ dt > \alpha.$$ This is possible by the virtue of intermediate value theorem as the function $x \mapsto \frac {1} {x^n}$  is continuous and decreasing on $(0, \infty)$ and since $$\left \lvert B(y,s) \right \rvert = \left \lvert B(0,s) \right \rvert = c_n s^n$$ for any $y \in \mathbb R^n$ and $s \gt 0$ (by the translation invariance of the Lebesgue measure),  where $c_n = \left \lvert B(0,1) \right \rvert$ is an absolute constant (independent of $y$ and $s$). Now let $x' \in B(x,r' - r_0)$ so that $\|x' - x\| \lt r' - r_0.$
Claim $:$ $B(x,r_0) \subseteq B(x',r').$
Indeed if $y \in B(x,r_0)$ then $\|y - x\| \lt r_0.$ Hence it follows that $$\|y - x'\| \leq \|y - x\| + \|x - x'\| \lt r_0 + (r' - r_0) = r'$$ i.e. $y \in B(x',r'),$ as claimed. So we have by $(*)$ $$\alpha \lt \frac {1} {\left \lvert B(x,r') \right \rvert} \int_{B(x,r_0)} |f(t)|\ dt \leq \frac {1} {\left \lvert B(x',r') \right \rvert} \int_{B(x',r')} |f(t)|\ dt$$ Here $\left \lvert B(x,r') \right \rvert = \left \lvert B(x',r') \right \rvert,$ by the translation invariance of the Lebesgue measure. This shows that $$\sup\limits_{r \gt 0} \frac {1} {\left \lvert B(x',r) \right \rvert} \int_{B(x',r)} |f(t)|\ dt \gt \alpha$$ i.e. $M f(x') \gt \alpha$ and hence $x' \in A_{\alpha}.$ So it follows that $B(x,r' - r_0) \subseteq A_{\alpha},$ which shows that $A_{\alpha}$ is an open set. $\blacksquare$