Proving $x \in \mathrm{int}(S \cap T)$ implies that $x \in \mathrm{int}(S) \cap \mathrm{int}(T)$

Question: Proposition If $x \in \mathrm{int}(S \cap T)$, then $x \in \mathrm{int}(S) \cap \mathrm{int}(T)$, where $\mathrm{int}(S)$ is the set of interior points of the set $S$.
I have proven this proposition by demonstrating that $\mathrm{int}(S \cap T) \subseteq \mathrm{int}(S) \cap \mathrm{int}(T)$, which is the typical, formal way in proving that one set is a subset of another.
Instead, could we just articulate the meaning of the symbols?
Proof
Since $x \in \mathrm{int}(S \cap T)$, then $x$ is an interior point of $S \cap T$, which is to say that $x$ is an interior point of $S$ and $T$. But this is precisely the same statement as $x \in \mathrm{int}(S) \cap \mathrm{int}(T)$. Hence, $\mathrm{int}(S \cap T) \subseteq \mathrm{int}(S) \cap \mathrm{int}(T)$.
$\blacksquare$
Is this a valid proof?
Comment: Fleablood's point is that if we say "...then x is an *oliphant* point of $S\cap T$, which is to say that x is an *oliphant* point of $S$ and an *oliphant* point of $T$," then we actually need to cite a definition for "*oliphant* point" and a reason why this might be so. A proof must not assume that what may seem obvious to you, is obvious to everyone.
Comment: Hmm, I don't quite understand your second argument. Can you write it differently? It sounds like you are saying that if $x$ is an interior point of $S\cap T$ then $x$ is an interior point of $S$, and an interior point of $T$ - but this is exactly what you are trying to prove.
Comment: What I mean is that I have proven the proposition in the "rigorous" manner, which is to show that $\mathrm{int}(S\cap T) \subseteq \mathrm{int}(S) \cap \mathrm{int}(T)$. But I was wondering if we could bypass the formal proof that I have just outlined, and instead use "wordplay," like I have done in the above post to which I raise my question. But I'll rewrite the post to hopefully better articulate my question.
Comment: "then x is an interior point of S∩T, which is to say that x is an interior point of S and T".  Why should that be true.?  That's precisely the statement you are trying to prove.
Comment: @fleablood So $x \in \mathrm{int}(S \cap T)$ is not the same as saying that $x$ is an interior point of $S$ and an interior point $T$? It seems to be true in virtue of the meaning of the word's employed, specifically $\mathrm{int}(S \cap T)$ and $S \cap T$.
Comment: No, it is the same but you can't accept that it is true without somehow demonstrating it.
Comment: If that were a given then the there is no point in the exercise at all as it'd just be a given.  Basically you are saying "It's true because it is true and is that a proof?"  No.  It isn't.
Answer: Any arbitrary point which is interior to the intersection of $S\cap T$ must also a point interior to a set which contains $S\cap T$ (a supraset). (Why?--refer to what "interior point" means here--)     Both $S$ and $T$ are suprasets to their intersection $(S\supseteq S\cap T), (T\supseteq S\cap T)$.   Thus $$\forall x: \Big(x\in\operatorname{int}(S\cap T) \implies x\in \operatorname{int}(S) \wedge x\in \operatorname{int}(T)\Big)\\ \operatorname{int}(S\cap T)\subseteq \operatorname{int}(S)\cap \operatorname{int}(T)$$
Argue for the converse.
Answer: You can't just claim being an interior point of the intersection is the same as being in the intersection of the interior points without some justification.
However the justification is simple.  If $x \in \text{int}(S \cap T) \implies$ there is an open ball $B$ around x such that $B \subset  S \cap T$.  As $ S \cap T \subset S$ and $ S \cap T \subset T$ we can say $B \subset S \cap T \subset S$ and $B \subset S \cap T \subset T$.  NOW you can point out the x is an interior point of T and an interior point of S.  So $x \in \text{int}(S) \cap \text{int}(T)$.
Answer: Without the definition of interior points, no proof.
Since you already did one side of the proof, here is the converse: if x ∈ int(S) ∩ int(T), then x ∈ int(S ∩ T).
x ∈ int(S) ⊂ S, and x ∈ int(T) ⊂ T, so x ∈ S ∩ T. And the intersection of a finite number of open sets is open, too, so int(S) ∩ int(T) is open, and x is an interior point of it. Thus, x is an interior point of S ∩ T.
Final result: int(S) ∩ int(T) = int(S ∩ T).
Answer: If a point $x$ is not in a set $S$ then we will say $x$ is a non-point of $S$, and we will write $\mathrm{non}(S)$ for the set of non-points of $S$.
I claim that $\mathrm{non}(S \cap T) \subseteq \mathrm{non}(S) \cap \mathrm{int}(T)$.
"Proof"
Since $x \in \mathrm{non}(S \cap T)$, then $x$ is a non-point of $S \cap T$, which is to say that $x$ is a non-point of $S$ and $T$. But this is precisely the same statement as $x \in \mathrm{non}(S) \cap \mathrm{non}(T)$. Hence, $\mathrm{non}(S \cap T) \subseteq \mathrm{non}(S) \cap \mathrm{int}(T)$.
Comment: Well, it's not *that* bad.  There is a condition of the definition of interior point that to be an interior point of a set a neighborhood must exist entirely in the set.  If a set exists in an intersection of sets it exists in each of the sets as well.  However, one does actually have to *state* this argument and point out that this *is* part of the definition.
Comment: @fleablood When trying to see why a proof of a true statement is invalid, I think it's helpful to look at a similar proof of an obviously false statement. I believe the question being asked is essentially "Doesn't $x \sim S \cap T$ mean the same thing as $x \sim S$ and $x \sim T$?"
Comment: I agree entirely, and I think it's not enough to say say "well it's clear" as I pointed out in the comments.  Bennedict basically scoffed and thought it was implicit in the definitions of intersection and interior.  And in a sense he is right.  Unlike an oliphant point or a non-point or hinklehufferdunk point an interior point's definition implies it and a neighbor are within a set.  And if they are in a set they are within all suprasets.  So the definition *does* imply it.  I don't the Benedict is actually ... to be continued....
Comment: ... continued ... is actually confusing $x \sim S \cap T$ with $x \sim S$ and $s \sim T$ and I don't think he'd make the same mistake with a hinklehufferdunk point.  But *my* point is even if something is "implicit" you still have to point out that it is so.  If it were *that* implicit we wouldn't have been asked to prove it in the first place.  I think among experience mathematicians it's okay to say "it's implicit as neghborhoods in the intersection of sets are in each individual sets".  This is, after all, why why state without blinking eye things like ... to be continued....
Comment: ....  $A \cap B \subset A$ because it is implicit.  Before we can state $A \cap B \subset A$ we *do* have to prove it.  Just once.  But it has to be done.  The same it true of this argument about the interior of an intersection is the intersection of interiors.  It's got a nice word play cadence and it's clear if you really think about it, but you can't just say "it's implicit" without explaining why.


No remotes/origin/HEAD with gitlab

Question: I'm pretty new to git, but I've been playing around with it on a remote server I set up and I'm pretty sure that I understand the basics.
I just set up gitlab and pushed some of my code to a new project on it. What I did was:

Get all my code in a directory
git init
git add .
git commit -m "Initial commit"
git push origin master

Where origin was set up with:
git remote add origin firstname.lastname@example.com:myproject.git

Now when I do git branch -a I see:
* master
  remotes/origin/master

Whereas when I was playing around before, I always saw:
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

I understand that the head is a pointer the currently checked out branch, so shouldn't it exist on the origin? Why wasn't it created?
Answer: Don't worry much about this remote HEAD. This line is simply artifact of the way original clone works, and represents state of remote's HEAD.
It can be considered as a default branch that is preferred by server (even on remote bare repository) - it will be checked out by your client git clone by default if -b branch option was not used.
Your local file .git/refs/remotes/origin/HEAD probably contains string ref: refs/remotes/origin/master now. You can remove it if you want (not that I recommend doing it, mind you), and git branch -a will not show it anymore.
Except for this usage of remote HEAD as default branch for first clone, for you state of remote HEAD never matters. You should only worry about state of real remote branches, not remote HEAD as it only makes sense for remote state as its default selected branch. And if remote is bare repository, it does not make much sense even on remote.
And the reason why you did not see remote HEAD when you did git remote add ..., git fetch, git pull is because in that case git did not have to make a decision on which default remote branch to pickup by default.
Answer: You can set it by command git remote set-head origin -a, which automatically set origin/HEAD to point to appropriate remote branch. Or using git remote set-head origin <branch> to specify a remote branch to point.
Also see: https://stackoverflow.com/a/8841024/1851492
Answer: I solve my problem in this way

First delete the index file in the .git folder.
Then open terminal and type git reset

No remotes/origin/HEAD with gitlab


Not able to place a lien on a project

Question: I am trying to set the VPC sharing for my organization. To start with I am trying to create a lien on central project. Even though I am the oranizational admin, I am not able to set restrict lein project removal on my organizational policy. Here is my command and error that is thrown
<code>gcloud alpha resource-manager org-policies enable-enforce     --organization ORGID  compute.restrictXpnProjectLienRemoval
ERROR: (gcloud.alpha.resource-manager.org-policies.enable-enforce) User [MyID] does not have permission to access organizations instance [ORGID:setOrgPolicy] (or it may not exist): The caller does not have permission
</code>
I did a gcloud init and also reauthorized myself. No luck. I also tried the beta command for the same. What should I do ? Please help.
Comment: Try adding the `Compute Shared VPC Admin` role to your identity at the ORG level.
Answer: A user with the orgpolicy.policyAdmin role can define an organization-level policy constraint (constraints/compute.restrictXpnProjectLienRemoval) that limits the removal of liens to just the following roles:

Users with roles/owner or roles/resourcemanager.lienModifier at the
organization level
User with custom roles that include the resourcemanager.projects.get
and resourcemanager.projects.updateLiens permissions at the
organization level.

Follow the steps mentioned below:

Authenticate to gcloud as an Organization Admin or IAM member with the orgpolicy.policyAdmin role. Replace ORG_ADMIN with the name of an Organization Admin:
<code>        gcloud auth login ORG_ADMIN
</code>

Determine your organization ID number by looking at the output of this command.
<code>        gcloud organizations list
</code>

Enforce the compute.restrictXpnProjectLienRemoval policy for your organization by running this command. Replace ORG_ID with the number you determined from the previous step.
<code>        gcloud beta resource-manager org-policies enable-enforce \
                   --organization ORG_ID compute.restrictXpnProjectLienRemoval
</code>

Note: By default, a project owner can remove a lien from a project,
including a Shared VPC host project, unless an organization-level
policy is defined to limit lien removal.

For further information, go through the Google documentation.

Not able to place a lien on a project


Android: How to Send user to Install an App on Google Play Store and then Detect Install Start and progress

