ajax request in angular and php

Question: I'm trying to start a simple web page in which I wanna load data to a combobox from a request to my php script; The problem that I'm having is that when I load the page it doesn't load, but if i assign the function to a button it does but i have to press it twice for it to start working... I just can't figure out why that's happening, I have the next code in my html:

       Categoría:
       <select id="pref-perpage" class="col-lg-9 lindo">
               <option ng-repeat="result in search.vendor">{{result.nombreCategoria}}</option>
               <option selected="selected">[ Seleccione ]</option>
       </select>

this is my javascript:
  search.buscar = function()
  {

    $.ajax({
      url: "Busqueda.php",
      type: "get",
      success: function(response) {
          search.vendor.push({'nombreCategoria':response});
        var JSONObject = JSON.parse(response);

          for(var x in parsed){
          search.vendor.push(parsed[x]);
        }

and the kind of data that I want to fill the array with would be something like:
search.vendor = [{'nombreCategoria':'data'}];

If've also tried the $http method from angular but it does the same; I fill the combobox with fake data manually and I have no problem!
server response: [{"nombreCategoria":"ACCESORIOS"},{"nombreCategoria":"CPU"},{"nombreCategoria":"IMPRESORA"},{"nombreCategoria":"MONITOR"}]
Comment: Use the $http Anuglar service for get data, not $.ajax
Comment: Yeah, as i wrote before i already tried that...and worked the same...still having the same problem; actually that's "old", i'm using the $http right now and gives me the next error: SyntaxError: Unexpected token o, in the line of the JSON.parse...
Comment: could you give us an example server response?
Comment: Yes, of course, the server response to that is: [{"nombreCategoria":"ACCESORIOS"},{"nombreCategoria":"CPU"},{"nombreCategoria":"IMPRESORA"},{"nombreCategoria":"MONITOR"}]
Comment: try replacing `search.vendor.push()` with `$scope.search.vendor.push()`
Comment: I got the same error man :/.
Answer: I'm working with Gabriel in this project.
The soluction was to add the method $scope.$apply(); after the .push() method...
So, the function looks like this:
search.buscar = function() {
    $.ajax({
        url: "Busqueda.php",
        type: "get",
        success: function(response) {
            search.vendor.push({'nombreCategoria':response});
            var JSONObject = JSON.parse(response);
            for(var x in parsed) {
                search.vendor.push(parsed[x]);
                $scope.$apply();
            }
        }
    });
}

By the way... I found the solution here (stackoverflow)

ajax request in angular and php


In python, when you pass internally defined functions into other functions, how does it keep the variables?

Question: For example, why does this work?
def func1(func1var):
    def innerfunc(innerfuncvar):
        if func1var == 1:
             print innerfuncvar
        else:
             print 5
    func2(innerfunc)

def func2(function):
     function(9)

When innerfunc is called in func2, how does it know the values of func1var?
Answer: You've created a closure. Basically, think of it like this, from the point of view of the inner function:
func1var = whatever

def func2(function):
    function(9)

def innerfunc(innerfuncvar):
    if func1var = 1:
         print innerfuncvar
    else:
         print 5

func2(innerfunc)

It doesn't care whether func1var is in an outer or global scope -- it just looks for it in each scope outward, starting with it's own local scope. It's just like when you reference a module global variable from inside a class or function in that module.
Answer: Python actually goes to some lengths to do this for you. When you define a function inside a function, you may use variables from the outer function in the inner function. This is true for any depth of nesting (that is, you can have a function inside a function inside a function inside a function... to any depth... and the innermost function can use variables from any of the enclosing functions). If there are conflicting names, the innermost variable with the name requested is used.
What's more, Python actually captures any variables you use from the outer function and stores them in the inner function, which is called a closure. So you can not only pass a function to another function, as you are doing, but you can return a function from a function, and variables you use from the outer function that were in effect when the function was defined will still be accessible from the returned function, even though the outer function isn't running any more. This is a fairly advanced feature, but it lets you do something like this:
def make_adder(increment):
    def adder(number):
        return number + increment
    adder.__name__ = "adder(%s)" % increment
    return adder

This function is a function that creates a function that adds the specified value to it. For example:
add1 = make_adder(1)
add5 = make_adder(5)

print add1(10)   # 11
print add5(10)   # 15

In this case, the value you pass to make_adder is captured and stored in the function that gets returned. This allows you to create a bunch of functions that add any number to their arguments. Which is a trivial example that isn't actually very useful in real life, but serves to illustrate the feature.
Comment: In Python anything can return anything!  Objects, baby.
Comment: @jathanism: Everything is indeed an object, in modern Python.  However, C functions can also return anything, as far as I know, so this feature is not related to objects.  Closures are yet another feature…
Answer: Each time you call func1(func1var), Python actually builds a new function innerfunc().  Since func1var is perfectly defined when innerfunc() is created, the code of the new innerfunc() function contains the correct value of func1var.


How to automatically add the permission "edit" on a node to a user who is not the author?

Question: I'm in D6
I have a node type "Person" and a node type "Company"
Each node "Person" has :

an unique field-node-reference to a node "Company"
an unique field-user-reference (to a user)

So, several persons can belong to the same company
Use case :

The person P1.1 (belongs to company C1) creates a node (article)

How to automaticly grant edit permission on this article to an other person (P1.2) who belongs to the same company (C1) ?
Thank you
Answer: Install Content Access and ACL, and then use Rules to add Person 1.2 as a person able to edit that content.

You may find this question helpful: Node access by role or user, what module(s) should I use?

The Content Access module gives you role permissions at the content type and (optionally) node level. By default, node level permissions are disabled but you can enable it on a type-by-type basis.
If you install ACL module, Content Access can give you per user permissions at the content type and node level.


How can I create a custom html tag in the CKeditor wysiwyg editor?

Question: I've created a custom HTML tag that pulls information from my database and displays it. Basically it uses preg_match_all to parse the body of articles for <profiletag>Person Name</profiletag> and replaces this tag with html of the person's profile.
Now what I want is to allow my writers to insert this HTML (<profiletag>Person Name</profiletag>) from the WYSIWYG editor rather than having to go into the source and insert a tag into the html. When they write <profiletag> etc. in the WYSIWYG editor obviously it gets all messed up. I'm looking for something like [profile]Person Name[/profile] markup for them to include these tags in the WYSIWYG side.
Is this possible, and if so how can I implement this functionality?
Comment: I think you will need to create a custom plugin http://ckeditor.com/forums/Plugins/Customtag-plugin
Answer: What you need is a custom filter. Filters are the check boxes you can set on input formats like 'Filtered HTML' and 'Full HTML'.
There is an example available in the examples module: https://www.drupal.org/project/examples
Basically, you need this:
1) You need to implement hook_filter_info() to let Drupal know there is a new filter
2) You need to a function to process the input. This is where you can use your regex.
I highly suggest looking at the examples module or any other modules that use filters.


Firebase OAuth Error: "Invalid id_token in idp response"

Question: I seem to have succeeded implementing Google OAuth to use it with Firebase. The problem is that sometimes, when I signOut & try to sign back in, it doesn't work and I get the error:
<code>[Invalid id_token in idp response: ...]".
</code>
From this point, SignIn doesn't work until maybe a few days later. Maybe after a certain expiration (I didn't find out why it got to work again). Any idea how to fix this?
Here is my code (SignInActivity):
<code>private void initializeGoogle() {
    final SignInButton objConnectButton = (SignInButton) findViewById(R.id.signin_google);

    GoogleSignInOptions objOptions = new GoogleSignInOptions
        .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(C.GOOGLE_CLIENT_ID).build();

    final GoogleApiClient objGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(@NonNull ConnectionResult aobjResult) {
                C.handleEvent(SignInActivity.this, R.string.msg_signin_connection_failed, aobjResult.getErrorMessage(), 7);
            }
        }).addApi(Auth.GOOGLE_SIGN_IN_API, objOptions).build();

    objConnectButton.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
        startActivityForResult(Auth.GoogleSignInApi.getSignInIntent(objGoogleApiClient),
            C.ReqCode.SIGNIN_GOOGLE);
        }
    });
}

private void signInWithGoogle(final GoogleSignInAccount aobjAccount, AuthCredential aobjCredential) {
    FirebaseAuth.getInstance().signInWithCredential(aobjCredential)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> aobjTask) {
            if (aobjTask.isSuccessful()) {
                startMainActivityWithValues(aobjAccount.getDisplayName(), C.SignInType.GOOGLE);
            }
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception aobjException) {
            C.handleEvent(SignInActivity.this, R.string.msg_signin_connection_failed, aobjException.getMessage(), 12);
        }
    });
}

@Override
protected void onActivityResult(int aintRequestCode, int aintResultCode, Intent aobjDataIntent) {
    super.onActivityResult(aintRequestCode, aintResultCode, aobjDataIntent);

    // Handle Google Auth
    if (aintRequestCode == C.ReqCode.SIGNIN_GOOGLE) {
        if ((aintResultCode == RESULT_OK)) {

            GoogleSignInResult objSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(aobjDataIntent);
            if (objSignInResult.isSuccess()) {

                final GoogleSignInAccount objAccount = objSignInResult.getSignInAccount();
                String strTokenID = (objAccount != null ? objAccount.getIdToken() : null);

                if (strTokenID != null) {
                        signInWithGoogle(objAccount, GoogleAuthProvider.getCredential(strTokenID, null));
                } else {
                        C.handleEvent(SignInActivity.this, R.string.msg_signin_connection_failed, getString(R.string.msg_signin_connection_invalid_token), 10);
                }
            } else {
                C.handleEvent(SignInActivity.this, R.string.msg_signin_connection_failed, objSignInResult.getStatus().getStatusMessage(), 8);
            }
        } else {
                C.handleEvent(SignInActivity.this, R.string.msg_signin_connection_cancelled, "", 9);
        }
    }
}

private void startMainActivityWithValues(String astrUsername, int aintAuthType) {
    Intent objIntent = new Intent(SignInActivity.this, MainActivity.class);

    objIntent.putExtra("USER_NAME", astrUsername);
    objIntent.putExtra("AUTH_SOURCE", aintAuthType);

    startActivity(objIntent);
    finish();
}

private void signOutFromGoogle() {
    final GoogleApiClient objClient = new GoogleApiClient.Builder(MainActivity.this)
        .addApi(Auth.GOOGLE_SIGN_IN_API, new GoogleSignInOptions.Builder(
        GoogleSignInOptions.DEFAULT_SIGN_IN).build()).build();

    objClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(@Nullable Bundle aobjBundle) {
            if (objClient.isConnected()) {
                objFbAuth.signOut();
                Auth.GoogleSignInApi.signOut(objClient).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status aobjStatus) {
                        if (aobjStatus.isSuccess()) {
                            startActivity(new Intent(MainActivity.this, SignInActivity.class));
                            finish();
                            Toast.makeText(MainActivity.this, getString(R.string.msg_signin_logged_out), Toast.LENGTH_SHORT).show();
                        } else {
                            C.handleEvent(MainActivity.this, R.string.msg_signin_disconnection_failed, "", 14);
                        }
                    }
                });
            }
        }

        @Override
        public void onConnectionSuspended(int aintCause) {
            String strMessage = "ConnectionSuspended (" + (aintCause == 1 ? "SERVICE_DISCONNECTED" : "NETWORK_LOST") + ")";
            C.handleEvent(getBaseContext(), R.string.msg_signin_connection_failed, strMessage, 2);
        }
    });

    objClient.connect();
}
</code>
Comment: Note: It seems to happen only on my emulator (BlueStack), I did'nt get the issue on a device. Any idea?
Answer: Here's a solution that seems to work: In Android Studio, open the File menu and click "Invalidate & Restart". Also: restart Bluestacks (close it via the tray icon). Maybe only one of these steps is needed but I haven't tried yet.
Answer: I was facing the same issue at night but next morning I checked, it was working. Just make sure that the SHA1 certificate fingerprint in App Signing screen(Google play conosle) is present on your  firebase configuration.


