Render custom twig in a specific language

Question: I need to specify the language,
which the drupal renderer uses,
when generating a custom render array.
$renderArray = [
    "#theme" => "DNMBE_email",
    "#body" => [
        "#theme" => "DNMBE_emailBody_groupMessage",
        "#author" => $groupMessage->author,
        "#group" => $groupMessage->group,
        "#message" => $groupMessage->message,
    ],
    "#leadin" => $partials->leadin,
    "#leadout" => $partials->leadout,
];

$render = \Drupal
    ::service('renderer')
    ->renderRoot($renderArray);
$html = (string)$render;

#theme parameters resolve to twigs, which, among other things, contain {{ "From"|t }} markup which is incorrectly rendered as From.
I already posted a similar question, which was marked as duplicate, with the answer suggesting using \Drupal::languageManager()->setConfigOverrideLanguage($language). I do not get the expected result.
When using the t() function, you can supply as third parameter an array, which can be used to specify the language. The renderer however does not take extra parameters, thus also not passing it to twig.
I verified that /admin/config/regional/translate has got the translated string, case-sensitive. I also use ['#cache']['max-age'] = 0 and I don't "precalc"-store any Drupal objects.
Comment: Your first question was unspecific and the duplicate was handling content and config translation. When you are asking specifically about interface translation this was asked several times before. A good overall answer is https://drupal.stackexchange.com/a/270809/47547 and you find an example for the mentioned fake negotiator here https://drupal.stackexchange.com/a/216051/47547
Comment: Thank you, but that is somewhat a circular reference there. The first question clearly states that LanguageNegotiator does not help - I have the same usecase and I get the same results. There must be some missing part to this.
Comment: Normally a template using t() depends on the global language context. Although it has some upvotes I'm not advocating the fake negotiator to override the language and @Berdir doesn't seems to do it either in his answer. IMHO the straightforward way to make a template language specific is to put the language code in a template variable and use it as option for t().
Answer: Currently, the only working way seems to be by passing local context - including a langcode in the render array and using |t([], {'langcode': 'XX'}) resp. {% trans with {'langcode': 'XX'} %} as mentioned in https://www.drupal.org/project/drupal/issues/2049241


cannot resolve symbol R?

Question: I'm new to android and saw other people having the same question but the solutions didn't work.
i tried multiple times to clean, sync and build the project after changes but every time is says that it can't resolve R
adding: import nl.test123.R; didn't work because than the next error popsup:Error:attribute 'nl.test123.soundboard:layout_background' not found.
also this didn't work
import android.R

this is the code:"MainActivity.java"
package nl.test123.testsoundboard;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
//import nl.test123.R;

public class MainActivity extends AppCompatActivity {
    MediaPlayer mysound1;
    MediaPlayer mysound2;
    MediaPlayer mysound3;

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_top:
//                    mTextMessage.setText(R.string.title_top);
                    return true;
                case R.id.navigation_latest:
//                    mTextMessage.setText(R.string.title_latest);
                    return true;
                case R.id.navigation_favorite:
//                    mTextMessage.setText(R.string.title_favorite);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        mysound1 = MediaPlayer.create(this, R.raw.bird);
        mysound2 = MediaPlayer.create(this, R.raw.bomb);
        mysound3 = MediaPlayer.create(this, R.raw.dog);
    }

    public void sound1(View view){
        mysound1.start();
    }
    public void sound2(View view){
        mysound2.start();
    }
    public void sound3(View view){
        mysound3.start();
    }
}

can anyone see what i'm doing wrong or forgetting to do.
see the xml below:"activity_main.xml"
 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="nl.marvinboontjes.cucumbersoundboard.MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="92dp"
        android:layout_marginTop="128dp"
        android:text="@string/title_home"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_light"
        android:onClick="Sound1"
        android:text="Bird"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="16dp"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sound2"
        android:text="Bomb"
        tools:layout_editor_absoluteX="147dp"
        tools:layout_editor_absoluteY="16dp"
        tools:ignore="MissingConstraints"  />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onclick="sound3"
        android:text="Dog"
        tools:layout_editor_absoluteX="269dp"
        tools:layout_editor_absoluteY="16dp"
        tools:ignore="MissingConstraints" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:layout_background="@color/colorPrimary"
        app:itemIconTint="@drawable/nav_item_color_state"
        app:itemTextColor="@drawable/nav_item_color_state"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

Error images:
picture1
picture2
Comment: like a said, i tried the solutions in the other questions but they don't work
Comment: solution `android:onClick="Sound1"` should be `android:onClick="sound1"`
Answer: use yourpackagename.R.
in your case it will be nl.test123.testsoundboard.R
I think you have an error in your layout. BottomNavigationView doesn't have app:layout_background attribute. remove it and rebuild again.
Comment: removed this line:  `app:layout_background="@color/colorPrimary"` but still get the error.
Comment: @Fcmarv please put new error message received, after removing that line.
Comment: still the same "cannot resolve symbol R"
Comment: i removed the line
    android:onClick="Sound1" on the buttons and the errors are gone?

cannot resolve symbol R?


Gradle changing module from nexus snapshot repo not updated