Question: I'm looking to send a user to install an app from the Play Store, then once they click the install button I want to send them back to my app and show a progress bar and helpful info.
There is an app called Mistplay that does this. I know they detect the app installation, but I'm not sure if they are faking the app Install progress or not.
Any suggestions on this? I'm able to use intents to launch the play store market but I don't know how to detect the user clicking install in Play Store and sending the user back to my app or any of the steps past that.
Edit 1:
So I am able to detect when the installation finishes by including the target app in my Manifest Queries section + having this code  (overly verbose for testing) in my main activity onCreate() + onDestroy unregister.
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_PACKAGE_ADDED)
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED)
        filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED)
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED)
        filter.addAction(Intent.ACTION_PACKAGE_RESTARTED)
        filter.addDataScheme("package")
        registerReceiver(appInstallBroadcastReceiver, filter)

Comment: I've looked at that. My understanding was that it was the information of what referred YOUR OWN app to be installed. Am I understanding that incorrectly?
Comment: This might be helpful - [Google Play Install Referrer](https://developer.android.com/google/play/installreferrer)
Answer: This might be helpful :
https://developer.android.com/reference/android/content/pm/PackageInstaller
Offers the ability to install, upgrade, and remove applications on the device. This includes support for apps packaged either as a single "monolithic" APK, or apps packaged as multiple "split" APKs.
An app is delivered for installation through a PackageInstaller.Session,...
Answer: Firstly, check if INSTALL_PACKAGES permission is granted:
if ((mPm.checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
        == PackageManager.PERMISSION_GRANTED)
        || (installerUid == Process.ROOT_UID)
        || mIsInstallerDeviceOwner) {
    mPermissionsAccepted = true;
} else {
    mPermissionsAccepted = false;
}

Later, Make your app the Device owner: Refrence
Once app is device owner we can install apk without any user intervention:
public static boolean installPackage(Context context, InputStream in, String packageName)
        throws IOException {
    PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
            PackageInstaller.SessionParams.MODE_FULL_INSTALL);
    params.setAppPackageName(packageName);
    // set package name in params and create a session
    int sessionId = packageInstaller.createSession(params);
    // open session
    PackageInstaller.Session session = packageInstaller.openSession(sessionId);
    // Track install progress
    OutputStream out = session.openWrite("COSU", 0, -1);
    byte[] buffer = new byte[65536];
    int c;
    while ((c = in.read(buffer)) != -1) {
        out.write(buffer, 0, c);
    }
    session.fsync(out);
    in.close();
    out.close();

    session.commit(createIntentSender(context, sessionId));
    return true;
}

// Listens when install is complete
private static IntentSender createIntentSender(Context context, int sessionId) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context,
                sessionId,
                new Intent(ACTION_INSTALL_COMPLETE),
                0);
        return pendingIntent.getIntentSender();
    }


Alignment layout at the bottom with listview

Question: I've a framelayout with a listview and a linearlayout (bottom bar) at the bottom of this.
When expand the listview, I can't scroll properly because the linearlayout at the bottom has covered the child of listview.
I don't understand where is the problem...I would like separate the bottom bar from the listview.
This is my layout (possibly, can you optimize this layout?):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.robertot.timereport.com.robertot.timereport.pages.WeeklyStatFragment">

    <RelativeLayout
        android:id="@+id/rlList"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/listWeek"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:layout_gravity="bottom"
        style="@android:style/Widget.Holo.Light.ActionBar.Solid">

        <Spinner
            android:id="@+id/spnYearW"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="8dp"/>

        <Spinner
            android:id="@+id/spnMonthW"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"/>

        <ImageButton
            android:id="@+id/btnFilter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_search"
            android:background="@null"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"/>

    </LinearLayout>

</FrameLayout>

thanks!!
Answer: The problem is your FrameLayout doesn't prevent your Views from overlapping, which is why your ListView appears below it. One solution, that wouldn't require you to change much, would be to put your bottom LinearLayout inside your RelativeLayout and use the alignParentBottom and layout_above attributes to position things:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.robertot.timereport.com.robertot.timereport.pages.WeeklyStatFragment">

    <RelativeLayout
        android:id="@+id/rlList"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/listWeek"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@+id/bottom_linear" />

        <LinearLayout
            android:id="@+id/bottom_linear"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal"
            android:layout_gravity="bottom"
            android:layout_alignParentBottom="true"
            style="@android:style/Widget.Holo.Light.ActionBar.Solid">

            <Spinner
                android:id="@+id/spnYearW"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="8dp"/>

            <Spinner
                android:id="@+id/spnMonthW"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_gravity="center_vertical"/>

            <ImageButton
                android:id="@+id/btnFilter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_search"
                android:background="@null"
                android:layout_weight="1"
                android:layout_gravity="center_vertical"/>

        </LinearLayout>

    </RelativeLayout>

</FrameLayout>


Android webview read cookies

Question: I have the following code to display a webpage in a webview:
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.loadUrl("http://the.url.com");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Now I want to read cookie of the webview. Is this possible?
Comment: `CookieManager.getInstance().getCookie("http://the.url.com")` . http://developer.android.com/reference/android/webkit/CookieManager.html#getCookie(java.lang.String)
Comment: It is working and in the page are two cookies. How can I select only first or second cookie and its value.
Comment: Read here http://stackoverflow.com/questions/5840966/android-reading-cookies
Comment: these two cookies associated to same url?
Answer: It was a quite late , but it might help someone
you can get the cookie value by this
public String getCookie(String siteName,String CookieName){
    String CookieValue = null;

    CookieManager cookieManager = CookieManager.getInstance();
    String cookies = cookieManager.getCookie(siteName);
    if(cookies != null){
        String[] temp=cookies.split(";");
        for (String ar1 : temp ){
            if(ar1.contains(CookieName)){
                String[] temp1=ar1.split("=");
                CookieValue = temp1[1];
            }
        }
     }
     return CookieValue;
}

Edit
Point to notice:
If you are loading URL like http://sitedomain.com (without www), the siteName with www will not work with this method.
Comment: A good solution, but not right. You shouldn't split a cookie with "=", because in a right part it may also contain "=". So, you should separate left and right parts only once with `split("=", 2)`.
Comment: Cookie name doesn't need to be pass in capital letters!! @NicolaeSurdu
Comment: Sorry, was to tired to check history. Edited the answer to reflect the current status.
Comment: I think you need a break after finding it, if you want to retrieve the first one only.
Comment: I need help to get cookies for url      (  https://www.dailymotion.com/   ) which contains www

Android webview read cookies


How to show download count of a product

Question: I am using drupal commerce for an e-commerce site. I have a view for listing the product. I want to show download count oof each product in product listing page as mentioned in the screenshot. How can I achieve this?
Answer: You can do it by setting up a view of product line items, adding both the product and order relationships, filtering by order state, turning on aggregation, grouping by Product ID and summing on the line item's quantity field.
Else try the https://www.drupal.org/project/commerce_reports commerce reports module.

How to show download count of a product


Angular Typescript Map to JSON

Question: How can I use JSON.stringify with a Typescript Map.  The presumption is the Map keys are all strings.
In this example, the console output is an empty {}
<code>const myMap = new Map<string, Employee>();
myMap.set('employee1', new Employee());
myMap.set('employee2', new Employee());
myMap.set('employee3', new Employee());

console.log('myMap', JSON.stringify(myMap));
</code>
Answer: this way you can stringify the Map value
<code> JSON.stringify([...myMap])
</code>
and if you want to convert the value back to Map
<code> let obj = JSON.parse(stringifyValue)
 let myMap = new Map();
 for (let k of Object.keys(obj)) {
   myMap.set(k, obj[k]);
 }
</code>
check this Converting ES6 Maps to and from JSON

Angular Typescript Map to JSON


alterar classes com angularjs

Question: Eu preciso mudar o estilo de um elemento quando clicado e se clicar de novo ele volta pra cor que tava (como se fosse uma "busca avançada").
Eu tenho o seguinte código:
...

    <form ... />
</>

Quando eu clicar no  ele tem que ficar com corAzul e abrir a div com o form. Se eu clicar de novo ele fecha a div do form e volta a corCinza.
O form já está funcionando, mas eu não consegui mudar a cor.
Tentei usar o ng-class como num "tutorial" mas não funcionou.
Alguém pode me ajudar?
P.S.: Eu só "programo" html e css. O máximo que codei foi um helloWorld simples em JS.
Answer: Você pode usar o ng-class que trabalha com condição, alterando a classe do elemento. Exemplo:

Quando exibirForm for false, a classe corAzul será adicionada.
Você também pode utilizar com mais de uma definição de classe, caso queira remover a classe existente, por exemplo:

Deste modo ele só exibe uma classe por vez.
Comment: Nossa @CelsomTrindade, eu estava pensando em soluções "mais complexas". Isso funcionou muito bem. Obrigada!
Comment: Não por isso ;) Apenas lembre-se: classe definida dentro de `class=""` é estática, não pode ser removida através do `ng-class`. Classe definida dentro do `ng-class=""` somente será adicionada ao `class=""` se a condição conferir.
Comment: Ook!! Mais uma vez obrigada! :D
Comment: @trofonia se resolveu o problema, não esqueça de marcar a resposta como aceita =D

alterar classes com angularjs


How can I stop a ListBox control from wrapping each item in a ListBoxItem?

Question: I am creating a timeline control that uses listbox to place my items on a canvas.
There are two parts to it. The base timeline to represent an 8 hour work day and the individual timeline elements which represent the type of work with start and end times.
The timeline element can be resized using a thumb control docked to the left and right of each element. The resizing works fine if I place the timline element on a canvas directly, but as I need to maintain a list of elements I thought that a listbox would handle it for me. So I made the ItemsPanel a canvas and sure enough everything rendered nicely. The only problem was that I could no longer resize the timeline elements. Quickly I relized, that setting the canvas.Left on my element when dragging would do nothing because the element was no longer on the canvas but inside a listboxitem (which is on the canvas).
Is it possible to have a Listbox stop wrapping each item in its own listboxitem and wrap them in say a custom ContentControl instead?
Comment: @Ilya: It must be. He's talking about a `Canvas`, so that's definitely not WinForms.
Answer: Try this:
class MyListBox : ListBox
{
    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
        return new ContentControl();
    }
}

Reference: How to change the default item container for ItemsControl?
Answer: It is possible by adding a UIElement directly to ListBox.Items (or ItemsSource). However, I'd recommend instead using ItemContainerStyle to change Canvas.Left and Canvas.Top. This style allows you to control properties on the container (the ListBoxItem) generated for each item in your ItemsControl.
<ListBox ItemsSource="{Binding MyItems}">
    <ListBox.ItemContainerStyle>

    </ListBox.ItemContainerStyle>
</ListBox>