Application is crashing when i click settings option in live wallpaper

Question: Nothing is posted in logcat.Application just stops working.
Here is my code form manifest
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <service android:name =".LiveWallpaperAndroid"
     android:label = "@string/app_name"
     android:icon = "@drawable/ic_launcher"
     android:permission = "android.permission.BIND_WALLPAPER" >
    <intent-filter>
            <action android:name="android.service.wallpaper.WallpaperService" />
    </intent-filter>
    <meta-data android:name ="android.service.wallpaper"
         android:resource ="@xml/livewallpaper" />
    </service>

    <activity android:label="@string/livewallpaper_settings"
        android:name=".LiveWallpaperSettings"
        android:theme="@android:style/Theme.Light.WallpaperSettings"
        android:exported="true"
        android:icon = "@drawable/ic_launcher">
    </activity>
</application>

Below is my settings Activity code
public class LiveWallpaperSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener
{
@Override
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
        getPreferenceManager().setSharedPreferencesName(LiveWallpaperScreen.SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.football);
getPreferenceManager().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
}

My xml file for settings is
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/livewallpaper_settings"
android:key="livewallpaper_settings">

<ListPreference
    android:key="livewallpaper_testpattern"
    android:title="@string/livewallpaper_settings_title"
    android:summary="@string/livewallpaper_settings_summary"
    android:entries="@array/livewallpaper_testpattern_names"
    android:entryValues="@array/livewallpaper_testpattern_prefix"/>
<CheckBoxPreference android:key="livewallpaper_movement"
    android:summary="@string/livewallpaper_movement_summary"
    android:title="@string/livewallpaper_movement_title"
    android:summaryOn="Moving test pattern"
    android:summaryOff="Still test pattern"/>
</PreferenceScreen>

What is wrong here.I am unable to come up with anything because nothing is shown in logcat about any error.
Comment: can you post your whole code .....
Answer: it occur many time with me also, i know this problem and solution well,i think you just forgot to change your package name in you xml folder wallpaper.xml file, just check following you got your answeres.
i think you wallpaper.xml // you understand your file name whatever you take
   <?xml version="1.0" encoding="utf-8"?>
   <wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
   android:settingsActivity="YourAllPAckageName.YourSettingActivity"
   android:thumbnail="@drawable/ic_launcher" />

like,
  <?xml version="1.0" encoding="utf-8"?>
   <wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
   android:settingsActivity="com.wallpaperexample.WallpaperSettingsActiity"
   android:thumbnail="@drawable/ic_launcher" />


Are there alternatives to the Bayesian update rule?

Question: Are there any other methods to update my belief in a hypothesis aside from the Bayesian update rule?
Comment: I believe--and I think this has been extensively substantiated--that the universally most popular method is to pray to one's deity of choice.  I am not being entirely facetious: because this question does not circumscribe the kind of "methods" or hypotheses, and because it does not ask for those with scientific or theoretical legitimacy, it would seem to open up the conversation to a large number of possibilities. It would be nice if you could edit this post to focus it better.
Answer: There are some alternatives, in fact, but they rely on using non-probabilistic methods. (The uniqueness of Bayes Law is implied by the uniqueness of a single probability measure, and the definition of joint probability - see this other answer for details)
Dempster Shafer theory is an alternative, as are more complex formalisms such as DSMT. Similarly, Imprecise probabilities can do similar things - but they still use Bayes' law. Fuzzy Logic and other formalisms may also be of interest.
Comment: See also _possibility theory_.
Answer: I'll add another perspective.  In E. T. Jaynes incredible book Probability Theory: The Logic Of Science, he gives a rigorous treatment of an extension of Aristotelian logic to degrees of belief (Jaynes was a baysean to the core).  That is, he explores a probability theory so that $P = 1$ and $P = 0$ correspond to True and False in classical first order logic.
He outlines a few desirable properties that such an extension must have:

I. Degrees of Plausibility are represented by real numbers.
II. Qualitative Correspondence with common sense.
IIIa. If a conclusion can be reasoned out in more than one way, then
  every possible way must lead to the same result.
IIIb. Always take into account all of the evidence
  relevant to a question. Do not arbitrarily ignore some of
  the information, basing its conclusions only on what remains.
  In other words, the theory is completely non-ideological.
IIIc. Always represent equivalent states of knowledge by
  equivalent plausibility assignments. That is, if in two problems
  the state of knowledge is the same (except perhaps for
  the labeling of the propositions), then it must assign the same
  plausibilities in both.

all of these statements are given rigorous interpretations in the book.
Then Jaynes gives a deeply fascinating and rigorous mathematical demonstration that Bayesian reasoning is the unique extension of logic to degrees of belief that satisfies these requirements.  So in the sense of Jaynes, the answer is actually no, if you want your theory to be compatible with Aristotle, Bayes is the only way.
Comment: I was looking in PT:LOS for the name of this law when I posted yesterday, that probability is a unique conception given these conditions, (which I mentioned in passing in my answer) - but thanks for explaining it clearly!
Answer: To my knowledge, if you assign a probability to your belief, the bayesian updating rule is the only way to act upon new datas in a consistent manner in line with probabilities.
You might have two reasons to leave the bayesian framework :

You don't want to assign probabilities to a belief.
You don't have (or don't want to specify) an alternative belief.