Question: I have a problem with a snapshot artifact not being uploaded.
I'm using snapshot version. Atrifact is marked explicitly as changing: true and cacheChangingModulesFor is set to 0 seconds.
When i run --refresh-dependecies the artifact is redownloaded properly.
I found the problem while using gradle 2.9. But after upgrading to 2.14.1 the issue remains.
Below is my build.gradle file:
buildscript {
    ext {
        springBootVersion = '1.3.5.RELEASE'
    }
    repositories {
        mavenCentral()
        maven { url 'http://repo.spring.io/plugins-release' }
    }
    // dependencies for plugins
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
        classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
apply plugin: 'propdeps'
apply plugin: 'propdeps-maven'
apply plugin: 'propdeps-idea'

configurations.all {
    // Check for updates every build
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

jar {
    baseName = 'someproject'
    version = '0.0.1-SNAPSHOT'
}

war {
    baseName = "someproject"
    version = '0.0.1-SNAPSHOT'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven {
        url 'http://nexus.example.com:8081/nexus/content/repositories/java-libs-snapshots/'
        credentials {
            username "someuser"
            password "somepassword"
        }
    }
}

// enables to run with dev profile: $ gradle local bootRun
task local << {
    bootRun.systemProperty 'spring.profiles.active', 'local'
}

bootRun {
    jvmArgs = ["-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"]
}

dependencies {
    compile 'mysql:mysql-connector-java'
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile group: "pl.example", name: "name", version: "0.7.6.1-SNAPSHOT", changing: true
    compile 'org.jadira.usertype:usertype.core:5.0.0.GA'
    compile group: 'com.rometools', name: 'rome', version: '1.6.0'
    compile group: 'org.jsoup', name: 'jsoup', version: '1.9.2'
    compile 'org.hibernate:hibernate-search:5.5.3.Final'
    compile 'org.projectlombok:lombok:1.16.6'
}

Comment: what gradle tasks are you running when you try to upload to the nexus?  Are you able to upload any other artifacts to the nexus?
Comment: @robjwilkins It's not a problem with uploading, uploading works fine. The problem is with downloading newer version of snapshot dependency.
Answer: I think you maybe have the syntax for the changing dependency slightly wrong.
Can you try replacing:
compile group: "pl.example", name: "name", version: "0.7.6.1-SNAPSHOT", changing: true

with:
compile ("pl.example:name:0.7.6.1-SNAPSHOT"){ changing = true }

Can you also try adding a line to the resolutionStrategy for cacheDynamicVersionsFor as follows:
configurations.all {
    resolutionStrategy {
        cacheDynamicVersionsFor 0, "seconds"
        cacheChangingModulesFor 0, "seconds"
    }
}

Comment: can you try adding cacheDynamicVersionsFor 0, "seconds" too?
Comment: I didn't because of 2 reasons. 1. Snapshot is changing not dynamic so it shouldn't matter. 2. "changing" property is afaik optional for snapshot version, as they are by default changing. And also both syntaxes should be equivalent.


Pigeonhole Principle Proof Verification

Question: Let $a_1<a_2<\ldots<a_{n+1}$ different integers. Prove that $$n!\Big|\prod_{1\leq i< j\leq n+1}{(a_j-a_i)}$$Here's my proof:

Let $k\in\bigl\{1,2,\ldots,n\bigr\}$.
$k<n+1$ and using the Pigeonhole Principle, there are $0\leq i<j\leq n+1$ (but $0\leq i<j\leq k+1$ is enough) such that $$a_i \equiv a_j\pmod{k}$$Thus, $$k\big|(a_j-a_i)$$Every $k\in\bigl\{1,2,\ldots,n\bigr\}$ satisfies this, and we are done.

Is the proof correct? I couldn't find a mistake myself but it seemed weird that the use of the Pigeonhole Principle had $n+1$ pigeons and only $k$ holes (when $k$ can be as little as $1,2,3$). Am I missing something?
Comment: Then I guess $k<n+1$ is redundant.
Comment: Your proof is not sufficient : you need to prove that the pair $(i,j)$ such that $k\mid (a_j-a_i)$ is different for every $k$. Otherwise with the same reasoning, you could prove that $2^{10} | 2$.
Comment: what do you mean by $k\in[n]$? What is $[n]$?
Comment: It's a symbol for $\bigl\{1,2,\ldots,n\bigr\}$. I thought about changing it before as I wasn't sure if it's a known symbol or not. I changed it now though.
Comment: It is very common, at least in combinatorics.
Comment: It's wrong. All you have proved is that the lcm of $1,2,...,n$ divides the product of those differences.
Answer: It seems to me that your argument shows that
$$
\prod_{1\leq i<j\leq n+1}(a_j-a_i)
$$
(you shouldn't allow $i=j$), which is actually a Vandermonde determinant, is divisible by all $k\leq n$.
This is not (yet) enough to conclude that $n!$ divides it: $3\cdot4\cdot 5=60$ has this property but is actually smaller than $5!$.

But it is possible that the argument can be improved upon.
Given a prime $p\leq n<n+1$ there are always $\lfloor\frac n{p^k}\rfloor+1$ elements among the $a_i$'s that give the same class modulo $p^k$ as long as $p^k\leq n$. This should account for the
$$
\lfloor\frac n{p}\rfloor+\lfloor\frac n{p^2}\rfloor+\lfloor\frac n{p^3}\rfloor+\cdots
$$
factors of $p$ that occur in $n!$.
(I leave to you to fill the details)
Comment: +1 Very nice elegance.

Pigeonhole Principle Proof Verification


Describe the units in $\mathbb{Z}[\sqrt{-d}]$

Question: I need help describing all the units in the ring $\mathbb{Z}[\sqrt{-d}]=\{a+b\sqrt{-d}|a,b\in\mathbb{Z}\}$ where $d>0$ and is square-free.
Thanks.
Comment: Assuming $d>0$, there are not many ways that $N(a+b\sqrt{-d})=a^2+d\,b^2$ is $\pm 1$.
Answer: First of all, $\mathbb{Z}[\sqrt{-d}]$ is a subring of $\mathbb{Q}[\sqrt{-d}]$ which has field norm $$N(a + b\sqrt{-d}) = (a + b\sqrt{-d})(a-b\sqrt{-d}) = a^2 + db^2.$$ This norm is multiplicative (i.e. $N(\alpha\beta) = N(\alpha)N(\beta)$).
Suppose $\alpha \in \mathbb{Z}[\sqrt{-d}]$ is a unit. Using the fact that there is an element $\beta \in \mathbb{Z}[\sqrt{-d}]$ such that $\alpha\beta = 1$, you can determine the possible values of $N(\alpha)$. Then it is just a matter of solving the equation $N(a + b\sqrt{-d}) = a^2+db^2 = N(\alpha)$ for each possible value of $N(\alpha)$. The difficulty of solving these equations changes drastically depending on whether $d$ is positive or negative.
Added later: As $d$ is now positive, $db^2 \geq 0$ for all $b \in \mathbb{Z}$; this makes things much easier. If $d$ were negative, you would need to solve Pell's equation (as well as a slightly modified Pell's equation), which is much harder. In fact, if $d$ is positive, there are only finitely many units (four if $d = 1$, and two if $d > 1$), but if $d$ is negative, there are infinitely many units (though they can all be expressed as powers of a single unit, which corresponds to the fact that Pell's equation and its variant possess a fundamental solution from which all other solutions can be generated).
Also note that for $d \equiv 2, 3 \pmod 4$, $\mathbb{Z}[\sqrt{-d}]$ is the ring of integers in the quadratic field $\mathbb{Q}[\sqrt{-d}]$. However, if $d \equiv 1 \pmod 4$, then $\mathbb{Z}\left[\frac{1+\sqrt{-d}}{2}\right]$, which contains $\mathbb{Z}[\sqrt{-d}]$ as a proper subring, is the ring of integers in the quadratic field $\mathbb{Q}[\sqrt{-d}]$. The distinction here is important. For example, there are only two units in $\mathbb{Z}[\sqrt{-3}]$ while there are six in $\mathbb{Z}\left[\frac{1 + \sqrt{-3}}{2}\right]$.


A nonlinear ordinary differential equation

Question: I've  got a ordinary differential equation basically on this form:
$$
\frac{(f'(x))^2 x^2}{\sinh^2\left(2\,q\,f(x)\right)}+K^2\sinh^2\left(2\,q\,f(x)\right)=\frac{a}{q^2}
$$
where $q>0$, $f(x)>0 $, and everything here is real. I would like a solution valid for all $x$, not a particular $x$. Does someone have a clue as to how I can proceed with this? Thanks for any help!
Best regards, Jakob
Answer: Denote $u(x)=\sinh(2\,q\,f(x))\;$. Then
$$
(u'(x))^2=4q^2(f'(x))^2\cosh^2(2\,q\,f(x))=4q^2(f'(x))^2(1-u^2(x))
$$
and the equation can be rewritten as
$$
\frac{x^2u'^2}{4 q^2 u^2 (1-u^2)}+K^2 u^2=\frac{a}{q^2}.
$$
The solution of which in the implicit form is
$$
\int\frac{du}{u \sqrt{(1-u^2)(a-K^2 q^2 u^2)}}=\pm2\log|x|+C.
$$
Comment: after that, just for the joke, please, post solution to this equation which gives Mathematica 8
Comment: @Norbert It can be done only in implicit form. I edited the answer.
Comment: @Norbert well, Mathematica do calculate the integral, but cannot get $u$ explicitly.
Comment: I know that. Semi-explicit formula was horribly huge. That's why I asked you to post it :)
Answer: If you want explicit solutions, Maple 16 gives
f(x) = -1/8*(-2*ln(-a^(1/2)+2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*(q^2*K^2*a^(3/2)*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*a^(5/2)-(q^2*K^2*a^4*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2*a^5-a^4*q^2*K^2-a^5)^(1/2))/a/(q^2*K^2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+a))+ln(a))/q,
f(x) = 1/8*(2*ln(-a^(1/2)+2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*(q^2*K^2*a^(3/2)*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*a^(5/2)-(q^2*K^2*a^4*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2*a^5-a^4*q^2*K^2-a^5)^(1/2))/a/(q^2*K^2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+a))-ln(a))/q,
f(x) = -1/8*(-2*ln(-a^(1/2)+2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*(q^2*K^2*a^(3/2)*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*a^(5/2)+(q^2*K^2*a^4*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2*a^5-a^4*q^2*K^2-a^5)^(1/2))/a/(q^2*K^2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+a))+ln(a))/q,
f(x) = 1/8*(2*ln(-a^(1/2)+2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*(q^2*K^2*a^(3/2)*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))*a^(5/2)+(q^2*K^2*a^4*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2*a^5-a^4*q^2*K^2-a^5)^(1/2))/a/(q^2*K^2*tanh(-2*ln(x)a^(1/2)+2_C1*a^(1/2))^2+a))-ln(a))/q


how to solve the differential equation $\sin^{2}(dy/dx)- x = 0$ for $y(0)=0$ and what is its domain for this point?

Question: how to solve the differential equation $\sin^{2}(dy/dx) - x = 0$ for $y(0) = 0$ and what is its domain for this point?
Note: I have calculated it with online tools, so i am not asking the result. I am asking the steps for the result.
Note2: The question is true, it is exactly as i wrote it.( It is not like sin^2(x) etc.) No editing required.
Comment: What "solution" did the online tools give you?  Is ask because no solution has a point on the $y$-axis.
Comment: This is not really an ODE, it is just an integration/quadrature problem with singular integrals. Can you check that the equation is complete as it is written here? There could possibly be a factor $y(x)$ missing in the second term.
Comment: the question is true, no edit required
Comment: Do you mean $\sin^2(x) y'$ or $\sin^2(y')$? The latter is an extremely weird thing to write, since $\sin^2$ is extremely non-injective...
Comment: No, the question is exactly as i wrote. I could not do it because dy/dx was inside the sin function
Comment: That makes absolutely no sense, what's the privileged choice of the inverse of $\sin^2$? Maybe the one with range $[0,\pi/2]$?
Answer: By the non-negativity of the square, your equation is defined on $x\in [0,1]$ and can be simplified to $\cos(2y'(x))=1-2x$. Then with the inverse cosine
$$
y'(x)=k\pi\pm\frac12\arccos(1-2x).
$$
Each $k\in\Bbb Z$ gives a valid solution.


Map with political borders similar to google charts, "clickable" countries

Question: I'd like to add a map of countries to my website where the user can choose a specific country by clicking on it. http://code.google.com/apis/chart/docs/gallery/map_charts.html has the looks i want, but it's not possible to underlay the countries with links, afaik(Besides lacking pan/zoom, nice to have). The interactive map(Geo Map) allows more options but it's based on flash which i'd like to avoid(Not sure if links would be possible anyway).
I've played with shapefiles/polylines and google-maps but thats too complex(Lots of data for the polylines, far too much for the simple functionality i need).
Do you know of alternatives which are similarly easy to implement as the google-api-options?
Thx
Christian
Comment: Sounds like you're looking for a client-side imagemap? When you say pan/zoom, is this real-time pan/zoom, or you click a button and the page reloads a new map?
Comment: Imagemap would not have been enough, as i need to generate parts of the map from a db. Solved it with SVG in the meanwhile, not perfect but good enough.
Answer: I would, if I may, suggest to check out Highmaps, from the people behind Highcharts (myself included). It's 100% Javascript based, and designed to get you up and going with very little effort. You can easily implement your own click-based events.
Highmaps is free for non-commercial use, works great with mobile browsers (full touch support) and old IE down to IE6. It also has support for advanced dynamic features like drilldown and rich tooltips, and is very customizable.
We supply a map collection with over 350 maps, to get you started quickly. The maps are optimized for size to keep things lightweight.


Select datas From Nested Array

Question: I got a problem, i've datas like this
$query = mysql_query("SELECT * FROM ticket");
while ($r = mysql_fetch_assoc($query)){
$data_workgroup=$r['workgroup'];
$explode= explode(",",$data_workgroup);
print_r($explode);

and I get this
Array ( [0] => Technical Support)
Array ( [0] => Marketing [1] => Network Engineer )
Array ( [0] => Technical Support )
Array ( [0] => Technical Support [1] => Network Engineer )

i need to get value from that array, so i can show data just for Workgroup Value
SELECT * FROM ticket where workgroup = ValueOFArray[Network Engineer/Technical Support]

Hope you can help Me. Sorry I Can't post Images. thanks :)
Comment: sorry like this `Select * FROM ticket, Division where Division.name_division = valueOFARRAY`
Answer: $explode is just a multidimensional array , so :
$query = "SELECT * FROM ticket where workgroup = '".explode[0][0]."';";

And you will execute a query like :
SELECT * FROM ticket where workgroup = 'Technical Support';

More here:
http://php.net/manual/es/function.explode.php
Comment: sorry i've fault from my first post `Select * FROM ticket, Division where Division.name_division = valueOFARRAY`
I want to get value from array.

Select datas From Nested Array


Find one variable that is most uncorrelated to current set of variables

Question: I'm currently holding 100 stocks. From another pool of 400 stocks, I want to pick one that are most uncorrelated to my current set of 100.
My plans are

Find the stock that has least total correlation in the sample correlation matrix with my current one
Regress each of the 400 stocks in the pool against my current set, find the one that has lowest $R^2$

Which one, if any, of the two is preferred? If neither, what are the general statistical methods for such problem?
Comment: Could you clarify what you mean by "most uncorrelated"?  For instance, would a stock that has negative correlation with all the others be "more uncorrelated" than a stock with zero correlation with all the others?  And given that any new stock will have 100 correlations with the existing one, how do you propose to summarize those 100 values into a single "correlation"?  Perhaps you're applying the CAPM?
Answer: Since the most uncorrelated new stock is what you want (1) and not which whose variance is best explained by another stock's variance (2) the first route should be followed since the second plan requires at least 400 regressions.
Calculate the correlation matrix for the existing 100 stocks and 400 candidates together, while remembering that the first 100 row and column indices are the existing pool (call it the first partition of the combined correlation matrix), and the remaining 400 row and column indices belong to the candidate pool (second partition). From there, locate the minimum correlation (off-diagonal) in the lower diagonal of the second partition, because this is the region where correlations between the first and second partitions will appear.
\begin{array} {|r|r|}\hline A & a,a & a,b & a,b & a,b \\ \hline a,a & A & a,b & a,b & a,b \\ \hline b,a & b,a & B & b,b & b,b \\ \hline b,a & b,a & b,b & B & b,b \\ \hline b,a & b,a & b,b & b,b & B \\ \hline  \end{array}
In the miniaturized example above, with partitions for groups $A$ (existing pool) and $B$ (candidate pool), the bottom left $3\times 2$ region consisting of $b,a$ off-diagonals would be your area of interest in the combined correlation matrix. In your case, just extend the framework to a $(100+400)\times (100+400)$ sized matrix
Comment: This answer appears incorrect because this one-variable-at-a-time approach does not fully account for the correlations among the variables.


How to remove orphaned actions if you get not authorized access as uid1?

Question: I get this error 1 orphaned actions (views_bulk_operations_archive_action) exist in the actions table. Remove orphaned actions
But when I click Remove orphaned actions I get You are not authorized to access this page..
And I'm logged in as UID1 user.
Can this be solved via drush?
Answer: Relative path /admin/config/system/actions shows a list of the actions available in the site.
If a site has orphaned actions, then relative path /admin/config/system/actions/orphan will provide the opportunity to remove them.
If you enter relative path /admin/config/system/actions/orphan and get redirected (automatically) to /admin/config/system/actions/manage, then that is an indication that there are no orphaned actions.
And if everything else fails, and you're willing to take the risk (+ a backup of your database first!), you might want to give it a try to edit the Drupal database using an SQL which looks like so:
delete from actions where aid = "views_bulk_operations_archive_action";


What is the difference between closed under intersections of finitely many subsets and closed under countable intersections?

Question: It is given in definition, that $\sigma$ algebra is a type of algebra of sets. So if algebra of sets is defined as being closed under intersections with finitely many subsets, does that mean that being closed under countable intersections implies being closed under intersections with finitely many subsets? Countable set is a set which is bijective to a subset of natural numbers? If so, does finitely many mean that you can also have a bijective function with natural number set? And then, why is that important in probability?
Comment: There are two good answers which give examples of families of subsets that are closed under finite intersection but not countable intersection. I will add that the fact that this is possible is the reason for the "$\sigma$" in the name "$\sigma$-algebra." A family of subsets closed under complement and *finite* intersection is just called an "algebra". The $\sigma$ is there to insist that it's closed not only under finite but also countable intersection.
Answer: $$
\bigcap_{n=1}^\infty \left( \frac{-1} n , \frac 1 n \right) = \{0\}.
$$
This is an intersection of countably many open sets, but it is not an intersection of finitely many open sets. An intersection of finitely many open sets would be open, but this set is not open. "Open" in this context would mean containing an open interval about each of its points.
Comment: @roundsquare This is exactly how he is using it. The open (in the topological sense) subsets of the reals are an example of a collection of sets that is closed (*not* in the topological sense) under finite intersections but not under countable intersections.
Comment: I think the question is about "closed" in a different sense. I don't know much about $\sigma$-algebras but here what I think it means is that if $x,y\in\Sigma$ then $x \cap y\in\Sigma$.
Comment: @roundsquare Yes, you're right. It is not about intervals.
Comment: @roundsquare : Closure of $\sigma$-algebras under finite intersections does mean that if $x,y\in\Sigma$ then $a\cap y\in\Sigma.$ How is that a different sense from what appears in my answer above? My example shows that closure of a particular class of sets (in this case open sets) under finite intersection does not mean that class is closed under countable intersection.
Answer: Being closed under arbitrary finite intersections does not imply being closed under countable intersections. For example, take the family of co-finite subsets of the natural numbers, that is, the family $F$ of sets whose complement is finite. So, e.g., $\{3,4,5,6,\ldots\}$, which omits the finite set {$0,1,2$}, is in $F$, but the set of even numbers is not (because it's complement is infinite).
Now, any intersection of finitely many sets from $F$ is in $F$ because the complement of that intersection is the union of the complements, i.e. a finite union of finite sets, which is finite.
But if you look at the countably many sets $A_n = N - \{n\}$ for $n = 0, 1,2,3,\ldots$, each one is in $F$, but their intersection is empty, and the empty set is not in $F$. So $F$ is not closed under countable intersections.
Comment: You shouldn't switch in and out of MathJax in the course of writing an expression in mathematical notation. Just stay in MathJax, thus:
$\{3,4,5,6,\ldots\}$ rather than {$3,4,5,6\ldots$} and $A_n = N-\{n\}$ rather than $A_n$ = N-{$n$}. The font sizes fail to match and you don't get proper spacing, and your minus sign looks like a hyphen, when you switch back and forth.
Comment: @Ned oK, I am really sorry, I wanted to ask the question other way round, because it seems that $\sigma$ algebra has more restrictive definition, if some collection of subsets can be defined as $\sigma$ algebra, does that implies that it is closed under intersection with finitely many subsets?
Comment: @Ned Why it's important in probability theory that $\sigma$ algebra not like general algebra of sets is closed under countable intersections?
So the biggest idea of $\sigma algebra$ is an empty set?
Comment: @user Yes, sigma algebra is more restrictive, any family closed under countable intersections is automatically closed under finite intersections by taking a finite intersection and making it infinite by repeating sets in the intersection. I'm not an expert (to put it mildly) on abstract probability, but one point is that you want to be able to do continuous probability (e.g. the normal distribution), which is very much like real analysis and measure theory, where countable unions and intersections occur everywhere.


break onclick event from method

Question: Button's OnClick event is called:
private void vkb7_Click_1(object sender, EventArgs e)
{
    //method
    button_start(object sender);

    // do stuff 2
}

Some method is triggered:
private void button_start(object sender)
{
    bool some = true;
    if (some)
    {
        return; // I'd also like to break "button click"
    }
}

I'd like to break "button click" event from method - how do I do it?
Comment: What do you mean "break" button click?
Answer: Simple, let button_start() return a boolean:
private bool button_start(object sender)
{
   bool some = ...;
   return some;
}

private void vkb7_Click_1(object sender, EventArgs e)
{
  //method
  if (button_start(object sender))
    return;

  // do stuff 2
}

Answer: If you are determining in button_start whether actions should occur in vkb7_Click_1, consider making button_start return bool and then use the return value in vkb7_Click_1.
On the other hand, if you are encountering an error condition in button_start, throw an exception.
Answer: You can't really "block" the event as it has already been fired. You can however handle the click manually depending on the result.
private void vkb7_Click_1(object sender, EventArgs e)
{
    bool result = button_start(sender);

    if (result)
        DoSomething();
    else
        DoSomethingElse();
}

private bool button_start(object sender)
{
    bool some = true;

    if (some)
        return false;

    return true;
}

Answer: First, Set the return type of button_start to bool
Second, If you want to pass sender of vkb7 button or properties of vkb7 button,
 Then you should pass it like this:

button_start(sender)
  So the code would be like this:

 private void vkb7_Click_1(object sender, EventArgs e)
 {
   //method
   if(button_start(sender))
   // do stuff 2
 }

Then in the method
 private bool button_start(object sender)
 {
    bool some = true;
    if (some)
    {
       return true; // I'd also like to break "button click"
    }
    else
    return false;
 }

break onclick event from method


Alguém tem alguma ideia de como criar uma paginação com API RESTFULL em Laravel?

Question: Alguém poderia me dar um exemplo de como fazer isso e o JQUERY montar a paginação? Nem que seja algum tutorial. Já pesquisei em vários locais e todos dizem a mesma coisa de criar uma paginação no próprio laravel e trazer numa view. Só que o meu problema é trazer essa paginação com JQUERY em outro projeto, via API em JSON. Será que alguém poderia me explicar e dar um exemplo?
Comment: pode explicar melhor o que deseja?
Answer: Eu creio que a resposta seja simples: Use o método paginate do Laravel.
Eu sempre uso isso nas minhas aplicações para fazer uma "paginação" (na verdade o que eu faço é um carregamento sobre demanda, usando a lógica da paginação do Laravel).
O que você precisa entender é que a paginação do laravel funciona passando o parâmetro page na query da url.
Ou seja:
Route::get('/api/users', function () {
     return User::paginate(10); // vai exibir de 10 em 10
});

No jQuery, você faz a sua lógica para parâmetro page ser adicionado dinamicamente:
var page = 1;

$.get('/api/users?page=' + page, function (response) {

});

Se você alterar o valor de pagepara 2, você observaria que a "próxima página" seria carregadas com os dados que você precisa. Sabendo disso, você poderá aplicar a sua lógica livremente.
Geralmente, o que eu costumo fazer é uma implementação com Angular e Inifinite Scroll.
Tenho uma biblioteca de onde você pode tirar mais exemplos.
Comment: Mas a lógica do page é você que vai implementar. Sua pergunta não está clara no sentido de como vai implementar.
Comment: Cara eu tentei fazer mas preciso que o page seja automático entendeu?
Comment: Vou colocar meu código na pergunta


Formatar uma duração "hora:minuto" para o formato ISO 8601

Question: Estou tentando transformar a string 05:25 para PT05M25S.
Consegui chegar até aqui, altera o : pelo M. Mas não consegui inserir o restante que ficou faltando.
$date = "05:25";

$date = preg_replace('/[:\/]/', 'M', $date);

echo $date;

Answer: Fiz desse jeito:
$duration   = 05:25;

$duration   = preg_replace('/[:\/]/', 'M', $duration);

echo 'PT' . $duration . 'S';

Resultado: PT05M25S
Answer: O problema com seu código é que as barras no início e fim são delimitadores da regex. Por isso, quando uma outra barra é encontrada no meio da expressão, o PHP acha que a regex já terminou e dá erro. Uma forma de resolver é a que você fez: escapar a barra com \.
Outra opção é usar um caractere diferente como delimitador, já que há vários outros caracteres que podem ser usados além da barra. De preferência, escolha um que não está sendo usado na regex, assim você não precisa se preocupar com o escape:
// usando # como delimitador
$duration = preg_replace('#[:/]#', 'M', $duration);

Mas neste caso, não sei se precisa de regex, afinal você só quer trocar o caractere : por M, então um simples str_replace já resolveria:
$duration = "05:25";
echo "PT". str_replace(':', 'M', $duration). "S";

Mas como você está trabalhando com durações (quantidades de tempo), talvez seja interessante usar um DateInterval:
$duration = "05:25";
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
$formatado = "PT";
if ($d->i > 0) {
    $formatado .= "{$d->i}M";
}
if ($d->s > 0) {
    $formatado .= "{$d->s}S";
}

echo $formatado; // PT5M25S

Pode parecer "pior" só porque o código ficou maior, mas creio que fica um pouco mais robusto, pois se a string não tiver números (por exemplo, se for "ab:xy"), ocorrerá um erro ao criar o DateInterval. Neste caso, bastaria verificar se ele foi criado mesmo:
$duration = "ab:xy"; // string inválida
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
if ($d) {
    // $d foi criado corretamente, formatar o valor usando o código acima
} else {
    echo "erro ao criar o intervalo";
}

Já usando replace, não é feita nenhuma verificação, e ele aceita qualquer string que vier.
Eu incluí uma verificação para não colocar o valor na string quando este for zero, então se a string for "00:25" o resultado será PT25S. A norma ISO 8601 (que define este formato para durações) diz que não há problema em ter valores zerados, mas que estes podem ser omitidos caso sejam zero. Fica a seu critério decidir se vai incluir ou não.

Obviamente dá para melhorar, pois eu não verifiquei se o array retornado por explode possui duas posições, etc. Também não está claro se o formato sempre é "minutos:segundos". Se for, outra opção é usar format:
$duration = "05:25";
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
echo $d->format('PT%iM%sS'); // PT5M25S

A diferença para o código anterior é que mesmo quando os valores forem zero eles serão incluídos na string. Por exemplo, para "00:25" o resultado será PT0M25S.


What are rifle specifications in Biathlon?

Question: I'm watching the Olympics Biathlon right now, and wonder what is that rifle? For sure, it must be a custom made rifle only for biathlon, but what are the specifications?
Is it a true bullet, or some kind of paintball? If a contestant was to go bonkers and try to shoot someone else, would it hurt/be deadly?
Answer: The rifles used are .22LR, a 130-year-old cartridge design that is the most sold type in the world, designated as the only acceptable round for Olympic shooting competition of any kind.
The rifles at the top level are designed for biathlon, with variants for the different categories. According to its manufacturer, the most popular rifle by far is the Anschutz 1827F, and further description of the details are provided by AccurateShooter.com.
They include adaptations to make carrying the rifle easier during the ski portion (lightweight and compact parts, aerodynamic magazine storage) and reduce impact on aiming while firing (straight pull action to reload, multiple magazine releases).
Yes, they are legitimate firearms and yes, they can injure or kill. Regulations are very strict on safety.
Answer: Yes, it can be deadly.
The Biathlon rifles from ANSCHÜTZ (and probably the others too) are Caliber .22 and are built for extreme precision, not for being safe against abuse (that would be impossible). And if you zoom in on that picture you can see that the ammo looks very serious too. Although the bullet speed is only 500 mph (normal bullets travel four to five times as fast) it will definitely hurt a lot.

Also the officials take safety risks very seriously. Just looking into the barrel gets you disqualified.
Comment: @Nij the extra bullets on the side (you need them in some events where you may reload up to three times before you have to run the penalty lap)
Comment: Where in the image can you see any of the cartridges or bullets? These rifles are magazine-fed.


How to prove that the line outside a convex polygon, having the minimum sum of distances is one of the edges?

Question: As part of a computational geometry question, I need a result for an intermediate step.
Suppose there is a convex polygon S, with finitely many points inside the polygon. Now, we want to find the line outside the polygon (i.e, the line can pass through a vertex or edge but cannot intersect) which minimizes the sum of perpendicular distances between the line and (vertices + interior points).
I have a hunch that we can prove that this line must be one of the edges, but I am unable to find a proof.
The simplest approach I tried was checking if rotating a line passing through vertex (but outside polygon) always decreases the sum till it reaches the edge. But this is clearly not true.
How to prove this?
Note 1: I think that this theorem must be true, but I have not seen it anywhere. It might be possible that it is actually false and the original question can be solved by a different method. If so, I would like to see a counterexample.
Note 2: The original question, the only answer proposes the theorem but does not provide a proof.
Comment: "... rotating a line passing through vertex (but outside polygon) always decreases the sum till it reaches the edge. But this is clearly not true."  For which point arrangements is this not true?
Comment: For almost all arrangements. Like if you rotate the line, you have split the plane into regions based on the perpendicular bisectors. Points lying in some regions can have their sum increased.
Comment: According to my analysis it cannot happen. The maximum distance sum is achieved if the line passing through a vertex is drawn perpendicular to the direction pointing to the centroid. Any rotation from this position will decrease the sum of distances.
Comment: What you said is correct, but it doesn't imply that it should continually keep decreasing till it reaches the edge. In other words, the function may not be monotonic. Maybe I'm just messing something up, but it isn't obvious to me.
Comment: Check your calculation. Until the line intersects the polygon the distance sum is proportional to the sine of the angle between the line and the direction to the centroid, and sine is a monotonic function on $[0,\pi/2]$.
Answer: A distance from a point $(x_i,y_i) $ to a line given by the equation $ax+by+c=0 $ is
$$
\frac{|ax_i+by_i+c|}{\sqrt {a^2+b^2}}.\tag1
$$
Now because the line is outside of the hull polygon the expression $ax_i+by_i+c$ has the same sign for all points, which we without loss of generality will assume to be positive. Hence we may drop taking the absolute value and write for the sum of distances:
$$
D (a,b,c)=\sum_{i=1}^N\frac{ax_i+by_i+c} {\sqrt {a^2+b^2}}=N\frac{aX+bY+c} {\sqrt {a^2+b^2}},\tag2
$$
where $(X,Y) $ are coordinates of the centroid of the points.
Now observe that the right hand side in (2) is nothing else but the multiplied by $N$ distance from the centroid to the line which is indeed minimized by one of the polygon edges, as claimed.


Javascript syntax , constants and logical-operators

Question: I was hoping someone could explain to me what this assignment operation does or point me in the right direction.
var CON = CON || {};
Thank you,
Aleks
Answer: The || (double pipe) means OR. So what this code does is:
If CON is truthy then it should be assigned to CON, else it should get an {} (empty object) as it's value.
It basically checks if the var CON is set, if not then it assigns {}. You find this short-hand code a lot in functions when you're not sure if all arguments are passed. Not sure why you would use it with constants, but I would have to see the rest of the code.
Answer: It can be used to prevent overwriting an object
Comment: This should be a comment


Changing pushViewController's "animated:" Flag Changes SpriteKit Resolution

Question: I have a subclassed UINavigationController that navigates through a series of view controllers by calling [self pushViewController:controller animated:YES].
Each of these view controllers contains an SKScene.
The transition between view controllers looks bad, so I decided to change it by switching the animated flag to NO, i.e. [self pushViewController:controller animated:NO]. However, when I change this flag from YES to NO, my SKScene doubles in size. It's as if it thinks that I'm changing the retina/@2x properties or something.
Why does the animation flag affect SKScene frame size? And how would I transition between view controllers without an animation?
Comment: you are not supposed to do that, instead transition between scenes not views and their controllers. It's inefficient to recreate sk views for every "transition".
Comment: In general, I agree. However, the issue here is that my `SKViews` are contained within view controllers who's logic changes. What should I do in this case?
Comment: Okay, still, in SK you have one view and one view controller. If you need to change some logic depending on the scene, this logic should go in the scene subclass. Your view controller should merely delegate any event to the scene as needed to allow the scene to handle it. In SK the scenes are kind-of like the view controllers for a given scene.
Comment: Hmmmm. My project uses a UICollectionView to display grid-squares (music notes) that SpriteKit nodes interact with. Is this implementation not advisable? How would I implement a UICollectionView in SpriteKit then?
Comment: well, for one you can't "add" sprites to the collection view as they aren't views themselves
Comment: Yes indeed. It is definitely the case that UIKit and SpriteKit don't play nice. I guess I'd like to conclude by asking two questions: 1. If you are building something in SpriteKit, is your entire codebase SpriteKit-based? 2. My original question: How should I push a view controller in a non-animated way? Thanks!
Answer: The issue here was with non-retina and retina assets. Make sure you have @2x and regular image assets, then you'll be fine.


Extracting list of the split of a lmtree object

Question: I am using the lmtree function from the partykit package
and I am looking for a function similar to the path.rpart function, ie,
a function which gives in a list the splits on the path from the root to the selected node.
It would like something similar to this  :
 set.seed(1)
 library(rpart)
 x=runif(100);z=runif(100);y=jitter(ifelse(z>.5,2*x,3*x+2),amount=.1);
 rp=rpart(x~y)
 path.rpart(rp,5)

 #node number: 5
 #root
 #y< 0.8785
 #y>=0.4081

with lmtree :
 library(partykit)
 tr=lmtree(x~y|z)
 #and here I need a function similar to path.rpart

I checked the node_party and get_paths functions but it is not what I need.
Does any one have suggestions for extracting this info from the lmtree object ?
Many thanks for your help.
Comment: Its easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and the code you used to build your model. Describe what the expected result is for that input so possible solutions can be tested and verified.
Comment: Too vague to be answered because you haven't explained clearly what you want.
Comment: @MrFlick and InfiniteFlashChess You right I edited my question
Comment: use `set.seed()` with your example so we can get the same sample data values. Right now when I run your code there is no node 10 so I get an error.
Comment: Done, thank you for your help
Answer: Models of class lmtree inherit from party just like the output from ctree(). Hence, the same approaches that are discussed here on SO for ctree() output can also be applied to lmtree() output. Namely, you can use the (still unexported) .list.rules.party() function:
partykit:::.list.rules.party(tr)
##                        2                        3
## "z <= 0.495593577856198"  "z > 0.495593577856198"

For further adaptations see: also:

ctree() - How to get the list of splitting conditions for each terminal node?
Get decision tree rule/path pattern for every row of predicted dataset for rpart/ctree package in R
Comment: Exactly what I need ! Thx


Let R be a field. Is R[x] a field then?

Question: Let R be a field. Is R[x] a field then?
I guess the answer is NO, but it doesn't come any counterexample in my mind. thanks for your help.
Comment: What do you mean no counterexample comes to mind? *Every* element of $R[x]$ that is not an element of $R$ is a counterexample.
Comment: You will find the answer in the site if you search.
Comment: For any field $\;R\;$ , the element $\;0\neq x\in R[x]\;$ has no inverse. Can you prove this?
Answer: No. For degree reasons, a polynomial $P(X)$ with positive degree cannot have an inverse in $R[X]$. This means the only invertible elements in $R[X]$ are the non-zero constants.
However it is a P.I.D., and as such, has a field of fractions, denoted $R(X)$.
Comment: I think it is also a Euclidean domain as well.
Comment: That's true, but it's not useful for this question.
Comment: Sure, just a remark for the sake of being complete.

Let R be a field. Is R[x] a field then?


Variance explained by a subset of random effects

Question: Given a fitted linear mixed model:
$$
y = X\beta + Zu + \epsilon
$$
where $y \in \mathbb{R}^n$, $X \in \mathbb{R}^{n \times p}$ is fixed effects design matrix, $\beta \in \mathbb{R}^p$ fixed effects, $Z \in \mathbb{R}^{n \times m}$ random effect matrix, and $ u \sim N(0, \sigma^2_z)$ , $e \sim N(0, \sigma^2_eI_n)$
Once fit, one can extract the random effects (or essentially the prediction of random effects) (given $y$, $\sigma^2_z$ and $\sigma^2_e$) and it would be something like $u \sim N(m, \Sigma)$ say through conditional distribution $E(u|y)$ and $Var(u|y)$
The question is: How can one estimate the percent variance explained $p$ by a subset of columns of $Z$, say $S$, without refitting the model and using the informtion provided by the fit above which are $\sigma^2_z$, $\sigma^2_e$ and  $u \sim N(m, \Sigma)$

I can think of the following approaches:
Approach 1: I have seen the following approach in the literature (particularly in genomics):
$$ p = \frac{w_2\sigma^2_z}{w_0\sigma^2_z + w_1\sigma^2_e}$$
where $w_1 = 1$ and $w_0 = \frac{1}{n-1}tr(CZZ^T)$ where $C = I_n - \frac{1}{n} 1_n1_n^T$ is the centering matrix. And the reason for doing this is $w_0$ is basically expected value of sample variance of $z \sim N(0, ZZ^T)$. Now as for the $w_2$ and assuming $S$ is a column subset of $Z$, I have $w_2$ being evaluated this way: $w_2 = tr(CSS^T)$
Approach 2: I also see the possibility of applying the same subsetting strategty to the blups. i.e. $u_s \sim N(\mu, V)$ where $u_s$ is the vector made up of elements of $u$ corresponding to the $S$ subset of $Z$. Since have are talking about the affine transformation then $b \sim N(Su_s, SVS^T)$ is the prediction vector of the subset. Now one can move forward with calculation of coefficient of determination and so on.
Answer: To estimate the proportion of variance explained by a subset of columns of $Z$, a proper approach would be to compare the residual error variance of the regressions with the full model and the reduced model after dropping the corresponding variables of those columns. But based on the restriction that refitting the model is not permitted, Approach 1 is sensible. There, in the denominator, the expectation of the residual sum of squares is taken. This residual sum of squares is the sum of due to the error component $\epsilon$ and the variance of the random effect $u$. On the numerator, you have the expectation of the explained sum of squares corresponding to the random effect $u$.


Can you configure IIS7 to use SSL for some pages but not others?

Question: We are deploying a MVC2 site to production and would like to restrict SSL to the login and home pages (Home page has a login box also). Is this a job for Url Rewrite?
Answer: Yes, URL Rewrite is great for this.
IIS itself makes SSL an option for you, but it's up to you to point users to https and back again in your HTML/site.  URL Rewrite then serves as a good layer of protection in case anyone bookmarks a page or types it in manually, or if you miss something in the HTML.
In URL Rewrite, use {HTTPS} = off and {URL} to check if the page needs to be redirected to https.
Comment: Scott, thanks for the quick reply. If I understand you correctly we need to make some code changes and also use the rewrite module. Yes?
Comment: Yes, the code changes aren't absolutely required, but if the links within the site directly point to the https or http absolute paths, it's cleaner.  URL Rewrite can get everything else, like direct links to your homepage and such.
Answer: Might be easier to do this from your application code. It should be two or three lines at most to redirect to https://{url}?{querystring}
Answer: I think this is probably a bad idea except in very particular use cases. Presumably you're passing a session cookie back after the user has logged in. Unencrypted, this cookie is incredibly easy to sniff out on public networks and use to hijack the session, as FireSheep has probably made evident to most developers by now.
If you're serious about protecting your users' logins, then you need to protect the session cookie and not just their password.


ImageStyles does not create thumbnail image while uploading large images

Question: I try to create a website using Drupal on a shared host, everything goes fine except ImageStyles.
When I try to upload large images (more than 1MB) thumbnails does not created , but works fine with smaller one.
I searched it and found these two:
Failing to create thumbnail, medium and large images
Image styles: Does not work with large images
but I can't use these solutions because I'm using a shared host.
Any suggestion will be appreciatived ;)
Answer: You can restrict the image upload size using field settings in the admin to less than 1 MB and show a help text that max upload size is 1 MB.
Other option already given by Molot.
Hope it will  help you.
Comment: Actually, this option was also already given by me, in point 1, but without details you provided... I believed hostings so restricted are song of the past anyway, and restricting images to something with poor quality sounds a bad idea. Way better than errors and missing thumbnails, of course, but bad anyway.
Comment: @Molot, I have already given priority to your answers.
Answer: If Drupal can't resize images due to not enough RAM or due to timeouts, and you can't change RAM and timeout settings, and can't change library, then you have only three options:

Limit image size to something your installation can handle.
Provide additional field for thumbnails and make your users prepare them.
Change hosting.

Personally I would go with 3.
Comment: how can I get the real problem is which one: Ram or Timeouts? I want to talk to host provider and ask him/her to fix it
Comment: Well, that's something only **he** can see, it's in the server's error log. Unless he provided you with error log access, of course. But if he would, you wouldn't be asking now.


Como obter latitude / longitude de um geoendereço usando Qt c ++ no windows?

Question: É possível obter as coordenadas (latitude e longitude), de uma localização geográfica usando apenas o endereço, no Qt c ++?
Eu conheço as bibliotecas QGeoCoordinates, QGeoLocation e QGeoAddress, mas eu não sei se é possível obter coordenadas de um endereço através delas.
Toda ajuda é bem-vinda.
Answer: Através de uma resposta que recebi de um usuário aqui do Stack Overflow em inglês, esta que pode ser encontrada aqui, pude elaborar uma função que consiga perfeitamente achar as coordenadas através do endereço, segue:
<code>QGeoCoordinate MainWindow::getGeoCoordinates() {
    QEventLoop loop;
    QGeoCoordinate qGeoCoord;
    QStringList qGeoSrvList = QGeoServiceProvider::availableServiceProviders();

    for (QString entry : qGeoSrvList) {
        QGeoServiceProvider qGeoService(entry);
        QGeoCodingManager *pQGeoCoder = qGeoService.geocodingManager();

        if ( ( qGeoService.error() == 0 ) && ( qGeoService.errorString().compare("") == 0 ) ) {
            QLocale qLocaleC(QLocale::C, QLocale::AnyCountry);
            pQGeoCoder->setLocale(qLocaleC);

            QGeoAddress qGeoAddr;
            qGeoAddr.setCountry( "país" );
            qGeoAddr.setPostalCode( "cep" );
            qGeoAddr.setCity( "cidade" );
            qGeoAddr.setStreet( "rua, número" );
            qGeoAddr.setState( "estado" );

            QGeoCodeReply *pQGeoCode = pQGeoCoder->geocode(qGeoAddr);

            connect( pQGeoCode, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();

            if ( pQGeoCode->error() != QGeoCodeReply::NoError ) {
                qDebug() << pQGeoCode->error() << " | " << pQGeoCode->errorString();
                break;
            } else {

                QList<QGeoLocation> qGeoLocs = pQGeoCode->locations();
                for (QGeoLocation &qGeoLoc : qGeoLocs) {
                    qGeoLoc.setAddress(qGeoAddr);
                    qGeoCoord = qGeoLoc.coordinate();
                }
            }
        }
    }

    return qGeoCoord;
}
</code>
OBS: Lembrando que no .pro deve ser adicionado QT += positioning location


How large is the certificate OCSP and CRL cache in my Windows server?

Question: How can I see the size of the in-memory OCSP cache to a CRL cache in my Domain Controllers?
In other words, most Windows process that uses CryptoAPIs have an in-memory cache of every CRL and OCSP relevant for that application.  This is important since there is a huge performance tradeoff between client memory usage and quantity of network IO requests.
In my case the CRL "client" is a server that validates WCF certificate authentication
Answer: Monitoring the cache size is important when any PKI application needs to verify the CRL of several certificates.  AD for example will consume 100MB of RAM for 50,000 OCSP users vs 4MB when using the CRL method of validating users' certificates.  reference
There are two types of caches, disk and memory.  Although this doesn't directly answer the question perhaps the size of the disk cache will help one infer the size of the memory cache
The CRL disk cache size is found by typing the command
<code> certutil -urlcache crl
</code>
...and multiplying by 80 bytes per entry
The OCSP  disk cache size is found by typing
<code> certutil -urlcache ocsp
</code>
and multiply the entry count by 2 kilobytes (KBs).


How to create an article sharing site?

Question: I need to design a site which would let people write & share their articles, essays, poems, pretty much any written stuff. It should have complete Facebook integration - registration, likes & comments all from Facebook API.
I found that Drupal would be perfect designing such a site.
I've never used Drupal before. Any advise on how to go about making such a site using Drupal? Are there any contributed modules I could use?
Comment: yes, Drupal is a great solution for your friend's website. Articles, essays, poems and other written stuff can be model with "content types" and there are several options for Facebook integration. A very quick way to get a taste of drupal is to checkout [drupalgardens.com](http://www.drupalgardens.com/). It's using Drupal version 7 and I recommend using version 7 over version 6.
Answer: Because you are very inexperienced with Drupal, you don't know that your question is actually a set of several questions.
If you never have used Drupal before, you must understand a few basic things about Drupal, then learn about how to install it, and how to administrate (and customize) your Drupal to add the features that you want.
Also, Drupal has installation profiles; there are a variety of "pre-configured" versions of Drupal you can download and use for common needs. I am not sure any profile exists that is specialized for your needs, but you can search and select the most suitable and customize according your needs.
Update:
If you have installed a Drupal version, and have reviewed the basics of Drupal administration, you can find and test several options for modules to (integrate with Facebook](http://drupal.org/search/apachesolr_multisitesearch/facebook%20Integration?filters=ss_meta_type%3Amodule). For letting people share their content, you can review that with Content Types and CCK fields (CCK is needed for Drupal 6) you can create separated types of content having custom fields according your needs.
here http://drupal.org/documentation/modules/field-ui and here http://drupal.org/node/774728 are documentation about how to create a Content Type, and here is screenshot about where you can add custom fields for Content Types:

Remember review Drupal profiles, can be a suitable answer that you can customize with content types and Facebook integration.

How to create an article sharing site?


Ridging a singular covariance matrix (SEM)

Question: Structural equation models sometimes cannot be fit due to a singular sample covariance matrix. Now some authors suggest to apply a "gentle ridging" to the diagonal which helps (this is for example done in Mplus).

How does ridging exactly work? and
If your preferred SEM software does not support ridging, how can you do it "by hand"?
Answer: I can kill two birds with one stone by explaining how you get an ols software to fit ridge regression for a fixed ridging parameter.  You simply augment the data set you have with one observation for each beta you intend to ridge but set the covariate pattern to be all zero except for the ridging variable which gets set to the square root of the ridging parameter.
This includes the intercept.  So you need to define your own intercept variable as it will have zeros in the data augmented version.
Also you set the data augmented "response" variable to whatever you want the betas to be shrunk towards.  Typically these are all zero.
If you do the maths on the augmented data set, you'll get the ridged beta estimate.
You will also find that the augmented x matrix is now full column rank.  I can add the maths if you want but I don't think you need it.
Note that this only helps with understanding for fixed value of the ridging parameter. Choosing a good value is another issue.
Comment: The paucity of capital letters leads me to suspect you're posting from a mobile device, again. :-) In Hastie, et al., there is a problem which leads the reader through this data-augmentation interpretation.
Answer: If you have a singular sample covariance matrix, it means that your variables are perfectly collinear, or one of the variables does not vary. I would say you have to reconsider your model, rather than to try to tweak something in the black box called Mplus to make it kinda work.


How do I scrape a website that ignores my headers?

Question: test_url = 'https://crimegrade.org/safest-places-in-60629/'

test_headers = {
    'accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'accept-encoding' : 'gzip, deflate, br',
    'accept-language' : 'en-US,en;q=0.9',
    'cache-control': 'no-cache',
    'cookie': '_ga=GA1.2.1384046872.1654177894; _gid=GA1.2.924008640.1654177894',
    'pragma': 'no-cache',
    'referer' : 'https://crimegrade.org/crime-by-zip-code/',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests' : '1',
    'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36'
          }

crime_response = requests.get(test_url, headers=test_headers)
print(crime_response.content)

I've managed to scrape other websites with a similar approach before, but I haven't been able to get parameters or a clean 200 status code for crimegrade.org. I think that's why I'm getting this response:
\
Please enable cookies.\

Do you have any advice on how to solve this?
Comment: It doesn't work, but thank you for listing this tech.
Comment: Maybe try cloudscraper? `https://github.com/VeNoMouS/cloudscraper`
Comment: It use antibot Cloudflare nothing to do with python requests. It works with playwright, when you open real browser and you can scrape it.
Comment: Playwright is a good option for raw scripting, but I'm using Jupyter. Playwright doesn't work with Jupyter on Windows 10. It's important for me since I can showcase the work more easily, so I'll hunt for a similar module.
Answer: Through a bit more reading, watching, & hunting on my end, I managed to get around this with a very conventional method of automating my browsing with Selenium. My code is below.
Note: .page_source gives the html data which can be parsed with BeautifulSoup. It is akin to the .content yield in my original post, except it's the information I need.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

crime_url = 'https://crimegrade.org/safest-places-in-73505/'
chrome_driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
chrome_driver.get(crime_url)
crime_html = chrome_driver.page_source
chrome_driver.quit()


Jquery get tr value

Question: in below code I want to get the values from a specified  in jquery.means I want to get the value of tr class=2 how can I achive this?

    ........

    >/tr>

    ......

    ........

Comment: Did you try anything for this?If yes ,Show the code you used
Comment: yes wait I will show you
Answer: If you want html of row, then try this, You should you meaningful name for class and should be alpha numeric if not aphabetical.
Live Demo
$('tr.2').html()

You have many errors in html of not closing the class attributes in quotes and using angle bracket of tr. check the corrected html.

                ........

                ...tr with class 2...

                ........

Answer: There are lots of selectors you could use, but I would use something like:
$("div.fav").find("tr.2")

However, the code you posted is missing some quotes around some of the class names which would stop it working:

........

>/tr>

......

........

Comment: But sir the tr class is not static its coming dynamically..
Comment: then how I get the value?
Answer: Try this,
$(document).ready(function(){

 var class_name="3"; //you can specify the class name here

 var x=$("div.fav").find("tr."+class_name+" td").html();
 alert(x);

});

Get
      ........

Comment: But the tr class is not static its coming dynamically.
Comment: @user2318361  Can you explane your requirement?When you need to find the value? On page load or on button click,Please specify
Comment: @user2318361,I ahve edited my answer,Now you can assign values dynamicaly to var  class_name

Jquery get tr value


Derive missing input values from input data probability distribution,

Question: Could you please provide me with information on how I can derive missing input values from input data probability distribution?
I mean for instance I have input features which are molar fractions of hydrocarbon compounds like CH4, C2H6, C3H8 ... C10H22.
The task is that in almost every training example I don't have data about molar fraction for three random components. Since these are real compositions from oil fields there's some distribution between compounds and some of the missing values can be retrieved considering known values of the rest of the components. The problem is that I cannot find any theory about it. I will be really grateful if someone can help me with the problem!
UPD:
I have points like (70,12,5), (45,26,12) etc. There's a clear dependence that the more the first value, the less the second and the third. Given points with missing values like (65, missing, 8) I would like to fill them with the most probable value according to joint probability distribution over whole my set (I know that first value is 65, I know the last value which is 8 and I have lots of such data where some values might be missing, but I need to utilize all the information from each entry (point) as much as possible to fill the missing value with the most probable value). I'm sure there's a solution, but I don't know the name of theory that describes how such tasks are solved properly.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Added explanation to the end
Answer: I think I understand what you are asking. I would use MICE (multiple imputations by chained equations). This has the advantage of using multiple imputations, rather than single mean imputations, which is frowned upon nowadays.
https://datascienceplus.com/imputing-missing-data-with-r-mice-package/
^ here is a really easy and detailed method for it in R
https://cran.r-project.org/web/packages/miceRanger/vignettes/miceAlgorithm.html
^ This also has some information on it too. Helpful for a methods section


Applying the Curl Thm. to a surface given its boundary

Question: The Question:
Let $F(x,y,z) = (y+\sin(x),z^2+\cos(y),x^3)$ and $\mathcal{C}$ is the curve parametrized by $r(t)=(\sin(t),\cos(t),2\sin(2t))$ with $t$ ranging in $[0,2\pi[$. Use the curl theorem to find $\displaystyle\int_\mathcal{C}F\cdot ds$.
My approach:
I know, by the curl thm. that $\displaystyle\int_{\partial S}F\cdot dr =\int_{ S}\operatorname{curl}(F)\cdot d\Sigma$
I calculated the curl for $F$ and the result was $\operatorname{curl}(F)(x,y,z)=(-2z,-3x^2,-1)$.
The boundary of the surface which the theorem talks about is the curve generated by the parametrization I was given, this means I need to find a surface $S$ such that $\partial S = \mathcal{C}$. Here lies my problem.
Once I've found the surface $S$,  I need to parametrize it with $\alpha:D\subseteq \mathbb{R}^2\to \mathbb{R}^3$. With this I get $\displaystyle\int_{ S}\operatorname{curl}(F)\cdot d\Sigma = \iint_D\text{curl}(F)(\alpha(u,v))\cdot (\alpha_u\times\alpha_v) dA\,$ which is a double integral that I can calculate.
My problem:
I can't find the surface whose boundary corresponds to $r([0,2\pi[)$. I've already plotted the curve in Mathematica and it looks like the border of a pringle potato.
My gut tells me that the surface I'm supposed to use is "the potato" but I can't get my head onto it. I feel like there are many surfaces which I can't imagine that have the curve $\mathcal{C}\,$ as a boundary.
Still, if it were the "potato" I am not able to find the parametrization for it. This is where I need help.
$\textbf{Concretely}$ I need to find the parametrization of the "pringle potato" whose boundary is my curve $\mathcal{C}$ and an explanation of why is that the correct surface to think about.
Answer: Two suggestions: You could take the cone on this curve, just sticking in an $r$ parameter in front of the whole thing ($0\le r\le 1$). But what you had in mind is to use that portion of the the "potato chip surface" $z=4xy$ lying inside the curve. (How did I get this? I used the double-angle formula to write $z=2\sin(2t)=4\sin t\cos t = 4xy$.) I haven't tried doing either surface integral to see which is more accessible; I leave those to you. :)
Comment: The suggestion about $z=4xy$ was incredible, I was able to find that the surface which I tried to describe is surface of that function bounded by a cylinder. With this I am able to find the $\alpha$ parametrization I needed. Thank you kindly.


How to enforce no-extend-native in es6 compiled using babel?

Question: I want to create a new method to built-in objects Array and Date. I have seen everywhere on the internet that using Object.prototype is evil. Also, I read that subclassing built-in objects is not supported in babel. So how can I add new methods to built-in objects using es6?
Comment: "you can't create subclass by extending built-in classes" is not correct.
Comment: You can do in ES6 everything you can in ES5. You can add methods to a prototype. I do it for polyfills often.
Comment: Your question title does not match your question body.
Comment: @Kulvar You can do in ES6 much more than you can in ES5 - specifically subclassing builtins.
Comment: I said that everything in ES5 is available in ES6, not that ES6 can't do more than ES5
Comment: @stri : One edit, I am using babel to compile ES6 to ES5. Hence, it gives type error if I try to subclass the built-in objects.
Answer: There is nothing stopping you from creating subclasses that extend built-in classes, in fact, it's often a good baseline solution for minor changes.

class Foo extends Date {
  bar() {
    console.log(this);
  }
}

const foo = new Foo();
foo.bar();


How do I load taxonomy terms basing on the current language?

Question: I am using the following code.
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('category', 0, 1);

How can I change it so it load the taxonomy terms basing on $language?
Answer: Use EntityRepositoryInterface::getTranslationFromContext:
$terms_translated = [];
foreach ($terms as $key => $term) {
  $terms_translated[$key] = \Drupal::service('entity.repository')
    ->getTranslationFromContext($term, $language);
}

BTW, you don't need to provide a language code, because the current content language is the default value for the second parameter in getTranslationFromContext() and in a standard multilanguage site this is equal to the current language.
Comment: Thanks @4k4 for answer. I have updated code. Getting error can you please help with that?
Comment: You need a 4th parameter to load the terms: `loadTree('category', 0, 1, TRUE)`. (don't edit the answer into the question, future readers don't see the original question)
Answer: You can also use:
foreach ($terms as $term) {
  if ($term->hasTranslation($langcode)) {
    $term = $term->getTranslation($langcode);
  }
  ...
}

probably more convenient as you dont have to inject entity.repository


Finding $\mathbb{E}(\xi|\eta)$

Question: Vector $(\xi, \eta)$ is evenly distributed in set $D=\{  (x,y): 0\leq x\leq 1, 0\leq y \leq 1, x+y \leq 1   \}$. I need to find $\mathbb{E}(\xi|\eta)$.
So first of all I found the size of $D$. It is $\int_{0}^{1}(1-x)dx= \frac{1}{2}.$
Now I think I need to find the density function $p(x,y)$. How could I find it? Is it 2?
Than am I right $p_1(x) = 2(1-x)$ and  $p_2(y)=2y?$
Next step maybe should be finding $p_2(y|x)$ and $p_1(x|y)$ and after than I can find $\mathbb{E}(\xi|\eta)$. Am I right? How to find all those density functions?
Comment: Without mentioning support, density function is meaningless.
Comment: Yes. The distribution possesses the value of $2$ throughout $D$
Comment: @MostafaAyaz yes! Is it because $1/|\mathcal{D}|$?
Answer: The area enclosed by the region $D$ is $\frac{1}{2}$.
Hence the density of $(X,Y)$ uniform on $D$ is
$$f_{X,Y}(x,y)=2\,\mathbf1_{0<x,y<1\,,\,x+y<1}$$
Rewriting the above we see that the density factors as
$$f_{X,Y}(x,y)=\underbrace{\frac{1}{1-y}\mathbf1_{0<x<1-y}}_{f_{X\mid Y}(x)}\,\,\underbrace{2(1-y)\mathbf1_{0<y<1}}_{f_Y(y)}$$
So $X\mid Y$ is uniformly distributed over $(0,1-Y)$, giving $$E(X\mid Y)=\frac{1-Y}{2}$$
Comment: I don't understand how did you get the second line... I trying to find $p_1(x)$ and $p_2 (y)$.
Comment: @Atstovas $f_{X,Y}$ is the joint density of $(X,Y)$, what you are calling $p(x,y)$. $X$ and $Y$ have the same distribution. Your $p_1,p_2$ is my $f_X,f_Y$, where $f_X(x)=\int_0^{1-x} 2\,dy\,\mathbf1_{0<x<1}$. The conditional density of $Y\mid X$ is $f_{Y\mid X}(y)=\frac{f_{X,Y}(x,y)}{f_X(x)}$ and similarly for $X\mid Y$.
Comment: Okey, so how should I do if I want also to find $\mathbb{E}(\eta|\xi)?$
Comment: @Atstovas That should be obvious. You tell me. I gave you pretty much everything to answer the question.
Comment: is $f_Y(x)=\int_{1-y}^1 2dx \mathbf{1}_{0<y<1}?$
Comment: @Atstovas As I said before, $f_X=f_Y$. Considering the symmetry of $X$ and $Y$, isn't it sufficient to find distribution of $Y$, distribution of $X\mid Y$, $\quad E(X\mid Y)$ to answer the same for $X$, $\quad Y\mid X$, $\quad E(Y\mid X)$ and vice-versa?

Finding $\mathbb{E}(\xi|\eta)$


AJAX error when ctools_modal_command_dismiss() is called

Question: So I'm having a problem with dismissing a Ctools modal within a form submit's callback function. Once I have processed any submit data, I'd like to dismiss the modal without redirecting the page (easy enough), but each time I click the submit button with ctools_modal_command_dismiss() included in the callback function, I'm presented with an AJAX error such as below:
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.
I'm stumped as to why this is happening. The modal works perfectly without the dismiss function.
function pay_rise_menu() {
  $items = array();
  $items['pay_rise/%ctools_js'] = array(
    'page callback' => 'pay_rise_modal_email_share',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );

  return $items;
}

function pay_rise_modal_email_share($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Share by email'),
    );

    $output = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('pay_rise_modal_email_share_form');
  }
}

function pay_rise_modal_email_share_form($form, &$form_state) {
  $form = array();

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#attributes' => array(
      'placeholder' => 'Recipient email...',
    ),
  );

  $form['body'] = array(
    '#type' => 'textfield',
    '#title' => t('Message'),
    '#attributes' => array(
      'placeholder' => 'Message...',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'pay_rise_modal_email_share_form_callback',
    ),
  );

  return $form;
}

function pay_rise_modal_email_share_form_callback($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
  $form_state['ajax_commands'] = ctools_modal_command_dismiss('Thanks. Your message has been sent.');
}

The above is invoked once the following link is clicked:
l('email', 'pay_rise/nojs', array('attributes' => array('class' => 'ctools-use-modal icon-mail')))

Comment: " Debugging information follows." - post it. Look in watchdog, in server's logs etc.
Comment: That's the thing - it says 'error', yet there are no AJAX errors after checking logs/posting to dblog. I initially thought it might have something to do with execution_limit, however the response code is a 200.
Comment: @AdamThomason Additionally you can see ajax request/response with Firebug extension(Console tab)
Comment: I've tried firebug too, but with no luck! I'm beginning to think it's something down to my vagrant configuration, although surely this wouldn't only affect one AJAX request!
Comment: @AdamThomason what it shows?
Comment: It has the same debug output as the 'error' window. It's strange, everything is showing as code 200, so I'm stumped.
Answer: You are doing it wrong, ctools modal works a little bit different. Better do it like this:
remove #ajax property from form submit button, let it work as usual:
...
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
...

define submit callback as usual:
function pay_rise_modal_email_share_form_submit($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
}

build modal callback:
function myCallback($js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => t('My modal title'),
    'ajax' => TRUE,
    'build_info' => array(
      'args' => array(),
    ),
  );

  $commands = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

  if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();
}

ctools itself handles ajax submission.. That's it.
Comment: Hi @xurshid29. I notice that you've taken that example from a guide on how to do this, which I googled for before posting my question. The reason I have not used a standard submit handler is because of other things going on within the callback. The above above does not work either I'm afraid, and still generates the exact same AJAX error.
Comment: @AdamThomason I've taken it from Ctools help directory:) and there are almost ten modal forms in my current project and they are all works by this way, they work fine, without any errors
Comment: @AdamThomason And I also see that there are some missing keys in your `$items` array in hook_menu implementation..
Comment: Just figured this out, see my answer. Thanks for all your help, much appreciated!
Comment: The code which I sampled and put in here is not the complete module. I have only put in the code that is relevant to this issue, else there would be thousands of lines which would be unsightly. Thanks for your help.
Answer: Managed to solve this myself with the following:
By default, the php.ini file on a precise64 vagrant box sets execution_limit to 30 (for some reason). Increasing this incrementally seems to have fixed the issue for me at least.


union of two locally connected sets is still locally connected

Question: Suppose $A$ and $B$ are spaces of $X$ and $A$ and $B$ are locally connected and $A\cap B\neq \phi$,Must $A\cup B$ locally connected?
Part of my thought:Suppose $x\in A$,  $ x\notin B$,for any open neighborhood of $x$ in $A\cup B$,$U$,there exists an open set in $X$ ,$V$,s.t. $U=(V\cap A)\cup(V\cap B)$.Considering open set in $A$,$V\cap A$,there exists a connected open connected neighborhood in $A$ contained in $V\cap A$.But this open connected neighborhood in $A$ may be not an open neighborhood in $A\cup B$. Can we disprove this statement from this detail?
Comment: @bof their intersection should be nonempty
Answer: Let $X=\mathbb R^2$ and let
$$A=\{(x,y):x\gt0\text{ and }y=\sin\frac1x\},$$
$$B=\{(x,y):x=0\text{ or }x=1\text{ or }y=2\}.$$
Then $A$ and $B$ are connected (which you did not require but perhaps intended) and locally connected, and $A\cap B=\{(1,\sin1)\}\ne\emptyset,$ but $A\cup B$ is not locally connected.


Gradle build failing after updating to Gradle 1.2.2

Question: I have a java project that utilizes Gradle for testing and building. I recently had to update my JVM to 1.7.0_75 to use Maven for another project for work.
Now I have gone back to my Gradle project, I found that gradle -v was returning command not found, and after I used brew install Gradle, my build script returns the following error:
* Where:
Build file '/Users/adamhardie/Documents/Workspace/sagepay-stub/build.gradle' line: 27

* What went wrong:
A problem occurred evaluating root project 'sagepay-stub'.
> No such property: testReport for class: org.gradle.api.tasks.testing.Test_Decorated
Possible solutions: testReporter

I have confirmed the build.gradle script has not been altered in any way since it was last working, so what could be the possible cause of this error?
Below is the part that seems to be causing issues ( it is the build script for this project: https://github.com/azagniotov/stubby4j )
if (project.name != 'main') {
  tasks.withType(Test) {
     Task testTask ->
        def totalSuiteCount = 0
        def successSuiteCount = 0
        testReport = false
        testLogging {
           events /*"passed", */"skipped", "failed"
           exceptionFormat "full"
           showExceptions true
           showCauses true
           showStackTraces true
        }
        doFirst {
           //println ""
           //println "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
           //println ":::::                         Running " + project.name.toUpperCase() + " module tests"
           //println "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
        }
        afterSuite { testDescriptor, testResult ->
           if (testDescriptor.getName().contains("$stubbyProjectGroup")) {
              totalSuiteCount += testResult.getTestCount()
              totalTestCounter += testResult.getTestCount()
              successSuiteCount += testResult.getSuccessfulTestCount()
           }
        }
        doLast {
           println ""
           println "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
           println ":::::                         Ran " + project.name.toUpperCase() + " module tests"
           println "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
           println ":::::                             Passed (" + successSuiteCount + "/" + totalSuiteCount  + ") tests"
           println ":::::               Total tests executed in $stubbyProjectName project so far " + totalTestCounter
           println "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
           println ""
        }
  }
}

Comment: Has gradle version being used changed?
Comment: i presume so, i had not updated in a while. I am not sure why gradle was removed from my classpath, so i used brew to re install. My current version is 2.2.1 but i am not sure what i was before
Comment: So it seems You've found the reason.
Comment: ok thanks, what would you suggest i do to solve this?  revert to an older version? i dont know why updating would break my build script, is it possible some component has been deprecated?
Comment: There's a hint in error message: `Possible solutions: testReporter`. Probably the component name was changed.
Comment: i did attempt that first , but i am getting another error to do with a boolean value
> Cannot cast object 'false' with class 'java.lang.Boolean' to class 'org.gradle.api.internal.tasks.testing.junit.report.TestReporter'
Comment: Share critical `build.gradle` part.
Comment: updated question with link to full project and sample of build script, thanks for input so far
Comment: As far as I understood your current gradle version is 2.2.1?
Comment: As far as I see You'd like to ignore test report? You previous version must have bean at least 1.12 - see here for deprecation: http://gradle.org/docs/1.12/javadoc/org/gradle/api/tasks/testing/Test.html
Comment: Let me know if it worked. Maybe will add it as an answer.
Comment: It is definitely depreciated, but i have not changed the build script. Instead I downgraded my gradle version to 1.12 in order to complete my work. I will try to alter the script once I have finished and update
Comment: it seems that replacing testReport = false with "reports.html.enabled = false" allows the script to continue, but there are multiple other depreciation errors caused by upgrading to 2.2.1. My issue is resolved though and I am able to build my Jar. Thank you for your help
Comment: May I add it as an answer for your acceptance?
Comment: of course! add and i will accept when i can.
Answer: Apologies for replying so late:
stubby4j has been upgraded to use Gradle 7.2 recently. To add more, the current project Gradle config has a standard configuration without any custom add-ons nor hacks.
Answer: It seems that gradle version was changed by accident and thus the problems. testReport for Test class is deprecated from at least 1.12 version of gradle.
Now reports can be configured via reports as stated here.


Determine if the solution to a division is odd or even

Question: Is there a way to quickly determine if the solution to a division operation will be odd or even? I need a quick way determine that in a program. Doing a complete a complete division takes up too much time.
Here is something that is known beforehand:

both numbers are even
there is no remainder
in $a/b$, b is not $2^n$

I tried to look into patterns in their binary representations to no avail. Currently what I have is
<code>isOdd = (a / b) & 1;  //pseudocode
</code>
but dividing two big numbers is just too expensive.
Comment: And you want things efficient as hell? The best is then almost certainly the `ctz` instruction (`count of trailing zeros`), might be named differently on different processors, and how to get it would depend on the compiler, something like `__builtin_ctzl` on gcc, might also work with clang. Without the machine instruction, I think `(a ^ (a-1)) == (b ^ (b-1))` would be the fastest, two subtractions, two xors, one comparison to tell you whether the quotient is odd.
Comment: Are they machine integers or an arbitrary precision type?
Comment: @DanielFischer They are integers (of type `unsigned int`.)
Comment: @DanielFischer Thanks! I will give that a try.
Answer: You have the numbers in binary form already?  Then just compute $ord_2$ of $a$ and $b$.  Here, $ord_2(n)$ denotes the greatest power of $2$ which divides $n$.  Thus $ord_2(5)=0$, $ord_2(24)=3$, and so on.  You can read this off from the binary forms...$ord_2(n)$ is the number of zeros before the first one in the binary representation (reading from right to left).  Thus $$ord_2(10111011000)=3$$
To solve your problem, note that the quotient $\frac ab$ will be even if and only if $ord_2(a)>ord_2(b)$.
Comment: Side note:  I passed this question on to my brother, who does this sort of thing for a living.  He (instantly) replied:  "rightmostAbit = A ^ (A & (A - 1));  /* that's an XOR in addition to the & and the subtraction */
rightmostBbit = B ^ (B & (B - 1));
if (rightmostAbit > rightmostBbit)
    then A/B is even, if integer (this was promised)"  Not entirely sure I follow, but perhaps you do.
Comment: Thanks for the answer, but determining the exact number of zeros might be slower than just a simple division operation. Is there's some fast way to determine that that I happen to not know?
Comment: Well, you don't need the exact number.  All you need is to know if the two counts match or not.  Just make a loop wherein you strike off a zero from the right so long as both terms have a zero there.  Once $b$'s zeros are done, just check to see if the units place of $a$ is $0$ or not.
Answer: C-style code:
<code>/* Assumes b!=0 and a divisible by b */
bit_index = 1
while (b&bit_index==0) {
  if (a & bit_index) { /* Error, a is not divisible by b; odd over even */ }
  bit_index = bit_index >> 1
}
return (a&bit_index)>0
</code>
Answer: if a is even then a = $2^n*a'$ for some odd a'.   b is even so b = $2^m*b'$.  So a/b = $2^{n-m}(a/b)$  which is even if n > m but odd if n = m.


Expected Value with RNG

Question: A random number generator generates one of the positive integers $1,2,\cdots,n$ at random, with any number $i$ having probability $p_i$ of being generated. The generator is repeatedly used and each time, the resulting number is written down on a list. For a positive integer $k$, find the expected value of the number of times the generator must be used before the list contains $k$ copies of some number.
Attempt: I tried to solve this problem, but ended up not getting an answer. This is what I did for this problem:
Let $X$ be the number of times the generator must be used before we $k$ repetitions of a number from $1, 2, \cdots, n$.
$$E[X]=\sum_{m=k}^{(k-1)(n)+1}mP[X=m]=\sum_{m=1}^{(k-1)(n)+1}mP[X=m]=\sum_{m=1}^{(k-1)(n)+1}\sum_{j=m}^{(k-1)(n)+1}P[R=j]=\sum_{m=1}^{(k-1)(n)+1}P[R \geq j]$$
Obviously, for $m=1, 2, \cdots, k$, $P[R \geq m]=1$. However, all other values I've found are harder to find.
Does anyone have a hint as to a solution of this problem?
Comment: As far as how I understand the problem, it is a negative binomial. You fail for a while until you stop failing.
Comment: So $k$ is fixed, no? Do you know negative binomial distribution? might be helpful.
Comment: @Phicar How useful would it be?
Answer: Let's say $T$ is the number of times the generator is used when we first have $k$ copies of some number in the list, so we want to know $E(T)$. We have $T>r$ when we have drawn $r$ numbers and no number has occurred more than $k-1$ times. The exponential generating function of $P(T > r)$ is
$$f(x) = \prod_{i=1}^n \left( 1 + p_i + \frac{1}{2!}  p_i ^2 + \dots + \frac{1}{(k-1)!}  p_i ^{k-1} \right)$$I.e.,
$$f(x) = \sum_{r=0}^{\infty} \frac{1}{r!} \;  P(T > r)\;  x^r$$
By a well-known theorem,
$$E(T) = \sum_{r=0}^{\infty} P(T>r)  $$so
$$E(T) = \int_0^{\infty} e^{-x} f(x) \; dx = \int_0^{\infty} e^{-x} \; \prod_{i=1}^n \left( 1 + p_i + \frac{1}{2!}  p_i ^2 + \dots + \frac{1}{(k-1)!}  p_i ^{k-1} \right) \; dx$$where we have made use of the identity
$$\int_0^{\infty} e^{-x} x^r \;dx =r!$$
Remark: We might think of this problem as a variant of the Birthday Problem in which we want to know the expected number of people required in order that $k$ of them have the same birthday, with unequal probabilities associated with each day of the "year".
Comment: I think you missed that the numbers generated are not uniform (first sentence of OP).
Comment: @MikeEarnest Oops, you are right!  I'll have to revise my answer--but I'm busy right now, so there will be a delay.  Fortunately, I think the same basic approach will still work.
Comment: @MikeEarnest OK, I think I've fixed it now.  Thanks for noticing.
Comment: Very nice application of EGFs. One last nitpick, now you have $p_i$ and $p_r$ meaning two different things.
Comment: @MikeEarnest (Groan) I've eliminated $p_r$, so the notation should now be consistent--I hope.

Expected Value with RNG


mistake in calculations for ImT and KerT

Question: I was asked to calculate ImT and KerT for the following linear transformation. I got to a result for both, but as can be seen from my conclusions, I know there must be a mistake somewhere along the way. Yet I cannot find it… Can anyone help out?
The linear transformation $T:M_{2x2}(R) \to R_3[x]$ is defined by:
$$T\begin{pmatrix}a&b\\c&d \end{pmatrix}$$$= (a-d)x^2+(b+c)x+5a-5d$
for every $$\begin{pmatrix}a&b\\c&d \end{pmatrix}$$$\in M_{2x2}(R)$
I reasoned in the following way:
For KerT:
a=d
b=-c
kerT:
$$\begin{pmatrix}a&b\\-b&a \end{pmatrix}$$=$$a\begin{pmatrix}1&0\\0&1 \end{pmatrix}$$+$$b\begin{pmatrix}0&1\\-1&0 \end{pmatrix}$$
So KerT = Sp{$$\begin{pmatrix}1&0\\0&1 \end{pmatrix}$$,$$\begin{pmatrix}0&1\\-1&0 \end{pmatrix}$$}
and as the matrices in KerT are clearly linearly independent, this is also a basis with dimension 2.
For ImT:
$(a-d)x^2+(b+c)x+5a-5d$ is a linear combination of the standard basis of R3[x], namely $(x^2,x,1)$. So $ImT = Sp\{x^2,x,1\}$. This set is per definition linearly independent and therefore $Sp\{x^2,x,1\}$ is a basis to ImT and its dimension is 3.
The problem is that according to my logic, n = dimKerT + dimImT = 5 and this is contradictory to the fact that n = dimKerT + dimImT = 4, as the dimension of $M_{2x2}(R)=4$
Comment: Use `$\{ X\}$` for $\{ X\}$.
Answer:
For ImT:
  $(a-d)x^2+(b+c)x+5a-5d$ is a linear combination of the standard basis of R3[x], namely $(x^2,x,1)$. So $ImT = Sp\{x^2,x,1\}$. This set is per definition linearly independent and therefore $Sp\{x^2,x,1\}$ is a basis to ImT and its dimension is 3.

It's not an arbitrary linear combination of those standard basis vectors, as the coefficients aren't independent. You could rewrite:
$$(a-d)x^2+(b+c)x+5a-5d = (a-d)(x^2+5)+(b+c)x$$
so it can also be written as a linear combination of (only) $x^2+5$ and $x$, so...

Or for a more general approach, rewrite as (split in all the coefficients):
$$(a-d)x^2+(b+c)x+5a-5d = a(\color{blue}{x^2+5})+b\color{red}{x}+c\color{purple}{x}+d(\color{green}{-x^2-5})$$
and reduce the spanning set $\left\{\color{blue}{x^2+5},\color{red}{x},\color{purple}{x},\color{green}{-x^2-5}\right\}$ to a basis by eliminating the linearly dependent elements.
Comment: Thank you! So my calculations for KerT were correct?
Comment: Yes, although you want to write a comma (instead of a $+$) between the two matrices that span the kernel (the basis has *two elements*, not the sum of two matrices); in the spanning set.
Answer: $$\text{Im}(T)\ne\text{Sp}\{1,x,x^2\}$$
This is because $T\Big(\begin{bmatrix}a&b\\c&d \end{bmatrix}\Big)=(a-d)(x^2+5)+(b+c)x=k_1(x^2+5)+k_2x$, which means $$\text{Im}(T)=\text{Sp}\{x,x^2+5\}$$ which is also a basis with dimension $2$.