Comment: Thats exactly what I have now and displays fine, the problem comes when I need to drag the thumb control on an timeline element to resize it. It cant work as the timeline element (which is a ContentControl) is not directly on the canvas. its wrapped up in the ListboxItem. I would need to apply the thumb control to the listboxitem instead for it to work.


Space between lowercase and uppercase letters in a string in JavaScript

Question: I want to add a space between a lowercase and uppercase in one string. For example:
FruityLoops
FirstRepeat

Now I want to add a space between the lowercase and uppercase letters. I don't know how I should start in JavaScript. Something with substr or search? Can somebody can help me?
Comment: @close voter: How exactly is this a duplicate of an XSLT question?!
Answer: var str = "FruityLoops";

str = str.replace(/([a-z])([A-Z])/g, '$1 $2');

Example: http://jsfiddle.net/3LYA8/
Comment: @Frank, @patrick: Note that this will not add spaces between adjacent capitals, e.g. "FruityXLoops" => "Fruity XLoops", not "Fruity X Loops". Whether that's a feature or a bug is down to you, Frank. :-)
Comment: @Matt: It's better to have been up-voted and lost, than to have never been up-voted at all. :o)
Comment: @patrick: hey now, I re-upvoted when you corrected the bug in your answer.
Comment: @Matt: Yes I saw that you re-up-voted. It was a poor transfer between a console version and a jsFiddle version. My console version worked, but was looser, then somewhere in the mix I only grabbed part of the revision. I figured that's why you removed it at first, and appropriate it was. Yoda?
Comment: @T.J. Crowder: Feature. *Always* a feature. ;o) Actually OP does state *"a space between the lowercase and uppercase"*.
Answer: something simple like that :
"LoL".replace(/([a-z])([A-Z])/g, "$1 $2")

is maybe sufficient ;)
Answer: You can do it with a manual search, but it may be easier with a regex. Assuming:

You know it starts with a capital
You don't want a space in front of that capital
You want a space in front of all subsequent capitals

Then:

function spacey(str) {
    return str.substring(0, 1) +
           str.substring(1).replace(/[A-Z]/g, function(ch) {
        return " " + ch;
    });
}

alert(spacey("FruitLoops")); // "Fruit Loops"

Live example
More efficient version inspired by (but different from) patrick's answer:
function spacey(str) {
    return str.substring(0, 1) +
           str.substring(1).replace(/([a-z])?([A-Z])/g, "$1 $2");
}

alert(spacey("FruityLoops"));  // "Fruity Loops"
alert(spacey("FruityXLoops")); // "Fruity X Loops"

Live example
Comment: Only solution I could find that deals with adjacent capital letters!! +1, good sir.
Comment: What does this mean - /([a-z])?([A-Z])/g, "$1 $2" ??? Look for small words that have small case letter followed by big. The small is optional. Put a space between the first group (small letter) and second group (capital)?
Comment: @stack1: Not words, characters. Other than that, yes, spot-on.
Answer: The regexp option looks the best. Getting the regexp right appears to be tricky though.
There's another question here with some more complex options to try:
Regular expression, split string by capital letter but ignore TLA
Comment: Most of that thread you link to is specific to C#, and won't work in JavaScript.


PHP-FPM occasional "FastCGI: failed to connect to server" error

Question: <code>Ubuntu 14.04.3 LTS
Apache 2.4.7
PHP 5.5.9
</code>
I switched from mod_php to PHP-FPM about two weeks ago.  Everything, for the most part is running smoothly.  Except twice now I've had a situation where apache/php would become unresponsive. A restart would fix the issue, however I'd like to know why this is happening.  Here are the error logs, its filled with hundreds of the similar type of error.
<code># /var/log/apache2/error.log
.
.
[Wed Dec 16 23:19:21.476641 2015] [fastcgi:error] [pid 32523] (104)Connection reset by peer: [client xx.xx.xx.xx:43676] FastCGI: comm with server "/usr/lib/cgi-bin/php5-fcgi" aborted: read failed
[Wed Dec 16 23:19:21.476866 2015] [fastcgi:error] [pid 32411] (2)No such file or directory: [client xx.xx.xx.xx:63082] FastCGI: failed to connect to server "/usr/lib/cgi-bin/php5-fcgi": connect() failed
[Wed Dec 16 23:19:21.477489 2015] [fastcgi:error] [pid 32527] (104)Connection reset by peer: [client xx.xx.xx.xx:49675] FastCGI: comm with server "/usr/lib/cgi-bin/php5-fcgi" aborted: read failed
[Wed Dec 16 23:19:21.478270 2015] [fastcgi:error] [pid 32548] (2)No such file or directory: [client xx.xx.xx.xx:59140] FastCGI: failed to connect to server "/usr/lib/cgi-bin/php5-fcgi": connect() failed
.
.
</code>
Apache config
<code># /etc/apache2/conf-available/php5-fpm.conf
<IfModule mod_fastcgi.c>
    AddHandler php5-fcgi .php
    Action php5-fcgi /php5-fcgi
    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
    FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

    <Directory /usr/lib/cgi-bin>
        Require all granted
    </Directory>
</IfModule>
</code>
PHP5-FPM Config ( included what I thought may be helpful )
<code># /etc/php5/fpm/pool.d/www.conf
listen = /var/run/php5-fpm.sock
.
.
user = www-data
group = www-data
.
.
pm.max_children = 10
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 1
pm.max_requests = 500
.
.
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
.
.
</code>
Connecting to sockets
<code># lsof -U | grep php
php5-fpm  14373   www-data    0u  unix 0xffff8801ff42bb80      0t0   1721 /var/run/php5-fpm.sock
php5-fpm  17084   www-data    0u  unix 0xffff8801ff42bb80      0t0   1721 /var/run/php5-fpm.sock
php5-fpm  18544   www-data    0u  unix 0xffff8801ff42bb80      0t0   1721 /var/run/php5-fpm.sock
php5-fpm  18544   www-data    4u  unix 0xffff8800da1e7700      0t0 701371 /var/run/php5-fpm.sock
php5-fpm  18649   www-data    0u  unix 0xffff8801ff42bb80      0t0   1721 /var/run/php5-fpm.sock
php5-fpm  19672   www-data    0u  unix 0xffff8801ff42bb80      0t0   1721 /var/run/php5-fpm.sock
</code>
Please let me know if there is any other information needed to help figure this out.  As I've stated this has only happened twice now. Thanks
Comment: Try to use -idle-timeout paramater on "FastCgiExternalServer" line to solve this problem.
Comment: I'll give it a shot and see how it behaves the next few days.
Answer: Don't use a socket for this purpose. They block too much to support even a medium-load site with lots of requests coming in. Use a TCP socket instead to connect httpd to php-fpm.
Refer to this for instructions: https://wiki.apache.org/httpd/PHP-FPM (look at the section entitled "TCP socket (IP and port) approach").
You also don't have very many workers set up. I usually recommend around two per available CPU core (assuming that most web requests will take 500ms). You can do your own math based on your average response time. If you need more workers to support your load, get more servers.
Answer: I've been able to solve the connection errors.  I did not have enough resources allocated to php-fpm.  I've increased the amount of workers ( thanks Joel ), set a timeout limit ( thanks Froggiz ) and set a max_requests value.  The following post explains in detail the issue I was having.
https://stackoverflow.com/questions/18009479/random-php-fastcgi-connection-reset-by-peer-incomplete-headers
Thanks!


Variance for hit-and-miss Monte Carlo method and importance sampling

Question: Variance for Hit-and-Miss Monte Carlo is given by $Var(\theta)=\frac{\Theta*(1-\Theta)}{N}$ where $\theta$ is the estimated probability of Hit and N is the number of simulations. Can someone explain why? And what will be the variance when Importance Sampling is used?
Comment: How do you define importance sampling in connection with hit-and-miss Monte Carlo? With no restriction, the minimal variance of an importance sampling estimate is zero.
Answer: The first is just the variance of $\hat{p} = X/n$ in a binomial.
If $X$ is the number of "hits" in $n$ trials,
$$\newcommand{\Var}{\operatorname{Var}}\Var(X) = n\theta(1-\theta)$$
(Wikipedia on the Binomial Distribution).
So
$$\Var(X/n) = \frac{1}{n^2} n\theta(1-\theta) = \frac{\theta(1-\theta)}{n}.$$
For a comparison of the variance between the plain binomial case and importance sampling, see this section of the Wikipedia article on importance sampling.


how i can Find the files inside the folder and save the file names in variables?

Question: how i can write bash file to Find files (number and name of files are variable) inside the folder and save the file names in variables ?
Answer: Put them in an array.
<code>files=(*)
</code>
Comment: ... That didn't help. Just use the array.
Comment: but how i can find it (search about it) inside the folder then i will save it
Comment: ... What does that even mean?
Comment: bash to proccess all files example for what bash do ? folder x contain 5 files bash search fild file no.1 and save name of it in variable y=no.1 ... this bash finshed its work when visit all files


Syntax for getting plain field value in computed field

Question: I have a couple of simple computed fields that combine other fields (such as first name and last name) but I'm not getting the right values from the fields. I sometimes get only the first letter of a text field (maybe just on the Title field), and when I call a longtext field I'm getting all the HTML markup when I really only want the plain text version of the field.
Here's an example where I'm trying to combine a pile of fields for purposes of searching them from one box:
$omnisearch = $entity->title[LANGUAGE_NONE][0]['value']."
".$entity->body[LANGUAGE_NONE][0]['value']."
".$entity->field_prerequisites[LANGUAGE_NONE][0]['value']."
".$entity->field_keywords[LANGUAGE_NONE][0]['value']."
".$entity->field_teachers[LANGUAGE_NONE][0]['value']."
".$entity->field_organizing_center[LANGUAGE_NONE][0]['value']."
".$entity->field_location[LANGUAGE_NONE][0]['value'];
$entity_field[0]['value'] = $omnisearch;

So is there a better parameter than 'value' to pull the plain/sanitized text from the field? And why am I only getting the first character of the title? I only theoretically grok arrays, so the answer may be obvious to others. Thanks for your help!
Answer: I'd suggest you to start by understanding the structure of your entity. You could do something like
<?php print_r($entity); ?>
 to print on screen your entity object and understand how to reference each one of its fields.
You'll discover that you could get your title just by using $entity->title (in your example you are getting the first letter because you are treating it as an array).  You could also find that not all your fields might be have by the 'value' key.
Once you do that, you could get the fields values using field_get_items(). A basic example:
$items = field_get_items('node', $entity, 'field_keywords', $entity->language);
$item = array_shift($items);
$keywords = $item['value'];

And maybe you could take it one step further and wrap that in a reusable function:
/**
 * Get a node field's first value.
 */
function YOUR_MODULE_node_get_field_single_value($node, $field_name, $key) {
  $items = field_get_items('node', $node, $field_name, $node->language);

  if (!empty($items)) {
    $item = array_shift($items);
    return isset($item[$key]) ? $item[$key] : NULL;
  }
  else {
    return NULL;
  }
}