One (amongst other) alternative to Bayesian Inference is the framework of Null Hypothesis Statistical Testing (NHST) framework to eventually reject your hypothesis. One could argue that rejecting a belief is a hard form of updating. You do not mention in your question an alternative hypothesis.
If your belief has some degree of freedom, this is a special case. There is no straight answer of how to judge which model is the best as different criteria coexist. There is a bayesian way to act (Bayesian Information Criterion), but also others (the field is known as model selection). I don't know if and how a belief can be updated in this case.
Comment: That NHST is the only alternative to Bayesian inference would be an absurd claim if that is what you are implying. It's entirely possible to centre thought and action on the likelihood, for example.
Comment: I appreciate your intent, but it's hard to confine a reply to a comment when you touch on the nature of statistical inference as a whole! A partial (and incomplete) reply is that I don't think you are in any sense obliged to phrase Bayesian updating in terms of _beliefs_ (a term I've managed to avoid in my statistical practice) or of binary states. In terms of your answer, there are other grounds why people don't use Bayesian ideas.
Comment: This is not my claim so I edited to avoid this misunderstanding. I am here to learn too, so I'd be interested to understand more your point. I chose to consider *"belief"* as binary (conserve/reject) and as a probability (update a prior). As far as my understanding go, the likelihood allows to update a prior by the computation of the bayesian factor.I don't know how it allows to *update my belief in a hypothesis* unless maybe in a kind of qualitative way.
Comment: Thanks. I understand now how - from your point of view - this question must be taken in a broader sense than mine. Maybe it would deserve another answer or an improvement of mine (that I would certainly accept).


Unique 6 digit number but not sequential for Customer ID (SQL)

Question: Our Customer table has an int Identity column for ID. This was going to be given out to customers, so when they phone they could just give their ID.
It is now obvious that our competitors would easily be able to register twice on our site, say a month apart and find out exactly how many people have registered.
Therefore, is there a nice simple way to create a "Customer ID" (in SQL or c#) which we could give to customers that is:
(a) 6 digits long
(b) is unique
(c) is not sequential(
Thanks in advance
Comment: Does it have to be numerical? Or can it be alphanumeric?
Comment: That's cool, you have a couple of answers to look at which should help.
Answer: If you choose any increment that is not a factor of 1000000, then you could take the last 6 digits of that number to provide the ID; ie (IDENTITY (1,7)) % 1000000.
But your competitors could still find the increment by a few sequential registrations, so this would not completely solve the issue.
So it would seem you want a number that is completely random - so for that, you'll have to check whether it already exists when you generate it, or pre-generate a list of numbers, sort them randomly, and pick the next when creating a new customer.
Another option to consider is some form of encryption, if you can find or create an appropriate algorithm that creates a short enough output.
If you take the large non factor increment route, you could then subsequently re-arrange the order of the digits to create a more random number - eg;
declare @inc int , @loop int
declare @t table (i int, cn int, code varchar(4))

select @inc = 5173, @loop = 1
while @loop<=10000
begin
    insert @t (i, cn)
    select @loop, (@inc*@loop)%10000
    select @loop = @loop + 1
end

update @t
set code = substring(convert(varchar(4),cn),2,1)
    + substring(convert(varchar(4),cn),4,1)
    + substring(convert(varchar(4),cn),3,1)
    + substring(convert(varchar(4),cn),1,1)

select code, count(*) from @t group by code having count(*)>1
select top 20 * from @t order by i

Depending on the number you choose, some sequential items will have the same difference between them, but this number will vary. So it's not cryptographically secure, but probably enough to thwart all but the most determined of competitors.
You could convert the above to a function to run off a standard IDENTITY(1,1) id field
Answer: Maybe this is insane, but here is my way of generating the Customer Numbers up front.
This will generate however many UNIQUE keys you want very quickly.
You could obviously save these into a real table.
Here is a SQLFiddle of the below: http://www.sqlfiddle.com/#!3/d41d8/3884
DECLARE @tbl TABLE
(
    ID INT IDENTITY(1,1),
    CustNo INT UNIQUE
)

DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @NumberRequired INT

SET @Lower = 100000 ---- The lowest random number allowed
SET @Upper = 999999 ---- The highest random number allowed
SET @NumberRequired = 1000 -- How many IDs do we want?

WHILE (SELECT COUNT(*) FROM @tbl) < @NumberRequired
BEGIN
    BEGIN TRY
        INSERT INTO @tbl SELECT (ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0))
    END TRY
    BEGIN CATCH
        -- If it goes wrong go round the loop again
    END CATCH
END

SELECT  *
FROM    @tbl

EDIT: Actually this is probably faster. It generates all 900000 possible keys in around 30 seconds on my dev machine, which is okay for a one-off job.
DECLARE @tbl TABLE
(
    ID INT
)

DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @i INT;

SET @Lower = 100000 ---- The lowest random number allowed
SET @Upper = 999999 ---- The highest random number allowed

SET @i = @Lower

WHILE @i <= @Upper
BEGIN
    INSERT INTO @tbl SELECT @i
    SET @i = @i + 1
END

SELECT  ID
FROM    @tbl ORDER BY NEWID()

Comment: Neat, but it will get much slower as the number of remaining keys decreases.
Comment: Yeah that's true! But surely anything method would suffer from that problem wouldn't it? It was very quick for 1000 keys (sub second) and less than ten seconds for 10,000 keys on my poor dev machine at work. If Dominic is worried about people seeing sequential keys then that might be enough to generate up front?! Especially since this is a one-off exercise.
Answer: You can have calculated column that generated from Identity column and create unique value that Expect.
for example calculated column like below :
100000 + Identity_Column * 7 + 3
Comment: Identify column is unique and surely above calculate column be unique.
Answer: What if juts use user registration timestamp. It doesn't contain user's count information and unique (If you don't register users each second for example). For instance if you use 10000 in this query you can register users each minute and get unique 9 symbol digit:
select cast(cast(current_timestamp as float)*10000 as int)

Comment: I don't think 6 digits give a big enough range of numbers so that this would work for fast registrations.
Answer: You could make a table with 2 columns, one with the values 100.000 to 999.999 and one with a marker whether the number has been given out. When making a new client assign an unassigned number from this table at random and mark it assigned.
Comment: actually a table with one column and removing the used numbers would also work. You could pre-randomize the table.


get next/previous month from a Time object

Question: I have a Time object and would like to find the next/previous month. Adding subtracting days does not work as the days per month vary.
time = Time.parse('21-12-2008 10:51 UTC')
next_month = time + 31 * 24 * 60 * 60

Incrementing the month also falls down as one would have to take care of the rolling
time = Time.parse('21-12-2008 10:51 UTC')
next_month = Time.utc(time.year, time.month+1)

time = Time.parse('01-12-2008 10:51 UTC')
previous_month = Time.utc(time.year, time.month-1)

The only thing I found working was
time = Time.parse('21-12-2008 10:51 UTC')
d = Date.new(time.year, time.month, time.day)
d >>= 1
next_month = Time.utc(d.year, d.month, d.day, time.hour, time.min, time.sec, time.usec)

Is there a more elegant way of doing this that I am not seeing?
How would you do it?
Answer: Ruby on Rails
Note: This only works in Rails (Thanks Steve!) but I'm keeping it here in case others are using Rails and wish to use these more intuitive methods.
Super simple - thank you Ruby on Rails!
Time.now + 1.month

Time.now - 1.month

Or, another option if it's in relation to the current time (Rails 3+ only).
1.month.from_now

1.month.ago

Comment: @Steve it doesn't assume 30 days when doing date arithmetic. It's actually pretty magical. try it! (see ActiveSupport::Duration, Date#plus_with_duration, and integer/time.rb in active_support). e.g. >> Time.utc(2010, 2, 1) + 1.months.
=> Mon Mar 01 00:00:00 UTC 2010
>> Time.utc(2010, 3, 1) + 1.months
=> Thu Apr 01 00:00:00 UTC 2010
>> Time.utc(2010, 4, 1) + 1.months
=> Sat May 01 00:00:00 UTC 2010

Or for an extreme example: >> Time.utc(2010, 1, 31) + 1.months
=> Sun Feb 28 00:00:00 UTC 2010
Comment: The `#month` method is a Rails extension. It also assumes 30 days in a month, and so will return the wrong answer on the 31st.
Comment: Fairplay, I was using the script/console - guess I'm too ROR'd for my own good.
Comment: >> Time.utc(2010, 1, 31) + 1.months
=> Sun Feb 28 00:00:00 UTC 2010
>> Time.utc(2008, 1, 31) + 1.months
=> Fri Feb 29 00:00:00 UTC 2008
Comment: @John: That's new, isn't it? Do you know what version of Rails added that?
Comment: @Steve 2007ish? http://github.com/rails/rails/commit/276c9f29cde80fafa23814b0039f67504255e0fd
Comment: 1.month.ago is easier (RoR)
Comment: @joaomilho For Rails 3+, for sure. I added it to the answer, thanks.
Comment: Shouldn't this be Time.now (Rather than DateTime.now) since 1.month returns a TIme object with timezone.
Comment: @Donato Your comment made me look up the main differences between `DateTime` and `Time`. Prior to Ruby 1.9, `DateTime` was a better choice but Ruby 1.9 and above, `Time` appears to be a better. Thanks for the nudge. Read more: http://stackoverflow.com/a/21075654/293280
Answer: Personally I prefer using:
Time.now.beginning_of_month - 1.day      # previous month
Time.now.end_of_month + 1.day            # next month

It always works and is independent from the number of days in a month.
Find more info in this API doc
Comment: Best answer so far
Comment: This is strange to me, but it works if you what you really want is the last day of the previous month or the first day of the next month. If all you want is the previous or next _month_ and could care less about what _day_ of that month, there's easier and more simplistic ways to get it.
Answer: you can use standard class DateTime
require 'date'

dt = Time.new().to_datetime
=> #<DateTime: 2010-04-23T22:31:39+03:00 (424277622199937/172800000,1/8,2299161)>

dt2 = dt >> 1
=> #<DateTime: 2010-05-23T22:31:39+03:00 (424282806199937/172800000,1/8,2299161)>

t = dt2.to_time
=> 2010-05-23 22:31:39 +0200

Answer: There are no built-in methods on Time to do what you want in Ruby. I suggest you write methods to do this work in a module and extend the Time class to make their use simple in the rest of your code.
You can use DateTime, but the methods (<< and >>) are not named in a way that makes their purpose obvious to someone that hasn't used them before.
Answer: below it works
previous month:
Time.now.months_since(-1)

next month:
Time.now.months_since(1)

Comment: undefined method `months_since'
Comment: months_since is activesupports's methods, you can execute `ri months_since` in your cli
Comment: what's your code environment, ruby version ? here is my code execute results `irb(main):053:0> Time.now.months_since(-1)
=> 2013-10-19 08:40:04 +0800`
Comment: $ ruby -v
ruby 1.9.3p327 (2012-11-10 revision 37606) [x86_64-darwin12.2.1]
$ irb
>> Time.now.months_since(-1)
NoMethodError: undefined method `months_since' for 2013-11-19 02:09:23 +0100:Time
Answer: If you do not want to load and rely on additional libraries you can use something like:
module MonthRotator
  def current_month
    self.month
  end

  def month_away
    new_month, new_year = current_month == 12 ? [1, year+1] : [(current_month + 1), year]
    Time.local(new_year, new_month, day, hour, sec)
  end

  def month_ago
    new_month, new_year = current_month == 1 ? [12, year-1] : [(current_month - 1), year]
    Time.local(new_year, new_month, day, hour, sec)
  end
end

class Time
  include MonthRotator
end

require 'minitest/autorun'

class MonthRotatorTest < MiniTest::Unit::TestCase
  describe "A month rotator Time extension" do
    it 'should return a next month' do
      next_month_date = Time.local(2010, 12).month_away
      assert_equal next_month_date.month, 1
      assert_equal next_month_date.year, 2011
    end

    it 'should return previous month' do
      previous_month_date = Time.local(2011, 1).month_ago
      assert_equal previous_month_date.month, 12
      assert_equal previous_month_date.year, 2010
    end
  end
end

Comment: This does not take year rolling into account.
Comment: Thanks for the heads up! Updated my answer accordingly.
Comment: Thank you for providing an answer that doesn't rely on active_support / rails.
Answer: I just want to add my plain ruby solution for completeness
replace the format in strftime to desired output
DateTime.now.prev_month.strftime("%Y-%m-%d")
DateTime.now.next_month.strftime("%Y-%m-%d")

Answer: You can try convert to datetime.
Time gives you current date, and DateTime allows you to operate with.
Look at this:
irb(main):041:0> Time.new.strftime("%d/%m/%Y")
        => "21/05/2015"

irb(main):040:0> Time.new.to_datetime.prev_month.strftime("%d/%m/%Y")
    => "21/04/2015"

Answer: Here is a solution on plain ruby without RoR, works on old ruby versions.
t=Time.local(2000,"jan",1,20,15,1,0);
curmon=t.mon;
prevmon=(Time.local(t.year,t.mon,1,0,0,0,0)-1).mon ;
puts "#{curmon} #{prevmon}"

Answer: Some of the solutions assume rails. But, in pure ruby you can do the following
require 'date'

d = Date.now
last_month = d<<1

last_month.strftime("%Y-%m-%d")

Answer: Im using the ActiveSupport::TimeZone for this example, but just in case you are using Rails or ActiveSupport it might come in handy.
If you want the previous month you can substract 1 month
time = Time.zone.parse('21-12-2008 10:51 UTC')
time.ago(1.month)

Answer: You can get the previous month info by this code
require 'time'
time = Time.parse('2021-09-29 12:31 UTC')
time.prev_month.strftime("%b %Y")

Comment: undefined method `prev_month' for 2021-09-29 12:31:00 UTC:Time (NoMethodError)
Answer: $ irb
irb(main):001:0> time = Time.now
=> 2016-11-21 10:16:31 -0800
irb(main):002:0> year = time.year
=> 2016
irb(main):003:0> month = time.month
=> 11
irb(main):004:0> last_month = month - 1
=> 10
irb(main):005:0> puts time
2016-11-21 10:16:31 -0800
=> nil
irb(main):006:0> puts year
2016
=> nil
irb(main):007:0> puts month
11
=> nil
irb(main):008:0> puts last_month
10
=> nil

Comment: Don't try this in January though.


Counting each filter near its label

Question: I've created a view in order to override the default search page form and results, then I've exposed the content type in order to have the possibility to filter by that, all now is working
How can I have the count of the relative content near each content type label on the filters?
Answer: Sounds like you want to use search facets.  Facets are ways of showing various search 'tag' information for the current results with/without counts.  Note that this is slightly different from a filter which will show all values even if there is no result with the specified search criteria.
That said, there is a defunct facets core search module. As the module page says, the best way to approach this with Drupal 8 is to use the Facets module which requires the Search API module with the included Search API DB engine (no Solr required).
This will add a bunch of extra functionality that the core search will not handle.  Stuff like full text search across multiple text fields, stemmed searches (e.g. search for work also finds working, works, and the like), ability to show extracts (were the word was found), and much more.
Answer: One way to create a filtering system that counts the results per category is by creating a Contextual filter for the type with the Summary option.
This will list all the types as links, and show the number of results next to each type name. When you click through those links you will see the results for that one filtered type under the Format you set in Views.
You can list all the results below the Summary if you use different displays as Blocks/Attachments and display them together. There are many different combinations how to configure this, details depend on your particular needs.

Another way to count the results according to some categorization is with Aggregation. When you turn it on in your Views all fields and filters get the neutral "group" setting. The field related to your rows (node ID, title, etc) can then be set to Count under Aggregation settings which will display the number instead of the actual field output. You have to be careful about the other fields you show because they can "break" the aggregation into individual rows instead of collapsing into one value of the counted items.
Sorting can affect Aggregation negatively so remove sort criteria while building the Aggregation.
After you get the count numbers, you can maybe group by the type field (under Format), and you can Rewrite output of fields to show the count where you want it, again it all depends on your needs.
Answer: I've found a solution with a different approach
With form_alter I've targeted the form and edited the filter labels, by adding a custom query and counting items from the search_index table with a left join to the node_field_data table in order to get the node type

Counting each filter near its label


If the joint distribution is uniform, then the random variables are independent?

Question:
This is a problem that I am stuck at. If $X_1$ and $X_2$ are independent, it would be easier. But, the problem asks me the converse.
For (i), I suspect that $X_1$ and $X_2$ are independent. But I find no way of showing this.
For (ii), I even have no idea if $X_1$ and $X_2$ are independent...I first tried $X_1$ and $X_2$ being polar coordinates. But, I don't think they form a uniform joint distribution.
Could please anyone help me with this problem?

This is the definition of independent random variables.
Answer: What is the definition of the independence of two random variables?  In other words, how can you mathematically determine whether two random variables are independent?
Your intuition for part (i) is correct, but you need to figure out why.  The beginning step is to answer the above question.
For part (ii), suppose I generated a realization of $(X_1, X_2)$ according to the distribution specified in this part of the question.  Without telling you $X_1$, I tell you that $X_2 = 0.95$.  What information does this convey about the possible value of $X_1$?  For example, could $X_1 = 0.5$ if $X_2 = 0.95$?  Why or why not?  What does this suggest about whether $X_1$ and $X_2$ are independent?
Comment: Some friendly advice if you really want to learn.  Don't just regurgitate a book definition.  You have to **understand** what you read.  The level of the text you are referencing is **way** higher than the level of understanding you seem to be at with your question; this suggests that you are not using a suitable text for what you are trying to learn, or that you have insufficient prerequisite knowledge on this topic.  When I asked you for the definition of independence, I was not expecting a measure-theoretic one.  It's overkill for what you actually need for this question.
Comment: When I say "generated a realization," what I mean is I observed some outcome of the random variable.  If I have a random variable $U$ that is uniformly distributed on $[0,1]$, then a "realization" of this random variable can be generated by picking at random some real number between $0$ and $1$.
Comment: I editted the question by adding a definition of independence I learned. And, what does it mean by realization of (X_1, X_2)?
Comment: What do you mean by X_2 =0.95 ?
Comment: I have learned real analysis; and I'm taking a class some kind of "advertising" the probability theory. I first thought that probability theory is quite similiar to real analysis, just using probability measure instead of arbitrary measure. But, now I'm having much difficulty with the concept of independence...yes I acknowledge that.
Answer: (i) Note that uniform on the square means that $p(S) = m(S \cap [0,1]^2)$, where $m$ is the Lebesgue measure on the square (I will use the
same symbol for the Lebesgue measure in the line).
Suppose $A, B \subset [0,1]$. Then $p(X_1 \in A, X_2 \in B) = p( (X_1,X_2) \in A \times B) = m(A \times B)=m(A) m(B)$.
$p(X_1 \in A) =  m(A)$, and similarly
$p(x_2 \in B) = m(B)$. Hence $p(X_1 \in A, X_2 \in B) = p(X_1 \in A) p(x_2 \in B)$.
It should be clear that since $p(X_1 \in A) =  m(A \cap [0,1])$, that
$X_1$ is uniformly distributed on $[0,1]$. Similarly for $X_2$.
(ii) In this case, we have $p(S) = {1 \over \pi}m(S \cap B(0,1))$.
Let $I=[{1 \over \sqrt{2}}, 1]$. It is easy to see that
$p(X_1 \in I) = p(X_2 \in I) >0$, but
$p(X_1 \in I, X_2 \in I) = 0$.
Since $p(X_1 \in A) = {1 \over \pi}  m((A \times \mathbb{R}) \cap B(0,1)) = {1 \over \pi}\int 1_A(x_1) 1_{B(0,1)}(x) dx$, we see that
$p(X_1 \in A) = {2 \over \pi}\int_{A \cap [-1,1]} \sqrt{1-x_1^2} dx_1$,
and similarly for $X_2$.
Answer: You need to recall what variable independence actually means, intuitively.
$X_1$ and $X_2$ being independent means that learning about one of them gives you absolutely no information about the other.
This is obviously not the case for (ii). If you learn that $X_1=1$, you can deduce that $X_2=0$. If you learn that $X_1=0.5$, you restrict the possible values for $X_2$, and in this restricted range the distribution is different.
It's also clear that in (i) the variables are independent. The marginal distribution $X_2$ is uniform on $[0,1]$, and given any specific value of $X_1$, the conditional distribution of $X_2$ is the same.
Now it's just a matter of formalizing these intuitions based on the measure-theoretic definitions.


Mail bouncing back

Question: I am getting a lot of mail bounced back mails. The bounced message says:

We cannot accept email from IP 22.214.171.124 without a DNS PTR
  record. Contact your ISP/HSP to set up a PTR record for your server.

I have verified that our mail server (mail.royalgroup.ae) is listed as the PTR record for the IP in question. What I don't understand is why the IP address of our firewall (.186) is listed in the bounce message.
I have included the whole bounced message with headers below.
<code>-------------------------------------------------------------------------- MDaemon Delivery Status Notification - http://www.altn.com/dsn/
--------------------------------------------------------------------------

The attached message had PERMANENT fatal delivery errors.

After one or more unsuccessful delivery attempts the attached message has been removed from the MDaemon mail queue on this server.  The number and frequency of delivery attempts are determined by local configuration.

-------------------------------------------------------------------------- YOUR MESSAGE WAS NOT DELIVERED TO ONE OR MORE RECIPIENTS
--------------------------------------------------------------------------

Failed address: firstname.lastname@example.com

--- Session Transcript ---  Tue 2013-04-23 08:27:00: Parsing message <xxxxxxxxxxxxxxxxxxxxxxxx\pd35000094660.msg>  Tue 2013-04-23 08:27:00:
*  From: email@example.com  Tue 2013-04-23 08:27:00: *  To: email@example.com  Tue 2013-04-23 08:27:00: *  Subject: a  Tue 2013-04-23 08:27:00: *  Size (bytes): 32512  Tue 2013-04-23 08:27:00:
*  Message-ID: <002d01ce3fdb$53e0eb40$fba2c1c0$@ae>  Tue 2013-04-23 08:27:00: Attempting SMTP connection to [mail.ru]  Tue 2013-04-23 08:27:00: Resolving MX records for [mail.ru] (DNS Server:
188.8.131.52)...  Tue 2013-04-23 08:27:00: *  P=010 S=000 D=mail.ru TTL=(8) MX=[mxs.mail.ru] {188.8.131.52}  Tue 2013-04-23 08:27:00: Attempting SMTP connection to [22.214.171.124:25]  Tue 2013-04-23 08:27:00: Waiting for socket connection...  Tue 2013-04-23 08:27:00: * Connection established (127.0.0.1:3187 -> 126.96.36.199:25)  Tue 2013-04-23 08:27:00: Waiting for protocol to start...  Tue 2013-04-23 08:27:01: <-- 220 Mail.Ru ESMTP  Tue 2013-04-23 08:27:01: --> EHLO mail.royalgroup.ae  Tue 2013-04-23 08:27:01: <-- 250-mx142.mail.ru ready to serve  Tue 2013-04-23 08:27:01: <-- 250-SIZE 73400320  Tue 2013-04-23 08:27:01: <-- 250 8BITMIME  Tue 2013-04-23 08:27:01: --> MAIL From:<email@example.com> SIZE=32512  Tue 2013-04-23 08:27:02: <-- 250 OK  Tue 2013-04-23 08:27:02: --> RCPT To:<firstname.lastname@example.com>  Tue 2013-04-23 08:27:02: <-- 250 OK  Tue 2013-04-23 08:27:02: --> DATA  Tue 2013-04-23 08:27:03: <-- 354 Go ahead  Tue 2013-04-23 08:27:03: Sending <xxxxxxxxxxxxxxxxxxxxxxxx\pd35000094660.msg> to [18.104.22.168]  Tue 2013-04-23 08:27:03: Transfer Complete  Tue 2013-04-23 08:27:05: <-- 550 We cannot accept email from IP 220.127.116.11 without a DNS PTR record. Contact your ISP/HSP to set up a PTR record for your server.  Tue 2013-04-23 08:27:05: --> QUIT
--- End Transcript ---
</code>
Answer: Your firewall is most likely a transparent SMTP proxy for filtering spam and viruses. Add a PTR record for the firewall's external IP. While you're at it, make sure you're updating your SPF record (if any).
Comment: Sorry Sir I didn't get you, how can i solve it where i have to go for add PTR record ,my firewall model is Sonic-wall 2400 and my mail server is Mdaemon version 11.0. I am  getting this bounced message only from some domain Example i cannot send any mail to *.@mail.ru
Comment: A PTR record is, in DNS speak, a reverse record that enable the lookup of a host name based on an IP address. Some mail admin goes by the belief that requiring a PTR record for connecting email server lower the amount of spam. It has therefore become a common step to prepare such a record for any server that will send out message in behalf of your domain. Unfortunately, you can't set it up yourself: it has to be done by your ISP.
Answer: You need to ask your datacentre or ISP to add PTR record for your mail server IP wghich is 126.96.36.199
So when someone do nslookup 22.214.171.124 it should get resolved to your mail server hostname.
Answer:
I have verified that our mail server (mail.royalgroup.ae) is listed as the PTR record for the IP in question

Not from here it isn't...
<code>** server can't find 18.104.22.168.in-addr.arpa.: NXDOMAIN
</code>
And you don't have SPF configured.

What I don't understand is why the IP address of our firewall (.186) is listed in the bounce message.

Have you checked to see what IP address is on the packets on the other side of the router? Most likely it's been configured to masquerade.

Mail bouncing back


Derive percentiles from binned data

Question: The question below was asked on a sister site (Stack Overflow) back in 2010 by a user still active there (to me it seems more suitable here, for example quite similar to 21422):

I have a bunch of data in Excel that I need to get certain percentile
information from. The problem is that instead of having the data set made up of
each value, I instead have info on the number of or "bucket" data.
For example, imagine that my actual data set looks like this:
1,1,2,2,2,2,3,3,4,4,4

The data set that I have is this:
Value    No. of occurrences
  1              2
  2              4
  3              2
  4              3
Is there an easy way for me to calculate percentile information (as well as the
median) without having to explode the summary data out to full data set? (Once I
did that, I know that I could just use the Percentile(A1:A5, p) function)

This is important because my data set is very large. If I exploded the data out,
I would have hundreds of thousands of rows and I would have to do it for a
couple of hundred data sets.
I doubt after all this time the OP is still concerned but if not off topic here I would appreciate your views (but won't be upset if this is closed!)
I am interested because (from a very long time ago!) I thought I had learned that, once binned, key information for accurate calculation of percentiles was irretrievably lost. But this is much more more my curiosity than a pressing need.
Comment: If the bins are labelled '1', '2' and so on, this is now discrete data; and the counts are in effect giving a histogram. You can work out which quantiles correspond to which bins easily enough - just cumulate the counts and divide by the last count, and you have what is in effect the entire ECDF.
Comment: @pnuts, I am wondering if you were able to implement this in Excel somehow, every solution I come up is more convoluted than the other :)
Answer: It is quite easy actually.
Let's say the sum of the counts is N, and you that you want the 0.3 (30%) bottom percentile. This means the threshold value will occur after 0.3*N counts.
Now you look at the cumulative distribution, and when it reaches 0.3*N, you have the value. It is very easy to implement.
For example, you had this:
Value    No. of occurrences
  1              2
  2              4
  3              2
  4              3

So you convert it into the cumulative:
Value    No. of occurrences
 <=1              2
 <=2              6
 <=3              8
 <=4              11

Here N=11 so 0.3*11=3.3. This happens in the second bin, so the 0.3 percentile is 2.
Comment: Hi Bitwise, I have read your answer several times to make sure I am not crazy. But isn't the 30th percentile 2 in this case?
Comment: @Jeanno of course, nice catch! Corrected.
Comment: thanks for the follow up :), I am struggling to implement this in Excel, I am wondering if you have some ideas ?
Comment: @Bitwise, thanks again for your response. I was able to put together a little VBA code to compute the percentile using binned data. To answer your question, the function PERCENTILE does not work for binned data, you basically have a column of all your data (doesn't have to be sorted)
Answer: PercentileBinnedData is an implementation of the algorithm described above that I have developed, QuickSort will ensure that your binned data is sorted in increasing order
Function PercentileBinnedData(rng As Range, percentile As Double) As Double
    Dim v As Variant
    v = rng.Value
    QuickSortArray v, , , 1 ' sort 2D array
    Dim i As Long
    Dim totalOccurences As Long

    'Convert to cumalative distribution
    For i = LBound(v, 1) To UBound(v, 1)
        If i < UBound(v, 1) Then
            v(i + 1, 2) = v(i + 1, 2) + v(i, 2)
        End If
    Next i
    totalOccurences = v(UBound(v, 1), 2) ' number of occurences is equal to last number of occurences
    Dim rank As Double: rank = percentile * totalOccurences
    For i = LBound(v, 1) To UBound(v, 1)
        If i = LBound(v, 1) And rank <= v(i, 2) Then
            PercentileBinnedData = v(i, 1)
        End If
        If i > LBound(v, 1) Then
            If rank > v(i - 1, 2) And rank <= v(i, 2) Then
                PercentileBinnedData = v(i, 1)
            End If
        End If
    Next i
End Function

Public Sub QuickSortArray(ByRef SortArray As Variant, Optional lngMin As Long = -1, Optional lngMax As Long = -1, Optional lngColumn As Long = 0)
    On Error Resume Next

    'Sort a 2-Dimensional array

    ' SampleUsage: sort arrData by the contents of column 3
    '
    '   QuickSortArray arrData, , , 3

    '
    'Posted by Jim Rech 10/20/98 Excel.Programming

    'Modifications, Nigel Heffernan:

    '       ' Escape failed comparison with empty variant
    '       ' Defensive coding: check inputs

    Dim i As Long
    Dim j As Long
    Dim varMid As Variant
    Dim arrRowTemp As Variant
    Dim lngColTemp As Long

    If IsEmpty(SortArray) Then
        Exit Sub
    End If
    If InStr(TypeName(SortArray), "()") < 1 Then  'IsArray() is somewhat broken: Look for brackets in the type name
        Exit Sub
    End If
    If lngMin = -1 Then
        lngMin = LBound(SortArray, 1)
    End If
    If lngMax = -1 Then
        lngMax = UBound(SortArray, 1)
    End If
    If lngMin >= lngMax Then    ' no sorting required
        Exit Sub
    End If

    i = lngMin
    j = lngMax

    varMid = Empty
    varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)

    ' We  send 'Empty' and invalid data items to the end of the list:
    If IsObject(varMid) Then  ' note that we don't check isObject(SortArray(n)) - varMid *might* pick up a valid default member or property
        i = lngMax
        j = lngMin
    ElseIf IsEmpty(varMid) Then
        i = lngMax
        j = lngMin
    ElseIf IsNull(varMid) Then
        i = lngMax
        j = lngMin
    ElseIf varMid = "" Then
        i = lngMax
        j = lngMin
    ElseIf VarType(varMid) = vbError Then
        i = lngMax
        j = lngMin
    ElseIf VarType(varMid) > 17 Then
        i = lngMax
        j = lngMin
    End If

    While i <= j
        While SortArray(i, lngColumn) < varMid And i < lngMax
            i = i + 1
        Wend
        While varMid < SortArray(j, lngColumn) And j > lngMin
            j = j - 1
        Wend

        If i <= j Then
            ' Swap the rows
            ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2))
            For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2)
                arrRowTemp(lngColTemp) = SortArray(i, lngColTemp)
                SortArray(i, lngColTemp) = SortArray(j, lngColTemp)
                SortArray(j, lngColTemp) = arrRowTemp(lngColTemp)
            Next lngColTemp
            Erase arrRowTemp

            i = i + 1
            j = j - 1
        End If
    Wend

    If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn)
    If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)

End Sub

Derive percentiles from binned data


What is the advantage of using an indexing set?

Question: For countable sets, what is the advantage of using an indexing set, such as $i \in I$, compared to just using the naturals and the normal enumeration of $1, 2, 3, \ldots$? To me it seems they equivalent unless the sets are uncountable, in which you cannot use something like $\mathbb{N}$ to index your set.
Comment: I don't think there's a significant advantage. It might seem aesthetically displeasing to order the indices arbitrarily, if there's not a natural way to order them.
Comment: You can arrange things more neatly by doing so when the contents of the indexing set are more important than the size of the indexing set.  For example, $\det(A)=\sum\limits_{\sigma\in S_n}\left(\text{sgn}(\sigma)\prod\limits_{i=1}^n A_{i,\sigma(i)}\right)$, indexing over the elements in $S_n$ rather than worrying about how to label the elements in $S_n$ from $1$ to $n!$
Comment: @littleO So if I were to somehow index a finite number of elements in an uncountable infinite set, how would I do that in terms of notation? For example, if I were to index the $n$ arbitrary irrationals in $\mathbb{R}$.
Comment: @CBBAM You don't try to force a different indexing on it, you just do it the natural way: if the set of length-$n$ ordered tuples of irrationals is denoted $(\mathbb{R}\setminus\mathbb{Q})^n$, and you can just use that as your index set.
Comment: There isn't much of a difference - for any enumeration you do with an index set, you can do the same such enumeration with the natural numbers. This is the definition of countability.
Answer: Even ignoring the advantage of avoiding a notational disagreement between countable and uncountable cases, just because something is countable doesn't mean that there is a canonical bijection between it and $\mathbb{N}$. By being flexible about index sets we can make sure that the Cartesian products we build don't have (or require us to input any!) any "extraneous information."
To see how this might get used in an argument, consider for example the following:

$(*)\quad$ Given a countable set $S\subseteq\mathbb{R}$, let $\mathcal{F}$ be all the ways of assigning to each $s\in S$ some $t<s$.

For each $S$ this is a Cartesian product; specifically, it's $$\prod_{s\in S}\{t\in\mathbb{R}: t<s\}.$$ Now if we really want to, since each $S$ is countable we could instead look at $$\prod_{n\in\mathbb{N}}\{t\in\mathbb{R}: t<f(n)\}$$ for some fixed bijection $f:\mathbb{N}\rightarrow S$, but this adds a layer of complexity: we need to fold in some choice of $f$, and in general there won't be a "best" choice to make here. In particular, if we insist on doing this then the definition of $\mathcal{F}$ given in $(*)$ is incomplete for our purposes since it doesn't tell us which $f$ to pick.


Does Mercurial have a template to capture output of "hg grep"?

Question: I was searching for a change that included "foreach" so I used this Mercurial command:
$ hg grep -r "user(mjh) & public() & date(-30)" --diff -i foreach

and it does return the hits where "foreach" was added and removed.
However, I'd like to know the actual commit hashes too.  If I add a template:
$ hg grep ... -T '{date|shortdate}\n{node|short}\n{desc|firstline}\n\n'

then I get the commit hash and description as expected, but then I don't see the changed files listed.
Is there a template to capture the output of hg grep?  The {files} template lists the files associated with a commit, but that's not the actual grep output.  Is there an iterable template keyword available for the grep results?
Answer:
Please, re-read carefully hg help grep -v (-v is important option), note the following part (new and unexpected for me also)

The following keywords are supported in addition to the common
template
keywords and functions. See also 'hg help templates'.
change        String. Character denoting insertion "+" or removal "-".
              Available if "--diff" is specified.
lineno        Integer. Line number of the match.
path          String. Repository-absolute path of the file.
texts         List of text chunks.

After it you'll be able to repeat (so-so, because some details will differ slightly) default output of grep in you template
>hg grep --diff -i -r 1166 to_try

>hg grep --diff -i -r 1166 -T "{path}:{rev}:{change}:{texts}\n" to_try
hggit/compat.py:1166:-:    for args in parameters_to_try:
hggit/compat.py:1166:+:    for (args, kwargs) in parameters_to_try:

and after replacing {rev} by {node|short}
>hg grep --diff -i -r 1166 -T "{path}:{node|short}:{change}:{texts}\n" to_try
hggit/compat.py:f6cef55e6aeb:-:    for args in parameters_to_try:
hggit/compat.py:f6cef55e6aeb:+:    for (args, kwargs) in parameters_to_try:


Availability of side-by-side line-by-line English-Italian.....opera libretti

Question: We've been taking advantage of the Met Opera's daily showings
Met Opera viewings
--and I particularly enjoy them when I have side-by-side line-by-line English-Italian (French, Russian...) libretti with which to follow along.
I've managed to get such libretti a few times on-line, through murashev.com--but even then not in any particularly systematic manner. So, specifically I'd like such libretti, if available,  for the upcoming Met Opera's viewings, and for operas, in general.
I suspect that in most cases, this will not be doable.
Comment: In principle CD booklets often provide those; some labels even have them downloadable for free. In the era of streaming services this will probably diminish soon. If different cuts are being made, some differences will remain.
Comment: You seem to be experienced enough to realize that only in rare cases will a strictly line by line translation be possible, but others might not be.  For example, a subordinate clause that takes up two lines would normally have the verb in the first of those lines in English but at the end if the second line in German.
Comment: OK, phoog! That's fine in any case. I'm just trying to view these operas in a somewhat more active--rather than passive (not comprehending the sung words by and large) role.
Answer: I use Opera Folio as the go-to place to get libretto. They usually have translations of the original text too, if you want to follow along. For some of the older public domain operas, IMSLP will have the libretto on their site. Generally, I go for the vocal scores on IMSLP because I like following along with the music. Sometimes the scores have the English translation side-by-side with the original language. Hope this helps.
Comment: Thanks. Will investigate-it's the side-by-side ones I really enjoy. (I have some knowledge of Italian, French and Russian--but it's often hard to discern the sung words--and the side-by-sides help.)  I'll check out the scores too, although I don't read the music itself.
Answer: Two other approaches that seem worth pursuing are to: (1)  enter as a search
English-Italian (French,...) libretto opera-in-question murashev.com
and (2) check the external links in the corresponding wikipedia article for the opera in question, the latter approach giving me  English-French side-by-side (termed "Parallel") libretto, courtesy of Project Gutenberg
https://en.wikipedia.org/wiki/The_Tales_of_Hoffmann


How to find the appropriate weights to maximize the third coordinate while the first two are zeros

Question: Let's assume, that $v_1, ..., v_n \in \mathbb{R}^3 $ and $ \lambda_1, ..., \lambda_n \in [0, 1] $
The $ v_1, ..., v_n $ vectors are given. I have to find the appropriate weights ($ \lambda_1, ..., \lambda_n$) where:
$$ \sum_{i=1}^{n} \lambda_i * v_i \approx \begin{pmatrix}
0\\
0\\
max
\end{pmatrix} $$
The first two coordinates should be around zero, and the third one have to be the as high as possible.
So I am looking for the appropriate weights, to reach the maximal value of the third coordinate if the first two are zeros.
I don't know about any algorithm using I could solve this. I am sure it exists, I just don't know the keywords to find it.
But if it is not that hard, then please give me hints about how could I solve it myself.

Edit
I've tried to solve it using the Simplex Method.
In this case $n=3$ and the values of the vectors are:
$$ v_1 = \begin{pmatrix} -2\\ 2\\ 1 \end{pmatrix} v_2 = \begin{pmatrix} 1\\ -1\\ 2 \end{pmatrix} v_3 = \begin{pmatrix} 1\\ 1\\ 1 \end{pmatrix} $$
In this example, the result is trivial ($ \lambda_1 = 0.5, \lambda_2 = 1, \lambda_3 = 0 $), but I would like to solve it using the simplex method, to understand it, and use it for $n > 3$ and/or different $v_i$ values.
The equations are:
$$ -2\lambda_1 + 1\lambda_2 + 1\lambda_3 \le 0 $$
$$ 2\lambda_1 - 1\lambda_2 - 1\lambda_3 \le 0 $$
$$ 2\lambda_1 - 1\lambda_2 + 1\lambda_3 \le 0 $$
$$ -2\lambda_1 + 1\lambda_2 - 1\lambda_3 \le 0 $$
$$ 1\lambda_1 + 2\lambda_2 + 1\lambda_3 = p $$
$$ \lambda_{1, 2, 3} \le 1 $$
After rearranging equations:
$$ -2\lambda_1 + 1\lambda_2 + 1\lambda_3 + 0S_1 + 0S_2 + 0S_3 + 1S_4+0S5+0S6+0S7+0p= 0 $$
$$ +2\lambda_1 - 1\lambda_2 - 1\lambda_3 + 0S_1 + 0S_2 + 0S_3 + 0S_4+1S5+0S6+0S7+0p= 0 $$
$$ 2\lambda_1 - 1\lambda_2 + 1\lambda_3 + 0S_1 + 0S_2 + 0S_3+0S_4+0S5+1S6+0S7 + 0p= 0 $$
$$ -2\lambda_1 + 1\lambda_2 - 1\lambda_3 + 0S_1 + 0S_2 + 0S_3+0S_4+0S5+0S6+1S7 + 0p= 0 $$
$$ -1\lambda_1 - 2\lambda_2 - 1\lambda_3 + 0S_1 + 0S_2 + 0S_3+0S_4+0S5+0S6+0S7 + 1p = 0 $$
$$ 1\lambda_1 + 0\lambda_2 + 0\lambda_3 + 1S_1 + 0S_2 + 0S_3+0S_4+0S5+0S6+0S7 + 0p = 1 $$
$$ 0\lambda_1 + 1\lambda_2 + 0\lambda_3 + 0S_1 + 1S_2 + 0S_3 +0S_4+0S5+0S6+0S7+ 0p = 1 $$
$$ 0\lambda_1 + 0\lambda_2 + 1\lambda_3 + 0S_1 + 0S_2 + 1S_3+0S_4+0S5+0S6+0S7 + 0p = 1 $$
From these equations, the simplex table is:
$$
\begin{array}{|c|c|c|c|c|c|c|c|}
\hline
\lambda_1 & \lambda_2 & \lambda_3 & S_1 & S_2 & S_3 & p &  \\ \hline
-2 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\ \hline
2 & -1 & 1 & 0 & 0 & 0 & 0 & 0 \\ \hline
1 & 0 & 0 & 1 & 0 & 0 & 0 & 1 \\ \hline
0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 \\ \hline
0 & 0 & 1 & 0 & 0 & 1 & 0 & 1 \\ \hline
-1 & -2 & -1 & 0 & 0 & 0 & 1 & 0 \\ \hline
\end{array}
$$
I select the column, where the last row has the most negative value. That is the $\lambda_2$ row. Then I have to select the row, where the value in the last column divided by the value in the selected column is the smallest. But the value of the last column at the first two rows are always zero, and I don't know which one should I choose.
Comment: This is a typical linear programming problem. Look up the simplex algorithm to solve it. https://en.wikipedia.org/wiki/Simplex_algorithm
Comment: I tried to use simplex algorithm, but my case is special, because $v_i$ can be negative, and the sum of the first two coordinates of the vectors (multiplied by the weights) have to be exactly zero.
Comment: the lowest non-zero ratio, or the lowest absolute value ratio?
Comment: Try making a harder example. This $n=3$ example proved too easy...
Answer: Let $v_i= \begin{pmatrix}
v_{i1}\\
v_{i2}\\
v_{i3}
\end{pmatrix} $
Then your LP will take the form:
Maximise $v_{13}\lambda_1+ v_{23}\lambda_2+ ... +v_{n3}\lambda_n $
Such that
$v_{11}\lambda_1+ v_{21}\lambda_2+ ... +v_{n1}\lambda_n =0$
$v_{12}\lambda_1+ v_{22}\lambda_2+ ... +v_{n2}\lambda_n =0$
$\lambda_1\le1$
$\lambda_2\le1$
$...$
$\lambda_n\le1$
Your variables are the $\lambda_i$ and they will be constrained automatically to be greater than or equal to zero. The signs of the $v_{ik}$ do not make any difference to the success of this approach.
Rewrite the equalities as pairs of inequalities:
Maximise $v_{13}\lambda_1+ v_{23}\lambda_2+ ... +v_{n3}\lambda_n $
Such that
$v_{11}\lambda_1+ v_{21}\lambda_2+ ... +v_{n1}\lambda_n \le 0$
$-v_{11}\lambda_1- v_{21}\lambda_2- ... -v_{n1}\lambda_n \le 0$
$v_{12}\lambda_1+ v_{22}\lambda_2+ ... +v_{n2}\lambda_n \le 0$
$-v_{12}\lambda_1- v_{22}\lambda_2- ... -v_{n2}\lambda_n \le 0$
$\lambda_1\le1$
$\lambda_2\le1$
$...$
$\lambda_n\le1$
You're going to have use a two-stage simplex algorithm because of equalities... thought you might have been able to get away without doing so, but no...
I have looked again at this and I can see how you can avoid the two-stage simplex algorithm.
In your example case you have the equations:
$$ -2\lambda_1 + 1\lambda_2 + 1\lambda_3 = 0 $$
$$ 2\lambda_1 - 1\lambda_2 + 1\lambda_3 = 0 $$
$$ 1\lambda_1 + 2\lambda_2 + 1\lambda_3 = p $$
$$ \lambda_1 \le 1 $$
$$ \lambda_2 \le 1 $$
$$ \lambda_3 \le 1 $$
Set $\lambda_3=2\lambda_1-\lambda_2$ and substitute throughout to yield:
$$ 2\lambda_1 - 1\lambda_2 + (2\lambda_1-\lambda_2) = 0 \Rightarrow 4\lambda_1-2\lambda_2=0 \Rightarrow \lambda_2=2\lambda_1$$
$$ 1\lambda_1 + 2\lambda_2 + (2\lambda_1-\lambda_2) = p \Rightarrow 3\lambda_1 + \lambda_2 = p$$
$$ \lambda_1 \le 1 $$
$$ \lambda_2 \le 1 $$
$$ 2\lambda_1-\lambda_2 \le 1 $$
We are left with
$$\lambda_2=2\lambda_1$$
$$3\lambda_1 + \lambda_2 = p$$
$$ \lambda_1 \le 1 $$
$$ \lambda_2 \le 1 $$
$$ 2\lambda_1-\lambda_2 \le 1 $$
Set $\lambda_2=2\lambda_1$ and substitute throughout to yield:
$$3\lambda_1 + 2\lambda_1 = p \Rightarrow 5 \lambda_1=p$$
$$ \lambda_1 \le 1 $$
$$2\lambda_1 \le 1 \Rightarrow \lambda \le \frac 12$$
$$2\lambda_1-2\lambda_2 \le 1 \Rightarrow 0 \le 1$$
We are left with
$$p = 5\lambda_1$$
$$ \lambda_1 \le \frac 12$$
You don't even need to use simplex algorithm!
To maximise $p$ you just need to maximise $\lambda_1$, so set $\lambda=\frac 12$.
Then $\lambda_2=2\lambda_1=1$
$\lambda_3=2(\frac 12)-1=0$
$p=5(\frac 12)=2.5$
Comment: I've tried to follow this tutorial: https://www.youtube.com/watch?v=vVzjXpwW2xI  I my case there is no $S_1$ and $S_2$ and the last column in the first two rows are zeros. In each step I have to choose the row, where the value in the last column divided by the value at the selected column is te lowest. But $ 0 / x = 0 / y $, so I don't know which row should I choose. Only the $ \lambda_1 < 1 $ rows have a value of 1 at the last column, but they will never be selected, because $1/x$ is always larger than $0/y$
Comment: I've updated the question


Finding eigenvectors of a $2\times 2$ matrix.

Question: I need to find the eigenvectors of the following matrix. The eigenvalues are 0.8 and 1 (this was double checked with Wolfram Alpha).
$\begin{bmatrix}0.8 & 0\\ 2 & 1\end{bmatrix}$
To find the eigenvector of 1:
 $\begin{bmatrix}0.8 & 0\\ 2 & 1\end{bmatrix}$-$\begin{bmatrix}1 & 0\\ 0 & 1\end{bmatrix}$=$\begin{bmatrix}-0.2 & 0\\ 2 & 0\end{bmatrix}$. Which implies that the vector is $\begin{bmatrix}0 \\ 0\end{bmatrix}$.
To find the eigenvector of 0.8:
$\begin{bmatrix}0.8 & 0\\ 2 & 1\end{bmatrix}$-$\begin{bmatrix}0.8 & 0\\ 0 & 0.8\end{bmatrix}$=$\begin{bmatrix}0 & 0\\ 2 & 0.2\end{bmatrix}$, which implies the vector is $\begin{bmatrix}0.1\\ 1\end{bmatrix}$.
However, my answers are incorrect. Wolfram says the answers are respectively $\begin{bmatrix}0 \\  1\end{bmatrix}$ and $\begin{bmatrix}0.0995\\ -0.995\end{bmatrix}$.  (link here:http://www.wolframalpha.com/input/?i=eigenvectors+of+%7B%7B0.8%2C0%7D%2C+%7B2%2C1%7D%7D)
What did I do wrong? I've tried this problem many times without success.
Comment: By definition, for an eigenvector $\vec x$ it holds $\vec x\neq \vec 0$.
Comment: @thanasissdr that's what rung a bell that told me something was off.
Answer: Let's say that we want to find an eigenvector that corresponds to the eigenvalue $\lambda_1=1$. We can solve the equation:
$$\begin{array}{l}A\cdot \mathbf{x} = 1\cdot \mathbf {x}\\[2ex]
\begin{bmatrix} 0.8&0\\2&1\end{bmatrix}\cdot \begin{bmatrix}x_1\\x_2\end{bmatrix}= \begin{bmatrix}x_1\\x_2\end{bmatrix}\\[3ex]
\left\{\begin{array}{l}
0.8x_1+0x_2=x_1\\
2x_1+x_2=x_2
\end{array}
\right.
\end{array}$$
From the first equation, we have that $x_1=0$ and plugging that to the second equation we have that $x_2 = x_2$, which implies that $x_2$ can be any real number except for zero! Thus, we can select $x_2=1$. So, the first eigenvector (one of the ones that correspond to the eigenvalue $\lambda_1 =1$) is $\mathbf{x} = \begin{bmatrix} 0 \\1 \end{bmatrix}$.
Answer: for $\lambda = 0.8$ you need to solve
$$\begin{bmatrix}0.8 & 0\\ 2 & 1\end{bmatrix} \begin{bmatrix}x \\ y \end{bmatrix} = 0.8\begin{bmatrix}x \\ y \end{bmatrix} $$
so $$ \begin{bmatrix}0.8 x \\ 2x+y \end{bmatrix} =\begin{bmatrix}0.8x \\0.8 y \end{bmatrix}    $$
$0.8x=0.8x$ doesn't tell you anything but $2x+y=0.8y$ gives you $y=-10x$ so the eigenvector is any vector of the form  $$k\begin{bmatrix} 1 \\ -10 \end{bmatrix}$$
Wolfram Alpha chooses $k=0.0995$ to make the eigenvector a unit vector.
Answer: Your first system of equations is:
$-0.2x + 0y = 0\\2x + 0y = 0.$
This tells us $x = 0$, but does not restrict $y$ in any way. Thus ANY non-zero value of $y$ lead to an eigenvector, $(0,y) = y(0,1)$.
Since any non-zero scalar multiple of an eigenvector is ALSO an eigenvector, we can choose ANY basis vector generating the subspace $\{(0,y):y \in \Bbb R\}$. It is traditonal to choose the eigenvector $(0,1)$, but any non-zero element of the subspace would do just as well.
Indeed we find that:
$\begin{bmatrix}0.8&0\\2&1\end{bmatrix}\begin{bmatrix}0\\y\end{bmatrix} = \begin{bmatrix}0\\y\end{bmatrix}$
which confirms $(0,y)$ is an eigenvector belonging to the eignevalue $1$ for any non-zero $y$.


How to calculate $|f|_{0}$?

Question: Again I am stuck with this problem in Rudin:
Assume that $|f|_{r}<\infty$ for some $r<0$. Prove that
$$\lim_{p\rightarrow 0}|f|_{p}=e^{\int_{X}\log |f|d\mu}$$
Let $r<p<0$ and we have $K=\frac{r}{p}>1$. Denote its conjugate by $K'$. Then we have $$\int f^{p}d\mu=\int (f^{p})*1d\mu\le (\int [f^{p}]^{\frac{r}{p}})^{\frac{p}{r}}$$ since by assumption $\mu(X)=1$. So in particular we have $$|f|_{p}\le |f|_{r}<\infty$$ Since $|f|_{p}$ is monotonely decreasing with $p\rightarrow 0$, it must have a limit.
We now apply Jensen's inequality, which gives us $$\log^{\int_{X}Fd\mu}\ge \int_{X}\log[F]d\mu$$ Here $F=f^{p}$. So we have
$$
\int_{X}f^{p}d\mu\ge (e^{\int_{X}\log[f]d\mu})^{p}
$$ taking the $p$-th root on both sides we conclude that $$|f|_{p}\ge e^{\int \log|f|d\mu}$$
But then I got totally stuck. It is worth pointing that Jensen's inequality is only an equality when $f^{p}=c$ is a constant. Therefore $f$ has to be a constant as well.
Comment: This has already been asked on the site. See, for example, http://math.stackexchange.com/questions/158049/lp-norm-and-integral-equality-prove/158118#158118
Comment: .......:( sorry! I am not good at searching...
Comment: But there is a difference; here the $p$ is approaching from negative instead of positive.
Comment: No worries. It actually took me several minutes to find the duplicate, and that was because I vaguely remembered having answered a similar question.
Comment: I see. In your arguments you seem to use Hölder's inequality for negative exponents: what is your source for that?
Comment: I did not use the one for negative exponents; $\frac{r}{p}$ is positive.
Comment: I see. In any case, problem 5 in chapter 3 from Rudin asks your question with $r>0$. What's the source to believe that this works for $r<0$?
Comment: No, my book states the problem with $r<0$.
Comment: I see a problem. $p$ is negative, so taking $\frac{1}{p}$'s power on both sides at that step actually does not give us the desired relationship. Let me think about it.
Comment: I'm curious about which edition you are looking at. I have copies of both the first and third edition, and in both it says $r>0$.
Comment: The edition is the 1966 edition, with no "x edition" sign on it.
Comment: I'm fairly sure that it is a typo. In any case, $$|f|_r=\frac1{|1/f|_{-r}},$$ so one can get the result for $r<0$ from the case $r>0$.
Comment: I have not read your proof carefully, but the other proof clearly broke down when $p<0$. His proof will not work even for $f=0$.
Comment: But thank you! I need to read your proof carefully.
Comment: I should ask: Is it possible to prove this by Jensen's inequality alone?
Comment: This is possibly a duplicate of http://math.stackexchange.com/questions/156878/integrate-and-measure-problem
Comment: Yes, please close it. Thank you.
Answer: Note that for $u>0$,
$$
k(u)=u\log(u)-u+1\ge0\tag{1}
$$
This is because $k'(u)=\log(u)$ and $k''(u)=1/u$ show that $k(u)$ has a minimum at $u=1$.
Now, by L'Hospital, we have
$$
\lim_{p\to0}\frac{x^p-1}p=\log(x)\tag{2}
$$
Furthermore, applying $(1)$ yields
$$
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}p}\frac{x^p-1}p
&=\frac{p\log(x)x^p-x^p+1}{p^2}\\
&=\frac{k(x^p)}{p^2}\\
&\ge0\tag{3}
\end{align}
$$
Thus, by Dominated Convergence, we have
$$
\begin{align}
\log\left(\lim_{p\to0}\left(\int_X|f(x)|^p\,\mathrm{d}\mu\right)^{1/p}\right)
&=\lim_{p\to0}\frac1p\log\left(\int_X|f(x)|^p\,\mathrm{d}\mu\right)\\
&=\lim_{p\to0}\frac1p\log\left(1+p\int_X\frac{|f(x)|^p-1}{p}\,\mathrm{d}\mu\right)\\
&=\lim_{p\to0}\frac1p\log\left(1+p\int_X\log|f(x)|\,\mathrm{d}\mu\right)\\
&=\int_X\log|f(x)|\,\mathrm{d}\mu\tag{4}
\end{align}
$$
Therefore,
$$
\lim_{p\to0}\left(\int_X|f(x)|^p\,\mathrm{d}\mu\right)^{1/p}
=\exp\left(\int_X\log|f(x)|\,\mathrm{d}\mu\right)\tag{5}
$$
Comment: @mnmn1993: any one of the integrals $\int_X\frac{|f(x)|^p-1}{p}\,\mathrm{d}\mu$ dominates those for smaller $p$ and for the $\log$. That is what Dominated Convergence requires, not that the limit function dominates the sequence. That would be Monotone Convergence.
Comment: We can find a $p$ small enough so $\left|\int_X\frac{|f(x)|^p-1}p\,\mathrm{d}\mu-L\right|\le\epsilon/2$ where $L=\int_X\log|f(x)|\,\mathrm{d}\mu$. Then we can use that $p$ or a smaller one so that $\left|\frac1p\log(1+pL)-L\right|\le\epsilon/2$.
Comment: Thank you so much for the help!
Comment: You're welcome. Each time I prove this theorem, I see some new underlying idea that makes it simpler.
Comment: How can you jump your lines to (4)? by Dominated Convergence?
Comment: @mnmn1993: yes. For any $p\gt0$, $\frac{|u|^p-1}p\ge\log|u|$.
Comment: I think it shows that $\dfrac{\int|f|^p-1}{p}\geq \int \log|f|$, but what next? How can you change  $\int\dfrac{\int|f|^p-1}{p}$ to $\int \log|f|$?
Comment: $\lim\limits_{p\to0^+}\frac{x^p-1}p=\log(x)$ and the left side dominates the right. I don't know where the second integral sign comes from.
Comment: I am sorry that I write it not clearly. Since $|f(x)|^p \rightarrow 1$ pointwise if $f\neq0$, then $\lim\limits_{p\to 0}\dfrac{|f(x)|^p-1}{p} =\log f(x)$ pointwise. But how to find the dominator for  $\int_X \dfrac{|f(x)|^p-1}{p}$? The inequality you mentioned is in reversed sign.
Comment: Thanks! But one more question, how can you take the limit inside since there are some $p$ multiplied in front of it $ \lim_{p\to0}\frac1p\log\left(1+p\int_X\frac{|f(x)|^p-1}{p}\,\mathrm{d}\mu\right) $, I am not sure that how we can take the limit inside.

How to calculate $|f|_{0}$?


Web Audio API - record to MP3?

Question: I am asking because I couldn't find the answer anywhere.
I have successfully implemented RecorderJS in order to record microphone input in JS. However, the recorded file is WAV which results in large files. I am looking for a way to record with JS directly to MP3, or encode the bits somehow to MP3 instead of WAV.
How can it be done? Is there a Web Audio API function that can do that or JS MP3 encoder of some sort?
Comment: I only know of the other way round decoding, meaning going from MP3 to WAV - https://github.com/audiocogs/mp3.js. You will probably need to dig into https://github.com/kripken/emscripten to get a wav to mp3 encoder in JS.
Comment: Thanks, I am looking into Emscripten but I still don't see how it can help.
Comment: Well you need to get some C-Written wav-mp3 decoder, and than decode wav into mp3 in the browser :)
Answer: The only Javascript MP3 encoder I've seen is https://github.com/akrennmair/libmp3lame-js, which is a port using emscripten.  It's supposed to be slow, and I've never used it.
I don't know of any natively-written Javascript MP3 encoders, and encoding is not covered by the Web Audio API.
Answer: There's a library written in pure javascript, called lamejs. To encode mp3s from raw audio. It is much faster than emscripten compile of libmp3lame. https://github.com/zhuker/lamejs
Example usage:
lib = new lamejs();
mp3encoder = new lib.Mp3Encoder(1, 44100, 128); //mono 44.1khz encode to 128kbps
samples = new Int16Array(44100); //one second of silence
var mp3 = mp3encoder.encodeBuffer(samples); //encode mp3

Comment: lamejs worked well for me. It seems to have no trouble keeping up with realtime, eliminating the need for worker threads. I created a test page at [my site](https://aws.nlited.org/mp3.htm) with a detailed explanation.
Answer: I was frustrated with this problem, and existing solutions, so I came up with something simpler:
https://github.com/sb2702/audioRecord.js
Usage
Create a recorder object (async because requires user permission)
    Recorder.new(function(recorder){

    });

Start recording
         recorder.start();

Stops recording
         recorder.stop();

Export as mp3
         recorder.exportMP3(function(mp3Blob){

            console.log("Here is your blob: " + URL.createObjectURL(mp3Blob));

          });

Mostly based on RecorderJS, but changed some things around to export to mp3 files, and to not have to muck around with AudioContext  / navigator.getUs
Answer: I have found a nice library with live demos: MediaStreamRecorder
One of demos is here: Audio Recording
RecordRTC is also can be useful but MSR it seems is easier to start with.
Answer: Encoding into smaller formats is currently only supported by Firefox:

http://w3c.github.io/mediacapture-record/MediaRecorder.html
https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder

Chrome        Firefox (Gecko)  Internet Explorer  Opera           Safari (WebKit)
Not supported  25.0 (25.0)     Not supported      Not supported   Not supported

AFAIK only OGG is supported. But better OGG than WAV.
Answer: To record mp3 using javascript without any other framework using a web worker, you can use this project: https://github.com/nusofthq/Recordmp3js which is also very well explained here:
http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/
With this, it's also possible to write to a .mp3 file and to make it downloadable.
Answer: I made an easy-to-use wrapper for lamejs for my project. It records to MP3 in mono or stereo at any bitrate. You just tell it what AudioNode you want to record.
    import { Mp3Recorder } from './Mp3Recorder.mjs';

    let recorder = new Mp3Recorder();

    await recorder.configure(inputAudioNode, channels, bitRate);

    recorder.start();

    recorder.pause();

    recorder.resume();

    let bytes = await recorder.getRecordedSize();

    let mp3 = await recorder.stop();

For instance, to record the user's microphone in mono at 128 kbps:
    const audio = new AudioContext();
    let micStream = await navigator.mediaDevices.getUserMedia({ audio: true })
    const mic = audio.createMediaStreamSource(micStream);

    await recorder.configure(mic, 1, 128);
    recorder.start();

    // ...later, when you're ready to stop recording:
    let mp3 = await recorder.stop();

Live demo and source here.

Web Audio API - record to MP3?


Trigger event when angular 2 model value is complete binding in the view

Question: I need generate pdf from a angular 2  page automatically, when all the model value was load on the page. How can I know when all the model information was loaded into the view?
Comment: I think you're after `MutationObserver`
Comment: How do you load your model ? Can you give more details ? But as it said bellow take a look at subscribe method
Answer: If your model is coming through an @Input() you can use the OnChanges module to track when the data is loaded. If you are loading the data through a promise, you can use a .subscribe() function to know when data is loaded, like this
this.myModule.myFunction().subscribe(success => {createPDF()})
But I don't know how to observe when the data is actually displayed in the html, but you could use a debounceTime or a setTimeout


Do new routes require a static first portion?

Question: Using mymodule.routing.yml, I can successfully create a custom route at /foo/{bar}/{baz}, but I cannot use /{bar}/{baz} or /{bar}/foo/{baz} as path for a route; they just return a 404 error.
Why? Is there any way to create a route for /{bar}/{baz} (with strict requirements for bar)?
I've read the entirety of the routing API and I can't seem to find any answers.
Comment: "Do new routes in Drupal 8 *require* a static first portion?" - yes.
Answer: In the routing system you can't do this. What you can do is path aliasing.
Inbound: /{bar}/foo/{baz} -> /foo/{bar}/{baz}
Outbound: /foo/{bar}/{baz} -> /{bar}/foo/{baz}
You need a pattern to apply a regular expression on the path inbound, so /{bar}/{baz} is only possible if the parameters themselves have a distinctive pattern.
I didn't find a tutorial how to build a path processor, but you can use the
PathProcessorFront class as example.
Register both as tagged service in the .services.yml file for the module.
services:
  path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']

Comment: Awesome, that even answers the next question I was going to ask!
Answer: See Routing System on Drupal.org.

Path (required): The URL to the route, with a leading forward slash (e.g., path: '/book'). You can use dynamic properties by including them in curly braces. (e.g., path: '/node/{node}/outline'). These will be passed along as arguments via parameter converters to the controller/form (see below). Note that the first item of the path must not be dynamic. You can also define optional parameters at the end of your path (See 'Optional Parameters' on this page).

I hope this is enough to understand that routes cannot start with a slug.  It must be a static value.
Comment: Voting up for the attempt, but screenshots aren't very useful to this community, I suggest a quote instead, this may be why you received a downvote.
Comment: Yep. I've added some emphasis to the bit that really answers the question too.


Blind source separation of convex mixture?

Question: Suppose I have $n$ independent sources, $X_1, X_2, ..., X_n$ and I observe $m$ convex mixtures:
\begin{align}
Y_1 &= a_{11}X_1 + a_{12}X_2 + \cdots + a_{1n}X_n\\
...&\\
Y_m &= a_{m1}X_1 + a_{m2}X_2 + \cdots + a_{mn}X_n
\end{align}
with $\sum_j a_{ij} = 1$ for all $i$ and $a_{ij} \ge 0$ for all $i,j$.
What's the state of the art in recovering $X$ from $Y$?
PCA is out of the question because I need the components to be identifiable.
I've looked at ICA and NMF - I can't find any way to impose nonnegativity of the mixing coefficients for ICA, and NMF doesn't seem to maximize independence.
Comment: I would think that this should be called "nonnegative independent component analysis", but it seems that this name has been used for ICA with the nonnegativity constraint on the sources $X$, not on the mixing matrix $A$ (https://www.eecs.qmul.ac.uk/~markp/2003/Plumbley03-algorithms-c.pdf). So this does not apply to your case. Interesting question.
Comment: What ICA algorithms have you tried? I'm a little rusty, but think the non-negativity assumption of the mixing coefficients can be imposed in some algorithms that assume certain models for the signals like the Weights-Adjusted Second Order Blind Identification (WASOBI) algorithm, as it assumes you can model the signals as AR processes and, thus, you can impose conditions in the coefficients.
Comment: The sources are all supported on the set {1,2,...,96}
Comment: This is not unique. https://link.springer.com/article/10.1007/s11634-014-0192-4 Mixture distributions are ubiquitous and also problematic for those organic applications that I have examined. I have yet to see a circumstance in which they are preferred over dependent processes like convolutions of components upon testing.
Comment: Your question looks like a difficult open research problem. It would be really cool if it gets answered here, but alas, there are not many specialists on ICA here (as manifested by the very low number of views and only a single upvote of your question), perhaps even none. Was a brave move to offer a bounty!
Comment: @amoeba I was worried it might just be open. But I'll hold out hope for the next 6 days!
Comment: @user43228 Can you give some context for the problem (ie what the sources are, why you need to solve it)? Also, more specifically: do the sources have a known, finite support?
Comment: Can you explicitly state in your question whether you are looking to discern independent signals, i.e. the matrix $A$ containing the coefficients $a_{ij}$ should be orthogonal?
Comment: @means-to-meaning The mixing matrix is nonnegative and the convex mixtures are true mixtures, i.e. this is not a vector quantization problem, so I don't think A should be orthogonal. As stated in the question, I am looking to as best as possible recover the signals under the assumption they are independent.
Comment: @Néstor These signals aren't really time series; I'm not sure they qualify as AR processes. But I don't know almost anything about the area so that could be wrong.
Comment: It doesn't matter if they are time series or not. AR models work fine on any indexed series, not only on time series.
Comment: Don't you want the sums to run over j instead of i? Can you assume the sources are approximately gaussian? if they are unimodal and have sufficiently fast decay, it is possible that fitting a GMM would suffice.
Comment: @YairDaon Ah yes thanks, good catch. Unfortunately the sources are discrete and don't even look like mixtures of gaussians. But perhaps I could coarsely approximate them as gaussian mixtures and then further refine. But it would be nice to have something more general/robust
Comment: See my answer below with links to nonnegative independent component analysis.
Answer: What you are looking for is Non-negative Independent Component Analysis (nICA). nICA is a variant of ICA that incorporates non-negativity constraints, hence it maintains the desirable properties of ICA (maximization of statistical independence of the reconstructed sources) while also imposing non-negativity of the mixing coefficients. If would like to have both nonnegativity constraints and linear equality constraints on the mixing coefficients then you would need to use a quadratic programming solver (e.g. osqp) to calculate the updates, though I haven't seen an off-the-shelf implementation. See this article and references therein and Chapter 11 in this book. Here is a Matlab implementation, and here is a Python one of nICA, which would be a good start and with some modification could be made to also allow for linear equality constraints.
Answer: This is just ICA with a constraint on the mixing matrix. Look up an ICA book or survey paper for cost functions associated with ICA, using fixed or adaptive source distributions depending on the distribution of the components. Then add a constraint that the rows of the mixing matrix satisfy the equality and inequality constraints, and use the update rule as the direction in a non-linear programming routine.
Comment: The ICA book by Hyvarinen would be a good start. The update rules for Extended Infomax or FastICA, formulated in terms of the mixing matrix rather than the unmixing matrix, represent a direction related to the gradient, for the vectorized mixing matrix. This can be used in a standard non-linear programming routine with equality and inequality constraints. The cost function, which is basically a log likelihood, has to be formulated as well. The Hyvarinen chapter on Maximum Likelihood methods should provide a likelihood function and corresponding (natural) gradient update.
Comment: I think the BSS book by Cichocki has natural gradient updates for the mixing matrix if the Hyrvarinen book doesn't.
Comment: This is correct, but the OP would be better helped if you could give a good link to "an ICA book or survey paper for cost functions associated with ICA"... You also need to be a bit more specific than "and derive update rule using an optimization method". What optimization method in this case? Quadratic programming?
Answer: It could be achieved by using an exponential non-linearity instead of the typical/default tanh(), if X is also non-negative.
Formula 40 in https://www.cs.helsinki.fi/u/ahyvarin/papers/NN00new.pdf and available in most implementations.
E.g. in sklearn simply use fun='exp'
https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.FastICA.html
Comment: Welcome to Stats.SE. Can you please edit your answer and expand it in order to explain the key steps of the links you provide? This way, the information is searchable in here (and sometimes links break). You may want to take a look at some [formatting help](https://stackoverflow.com/editing-help). While you're at it, you can use [LaTeX / MathJax](https://math.meta.stackexchange.com/q/5020).
Comment: I don't think this would work - with transformation one also wouldn't have independence on the original scale - typically one would like hard nonnegativity constraints in problems like this... Nonnegative independent component analysis is what you would need here, see Chapter 11, https://www.google.be/books/edition/Blind_Source_Separation/hQeaAgAAQBAJ?hl=en&gbpv=1&dq=cichocki%20%22nonnegative%20independent%20component%20analysis%22&pg=PT169&printsec=frontcover. And my answer below.
Answer: Transformation of variables is a good option when that linearizes the problem. That procedure can be used to increase the correlations, reduce the residuals, and decrease the number of parameters needed to produce a good fit to the data.
For example, $\ln Y=a_0+a_1\ln X_1+a_2\ln X_2\to Y=e^{a_0}X_1^{a_1}X_2^{a_2},$ might be vastly superior to $Y=a_0+a_1X_1+a_2X_2$. A hint as to what to do is often provided by examination of the data or its residuals. For example, if one has fan shaped heteroscedasticity of parameters, like in this paper

That particular type of log-log transform may be of interest. More generally, there are lots of transforms to consider: taking square roots, exponentiation, taking reciprocals, and so forth. Another indication of how one should treat the data comes from considering the physics of the problem. For example, if a regression problem cannot take negative $Y$-values, that problem may not be linear, as lines may become negative.
Comment: I don't think this would work - one also wouldn't have independence on the original scale - typically one would like hard nonnegativity constraints in problems like this... Nonnegative independent component analysis is what you would need here, see Chapter 11, https://www.google.be/books/edition/Blind_Source_Separation/hQeaAgAAQBAJ?hl=en&gbpv=1&dq=cichocki%20%22nonnegative%20independent%20component%20analysis%22&pg=PT169&printsec=frontcover. And my answer below.
Comment: @TomWenseleers Independence on the original scale is irrelevant when the original scale is unmotivated. The data above are mass (W) and volume (V) which are definite positive AND are inappropriately dimensioned to be properly related on the original scale. Frankly, I don't follow what you are saying, it doesn't compute.
Comment: Well that in this example the aim is to recover a set of orthogonal sources X_i. But what was required was orthogonality on the original untransformed scale X_i, not orthogonality on some log-log scale. And that's typically tackled using nonnegativity constrained independent component analysis (nnICA). Also, the aim is to decompose the signal in additive components, but a log transforms would decompose the signal in multiplicative components, which is not what is asked for here...
Comment: You would be claiming that a nonnegative matrix factorization would be equivalent to an unconstrained matrix factorization after log transform. But that's not the case as the latter would be a matrix decomposition into multiplicative rather than additive components. Plus we need the orthogonality constraints, so that would be nonnegative independent component analysis...
Comment: OK I see, but that's really not the question here... The question is how to deparate a number of independent sources for the cases where the observed signal is a nonnegative linear (convex) combination of the sources subject to the sources being independent of each other. Nonnegative independent component analysis would solve that problem.
Comment: @TomWenseleers Nonnegative component analysis would add nothing to the uses to which I applied the regression analysis. It can be "interesting" in certain situations, but is irrelevant to the uses to which I put the data analysis. Without transformation by taking logarithms, the regression has greater error, heteroscedascity, and lots of other red flags. Your comments are unhelpful.
Comment: Well anyway, I gave the references above. If there is heteroscedasticity it is also possible to fit models similar to nICA but using 1/variance weights, which are approx 1/(y+small epsilon) in case of Poisson noise...
Comment: @TomWenseleers Also useless.


Is it possible to do a Drush make custom installation profile?

Question: Is is possible to make a selective Drush Make file?
For example:
The site has 3 modules, with 3 library files.
A normal drush make will give me all modules and files.
But it is possible to selectively, fetch some modules and files?
For example: fetch module 1 and file 1 but not 2 and 3?
Answer: You can use the OPTIONAL ATTRIBUTES
root_element[first_key][next_key] = value

The 'projects' attribute is where you define the modules/themes that
  are to be packaged with the profile. The first key is the short name
  of the project (as seen in the drupal.org/project/{projectshortname}
  URI).
These projects are defined using the short form definition. You can
  use this form if you only want to declare the version of the
  project. The version is the value to the right of the core Drupal
  version in a full version string. For example, if you wanted to
  specify Views 7.x-3.1, you would use:

projects[views] = 3.1

For pre-releases, like CTools 7.x-1.0-rc1, use this format:

projects[ctools] = 1.0-rc1

You can also specify -dev releases of projects; however, this is
  generally NOT recommended, since it results in end users getting
  different sets of files at different times that distribution is
  built, which can cause confusing bug reports. If you really must use
  a -dev release, it's better to specify a Git revision (see below).

projects[media] = 2.x-dev

Reference

Full example drupal-org.make file.
Managing Drush make files for an installation profile.
Comment: That sounds good, but am I better with features? I want this for sites that are already set up with Aquica Dev Desktop. Can I create a "make" without the whole website? For example, a make that incorporates ONLY "ckeditor+IMCE+ their configuration settings" ? Is it possible, overkill? Features better?
Comment: @BrunoVincent if refers to the features modules vs drush make I think that you must open another question, because this is another explanation about the problem.


Is inverse of Dirichlet convolution unique ?

Question: We know that the Dirichlet inverse of the constant function 1 is the Möbius function.
I just want to confirm that Möbius function is the only function which is the inverse of constant function for Dirichlet convolution.
Can anyone confirm this ?
Thank you.
Comment: Please only use one of the two tags [tag:number-theory] and [tag:elementary-number-theory].
Answer: The general uniqueness of inverses (as far as they exist) in rings applies.
Answer: Suppose that $g_1$ and $g_2$ are two inverses of $f$. Then we have:
$$g_1 = g_1*e = g_1*(f*g_2) = (g_1*f)*g_2 = e*g_2 = g_2 $$
Using only the properties of the convolution product.