And call it like this (assuming that this field has a single value in it):
$keywords = YOUR_MODULE_node_get_field_single_value($entity, 'field_keywords', 'value');

Please note that the above function is just an example, your field might have multiple values in it. In that case, you'll need to iterate the array returned by field_get_items.
Comment: Thanks! I don't have access to the site files (eg: theme or modules) so I can't make a function or easily print_r. I'm trying to get all this done via the Computed Field module which takes a PHP argument to calculate the value to output. I'll see if field_get_items will work here.
Comment: Yeah, basically any PHP code will work in the "Computed code PHP" textarea available in any computed field. So you should be fine. Let me know if you run into any issues.

PD. Please note it's not a good practice to include PHP code in a field, but if it's your only option, go ahead.
Comment: In the computed field I've tried: Computed Code (PHP):
'$entity_field[0]['value'] = print_r ($entity);'

Display Code (PHP):
'$display_output = $entity_field_item['value'];' which results is "1". And I also tried creating a block with PHP input with '' which throws the error: 'Notice: Undefined variable: entity in eval() (line 2 of /home/public/modules/php/php.module(80) : eval()'d code).' I think there is other stuff going on here which I can't control, as I'm not the owner of the site.
Comment: Well dang. I just discovered a new kind of View filter that I'd never seen before. This actually solves my problem without the use of the computed field at all: http://drupal.stackexchange.com/questions/73731/how-do-you-combine-exposed-filter-string-text-searches-into-one-input-field-for  Thanks for your help, @Typologist!
Comment: Awesome, I'm glad you found a solution :)


Small, downward-pointing diagonal line in Chopin's Ballade in G Minor

Question:
The small diagonal line shown above comes from Chopin's Ballade #1 in G minor, measure 170. What does the small diagonal line between the two notes mean?
Comment: Please show that bar and the ones either side.
Comment: Related question: [What does this split stem notation mean?](https://music.stackexchange.com/q/24030/70803).
Answer: It is a "chord" consisting of both B flat and B natural.
The 19th-century notation for this was just two notes on the same stem, with two accidentals (flat and natural) in front of them. In the 20th century some composers started using two separate notes joined by a "forked" stem. The OP's graphic looks like a poor attempt to reproduce this with an (unknown) notation software application that can't do it right - or the user didn't know any better.
Klindworth's edition (1880): (note the horrible 5:3 tuplet notation with the tiny slur over the 5!)

Breitkopf und Härtel (1878) has staccato dots over the notes, which somebody may have mistaken for the slanting line:

More modern notations:
Comment: Nice detective work.  Given that the original slant bar doesn't even show up in Dolmetsch's list, this looks like a good interpretation.
Comment: Sorry for the late reply and thanks for the answer. And yes, it is Chopin's Ballade.
Answer: The B natural and B flat should be played together as a chord.
The notation in the OP is an attempt to reproduce the one used in the 1894 Mikuli edition of the Ballade.

The more modern notation mentioned by user19146 is used, for example, in the Dover/Paderewski edition (1981).
Answer: Looks like a slide.  You can't do that on a piano, but you can emulate smearing from B natural to B flat (which I presume this notation is supposed to suggest) by striking both right after another and releasing the B natural after striking the B flat and then release the B flat "regularly" on time.
Probably intended to render a "blue note".
Comment: Normally the first note will be written as a grace note, smaller than the ordinary dot.
Comment: -1. This is Chopin, not 20th century notation!
Comment: @alephzero you sure about that?  I don't see that note pair in an IMSLP copy.
Comment: I don't see a match in the Grieg either...
Comment: @CarlWitthoft See my answer, when I've finished writing it!
Comment: .... or Brahms...
Comment: @Tim not if it really is the Chopin ballade - it's not a grace note.


Dynamically building collection to loop over in Airflow dag

Question: I have been working with Airflow a lot recently and finding a very common pattern is to loop over some collection to create multiple tasks. Very similar to the example_python_operator.py dag found in the example dags folder in github.
My question has to do with dynamically building up the collection the loop is iterating over. Let's say you want to create a task for each of an unknown set of clients stored in a database and you plan to query them as a means to populate your list. Something like this:
first_task = PythonOperator(
    task_id='some_upstream_task',
    provide_context=True,
    python_callable=some_upstream_task,
    dag=dag)

clients = my_database_query()

for client in clients:
    task = PythonOperator(
        task_id='client_' + str(client),
        python_callable=some_function,
        dag=dag)

    task.set_upstream(first_task)

From what I have seen this means that even if your dag only runs weekly your database is being polled every 30 seconds for these clients. Even if you set an upstream operator from the iterator and return the clients via xcoms and replace the my_database_query() with an xcom_pull() your still polling xcoms every 30 secs. This seems wasteful to me, so I'm wondering if there are any better patterns for this type of dag?
Comment: I think dynamic DAG is a bad practice in Airflow. On each DAG rendering, all previous DAG runs will be changed. You might lose some history/logs + you can accidentally trigger unneeded execution as tasks in old DAG runs will be added in "no state". If you touch such DAG run they will be triggered.
Comment: https://stackoverflow.com/questions/55672724/airflow-creating-dynamic-tasks-from-xcom This should give you some ideas
Answer: In your code sample we don't see the schedule interval of the DAG, but I'm assuming that you have it scheduled let's say @daily, and that you want the DB query to run once a day.
In Airflow, the DAG is parsed periodically by the scheduler (hence the "every 30 seconds"). So your python code causes an issue.
In your case, I would consider changing perspective : why not trying to run the database query in a PosgresOperator link and then make that part of the DAG ? Based on the output of that Operator (that you can propagate via XCOM for example or via a file in Object Storage) you can then have a PythonOperator downstream that does not run a function for one client but for all of them.
Comment: this seems to intuitive but airflow doesn't support this behavior since xcoms are generated at runtime not at parse time. Hence while those xcoms values would never be available for building dag. File Object will cause the same issue since at the time of parsing File object should be present. I am trying to implement same but it seems to be impossible to do it without having top level python fetching values from database.


What is the process for determining transitivity of a relation set?

Question: Given the relation on the set $\{1,2,3,4\}$ why is
$\{(2,2),(2,3),(2,4),(3,2),(3,3),(3,4)\}$ considered to be transitive?
As I go through it I can see that we have $(2,2)$ and $(2,3)$ so we'd need $(3,2)$ as well. But then I see $(3,3)$ and $(3,4)$ but not $(4,3)$? Obviously my processing of this is flawed, so I am asking this:
What is the process one would go through to determine if a relation set is transitive? Does the sequence/ordering of the set matter? I feel there's a key I don't understand yet.
Comment: ordering matters. If you compose (2,2) and (2,3) you get (2,3) which is already there. (You do not get (3,2).) If you compose (3,2) and (2,4) you get (3,4) which is already there. In general a relation is transitive if it is the same as its transitive closure https://en.wikipedia.org/wiki/Transitive_closure
Comment: Oh, sorry. I'm pretty new here so I didn't think it was such an issue. I appreciate you taking the time to do it for me.
Comment: Ah, that makes a lot more sense then!
Answer: You've misunderstood transitivity. Transitivity says that if $(x,y)$ and $(y,z)$ are in the set, then $(x,z)$ must also be; transitivity tells us nothing about $(z,x),(z,y),$ or any other ordered pair made from these elements.
With transitivity, $(3,3)$ and $(3,4)$ together only imply that $(3,4)$ and $(3,3)$ must be part of the set, which they clearly are. The situation is exactly the same for $(2,2)$ and $(2,3)$; $(3,2)$ may be in the set, but we could exclude it without violating transitivity.
But we do have things like $(2,3)$ and $(3,2)$ in our set, and it would not be transitive if we didn't have $(2,2)$ in as well. Likewise, if we notice that we have $(3,4)$ and $(2,3)$, we'd better have $(2,4)$, which we do.


Does sample size have measurement unit?

Question: Sample size (n) refers to the number of participants or observations included in a study through which statistical inferences for the whole population are made. Can sample size have measurement unit, such as $km^2$ (kilometre square)?
In a paper on hydrology, researchers collected data from some areas, but they didn't specify the number of areas, rather said they collected the data from a area of size $20km^2$. Is this $20km^2$ the sample size in the study? I didn't find any other information in the paper which can be potential as a sample size.
Answer: Yes, $km^2$ can be used as a measurement unit but I would say that 20$km^2$ is not the sample size but rather than these 20 $km^2$ are part of the sample area of the study. For example, if we have 10 areas of 2 $km^2$ each, our sample size is $n$=10 with a total sample area of 20 $km^2$.
Usually in cases where the sampling area (or time) is varying among our samples we would consider using that information as an offset in our analysis. As such we would not have to explicitly transform our response variable; see the CV.SE: When to use an offset in a Poisson regression? for more details.
Comment: Thank you for your reply. If another study report $12km^2$ of area with $3km^2$ for each, then it will become $n=4$. Is that the region behind using offset since each area size is variant?
Comment: Will the adjustment for including an offset is always dividing the response by the offset? That is, (response/area size) in my particular case?
Comment: In this example: while the original study would have an offset of 2 this new study would have an offset of 3 ($km^2). It  does not necessarily "divide" our response, rather it controls for proportional changes across a dimension (usually time or area) that are irrelevant to our research question.

Does sample size have measurement unit?


AngularJS Controller instance method

Question: I have an angular js controller that I am writing in a way so other controllers can inherit from it. Instead of defining the function as a single one in the angular's controller function I am writing it in the following way:
<code>   function SomeCtrl($scope)
   {
       this.some_field = "1234";
       this.scope.externalMethod = angular.bind(this, this.externalMethod);
       this.scope.anotherMethod = angular.bind(this, this.anotherMethod);
       return this;
   }

   SomeCtrl.prototype.externalMethod = function()
   {
       //Do something
       //....(Don't worry about this method, its just to highlight that I can call this method from $scope.externalMethod)
   }

   //These are the methods of interest
   SomeCtrl.prototype.instanceMethodOne = function()
   {
       //Do something....
   }

   SomeCtrl.prototype.anotherMethod = function()
   {
       this.instanceMethodOne(); //---> Problem here!
       //Carry on
       //....
   }

   angular.module('some_module') //Previously defined
   .controller('SomeCtrl', SomeCtrl)
</code>
So the problem that I am having now is to have a reference (this) inside the method "anotherMethod", which calls a class instance method "instanceMethodOne". This resolves to null as the self reference "this" is not resolved at that point. Is there any way to reference an object inside its instance method like in this case?
Comment: What is invoking 'anotherMethod'?
Comment: anotherMethod should be invoked from $scope. In the case of unittest just from $scope itself ($scope.anotherMethod) and in the case of a view directly called from a button's press down event.
Answer: The problem has been resolved.
UPDATE AND FIXED:
Okay so I have looked into this problem. I should actually update the problem. It actually looks more like this:
<code>   function SomeCtrl($scope)
   {
       this.some_field = "1234";
       this.scope.externalMethod = angular.bind(this, this.externalMethod);
       this.scope.anotherMethod = angular.bind(this, this.anotherMethod);
       return this;
   }

   SomeCtrl.prototype.externalMethod = function()
   {
       //Do something
       //....(Don't worry about this method, its just to highlight that I can call this method from $scope.externalMethod)
   }

   //These are the methods of interest
   SomeCtrl.prototype.instanceMethodOne = function()
   {
       //Do something....
   }

   SomeCtrl.prototype.anotherMethod = function()
   {
       var aCallBack = function()
       {
          //Some stuff...
          this.instanceMethodOne(); //---> Problem here!
       }

       //Carry on
       //....
   }

   angular.module('some_module') //Previously defined
   .controller('SomeCtrl', SomeCtrl)
</code>
So the fix was to first create a reference to the object's method. That way I could call it within the callback function. The "this" in the callback function was referring to that function itself. Sorry for false alarm...This is fixed now! Thanks @sma for looking into it.
Comment: It will be good if you update this post with answer rather than pointing to the question to find answer in it.

AngularJS Controller instance method


Inserting or updating mysql datetime field with php

Question: I have a function which adds an item to the basket. In this function, it checks to see if a basket already exists for this user and creates or updates the basket accordingly. When creating or updating  the basket, I need a timeout field set to 4 hours in the future. However, when I create or update a basket, the dateTime field for the timeout is at 0000-00-00 00:00:00. Here is my code (php using the codeigniter framework):
$dateTime = date("Y-d-m h:m:s", strtotime("+4 hours"));

if($query->num_rows() != 1)
{

    $this->db->insert("baskets", array("basket_session" => session_id(), "basket_timeout" => $dateTime, "basket_delivery" => "0.00"));

}
else
{

    $this->db->where("basket_session", session_id());
    $this->db->update("baskets", array("basket_timeout" => $dateTime));

}

What am I missing?
Answer: The DATETIME format for MySQL is Y-m-d H:i:s.
Answer: TRy:
$dateTime = date("Y-m-d H:i:s", strtotime("+4 hours"));

Answer: Change
$dateTime = date("Y-d-m h:m:s", strtotime("+4 hours"));

to
$dateTime = date("Y-m-d H:i:s", strtotime("+4 hours"));


Material-UI DataGrid Component Refresh with new State Data

Question: Good morning,
We are using Material-UI to create a DataGrid table filled with users and want to be able to delete selected entries (checkbox) using a button.
Clicking the button updates the state of our object (removing the expected rows) and the DataGrid element of Material-UI takes as parameter this.state.rows (as explained in this Stack Overflow).
The logs shown below prove that the state element is indeed updated following the setState() call (blue rectangle) which re-renders the DataGrid Component (red rectangle). However nothing changes visually :(
Console Log
The code is shown below:
import { DataGrid } from '@material-ui/data-grid';
import * as React from 'react';

import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';
import DeleteIcon from '@material-ui/icons/Delete';

class EmployeeGrid extends React.Component {

    constructor(props) {
        super(props);
        this.handleDelete = this.handleDelete.bind(this);
        this.hrefs = {}
        this.columns = [
            { field: 'id', headerName: 'ID', width: 70 },
            { field: 'firstName', headerName: 'First name', width: 130 },
            { field: 'lastName', headerName: 'Last name', width: 130 },
            { field: 'description', headerName: 'Description', width: 200 }
        ];

        let employeeList = [];
        let id = 1;
        for (const employee of this.props.employees) {
            this.hrefs[id] = employee.url;
            employeeList.push({
                id: id,
                firstName: employee.entity.firstName,
                lastName: employee.entity.lastName,
                description: employee.entity.description
            });
            id++;
        }
        console.log(this.hrefs)
        console.log(employeeList)
        this.state={rows: employeeList, //populate initial state with all employees from database
                    selected: [],
                    nbRender: 1}
        console.log(this.state.rows);
    }

    handleDelete() {
        for (let id of this.state.selected) {
            this.state.rows.splice(id - 1, 1); //delete rows that were selected
            this.props.onDelete(this.hrefs[id]); //delete from database
        }
        this.setState({rows: this.state.rows, selected: [], nbRender: 2}, () => {
            console.log(this.state.rows) //checks state is indeed updated
        });
        console.log(this.state.rows);
    }

    render() {
        console.log("In render of EmployeeGrid");
        console.log(this.state.rows)
        return (

                    <DataGrid rows={this.state.rows} //populate grid with state.rows
                                columns={this.columns}
                                pageSize={this.props.pageSize}
                                checkboxSelection
                                onSelectionChange={(newSelection) => {
                                    this.setState({selected: newSelection.rowIds})
                                }}/>

                    <Button variant="contained"
                            color="secondary"
                            startIcon={<DeleteIcon />}
                            onClick={this.handleDelete}>
                                Delete
                    </Button>

        )
    }
}

export default EmployeeGrid;

EDIT 1
After more analysis, we found that the reason why the log shows 4 rows in the console logs is because we updated the state inplace at line:
this.state.rows.splice(id - 1, 1); //delete rows that were selected

We now notice that the following line is never called which in turn does not re-render the page update.
 this.setState({rows: this.state.rows, selected: [], nbRender: 2}, () => {
            console.log(this.state.rows) //checks state is indeed updated
        });

Once again any ideas on why this could arise would be much appreciated!
Cheers and keep safe
Answer: Seems like you mutate state here
this.state.rows.splice(id - 1, 1)

Try this one
handleDelete() {
    for (let id of this.state.selected) {
        this.props.onDelete(this.hrefs[id]); //delete from database
    }
    this.setState((prevState) => ({
      ...prevState,
      rows: prevState.rows.filter((row) => !prevState.selected.includes(row.id)),
      selected: [],
      nbRender: 2
    }));
}

Comment: Thank you Sergey for your reply. We tried your solution but this did not change what we found i.e. this.setState is never called and the state is never updated as shown in our Edit 1 above in the original post.


How to redirect back if validate method fails with Laravel

Question: I am using Laravel 6.
I created a form to insert a meeting and I created a validate method in the controller to check if the data inserted in the db are correct.
Unfortunately when the validate method fails the default redirect back deletes every field that has been compiled by the user.
I tried many times but I am unable to understand how to do in case of failure a redirect back with the previous values filled in by the user.
Controller:
    {

        $this->validate($request, [
            'participants' => [ 'required', new CheckParticipant() ],
            'description' => 'required',
            'room' => [ 'required', new CheckRoom() ],
            'date_meeting' => [ 'required', new CheckDateTime() ],
            'start' => [ 'required', new CheckTime() ],
            'end' => 'required',
        ]);

        $meeting = new Meeting();

        $participants = request('participants');
        $meeting->id_participants = implode(';', $participants);

        $meeting->description = request('description');
        $meeting->id_room = request('room');
        $meeting->date = request('date_meeting');
        $meeting->start_hour = request('start');
        $meeting->end_hour = request('end');

        $meeting->save();

        $message_correct = "The meeting has been correctly inserted!";

        return redirect()->route('home')->with('success', $message_correct);

    }

Finally if the user filled in for example the name of a participant to the meeting but the validate method fails I would like that the participant appears already selected in the dropdown menu after the default redirect back.
Is someone able to help me?
Comment: Have you put the code to use the eventual previous data into the form's fields?
Answer: In your view, you can use the old function to retrieve data flashed from the previous request.
Answer: Instead of calling $this->validate try this:
$validator = Validator::make($request->all(), [
    'participants' => [ 'required', new CheckParticipant() ],
    'description' => 'required',
    'room' => [ 'required', new CheckRoom() ],
    'date_meeting' => [ 'required', new CheckDateTime() ],
    'start' => [ 'required', new CheckTime() ],
    'end' => 'required',
]);

if($validator->fails()) {
    return redirect('your/url')
    ->withErrors($validator)
    ->withInput();
}

Then, in your view you can access the old inputs with old('yourValue').


Product of power means inequality: prove $M_0^{\frac{n}{n+k}}M_k^{\frac{k}{n+k}} \leq M_1$

Question: Inspired by this question Prove that $\frac{{x_1}^2+{x_2}^2+\cdots+{x_n}^2}{n}x_1x_2\cdots x_n\le\left(\frac{x_1+x_2+\cdots+x_n}{n}\right)^{n+2}$, I wonder if the following is true:
Let $k > 0$, and define $M_k(x_1,\ldots,x_n) = \left(\frac{1}{n}\sum_{i=1}^n x_i^k\right)^{1/k}$, and $M_0 = \left(x_1\cdots x_n\right)^{1/n}$. In the question it was proved that $$\tag{Q}\label{eq:Q}M_0(\mathbf{x})^{\frac{n}{n+2}}M_2(\mathbf{x})^{\frac{2}{n+2}}\leq M_1(\mathbf{x}),\qquad \mathbf{x}\succeq 0.$$ For brevity I'll omit $\mathbf{x}$ from the following.
Can we generalize $\eqref{eq:Q}$ to e.g.
$$\tag{1}\label{eq:1}
M_0^{\frac{n}{n+k}}M_k^{\frac{k}{n+k}} \leq M_1,
$$
or perhaps even
$$\tag{2}\label{eq:2}
M_0^\theta M_t^{1-\theta}\leq M_1,
$$
where $\theta \in (0,1), t = n(\theta^{-1}-1)$?
In a way this seems related to moment interpolation: if $\mu_t = \int_0^\infty x^tf(x)dx$ for some integrable function $f:[0,\infty]\mapsto[0,\infty]$, then we have the inequality
$$
\mu_t\leq\mu_{t_0}^{1-\theta}\mu_{t_1}^\theta~,\qquad t = (1-\theta)t_0+\theta t_1, \theta \in[0,1],
$$
which is proven using Hölder's inequality.
Whether $\eqref{eq:1}$ and $\eqref{eq:2}$ are true or not, I wonder if there are even "nicer" generalizations to $\eqref{eq:Q}$.
Comment: Not quite what you ask for, but the https://en.wikipedia.org/wiki/Lehmer_mean inequlaity may be of interest.
Comment: @dezdichado Ah I see, you're right. Your method is indeed very elegant (+1'd long time ago), I will give it a try and play around with generalizations.
Comment: did you look at the solution I wrote to the linked question? That method will certainly give you some version of your inequality but I am not sure if it will be $\dfrac{k}{n+k}$ weight on $M_k.$ It should hold when $k<<n$ in some appropriate sense though.
Comment: @dezdichado Yes, as I commented under your answer, it is a very nice generalization :) I suspect that we can generalize even further, by looking at this bound as a sort of "interpolation" between means? Alas, I sort of abandoned this question for awhile, will look at it more seriously soon.
Comment: you are looking at the wrong answer then. If you use my method, then $\dfrac{k}{n+k}$ would be too large for when $k$ and $n$ are of the same order. But you can definitely derive an interpolation like you want using the same idea.
Answer: Let $$M_s(x)=\left(\frac{\sum_{i=1}^n x_i^s}{n}\right)^{1/s}$$ and $M_0(x)$ be the corresponding geometric mean.
It is well known that the mean $M_s(x)$ is increasing in $s$ for $-\infty<s<\infty,$ and for positive $n-$tuples $(x_1,\ldots,x_n).$
In Mitrinovic's Analytic Inequalities, published by Springer many years ago in the Grundlehren series, one finds, on page 79, the following inequality on the ratio $Q_{s,t}(x)=M_s(x)/M_t(x)$ of means of order $-\infty<t<s<\infty:$
$$
Q_{s,t}(x)\leq
\left( \frac{t(C^s-C^t)}{ (s-t)(C^t-1)  } \right)^{1/s}
\left( \frac{s(C^t-C^s)}{ (t-s)(C^s-1)  } \right)^{-1/t},\quad st\neq 0,
$$
and
$$
Q_{s,t}(x)\leq
\left( \frac{C^{t/(C^t-1)}}{ e \log(C^{t/(C^t-1)})  } \right)^{-1/t},
\quad s= 0,
$$
where $$C=\frac{\max_i x_i }{\min_i x_i}.$$
I believe careful use of these inequalities can yield some conditions under which your desired results would hold, or maybe rule them out.
Comment: Interesting, thanks for the reference (incidentally I happen to have this book). But I don't see how this helps us. I'll try to prove the inequality using induction, as is done in the original question. I think however that the inequality is not true, since if we take $k\to\infty$ then we approach $M_\infty \leq M_1$, which is false.


Residuals dont sum to zero: Stata bug? Or User error?

Question: This is my first post to this wonderful community. I am having a vexing problem with Stata 13 MP 64 bit.
The use of .xtpcse and .predict are not generating residuals that sum to zero ( residuals = observed values - fitted values) .  Residuals summed to a positive 41,716.38 (from pairs of 13,443 observed and fitted values. The absolute values of obs values had average of 27.7), so the fitted values were low by about 3.1 on average. Why???
I found the same problem when I manually calculated the predicted values.
Here is my main model with its stata output. Further below, I discuss the consequences when I used .reg with and without aweights and  .xtpcse with and without aweights.
xtpcse rep_code_vlist  avr_ph_i   avr_ph_ii  stg1_pricon_d   stg2_pricon_d    prim_reg_season  stg2_pricon_r_x_olmom    poc_decimal_91  poc_decimal91_x_18t22_x_ph2 poc_decimal91_x_23t30_x_ph2 poc_decimal91_x_31t37_x_ph2 poc_decimal91_x_38t43_x_ph2      _18_to_22 _23_to_30  _31_to_37 _38_to_43 _44_to_66         shd1     shd2     shd3     shd4     shd5     shd6     shd7     shd8     shd9     shd10     shd11     shd12     shd13     shd14     shd15     shd16     shd17     shd18     shd19     shd20     shd21     shd22     shd23     shd24     shd25     shd26     shd27     shd28     shd29     shd30     shd31     shd32     shd33     shd34     shd35     shd36     shd37     shd38     shd39     shd40     shd41     shd42     shd43     shd44     shd45     shd46     shd47     shd48     shd49     shd50     shd51     shd52     shd53     shd54     shd55     shd56     shd57     shd58     shd59      w1     w2     w3     w4     w5     w6     w7     w8     w9     w10     w11     w12     w13     w14     w15     w16     w17     w18     w19     w20     w21     w22     w23     w24     w25     w26     w27     w28     w29     w30     w31     w32     w33     w34     w35     w36     w37     w38     w39     w40     w41         y10   y12     y14    y16  pres_year  [aw= aweight ], corr(ar1)

Here are the results. I trucated the list of variables, coefs, etc.
>Prais-Winsten regression, correlated panels corrected standard errors (PCSEs)
>
>Group variable:   state_house_district          Number of obs      =     13444
>Time variable:    weeks_after_jan_1_2006        Number of groups   =        60
>Panels:           correlated (unbalanced)       Obs per group: min =       149
>Autocorrelation:  common AR(1)                                 avg =  224.0667
>Sigma computed by casewise selection                           max =       249
>Estimated covariances      =      1830          R-squared          =    0.8216
>Estimated autocorrelations =         1          Wald chi2(121)     =   1347.17
>Estimated coefficients     =       122          Prob > chi2        =    0.0000
>
>---------------------------------------------------------------------------------------------
>                            |           Panel-corrected
>             rep_code_vlist |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
>----------------------------+----------------------------------------------------------------
>
>                   avr_ph_i |  -20.75933   9.694859    -2.14   0.032     -39.7609   -1.757752
>                  avr_ph_ii |   172.3479   19.48763     8.84   0.000     134.1528    210.5429
>              stg1_pricon_d |   17.34981   11.01055     1.58   0.115    -4.230477    38.93009
>              stg2_pricon_d |    42.2724   11.29455     3.74   0.000     20.13548    64.40932
>            prim_reg_season |  -32.76939    10.0791    -3.25   0.001    -52.52406   -13.01472
>      stg2_pricon_r_x_olmom |   29.97346   15.29307     1.96   0.050    -.0004098    59.94734
>             poc_decimal_91 |  -.9604848   4.702387    -0.20   0.838    -10.17699    8.256025
>                 .
>                 .
>                 .
>
>                        y14 |   12.81982   8.375178     1.53   0.126    -3.595228    29.23486
>                        y16 |   26.23057   6.787419     3.86   0.000     12.92747    39.53366
>                  pres_year |    25.0513   8.327703     3.01   0.003       8.7293    41.37329
>                      _cons |   -13.2098   31.56652    -0.42   0.676    -75.07905    48.65945
>----------------------------+----------------------------------------------------------------
>                        rho |   .1980228
>---------------------------------------------------------------------------------------------

I then used . . .
>. predict fitted_values

I got the results that I discussed above.
When I tried .reg with aweights, residuals still did not sum to zero. I also tried .xtpcse without aweights and had the same problem.  I tried a few other variations with similar outcomes.  Also, R2 fluctated wildly between models. Coefficients were fairly stable between models.
When I used the nonconstant option along with .xtpcse aweights, the sum of residuals skyrocketted to a minus 118,205.527 and the R2 plummeted from .8216 to that of 0.5217.
The only estimator and model that gave residuals that summed to zero was .reg when aweights were NOT USED.  However, again, .reg witih aweights gave residuals that did not sum to zero.
I also tried closing stata and starting the software (Stata 13/MP 64 bit), but the same problem persisted. I am using Windows 10 64 bit.
Any ideas as to what is going on? Bug or user error?  I am dumbfounded. I dont have the budget to upgraded to a newer version of stata.
Answer: The residuals should not typically sum to zero in weighted least squares, generalised least squares,  or mixed models for unbalanced panel data.
The regression coefficients are solving some equation of the form
$GX\beta=GY$
where $G^TG$ is the weight matrix.  This equation implies
$G(Y-X\beta)=0$.
For ordinary least squares, the corresponding equation is
$X\beta=Y$, implying $Y-X\beta=0$, with the quantity on the left being the sum of the residuals.
For weighted least squares or generalised least squares, then, it's not the sum of the residuals that's exactly zero, but a suitable weighted sum.  The whole point of the estimation procedure is not to give all residuals equal weight, so it doesn't.
Using the nonconstant option changes the intercept from -13 to zero, in just over 13 thousand observations, so you shouldn't be surprised by a change in the residual sum that's anything up to about $13\times 13000=169000$


IOS BLE scanForPeripheralsWithServices:options: on Background

Question: CentralManager doesn't scan BLE device on Background....
I already set UIBackgroundModes, bluetooth-central in info.plist.
also tried input UUID for service like this..
[CentralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"0xFFA0"]] options:nil];

(0xFFA0 is UUID for Service.)
also tried "C337FA9-4DCF-****-77AB-************"; UUID for device.
whatever I put the UUID in Services. not found any device on Background.
when foreground.. scanForPeripheralsWithServices:nil found all devices.
but not scanForPeripheralsWithServices:someuuids
can anyone help me?
Comment: Do you try scan scanForPeripheralsWithServices with some uuid ?And do you get someresult when in this case in foreground?
Comment: No. I didn't get any device, when it scan with some uuid in foreground.
Answer: 1.if you use
scanForPeripheralsWithServices:someuuids

There must be some device advertise bluetooth packets with this uuids.This can work well in both foreground and backgournd
2 if you use
scanForPeripheralsWithServices:nil

You can get all device you want ,but this does not work when in background.
So,if you want to get result in background,you have to set your Peripherals advertise BLE packets with UUID.


Reading from option value and creating link

Question: Suppose I have some options which have some values
<option value = "google.com"></option>
 <option value = "yahoo.com"></option>
 <option value = "linkedin.com"></option>

I know that I can take this value and display it as text. (I can convert the value into an h5,h4 etc. But is it possible to make an href redirecting to the value of the option? Of course I can just manually make , but I was just wondering if this was possible
TLDR
Given an option html element, take the value display it on the screen as a link.
I would never do this, but a colleague asked me how to do this today, and I couldnt really think of a way off the top oh my head.
Answer: This code will create a link out of the values of all the options with the link name.
$("option").each(function(){
 $(this).html('link Name');
});

You would of course have to come up with your own text for the anchor tag, and I'm not sure where you would get that based on the snippet you provided.


Get a list of revision IDs for any given entity?

Question: What's the most uniform method for getting a list of revision IDs for any given entity, programmatically?
Comment: possible duplicate of [Get the last revision id of any given entity?](http://drupal.stackexchange.com/questions/106882/get-the-last-revision-id-of-any-given-entity)
Comment: Interestingly enough I'm the one who asked that question O_o. I believe the problem I'm having is slightly different so I'm going to alter my question to fit the context, ever so slightly.
Comment: i know, that confused me greatly :)
Comment: Okay so I updated this question so that it's no longer a duplicate. Now I'm going to udpdate the other question to clarify the issue.
Comment: There are an additional 3 votes to close since I last viewed this question (and also changed the question). It's really not appropriate to close this issue anymore as the linked "duplicate" question is no longer a duplicate. This question asks to get the entire revision ID list, not get the last revision of an entity. Please remove your votes.
Answer: Figured it out. I'll leave it here because it might be useful to someone down the road.
You can use this function to get a list of all revisions ids for any given entity.
<code>/**
 * Get a revision id list for a particular entity.
 */
function get_entity_revision_list($type, $entity) {
  $info = entity_get_info($type);
  if (!isset($info['revision table'])) {
    // If this entity does not track revisions then return FALSE.
    return FALSE;
  }
  if (!isset($info['entity keys']['revision'])) {
    // If for whatever reason a revision table was defined, but no revision key
    // then also return FALSE.
    return FALSE;
  }
  $revisions = db_select($info['revision table'], 'r')
    ->fields('r', array($info['entity keys']['revision']))
    ->condition($info['entity keys']['id'], $entity->{$info['entity keys']['id']})
    ->execute()
    ->fetchAllAssoc($info['entity keys']['revision']);
  return array_keys($revisions);
}
</code>
Comment: Please notice that depending on your particular scenario, this funcion can be optimized. Although the function above expects a full entity as second parameter, $entity is only used once, to get the Entity ID. So with little modifications on the code, you can get your entity's revisions from its ID. There's no need to load a full entity for this function to run.


Banach-Steinhaus variant

Question:
Let $T_n$ be a sequence of continuous linear operators from a Banach
  space $X$ to a normed linear space $Y$. Now, for all $x \in X$,
  $\lim_{n \rightarrow \infty} T_n(x)$ exists in $Y$. Define $T(x) = \lim_{n \rightarrow \infty} T_n (x)$ on $X$. Show that $$\|T\| \leq \liminf \|T_n\|.$$

Here's my proof:

Convergence of $T_n(x)$ implies that for all $x \in X$, $\|T_n(x)\|\leq M_x$ for some $M_x$. The uniform boundedness principle implies $T_n$ is uniformly bounded, in particular, $\liminf  \|T_n\| < \infty.$ Now for all $z \in X$ with $\|z\|=1$, $$\|T(z)\|=\lim \|T_n(z)\| \leq \liminf  \|T_n\| \|z\| = \liminf  \|T_n\|.$$

I'm not too sure about that last line. How can I improve this proof?
Comment: @Seirios The assumption says $Tx=\lim T_nx$. By the reverse triangular inequality, $\|Tx\|=\lim \|T_nx\|$.
Comment: You can also think that $\|\cdot\|$ is continuous so $T_nx \to Tx$ implies $\|T_nx\| \to \|Tx\|$. In other words, $\lim \|T_nx\| = \|Tx\|$. (I know I'm late, but people who are even later than this might find this useful, as I did this question)
Answer: You are correct. Let me just add a tiny intermediate step to convince you you are right.
Fix $x$.
For all $n$
$$
\|T_{n}x\|\leq \|T_{n}\|\|x\|.
$$
So
$$
\|Tx\|=\lim \|T_nx\|=\liminf\|T_{n}x\|\leq \liminf \|T_{n}\|\|x\|
$$
for all $x$.
Hence
$$
\|T\|\leq \liminf \|T_n\|.
$$
Note: we have $\lim \|T_nx\|=\|Tx\|$ because $\lim T_nx=Tx$ and $|\|T_nx\|-\|Tx\||\leq \|T_nx-Tx\|$.

Banach-Steinhaus variant


How can I use a native DLL from C#?

Question: Given a native DLL, with no documentation or anything, and assuming it is not a COM component, is there any way to extract some sort of interface from that DLL so it can be called from C#?
I know about PInvoke, but that requires me to already know the method names and signatures. I don't have those.
Is it even possible?
Comment: If method signatures are exported, there are tools you can use to read them then use P/Invoke to interop with the dll. Otherwise you're going to have to figure out some other way of finding "entry points" and invoking them. Probably have to do that with C++/CLI or something...
Answer: You can use a PE reading tool to list the exported functions. For example Dependency Walker will do that for you.
There's not a right lot you can do with that information though. There's no metadata with a native DLL that tells you how to call those functions, what their signatures are. Or even what the parameters represent.
Something has gone wrong with this project. A DLL on its own is not enough. You need a header file and some documentation.
Comment: No, nothing is wrong with the project. I'm really conducting a fact-finding exercise to work out whether the project is feasible in spite of a non-cooperative third party. It looks like the answer is no - so plenty of time saved :)

How can I use a native DLL from C#?


Is this a horizontal asymptote?

Question: Consider the following function: $f(x) = \frac{(x-2)^2}{(x^2-1)}$.
To calculate the horizontal asymptote, we take the limit:
$\displaystyle{\lim_{x \to \infty}} f(x) = 1$
However, $f(x)$ still intersects with $y = 1$, namely at the point $(1.25;1)$.
So is $y = 1$ the horizontal asymptote? Because it still intersects with $y = 1$, but the function approaches 1 as x approaches to infinity.
Comment: $y=1$ is horizontal asymptote, you got it right. Consider function $y=\sin \frac{1}{x}$, it has infinitely many intersections with $y=0$ which is  horizontal asymptote
Comment: Yes, that's right
Comment: Ah, that's really interesting. Thanks for the example! I assume vertical asymptotes can't be intersected, but horizontal asymptotes can right?
Answer: Yup. Horizontal asymptotes are happy to be intersected as many times as you like.
Comment: Oh alright, I thought horizontal asymptotes are never intersected, so the two contradicting results confused me. I've learned that horizontal asymptotes are values of y which the function approaches, but will never intersect, so that lead to the confusion.

Is this a horizontal asymptote?


How to emphasize a sudden drop in time series for the purpose of clustering?

Question: I would like to cluster uni-variate daily time series so that an emphasis is put on sudden drops in time series. Series that contain such uncommon drops should be in one cluster (drops should influence the distance to other series), whereas series that don't have such nosedives are in another cluster.
Each series consists of 96 values (a 15-minutes aggregation interval).
Below you can see five exemplary series before clustering:

And here, after - series have been clustered with k-means with euclidean distance as a similarity measure:

In this specific case I would like to obtain a clustering that yields the 1:4 grouping, in which the red series (see picture 1) is in one cluster (its distance to "normal" series is big) and four other series are in the second cluster.
What is a suitable distance metric to be used in order to achieve the desired result? Should series be represented in other way, for example as a feature vector? If so, what is a statistical property that accounts for such abrupt changes?
Comment: When you refer to "time series clusters", do you mean a subset of time series are *more* correlated than others? Or are you just trying to quantify a large "on average" drop?
Comment: I was originally thinking about a large drop on average, but any approach that results in a 4:1 and not 3:2 grouping is welcome.
Comment: This "grouping" method isn't clear, and has nothing to do with the question. Maybe, just maybe, you're sensing the challenge in not having a control series with which to compare. Matching doesn't synthesize a control, especially not in those data plotted. I think the approach most would advocate would be to implement some type of filtering process along with prediction bounds and detect if the time series drops (or ascends) beyond those bounds. A Kalman Filter or Bayesian Particle Filter come to mind... but TS experts would have to chime in on that.
Comment: I'll take a look at it. I didn't mean the grouping method (like k-means or dbscan) itself, and I'm not looking for it right now. What I would like to get is a mathematical tool that  makes the red series be away, different etc. (because of the drop) from the other series. In some way it's numerical value or distance from others should be different / far because of the drop.
Comment: The problem is you singled out the red series because you plotted it and singled it out for a particular reason. You can't use the same data that generated a hypothesis to test a hypothesis.
Answer: One approach would be to hand-engineer feature(s) that represents the characteristics that you care about. In this case you could try computing the moving median over maybe 5 steps, then for each time-step compute the difference to this median, and take the max of these differences across the entire series.
Another approach would be to use an Anomaly Detection algorithm. This has the benefit that it can also detect new kinds of abnormalities. Autoencoders are usually the best for time-series. For this you'd need to prepare a dataset with only "normal" data, to train on.
Answer: DTW is perfect for this, see examples at  https://www.cs.unm.edu/~mueen/DTW.pdf
Comment: I don't think this is a perfect case for dtw. From what I've read dtw comes in handy when you deal with series that have different length and/or are somehow shifted in time. In my case their are neither unlike length nor shifted in time. Moreover, the sudden drop is unique to the red line, so I can't see how dtw could catch it.


Are permutation groups used in statistics?

Question: I was told that there may be a connection between concepts in abstract algebra and applications in statistics (also confirmed by the 'algebraic statistics' tag on this website). I had no idea, so I'm curious. In particular, I wanted to understand how might permutation groups be used, as I believe they are a central and interesting concept in abstract algebra.
I'm trying to look into the theory online, but all I see are links to genuine research articles or other unhelpful things for me... I'm not a professional... If you can give me some examples, or perhaps easy to understand resources on such a topic, I would be glad.
I have an undergraduate understanding in statistics and algebra, so try not to use statistical word wizardry on this small tadpole of a mathematician.
Comment: Have you [searched our site](https://stats.stackexchange.com/search?q=group+permutation)?  Other good search terms include "symmetr*" (for symmetries) and "invariant."  Group theory underpins modern methods of [tag:combinatorics].  Some more advanced abstract algebra methods (still at the undergraduate level), such as rings and ideals, have been exploited here to solve some problems: see https://stats.stackexchange.com/a/6135/919 for instance.  Finally, at https://stats.stackexchange.com/a/288198/919 I apply the Orbit-Stabilizer theorem.
Answer: The Lecture on algebraic statistics provides an excellent introduction into this topic. A more comprehensive overview is provided by Seth Sullivants book Algebraic statistics.
One key player of algebraic statistics are toric ideals $I_A$ motivated by a matrix $A$ coming from a log-linear model. Typically, one wants to find a finite generating set of $I_A$ (called a Markov basis) as they can be used for statistical tests (like Fisher's exact test, you may also want to have a look here). Groups may appear in giving descriptions of the generating sets of those ideals, as typically, symmetry on the variables plays an essential role.
In section 4 of the seminal paper by Persi Diaconis and Bernd Sturmfels, an example of such a generating set of the toric ideal (here, even an universal Gröbner basis) of the "no-three-factor interaction" model using $S_n\times S_n$.


Customize search output

Question: I was trying to modify the search results page using a preprocess function:
<code>function arras_preprocess_search_result(&$variables) {

    $type = $variables['result']['node']->type;
    $variables['search_results'] = '';
    $nodeTypes = node_type_get_types();
    $resultTypes = array();

      $resultTypes[$type][] = $variables['result'];

    foreach ($resultTypes as $resultType => $resultTypeResults)
    {
        echo $resultType;
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result)
        {
            $value .= theme('search_result', $result,$resultType);
        }

        // add fieldset
        $variables['search_results'] .= theme('fieldset',
            array(
                '#title' => $nodeTypes[$resultType]->name,
                '#collapsible' => TRUE,
                '#collapsed' => FALSE,
                '#value' => $value,
            )
        );

    };

}
</code>
but I get this error:
<code>( ! ) Fatal error: Unsupported operand types in L:\wamp\www\drupal\includes\theme.inc on line 830
</code>
i.e on the line
<code>        $value .= theme('search_result', $result, 'cameras');
</code>
What is wrong?
Answer: From the Drupal 7 API theme_search_result:

This function is never used; see the corresponding template file
  instead.

Try overriding the page using search-result.tpl.php
Comment: Which function are you referring to here ?
Comment: theme_search_result. If you call theme('x'), a function theme_x is called in the background. The Drupal API states that theme_search_result is never used and you should use the corresponding template file: search-result.tpl.php
Comment: when we write theme('x') it will look for both theme_x() or x.tpl.php file too as per my understanding.
Comment: Yes, and in this case the API says that you should always use search-result.tpl.php instead of theme_search_result().

Customize search output


how the singular value decomposition of A can be used to solve the system of linear equations

Question: Let $A$ be a real, $n\times n$, non-singular matrix. How can the singular value decomposition of A be used to solve the system of linear equations $A x = b$, where $b, x \in \Bbb R^n$?
Answer: Remember that $U$ and $V^T$ have to be orthogonal matrices meaning that their transposes are also their inverses. The inverse of a diagonal matrix is another diagonal matrix with with reciprocal values of the original entires.
So we can solve $U\Sigma V^Tx= b$ using left matrix multiplication of the inverses of $U,\Sigma, V^T$ and then we have  $x = V\Sigma^{-1}U^Tb$.
Answer: From a Numerical Linear Algebra perspective, we must take into account the computational costs and feasibality of using SVD to solve the system of linear equations :
$$
\mathbf{Ax}=\mathbf{b}\tag{1}
$$
with $r:=\operatorname{rank}(\mathbf{A})\leq\min(m,n)$. Since $\mathbf{A}$ might not be full rank, we shall take advantage of the most imortant property of SVD which is that its pseudoinverse is well defined i.e., we can decompose $\mathbf{A}$ using the Economy SVD to two orthogonal matrices $\mathbf{U}_{r}\in\mathbb{R}^{m\times r}$ and $\mathbf{V}_{r}\in\mathbb{R}^{n\times r}$, and $\mathbf{S}_{r}:=\operatorname{diag}\begin{bmatrix}\sigma_{1}&\sigma_{2}&\cdots&\sigma_{r}\end{bmatrix}\in\mathbb{R}^{r\times r}$ containing the singular values of $\mathbf{A}$. Therefore, we have :
$$
\mathbf{A}=\mathbf{U}_{r}\mathbf{S}_{r}\mathbf{V}_{r}^{\top}
\tag{2}
$$
for which we can rewrite $(1)$ as :
\begin{align*}
\mathbf{Ax}&\;=\;\mathbf{b}\\
\mathbf{U}_{r}\mathbf{S}_{r}\mathbf{V}_{r}^{\top}\mathbf{x}&\;=\;\mathbf{b}\\
\mathbf{S}_{r}\mathbf{V}_{r}^{\top}\mathbf{x}&\;=\;\mathbf{U}_{r}^{\top}b \\
\mathbf{S}_{r}\mathbf{y}&\;=\;\mathbf{z}
\end{align*}
where $\mathbf{y}:=\mathbf{V}_{r}^{\top}\mathbf{x}$ and $\mathbf{z}:=\mathbf{U}_{r}^{\top}\mathbf{b}$. Therefore, all you need to do to solve $(1)$ numerically using SVD in the most effective way is to follow the procedure below :
$1$. Compute the Economy SVD of $\mathbf{A}$.
$2$. Compute $\mathbf{z}\quad \mathcal{O}(n^{2})$
$3$. Solve the system $\mathbf{S}_{r}\mathbf{y}=\mathbf{z}\quad\mathcal{O}(n)$
$4$. Compute $\mathbf{x}=\mathbf{V}_{r}\mathbf{y}\quad\mathcal{O}(n^{2})$
It is worth noting that computing the pseudoinverse directly is not recommended as it may lead to numerical instability.


Please explain the solution

Question:

Use a Taylor series expansion to compute an error estimate in approximating the derivative of the function $f:\mathbb R\to\mathbb R$ using the formula
  $$ f'(x_0) \approx \frac{f(x_0-2h)-4f(x_0-h)+3f(x_0)}{2h} $$

So $\left|f '(x_0)-G_h(x_0)\right| ≤ ch^p$ where $G_h(x_0)= \frac{f(x_0-2h)-4f(x_0-h)+3f(x_0)}{2h}$
\begin{align}
f(x_0-h) &= f(x_0)-hf '(x_0)+\frac{h^2}{2}f ''(x_0)-\frac{h^3}{3!}f '''(\varepsilon) \\
-4f(x_0-h) &= -4f(x_0)+4hf '(x_0)-2h^2f ''(x_0)-\frac{h^3}{3!}f '''(\varepsilon)+\frac{4h^3}{3!}f '''(\varepsilon) \\
f(x_0-2h) &= f(x_0)-2hf '(x_0)+\frac{4h^2}{2}f ''(x_0)-\frac{8h^3}{3!}f '''(\varepsilon_1) \\
2hG_h(x_0) &= 2hf '(x_0)+\frac{2h^3}{3}f'''(\varepsilon)-\frac{2h^3}{3}f'''(\varepsilon_1) \\
\left|G_h(x_0)-f '(x_0)\right| &= h^2\left|\frac{1}{3}f'''(\varepsilon)-\frac{2}{3}f'''(\varepsilon_1)\right|
\end{align}
so $p=2$ and $c=\max \left|f'''(\varepsilon_1) \right|$
In the second last line, was the $2hG_h(x_0)$ step done to make the algebra simpler?
Comment: It seems that way
Answer: Simplicity is subjective and varies from person to person. However, if the computation was to be done on blackboard, then I would choose to expand $2hG_h(x_0)$ rather than $G_h(x_0)$, so that I would not waste the space associated with a long fraction where the nominator is trivial and all the computational work takes place in the denominator.
Important details are omitted in the above calculation. Depending on expected outcome of the class, a student could lose a significant amount of points. Specifically, there is no mention of the fact that the function must be three times differentiable before Taylor's theorem can be applied to produce $\epsilon$ and $\epsilon_1$. There is no statement recording that $\epsilon$ is in the interval between $x_0$ and $x_0-h$ and that $\epsilon_1$ is in the interval between $x_0$ and $x_0-2h$. While Taylor expansions are mentioned in the problem description, it would be appropriate to invoke Taylor's theorem explicitly in the solution. While $h>0$ is the standard choice, there is no harm in eliminating any doubt.
Finally, the given value of $c$ should be adjusted. We are interested only in small $h$, so there is no harm in limiting ourselves to $0 < h \leq h_0$ for some choice of $h_0 >0$. In this case
\begin{equation}
c = \max \{ f^{(3)}(x) \: | \: x \in [x_0 - 2h_0,x_0] \}.
\end{equation}
There is still one catch! We need $f^{(3)}$ to be continuous or it might not assume its maximum value on the interval $[x_0-2h,x_0]$.

Please explain the solution


Pra que serve a interface Countable no PHP?

Question: Vi uma determinada classe cuja declaração estava dessa forma:
class Collection implements Countable {}

Percebi que ela estava implementando Countable, mas não entendi o que essa implementação estava fazendo lá.
Qual é a  finalidade de Countable? Isso é uma interface padrão do PHP?
Answer: Sim, é uma interface padrão do PHP. Serve para tornar um objeto compatível com a função count(). Se a sua classe implementa Countable e possui um método count, esse método será invocado quando uma instância da classe for passada para a função count global do PHP.
Por exemplo:
<?php
class Lista implements Countable {

    private $items = [];
    private $total = 0;

    public function add($item) {
        array_push($this->items, $item);
        $this->total++;
    }

    public function count() {
        return $this->total;
    }
}

$lista = new Lista();
$lista->add(1);
$lista->add('foo');

var_dump(count($lista)); // 2

Answer: Conforme a documentação é para obrigar a implementação do método Count(). É usada em classes de coleções de dados que precisam de forma padronizada de obter a contagem de todos itens contidos nela.
Em geral espera-se que a complexidade ela seja O(1), mas não é obrigado, e para isso a estratégia mais adotada é guardar a contagem do objeto em algum membro e qualquer alteração nela já ser refletida nesse contador.
Cada classe pode implementar como quiser o mecanismo desde que a API conforme com a interface.
Comment: Meu exemplo então não foi bom, porque é O(n) -- acho.
Comment: @bfavaretto idealmente não é bom mesmo, mas não impede de usar. Como eu disse pode fazer como achar melhor. Apenas que o normal, em linguagens decentes :D se espera que o programador faça O(1), mas não é requisito.
Comment: Troquei meu exemplo para uma implementação O(1) :-)
Comment: @bfavaretto na verdade não sei se aquela forma é O(N), eu acho que ela faz o mesmo que você está fazendo. Posso estar enganado, mas tudo que o `count()` da linguagem aceita para contar deve ter a contagem armazenada
Comment: Capaz mesmo. Mas considerando as "boas práticas" que você citou, achei melhor deixar um exemplo que cuida da própria contagem.
Comment: Eu tinha esquecido do +1 :p


Geometrically relating the solution to $a_1x+b_1y+c_1=0$ and $a_2x+b_2y+c_2=0$, and the cross product of vectors $(a_1,b_1,c_1)$ and $(a_2,b_2,c_2)$

Question: I recently came across two lines of the form $a_{1}x+b_{1}y+c_{1}=0$ and $a_{2}x+b_{2}y+c_{2}=0$.
I had noticed that, assuming the two lines intersect, if we multiply the cross product of the vectors $(a_{1},b_{1},c_{1})$ and $(a_{2},b_{2},c_{2})$ by a scalar such that the $z$ component of that vector is $1$, then the resulting first two elements of that vector is the solution to this system of equations.
I was wondering why this is true or if there exists a proof regarding this.
Answer: Given a plane $$ax+by+cz=k$$one normal vector to this plane is $(a,b,c)$.
In particular, given planes $a_1x+b_1y+c_1z=a_2x+b_2+c_2z=0$, the normal vectors $(a_1,b_1,c_1)$ and $(a_2,b_2,c_2)$ are such that the planes consist of all vectors (based at the origin) normal to the chosen normal vectors.
That's useful, because the cross product $(v_1,v_2,v_3)=(a_1,b_1,c_1)\times(a_2,b_2,c_2)$ is normal to both vectors, and thus, as a point, is in both planes.
If $v_3=0$, it isn't hard to see that the two lines were parallel. If not, since the planes are linear subspaces, the vector $v'=\left(\frac{v_1}{v_3},\frac{v_2}{v_3},1\right)$ is also in both planes.
Thus, we have $$a_1\cdot\frac{v_1}{v_3}+b_1\cdot\frac{v_2}{v_3}+c_1\cdot1=0$$$$a_2\cdot\frac{v_1}{v_3}+b_2\cdot\frac{v_2}{v_3}+c_2\cdot1=0$$But this just means that $\left(\frac{v_1}{v_3},\frac{v_2}{v_3}\right)$ is the solution.