When can a raider start riding in Kabaddi?

Question: Sometimes I see a raider waits for Umpire whistle to start raiding, but sometimes the raider just goes into raiding without waiting for the Umpire. What's the rule governing this?
I've seen some raiders just follow the opponent raider immediately and gets touch point. I don't understand this.
Answer: A defender following a raider into the opposite court is called Pursuit. Defenders cannot pursue when they feel like it, there are some rules to be followed.
Link to General Rules of Play:

viii. After a raider has reached his court, the opponents shall send
  their raider within 5 seconds. Each side shall continue to send their
  raider until the end of the game in this fashion. In case the raider
  fails to start his raid within 5 seconds the team loses its chance to
  raid and the opponent team is awarded a technical point.
ix. When a struggle takes place in a raid, on completion of such
  raid, Rule viii (above) will not be applicable. The next raid will
  start on the whistle of the referee after the out players have been
  seated in the out box.
x. If a raider, who is caught by one or more defenders, escapes from
  their attempt to hold and reaches his court safely, he shall not be
  pursued.
a. Note: But if a raider touches one of more defenders and reaches his
  court safely, he may be pursued.

Per rule ix., after raids in which a struggle took place, defender is not allowed to enter the opposite court until the referee blows the whistle, so he has to wait for the referee's whistle.
Per rule x. and rule x. a., a defender may pursue a raider if raider returns to his court after touching one or more defenders, but not if he escaped from a struggle.
Other than these cases, a defending team has to send a raider within 5 seconds, they don't wait for the referee's signal.
Answer: There are two cases here.

Raider can go immediately to the opposition court if the opponent raider had a empty ride.
But if the opponent raider gets touch point then the raider needs to wait till one person from opposition bench to join the defense. If he tries to raid before the opposition team member joins the team then the Umpire will whistles and asks the raider to start the raid again.


getConstructor with no parameters

Question: I can't seem to use getConstructor for constructors with no parameters.
I keep getting the following exception:
java.lang.NoSuchMethodException: classname.<init>()

Here is the code:
interface InfoInterface {
    String getClassName();
    String getMethodName();
    String getArgument();
}

class asa implements InfoInterface {
    @Override
    public String getClassName() {
        return ("jeden");
    }
    @Override
    public String getMethodName() {
        return ("metoda");
    }
    @Override
    public String getArgument() {
        return ("krzyk");
    }
}

class Jeden {
    Jeden() {
        System.out.println("konstruktor");
    }

    public void Metoda(String s) {
        System.out.println(s);
    }
}

class Start {
    public static void main(String[] argv) {
        if (argv.length == 0) {
            System.err.println("Uzycie programu: java Start nazwa_klasy nazwa_klasy2...");
            return;
        }

        try {
            for (int x = 0; x < argv.length; x++) {
                Class<?> c = Class.forName(argv[x]);
                InfoInterface d = (InfoInterface) c.newInstance();
                String klasa = d.getClassName();
                String metoda = d.getMethodName();
                String argument = d.getArgument();

                Class<?> o = Class.forName(klasa);
                // o.newInstance();

                Constructor<?> oCon = o.getConstructor();
                System.out.println("ASD");
                Class<?> p = (Class<?>) oCon.newInstance();
            }
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

o.newInstance(); prints "konstruktor" without problems.
Comment: has class o got any contructors in it? By default there is a no args one but as soon as you declare a constructor that has parameters then you will need to explicitly declare a no args one
Comment: It has only one, no args constructor. It work when I change it for one using string as argument and change the getConstructor accordingly.

I am told to use reflections, that's the point of this code
Comment: @pbabcdefp Yes it might work, but the parenthese suggest a method call, but this is not the case. It distracts a bit.
Comment: I think providing more code would be great
Comment: I updated the code for more info
Comment: Is `jeden` declared as an inner class? You should show all your code...
Comment: here is the rest of the code I got so far
Comment: are both classes in the same file?
Comment: Well, `return("jeden");` is not the proper way to return "something".
Comment: @Tom The brackets are redundant, but it works. Try it.
Comment: @RNJ: works when we add no-arg constructor in addition to the parameterized-constructor.
Answer: The problem is clear when you read the javadoc of .getConstructor():

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Emphasis mine.
In your code, the constructor is not public!
Example:
// Note: class is NOT public -- its default constructor won't be either
final class Test
{
    public static void main(final String... args)
        throws NoSuchMethodException
    {
        // throws NoSuchMethodException
        Test.class.getConstructor();
    }
}

Obligatory link to an SO answer which also gives the JLS reference. In particular, note that the default constructor has the same access modifier as the class.
Comment: @fge: works when we add no-arg constructor in addition to the parameterized-constructor.
Answer: It seems as if your class provides a constructor that is NOT a default constructor. The call to getConstructor() without parameters requires the class to have a default constructor. The following test illustrates this.
import org.junit.Test;

public class ConstructorTest {
    public static class ClassWithParameterizedConstructor {
        public ClassWithParameterizedConstructor(final String param) {
            // A parameterized constructor, no default constructor exists
        }
    }

    @Test
    public void testFoo() throws NoSuchMethodException {
        // Parameterized constructor lookup works fine
        ClassWithParameterizedConstructor.class.getConstructor(String.class);

        // This doesn't work since there is no default constructor
        ClassWithParameterizedConstructor.class.getConstructor();
    }
}

So, a possible solution is to either change the call to getConstructor() to include the correct type or to provide a default constructor on the object itself (but why would you do that?).
Answer: Read this: http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
It seems that both classes Class and Constructor have the method newInstance the difference is that in the Class class you can only call newInstance with no arguments, so the called constructor must have an no arguments (this also brings a problem when you have more that one constructor).
The methoe newInstance in the Constructor class allows you to call the constructor with arguments also, notice that you can also use the method getConstructors instead of getConstructor that returns you all the class constructors and allows you to call the constructor method you want.
In this case, since you only have one constructor only and with no arguments, Class.newInstance works fine. To use the getConstructor to have the same result you'll need to add in the end oCon.newInstance();
Answer: You can use getDeclaredConstructors() which returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object
class SomeClass{

    {
        System.out.println("I'am here!");
    }

}

public class Main {
    public static void main(String[] args) throws Exception{

        System.out.println(Arrays.toString(SomeClass.class.getDeclaredConstructors()));
        // returns public, protected, default (package) access, and private constructors

        // System.out.println(SomeClass.class.getConstructor());
        // in that case you got:
        // NoSuchMethodException: reflection.SomeClass.<init>()
        // because SomeClass don't have public constructor

        for (Constructor constructor : SomeClass.class.getDeclaredConstructors()){

            constructor.newInstance();
        }

    }
}

And if you have private constructor like this:
class SomeClass{

    private SomeClass(String val){
        System.out.println(val);
    }

}

You have to set accessible for constructor:
constructor.setAccessible(true);

And get something like this:
class SomeClass{

    private SomeClass(String val){
        System.out.println(val);
    }

}

public class Main {
    public static void main(String[] args) throws Exception{

        for (Constructor constructor : SomeClass.class.getDeclaredConstructors()){
            // constructor.newInstance("some arg");    // java.lang.IllegalAccessException
            constructor.setAccessible(true);
            constructor.newInstance("some arg");
        }

    }
}

Note: if your class declared as private his default constructor must be private too.
And be careful with nonstatic-inner classes, which receives an outer class instance
Answer: In this (somewhat convoluted) scenario, it's actually possible to get hold of the (non-public) constructor by replacing:
Constructor<?> oCon = o.getConstructor();

with
Constructor<?> oCon = o.getDeclaredConstructor();

The "default" visibility of the Jeden class (and its constructor) makes it accessible to the Start class, since it's defined in the same package.

getConstructor with no parameters


Node.js Page request slow with complex mongodb call, how to make faster?

Question: I'm loading a "archive" page which consists of searching though a mongodb collection and showing a number of documents on the page. However when doing this, the server call takes a while. any suggestions in making it faster? I think the slowness is coming from this line:
Publication.find().limit(perPage).skip(perPage * page).sort('-date').exec(function (err, _publications) {

full page request:
app.get('/archive', function (req, res) {

  function timeConverter(UNIX_timestamp){
    var a = new Date(UNIX_timestamp);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var time = date + ' ' + month + ' ' + year;
    return time;
  }

  var perPage = 6
  pageParam = req.query['page']
  if (pageParam == null) {
    pageParam = 0
  }
  var page = Math.max(0, pageParam)

  // find all publications
  Publication.find().limit(perPage).skip(perPage * page).sort('-date').exec(function (err, _publications) {
    if (err) return console.error(err)

    for (id in _publications) { // convert date to text
      _publications[id].date = timeConverter( Number(_publications[id].date) )
    }

    Publication.find().limit(perPage).skip(perPage * (page + 1) ).count({},function(err, count) { // check if it's last page
      if (err) return console.error(err)

      if (count == 0) {
        nextPage = false
      } else {
        nextPage = page + 1
      }

      res.render(__dirname + '/../source/views/archive', {
        publications: _publications,
        nextPage: nextPage,
        prevPage: page - 1
      })

    })

    console.log('serving archive')
  })

})

Answer: Doing .limit(perPage).skip(perPage * page) will affect your response time. This is now considered as best approach as mongo will first scan all of the previous documents in specified collection and then skip them.
A better solution will be getting all the docs with _id greater than sent in the first response. Something like
Publication.find({'_id': {'$gt': req.params.last_id}}, {}, { limit: perPage })

Here last_id is the id of the last document and this query will return you all (or specified number of) documents after that id.
Moreover, mongodb applies indexes on its generated id and it is always faster to search with this.
Main cause of slowness in your approach is because of using skip

The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return results. As the offset (e.g. pageNumber above) increases, cursor.skip() will become slower and more CPU intensive. With larger collections, cursor.skip() may become IO bound

Read more here
Thanks


How do I test the significance of a distribution of tau coefficients?

Question: I have (I think) a simple question. I estimated rank-orderings on a variable from a sample of 225 people, and I'm interested to know whether they generally correlated with a "correct" rank-ordering.
So I've computed Kendall's tau for the pairing of each participant's rank order with this correct rank-ordering. The distribution of the resulting coefficients is approximately normal... is there any reason I can't just perform a simple t-test to determine the significance of these correlations in aggregate? I can't see any reason why not, but if just feels too easy...
Comment: You first said that you computed ONE Kendall's tau. But then you talk about the "distribution of the resulting coefficients"... do you mean *multiple* values of Kendall's tau?  Please clarify.
Comment: What's your null here? Surely it's not that the correlation is 0 -- rejecting that won't tell you that they're 'generally correlated with a "correct" rank-ordering' in the sense that they're typically very alike, which is presumably what you're interested in.
Comment: I seriously doubt that leads to any useful conclusion at all. For example, what value would there be in knowing there's an *extremely* weak correlation in rankings, other than it telling you that a blind ant could do almost as well?  Of course the rankings won't be perfectly random / unrelated to the "correct" ordering, so rejecting that is nigh pointless.
Comment: @RachelAltman -- Yes, sorry. I've computed a Kendall's Tau for EACH participant, which compares their rank-ordering with one "correct" rank-ordering
Comment: @Glen_b uh oh... my null *is* that the correlation coefficient is zero? Truthfully I don't need to establish that the rank-orderings are very alike---only that there is any significant relationship at all
Answer: It's a shame this one was dismissed and left unanswered. Jonckheere (1954) and Stilson & Campbell (1962) independently proposed a significance test for the average Kendall's Tau against a "correct", or criterion ranking that seems to match the question perfectly.
A Kendall's Tau correlation between two separate rank-orderings can be transformed into the number of (dis)agreements on the relative ranking of each pair of objects (e.g. do both rankings agree object A is rated over B?), and forms the well-known Kendall's Tau distance, $\tau_D$ (a.k.a. the bubble sort distance).
$$\tau_D = \Bigg(\frac{1-\tau}{2}\Bigg)\tau_{Dmax}$$
Where $\tau_{D\text{max}} = k(k-1)/2$ and reflects the maximum number of possible disagreements (i.e. totally opposite rank-orderings), with $k$ objects being ranked. I've provided another answer exploring this previously here; transforming a Kendall's Tau correlation into Kendall's Tau distance is useful in this case because it underlies the null distribution used in the test.
If we calculate $\tau_D$ from the criterion rank-ordering for each independent rater, we can sum the total disagreements with bounds between $0$ and $n\tau_{D\text{max}}$ (i.e. all rank-orderings provided by the raters agree with the criterion, and all rank-orderings are exactly the opposite, respectively). Conceptually, this is the same as finding the average Kendall's Tau, and a relevant transform is provided below.
You can flip this by only counting agreements instead and come up with a similar measure if you're interested in quantifying how similar the rankings are to the criterion. The test proposed by Jonckheere basically defines a null distribution for the sum of total agreements for each ranking against a criterion ranking, defined as $P$.
The relationship between the average Kendall's Tau, $\bar{\tau}_c$ and $P$ is given by
$$P=\frac{nk(k-1)(\bar{\tau}_c+1)}{4}$$
Note that in Jonckheere and Stilson & Campbell compute this statistic directly, rather than calculating $\bar{\tau}_c$ as an intermediate step.
The distribution of $P$ under the null has a mean of
$$E(P)=\frac{nk(k-1)}{4}$$
and variance of
$$\text{Var}(P)=\frac{nk}{72}(k-1)(2k+5)$$
which can be used to create a test statistic
$$Z = \frac{P - (1/2)-E(P)}{\sqrt{\text{Var}(P)}}$$
which follows a standard normal distribution.
In R you could implement this test like so:
<code>criterion_tau <- function(tau, n, k){

    # Null sampling distribution
    mean_null_dist <- (n*k*(k-1))/4
    var_null_dist <- ((n*k)/72)*(k-1)*(2*k+5)

    # Observed stat
    P <- (n*k*(k-1)*(tau+1))/4

    # Test statistics
    Z <- (P - (1/2)-mean_null_dist)/sqrt(var_null_dist)
    p_val <- 1 - pnorm(Z)

    res <- list(P, Z, p_val)
    return(res)
}
</code>
You can replicate the results in Jonckheere (1954) fairly easily. He analyses a dataset of errors made by learners in an experiment, and expects that as subjects complete more trials, they should make fewer errors.
<code># Table 3 - Learning Experiment (Jonckheere 1954)
tab_3 <- matrix(
    c(0, 4, 10, 8, 5, 3, 12,
      2, 0, 7, 6, 8, 4, 5,
      1, 2, 9, 8, 5, 4, 10,
      0, 7, 5, 10, 6, 11, 9,
      4, 3, 8, 2, 9, 5, 7),
    nrow = 5, ncol = 7, byrow = TRUE,
    dimnames = list(
        subject = 1:5,
        trial = 7:1)
)

# Calculate average Kendall's Tau
tau_vals <- apply(tab_3, 1, function(x) cor(x, 1:7, method = "kendall"))

# Run the test
criterion_tau(mean(tau_vals), 5, 7)
# Z = 2.42, p = .008
</code>

References
Jonckheere, A. R. (1954). A test of significance for the relation between m rankings AND k ranked categories. British Journal of Statistical Psychology.
Stilson, D. W., & Campbell, V. N. (1962). A note on calculating tau and average tau and on the sampling distribution of average tau with a criterion ranking. Journal of the American statistical association, 57(299), 567-571.


Android google maps - keytool generates SHA1 instead of MD5 hash

Question: When I trying to generate MD5 key using Keytool "C:\Program Files\Java\jdk1.7.0\bin"
with this parameters:
C:>"C:\Program Files\Java\jdk1.7.0\bin\keytool.exe" -list -alias and
roiddebugkey -keystore "C:\Users\user1.android\debug.keystore" -storepass andro
id -keypass android
androiddebugkey, 20.09.2011, PrivateKeyEntry,
Huella Digital de Certificado (SHA1): ED:55:7E:68:28:7A:90:28:B1:2F:62:3A:B5:94:06:DD:C4:6C:D6:20
and when I'm trying to submit this "ED:55:7E:68:28:7A:90:28:B1:2F:62:3A:B5:94:
06:DD:C4:6C:D6:20" key to http://code.google.com/android/maps-api-signup.html - it is not working. How to make it work? Why am I having SHA1 instead of MD5 ?
Comment: solution found: I should have run this one: "C:\Program Files\Java\jre6\bin\keytool.exe"
Answer: Add -v in your commmand as shown below:
keytool -v -list -keystore .....

Comment: this actually works on jdk 1.7! it shows MD5, ShA1 and SHA256.
Answer: You have to use the Keytool from jdk1.6
Comment: can i get only keytool.exe for jdk1.6? will it work alone? if so where to get it?
Answer: Use this command to get your MD5 fingerprint.
C:\Program Files\Java\jdk1.6.0_16\bin>keytool -list -alias androiddebugkey
-keystore "Your debug key location" -storepass android -keypass android

You can also get the full tutorial at androidcookers.co.cc
Answer: Try
 C:\Program Files\Java\jdk1.6.0_20\bin>keytool.exe -list -v -alias androiddebugkey
-keystore C:\Users\DON\.android\debug.keystore -storepass android -keypass android

DON is ur system name
Answer: Try this one:
C:\Program Files (x86)\Java\jdk1.7.0_07\bin>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\itt\.android\debug.keystore" -list -v

Answer: I've not installed Java 7 myself, but there is a new command line argument to its keytool, namely -keyalg.
I know you can specify -keyalg RSA, so maybe -keyalg MD5 will give you the right key.


Number of integral points in a polytope

Question: I'm trying to count the number of integral solutions to the set of equations and inequalities
\begin{equation}
\begin{split}
 a_0 + a_1+a_2+a_3+a_4 = C \\
a_i \geq 0 \quad i \in\{0,1,2,3,4\} \\
a_0 \geq a_1 \geq a_2 \\
a_0 \geq a_3 \geq a_4 \\
\end{split}
\end{equation}
I know that the number of integral solutions for the first two equations is $\binom{C+4}{4}$. I've also seen when the $a_i$ are bounded by constants which has a nice generating function formulation. But I am stuck in figuring it out with the multivariable constraints.
I would greatly appreciate any help or ideas in how to solve this problem.
Comment: Hi Dave, anything more specific?
Comment: https://en.wikipedia.org/wiki/Partition_(number_theory)
Comment: What you're looking for is the number of integer partitions of $C$ with at most five parts (it is at most since you are allowing zeros). See https://en.wikipedia.org/wiki/Partition_(number_theory)#Restricted_part_size_or_number_of_parts specifically.
Comment: First, while I think the problems are related, they are not exactly the same since the solutions I'm looking for allow for different order of summands which partition theory ignores, unless you have a link where they don't. Second, I am not just trying to partition into 5 parts but also constraint the size of each part dependent on the sizes of the others.
Comment: The constraint that $a_0\geq a_1\geq\cdots\geq a_4$ takes care of the order. An equivalent definition of a partition of $C$ is a sequence $(a_j)_{j\geq 0}$ such that $a_j\geq a_{j+1}$ and $\sum_j a_j=C$.
Comment: Fair, but you haven't addressed my second point. My constraints are equivalent to $a_0 \geq a_1 \geq a_2$ and $a_0 \geq a_3 \geq a_4$. So i can't just fix the order and then count all the number of permutations.
Comment: I think Dave misread the constraints.  I did too, initially.  :)
Comment: Ah, I misread your constraint of $a_0\geq a_3$ as $a_2\geq a_3$. Sorry about the confusion.
Comment: No worries, let me rewrite it quick so as to avoid further confusion.
Answer: Let us define $f(n)$ as the number you are looking for, with $C$ replaced by $n$.
The sequence $(f(n))_n$ satisfies the linear recurrence relation:
$$f(n) - f(n-1) - f(n-2) + f(n-5) + f(n-6) + f(n-7) - f(n-8) - f(n-9) - f(n-10) + f(n-13) + f(n-14) - f(n-15) = 0.$$
From here, you can use any of your favorite method to solve it.
The characteristic polynomial decomposes as $$(x - 1)^5(x + 1)^2(x^2 + 1)(x^2 + x + 1)(x^4 + x^3 + x^2 + x + 1).$$ It can also be written as $(x - 1)(x^2 - 1)(x^3 - 1)(x^4 - 1)(x^5 - 1)$. Notice that every root is a root of unity, with common multiple $60$. Hence the $60$ subsequences $(f(60n + k))_n$ are all polynomials (of degree $4$) in $n$.
It is possible to write down a list of all these polynomials. They will look like:
\begin{eqnarray*}
f(60n + 0) &=& 27000n^4 + 8100n^3 + 855n^2 + 39n\\
f(60n + 1) &=& 27000n^4 + 9900n^3 + 1305n^2 + 71n\\
f(60n + 2) &=& 27000n^4 + 11700n^3 + 1845n^2 + 127n + 2\\
f(60n + 3) &=& 27000n^4 + 13500n^3 + 2475n^2 + 195n + 5\\
f(60n + 4) &=& 27000n^4 + 15300n^3 + 3195n^2 + 293n + 9\\
f(60n + 5) &=& 27000n^4 + 17100n^3 + 4005n^2 + 409n + 14\\
f(60n + 6) &=& 27000n^4 + 18900n^3 + 4905n^2 + 561n + 23\\
f(60n + 7) &=& 27000n^4 + 20700n^3 + 5895n^2 + 737n + 33\\
f(60n + 8) &=& 27000n^4 + 22500n^3 + 6975n^2 + 955n + 48\\
f(60n + 9) &=& 27000n^4 + 24300n^3 + 8145n^2 + 1203n + 65\\
f(60n + 10) &=& 27000n^4 + 26100n^3 + 9405n^2 + 1499n + 88\\
f(60n + 11) &=& 27000n^4 + 27900n^3 + 10755n^2 + 1831n + 115\\
f(60n + 12) &=& 27000n^4 + 29700n^3 + 12195n^2 + 2217n + 150\\
f(60n + 13) &=& 27000n^4 + 31500n^3 + 13725n^2 + 2645n + 189\\
f(60n + 14) &=& 27000n^4 + 33300n^3 + 15345n^2 + 3133n + 238\\
f(60n + 15) &=& 27000n^4 + 35100n^3 + 17055n^2 + 3669n + 294\\
f(60n + 16) &=& 27000n^4 + 36900n^3 + 18855n^2 + 4271n + 361\\
f(60n + 17) &=& 27000n^4 + 38700n^3 + 20745n^2 + 4927n + 436\\
f(60n + 18) &=& 27000n^4 + 40500n^3 + 22725n^2 + 5655n + 526\\
f(60n + 19) &=& 27000n^4 + 42300n^3 + 24795n^2 + 6443n + 625\\
f(60n + 20) &=& 27000n^4 + 44100n^3 + 26955n^2 + 7309n + 741\\
f(60n + 21) &=& 27000n^4 + 45900n^3 + 29205n^2 + 8241n + 869\\
f(60n + 22) &=& 27000n^4 + 47700n^3 + 31545n^2 + 9257n + 1016\\
f(60n + 23) &=& 27000n^4 + 49500n^3 + 33975n^2 + 10345n + 1178\\
f(60n + 24) &=& 27000n^4 + 51300n^3 + 36495n^2 + 11523n + 1362\\
f(60n + 25) &=& 27000n^4 + 53100n^3 + 39105n^2 + 12779n + 1562\\
f(60n + 26) &=& 27000n^4 + 54900n^3 + 41805n^2 + 14131n + 1788\\
f(60n + 27) &=& 27000n^4 + 56700n^3 + 44595n^2 + 15567n + 2034\\
f(60n + 28) &=& 27000n^4 + 58500n^3 + 47475n^2 + 17105n + 2308\\
f(60n + 29) &=& 27000n^4 + 60300n^3 + 50445n^2 + 18733n + 2604\\
f(60n + 30) &=& 27000n^4 + 62100n^3 + 53505n^2 + 20469n + 2933\\
f(60n + 31) &=& 27000n^4 + 63900n^3 + 56655n^2 + 22301n + 3287\\
f(60n + 32) &=& 27000n^4 + 65700n^3 + 59895n^2 + 24247n + 3677\\
f(60n + 33) &=& 27000n^4 + 67500n^3 + 63225n^2 + 26295n + 4096\\
f(60n + 34) &=& 27000n^4 + 69300n^3 + 66645n^2 + 28463n + 4554\\
f(60n + 35) &=& 27000n^4 + 71100n^3 + 70155n^2 + 30739n + 5045\\
f(60n + 36) &=& 27000n^4 + 72900n^3 + 73755n^2 + 33141n + 5580\\
f(60n + 37) &=& 27000n^4 + 74700n^3 + 77445n^2 + 35657n + 6150\\
f(60n + 38) &=& 27000n^4 + 76500n^3 + 81225n^2 + 38305n + 6769\\
f(60n + 39) &=& 27000n^4 + 78300n^3 + 85095n^2 + 41073n + 7428\\
f(60n + 40) &=& 27000n^4 + 80100n^3 + 89055n^2 + 43979n + 8139\\
f(60n + 41) &=& 27000n^4 + 81900n^3 + 93105n^2 + 47011n + 8894\\
f(60n + 42) &=& 27000n^4 + 83700n^3 + 97245n^2 + 50187n + 9707\\
f(60n + 43) &=& 27000n^4 + 85500n^3 + 101475n^2 + 53495n + 10568\\
f(60n + 44) &=& 27000n^4 + 87300n^3 + 105795n^2 + 56953n + 11491\\
f(60n + 45) &=& 27000n^4 + 89100n^3 + 110205n^2 + 60549n + 12467\\
f(60n + 46) &=& 27000n^4 + 90900n^3 + 114705n^2 + 64301n + 13510\\
f(60n + 47) &=& 27000n^4 + 92700n^3 + 119295n^2 + 68197n + 14611\\
f(60n + 48) &=& 27000n^4 + 94500n^3 + 123975n^2 + 72255n + 15785\\
f(60n + 49) &=& 27000n^4 + 96300n^3 + 128745n^2 + 76463n + 17020\\
f(60n + 50) &=& 27000n^4 + 98100n^3 + 133605n^2 + 80839n + 18334\\
f(60n + 51) &=& 27000n^4 + 99900n^3 + 138555n^2 + 85371n + 19716\\
f(60n + 52) &=& 27000n^4 + 101700n^3 + 143595n^2 + 90077n + 21181\\
f(60n + 53) &=& 27000n^4 + 103500n^3 + 148725n^2 + 94945n + 22719\\
f(60n + 54) &=& 27000n^4 + 105300n^3 + 153945n^2 + 99993n + 24347\\
f(60n + 55) &=& 27000n^4 + 107100n^3 + 159255n^2 + 105209n + 26053\\
f(60n + 56) &=& 27000n^4 + 108900n^3 + 164655n^2 + 110611n + 27855\\
f(60n + 57) &=& 27000n^4 + 110700n^3 + 170145n^2 + 116187n + 29741\\
f(60n + 58) &=& 27000n^4 + 112500n^3 + 175725n^2 + 121955n + 31729\\
f(60n + 59) &=& 27000n^4 + 114300n^3 + 181395n^2 + 127903n + 33807\\
\end{eqnarray*}

Explanation on the recurrence relation:
It is possible to deduce that recurrence relation by hand.
Firstly, we calculate $f(n)$ by partitioning the set: there are four subsets, $A = \{a_2 = 0\}$, $B = \{a_4 = 0\}$, $C = \{a_2 = a_4 = 0\}$, $D = \{a_2 \neq 0 \neq a_4\}$. It is clear that $f(n) = |A| + |B| - |C| + |D|$.
It is also clear that $$|A| = |B| = |\{(a_0, a_1, a_2, a_3):a_0 + a_1 + a_2 + a_3 = n, a_0 \geq a_1 \geq a_2 \geq 0, a_0 \geq a_3 \geq 0\}|.$$We denote this number by $g(n)$.
We also have $$|C| = |\{(a_0, a_1, a_3):a_0 + a_1 + a_3 = n, a_0 \geq a_1 \geq 0, a_0 \geq a_3 \geq 0\}|.$$ We denote this number by $h(n)$.
Finally, by mapping every $a_i$ to $a_i - 1$, we see that $|D| = f(n - 5)$.
Thus we obtain: $f(n) = 2g(n) - h(n) + f(n - 5)$.
Now if we do the same analysis for $g(n)$ (i.e. partitioning into $\{a_2 = 0\}$, $\{a_3 = 0\}$, $\{a_2 = a_3 = 0\}$, $\{a_2 \neq 0 \neq a_3\}$), and also for $h(n)$, we get similar recurrence relations, but involving again new functions such as $|\{(a_0, a_1, a_2): a_0 + a_1 + a_2 = n, a_0 \geq a_1 \geq a_2 \geq 0\}|$.
Each step will reduce the problem to simpler functions. Repeating this procedure, we will finally arrive at a recurrence formula for the original function $f$.
While this is totally doable by hand, it's probably a complicated task and has to be done very carefully. Therefore, I didn't use this approach.
Instead, seeing that a linear recurrence relation (of reasonable order, say $< 100$) must exist, I wrote a program to generate the sequence and then found the recurrence relation directly, by solving linear equations. That's the result in the beginning of the answer.
Comment: I'm impressed but a little bit confused. Can you elaborate how you converted my problem into that recurrence relationship?
Comment: Please tell me you used some kind of software to generate that list, and that you didn't type it all by hand...
Comment: @Math1000 Yes, some kind of software was used to generate that list (:
Comment: @WorkerBee I'll add some explanation.

Number of integral points in a polytope


Mudar diretorio default dos projetos feito em Zend 2

Question: Olá pessoal esse é meu primeiro post :D
Sou novo em Zend framework e estou usando o Zend 2 + PHP 5.5 + MySql + Apache
Tenho o sistema em meu servidor funcionando atraves do endereço http://localhost e não estou usando Virtual Host do Apache, estou usando somente o modo rewrite e arquivo .htaccess
O problema:

Quero colocar mais um NOVO sistema no mesmo servidor onde poderia ser acessado através localhost/sistema1 e localhost/sistema2 porem toda mudança que tento até abre o sistema, mas quando tento acessar os menus ele sempre tenta usar o endereço localhost e não localhost/sistema1.

É como se o Zend tivesse algum lugar onde eu possa configurar qual é o diretorio raiz do projeto.
E mesmo se eu não usar os menus e digitar diretamente o url ele tb não funciona. Estou usando para menus o Zend Navigation.
OBS.: Não gostaria de usar Virtual Host, pois quando eu for hospedar o sistema em uma hospedagem geralmente eles não deixa vc mexer nas configurações do Apache.
Segue o .htaccess que estou colocando dentro de localhost/sistema1 :
# Turn on rewrites.
RewriteEngine on

# Only apply to URLs on this domain
RewriteCond %{HTTP_HOST} ^(www.)?localhost$

# Only apply to URLs that aren't already under folder.
RewriteCond %{REQUEST_URI} !^/public/

# Don't apply to URLs that go to existing files or folders.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all those to insert /folder.
RewriteRule ^(.*)$ public/$1

# Also redirect the root folder.
RewriteCond %{HTTP_HOST} ^(www.)?localhost$
RewriteRule ^(/)?$ public/index.php [L]

Gostaria tb se possível fazer com que os dois sistemas usasse o mesmo Zend, para não precisar ficar redundante o diretorio da Zend em TODOS os novos sistemas. Mas isso não é tão importante agora. Tenho urgencia em resolver o item anterior.

Obrigado pessoal e lembrem q sou novato no Zend então deem uma explicação um pouco mastigada. (mas no PHP mexo a muitos anos)
Answer: consegui resolver o problema.
Vou postar aqui a solução caso alguém passar pelo mesmo problema no futuro.
A solução foi através do arquivo .htaccess, acrescentei no final do arquivo:
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteRule ^(.*)$ public

Com isso qualquer requisição feita dentro do diretório /sistema1 ou /sistema2 será redirecionado para o diretório public.
Dentro de public tem outro .htaccess que já vem com o skeleton do Zend, que faz todo o resto acontecer.
Meu .htaccess do diretório /sistema1 ficou assim:
# Turn on rewrites.
RewriteEngine on

## Only apply to URLs on this domain
RewriteCond %{HTTP_HOST} ^(www.)?localhost$
#
## Only apply to URLs that aren't already under folder.
RewriteCond %{REQUEST_URI} !^/public/
#
## Don't apply to URLs that go to existing files or folders.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#
## Rewrite all those to insert /folder.
RewriteRule ^(.*)$ public/$1

# Also redirect the root folder.
RewriteCond %{HTTP_HOST} ^(www.)?localhost$
RewriteRule ^(/)?$ public/index.php [L]

RewriteCond %{REQUEST_URI} ^(.*)$
RewriteRule ^(.*)$ public

É obvio que quando for colocar em um domínio válido a palavra localhost deverá ser substituída pelo seu domínio.
Já o meu .htaccess do /public ficou assim: (isso já vem no Zend)
RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

Bem, no mais muito obrigado e agora com essa solução talvez eu consiga colocar até em uma hospedagem que eu uso no Locaweb ;)


Preventing a field from rendering on a page

Question: How would I prevent field_home_slider from rendering when $page['content'] is loaded? I only want it to load when I call it separately. I also still want the page content to be displayed just do not include the field_home_slider
Display image by itself
  if(isset($node->field_home_slider)){
     $field = field_get_items('node', $node, 'field_home_slider');
     $bannerImage = field_view_value('node', $node, 'field_home_slider', $field[0]);
     print render($bannerImage);
  }

and below to display content on the page
print render($page['content']);

Comment: Try to use view mode in this. Set a view mode in manage display and exclude that field which you dont want to render from this view mode.
Answer: Go to  Display management of your content type  in admin/structure/types/manage/{yourcontenttypename}/display  and  set Formatter as Hidden.
Also you can  hide it with hide function  before render it in node template.
  hide($content['field_home_slider']);
  print render($content);


drupal_set_message for anonymous user

Question: I am having hard time displaying drupal message for anonymous users. My scenario is, I need to display message if there is certain query string and remove the query string with message. I am using following code but without success. I also tried with session variable without success.
 if(isset($_GET['action']) && $_GET['action'] === 'loggedoff'){
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    \Drupal::logger('vrpboostrap')->notice('query parameter has value loggedoff');
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: '. base_path() . $alias);
    exit;
  }

With Session variable, I tried with:
if (isset($_GET['action']) && $_GET['action'] === 'loggedoff') {
    $_SESSION['vrp_action'] = 'loggedoff';
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: ' . $url);
    exit;
  }
  if (isset($_SESSION['vrp_action']) && $_SESSION['vrp_action'] === 'loggedoff') {
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    session_unset('vrp_action');
  }

Can you guys advise me what am I doing wrong here and to display message for anonymous users?
Answer: The fact that you use header() and exit is most likely the problem.
You need to use response objects that you return to properly terminate the request and write the session data.
You can't do this anywhere, I'd recommend implement a Request event subscriber. \Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber is a simple example for this:
class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.
    $path = $request->getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}

And then register that in yourmodule.services.yml:
redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }

drupal_set_message for anonymous user


can xsd definition of type reference the xml file itself?

Question: I am trying to describe a set of java classes using XML. I need to have an xsd document as robost as possible, so it saves me headaches later on.
Suppose I have a class node inside which I have a set or properties. Each property have a type attribute, the value of this attribute could be a class name in the xml document, or a set of primitive names like "integer" "float" etc.
Can this scenario be defined in a xsd document?
thanks a bunch.
Comment: In general, yes it can. Do you need some further explanations? What exactly is your problem?
Comment: I have specific need that cannot be addressed with current frameworks. Amont them is the fact that the data is coming in in multiple files. Anyhow that is not the point, the point is how can I address this issue in XSD, that is the real question. I want xsd to be as restrictive as possible.
Comment: I've recently written part of a framework that generates metadata descriptors in XML for Java classes. The XML documents are created by constructing a bean tree in an annotation processor, then marshalling via JAXB. When the descriptors are needed at runtime, they're unmarshalled from XML back to the beans, again using JAXB. While it sounds simple, I can assure you that a good understanding of W3C XML Schema and Java inheritance are required to pull this off. Your self-accepted answer leads me to believe you should first study XML Schema thoroughly.
Answer: It can be achieved with ref/refid and key in the xsd.
Comment: This answer is as incomprehensible as the question. It goes no clue as to the actual problem that you were trying to solve, nor how using references will help you. SO would be better off if you simply deleted the question.


Redirecionamento de URL http

Question: Estou tentando fazer um redirecionamento de url, mas não está funcionando, alguém poderia me dizer o que está de errado?
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{QUERY_STRING} ^(.*)/teste(.*)$ // verifica se tem /teste em alguma url
    RewriteRule ^(.*)$ ^/parcerias/teste.html?utm_source=teste&utm_medium=site&utm_campaign=parcerias  [R=302,L] // envia para está url
</IfModule>

Comment: Opa, deu certo. Muito obrigado!
Comment: Isto `%{QUERY_STRING} ^(.*)/teste(.*)$` verifica se tem `/test` na QUERY_sTRING, algo como `http://localhost/foo/bar?foo=/test`, é isso mesmo o que deseja? Agora se o objetivo é chegar na URL isto esta errado.
Comment: Eu desejo http://localhost/teste < verificar isso, depois da url base do site verificar se tem o valor teste.
Comment: Como eu faria para pegar o valor depois da url base e substituir?
Comment: Então QUERY_STRING não faz sentido, porque isso verifica o conteudo da querystring como `?foo=bar` e não do PATH.
Comment: Estou criando uma resposta.
Comment: Ah sim, parece que entendi o que vc quer dizer, ok estou aguardando
Comment: Postei uma resposta, mas não tenho certeza do que você deseja, testa o código e se não funcionar explique qual o objetivo para que eu possa editar a resposta dentro de sua necessidade.
Comment: Ele joga um valor antes da url, saberia o pq disso? `%5e/parcerias`
Comment: Gustavo editei a resposta, provavelmente o sinal de `^` na frente de `^/parcerias/teste.html` esta errado, este sinal é para regex, e ali não é regex é o caminho de destino apenas, então remova-o,
Answer: Isto %{QUERY_STRING} ^(.*)/teste(.*)$ verifica se tem /test na QUERY_STRING, algo como http://localhost/foo/bar?foo=/test, é isso mesmo o que deseja? Agora se o objetivo é chegar na URL isto esta errado.
Outro detalhe, provavelmente o sinal de ^ na frente de ^/parcerias/teste.html esta errado, este sinal é para regex, e ali não é regex é o caminho de destino apenas, então remova-o, deve ficar assim:
RewriteRule ^(.*)$ /parcerias/teste.html

Creio que o quer seja o REQUEST_URI para verificar o PATH (caminho na URL):
RewriteEngine On

RewriteCond %{REQUEST_URI} ^(.*)/teste(.*)$
RewriteRule ^(.*)$ /parcerias/teste.html?utm_source=teste&utm_medium=site&utm_campaign=parcerias [R=302,L]

Ou simplesmente aplicar no RewriteRule:
RewriteEngine On

RewriteRule ^(.*)/teste(.*)$ ^/parcerias/teste.html?utm_source=teste&utm_medium=site&utm_campaign=parcerias [R=302,L]

Claro que isto provavelmente vai causar um loop, já que a URL redirecionada também tem /teste em /parcerias/teste.html, provavelmente você quer o contrário, impedir o redirecionamento se já estiver em uma URL com /teste, então o que você deseja é uma condição de não contêm /teste, neste caso basta usar o sinal de !, assim:
RewriteEngine On

RewriteCond %{REQUEST_URI} !^(.*)/teste(.*)$
RewriteRule ^(.*)$ /parcerias/teste.html?utm_source=teste&utm_medium=site&utm_campaign=parcerias [R=302,L]

Redirecionamento de URL http


Is the following statement is True/false regarding a non-trivial homomorphism

Question: Is the following  statement True ?

For every integer $n \geq 2$, there is a unique non-trivial homomorphism
  $\phi:S_n \rightarrow \mathbb{C}^*$. where  $\mathbb{C}^*$,denotes  the multiplicative group of non-zero complex number.

My attempt  :  This   is  false,   because  this  only true  for   $n \le 4$ because cyclic  groups  map  to cyclic  group, as as  every finite   subgroup of $ \mathbb{C}^*$  is  cyclic
Is it  correct ?
Comment: Your argument does not really make sense to me. How does the image being cyclic rule out the existence of the map?
Answer: What about this ? $$g:\sigma \mapsto \begin{cases} 1&\text{if}\;\sigma \;\text{is even}\\-1 &\text{otherwise}\end{cases} $$

Uniqueness :
Suppose there is another non trivial homomorphism, say, $f$. Then $\ker f$ is a normal subgroup of $G$. But for $n \geq 5$, $A_n$ is the only proper normal subgroup of $S_n$. So $$\ker f\in\Big\{\{e\},A_n,S_n\Big\}$$

$\ker f=S_n$ implies $f$ is trivial, which is not under consideration
$\ker f=\{e\}$ implies $f(S_n)$ is a subgroup of order $6$ in $C^*$ and so cyclic, which is not true

Hence $\ker f=A_n$ and so $f=g$
Comment: Are you preparing CSIR?
Comment: see this post (https://math.stackexchange.com/questions/2843703/book-recommendation-for-csir-ugc-net-exam/2843803#2843803) and my answer. I think it helps a little
Comment: Don't worry and prepare well! first attempt part C and complete this section within 90 minutes and then move on to part B. Real Analysis, linear algebra and abstract algebra is ENOUGH to clear CSIR NET. All the best!
Comment: im  not getting  can  u elaborate more ..
Comment: @Chinnaapparaj ya  im preparing  and what  about u ?
Comment: I see this question is in CSIR , that why I'm asking! & Yes to your second question. I already got lectureship, but this time, I try to got JRF!
Comment: @Chinnaapparj    can  u give  me some  tips  how  to qualify  csir  net ?  im  very  fear about  exam, ?  i
Comment: Are you going to write CSIR first time ?
Comment: no..this  is my second times,  last time  i didn't prepare  much
Comment: oksss let me see  and thanks u  so much
Comment: thanks  a lots once again and ur valuable  Guidance   i will try my best  effort @Chinnapparaj


Is there a library which can generate animated SVG diagrams like this example?

Question: I'm constantly doing some flow diagrams using rather "primitive" tools like draw.io / lucidchart / etc. I accidentally landed on https://thingsboard.io/docs/iot-gateway/what-is-iot-gateway/ while researching a completely different topic and immediately noticed the animated SVG diagram.
I'm wondering if there is an existing library which can generate animated SVGs based on mermaid markdown perhaps? The link contains python so maybe there's a python library for this?
Answer: I was also curious so I consulted their thingsboard/thingsboard issues.
Then I found an issue on thingsboard/thingsboard-gateway.
The tool is Figma, though I know nothing about using Figma to create animated SVGs.
Comment: https://github.com/otti/EnergyFlowAnimation


Understanding part of a proof of l'Hôpital's Rule

Question: I am studying a proof of a simple l'Hôpital's rule.
The theorem is as follows:
Let $x_0 \in (a, b).$
Suppose that $f, g$ are differentiable on $(a, b)$.
Suppose $\lim_{x\to x_0}f(x) = \lim_{x\to x_0}g(x) = 0$ and $g'(x) \not= 0.$
Then
$$\lim_{x\to x_0}\frac{f(x)}{g(x)} = \frac{f'(x_0)}{g'(x_0)}.$$
The beginning of the proof is as follows:
Since $g'(x_0) \not= 0$, there is an interval $(x_0 - r, x_0 + r) \subset (a, b)$ on which $g(x) - g(x_0) \not= 0.$
By the algebra of limits, for $x \in (x_0 - r, x_0 + r),$
$$\lim_{x\to x_0}\frac{f(x)}{g(x)} = \lim_{x\to x_0}\frac{\frac{f(x) - f(x_0)}{x - x_0}}{\frac{g(x) - g(x_0)}{x - x_0}} = \cdots$$
NB: I have cut the proof short by inserting the ellipsis.
I do understand why both $f(x)$ and $g(x)$ can be divided by $x - x_0$.
However, I do not yet understand why
$$\lim_{x\to x_0}\frac{f(x)}{g(x)} = \lim_{x\to x_0}\frac{f(x) - f(x_0)}{g(x) - g(x_0)}.$$
This would be the implicit step taken before dividing through by $x - x_0$.
Could someone please explain why this implicit step holds?
Answer: Because by assumption $f(x_0)=g(x_0)$. Well actually only $\lim_{x\to x_0}f(x)=\lim_{x\to x_0}g(x)=0$, gut as $f,g$ are differentiable at $x_0$, they are also continuous at $x_0$.
Comment: it is important that $f(x_0)=g(x_0)=0$


Data preprocessing with apache spark and scala

Question: I'm pretty new to spark and scala and therefore I have some questions concerning data preprocessing with spark and working with rdds.
I'm working on a little project and I want to implement a machine learning system with spark. Working with the algorithms is ok I think but I have problems with preprocessing the data.
I have a dataset with 30 columns and about one million rows. But for simplicity lets assume I have the following dataset (csv-file):
columnA, columnB, column_txt, label
1      , a      , abc       , 0
2      ,        , abc       , 0
3      , b      , abc       , 1
4      , b      , abc       , 1
5      , a      , abc       , 0
6      ,        , abc       , 0
7      , c      , abc       , 1
8      , a      , abc       , 1
9      , b      , abc       , 1
10     , c      , abc       , 0

After loading the data in spark I want to do the following steps:

Remove all columns that end with "_txt"
Filter out all rows where columnB is empty (this I figured out already)
Delete those columns that have more than 9 levels (here columnA)

So I have problems with issue 1. and 3.
I know I can't remove columns so I have to create a new rdd but how do I do that without certain columns?
For now I'm loading the csv file without a header in spark but for my tasks I need to. Is it recommendable to load the header in a separate rdd? But how can I interact with that rdd to find the right columns then?
Sorry, I know lots of questions but I'm still at the beginning and trying to learn.
Thanks and best regards,
Chris
Comment: If I were doing this "by hand" I would create an RDD, call `.take(1)` on it to get the headers in the master, do whatever processing/parallelizing I needed to with the headers, and then drop the first row to get the data in the RDD.
Answer: Assuming data frame is loaded with headers and structure is flat:
val df = sqlContext.
    read.
    format("com.databricks.spark.csv").
    option("header", "true").
    load("data.csv")

something like this should work:
import org.apache.spark.sql.DataFrame

def moreThan9(df: DataFrame, col: String) = {
    df.agg(countDistinct(col)).first()(0) match {
        case x: Long => x > 9L
        case _ => false
    }
}

val newDf = df.
    schema. //  Extract schema
    toArray. // Convert to array
    map(_.name). // Map to names
    foldLeft(df)((df: DataFrame, col: String) => {
        if (col.endsWith("_txt") | moreThan9(df, col)) df.drop(col) else df
    })

If it is loaded without header then you can do the same thing using mapping from automatically the assigned ones to the actual.
Comment: Thanks a lot for your answer! I will try it within the next few days.
Comment: Why foldLeft and not filter?
Comment: @dskrvk Do you mean something like `.filter(...).foreach(col => df = df.drop(col))`? Simply a matter of referential transparency and a personal taste I guess.


drupal 7 pagination

Question: I used the below code but it gives me error. Below is my code:
if(isset($_GET['tid']))
        {
         $id=($_GET['tid']);
         $query = new EntityFieldQuery();
         $query->entityCondition('entity_type', 'node');
         $query->entityCondition('bundle', 'escorts_product');
         $query->propertyCondition('status', 1);
         $query->fieldCondition('field_product_sub_cat', 'tid', $id,'=');
         $result = $query->execute();
         $total=count($result);
function pager_default_initialize($total, $limit = 2, $element = 0)
        {
         global $pager_page_array, $pager_total, $pager_total_items;
         $page = pager_find_page($element);
         $pager_total_items[$element] = $total;//total items
         $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
         $pager_page_array[$element] = max(0, min($page, ((int) $pager_total[$element]) -1));
         $pager_limits[$element] = $limit;
         return $pager_page_array[$element];
         //print "
";print_r($pager_page_array[$element]);
         }
         print theme('pager', array('quantity',count($result)));
error on this line function pager_default_initialize($total, $limit = 2, $element = 0)
,can anyone please guide me?
Comment: Can you please specify what error you are getting?
Comment: "Can not redeclare pager_default_initialize", I think it is already declared just need to call this, I also call this by just writing       `pager_default_initialize($total, $limit = 2, $element = 0);`                                                      , error is not appearing now but also not paging?
Answer: You have missed a parenthesis } before the line: function pager_default_initialize($total, $limit = 2, $element = 0).
Please put it and check the result.
Comment: Thanku @Nilesh, error is fixed but paging not appearing.
Comment: You are welcome, Here you have define the function: function pager_default_initialize($total, $limit = 2, $element = 0) but where you have called that function? You will need to call it at appropriate place.
Comment: I have my custom template file `product-categoies.tpl.php`, after defining I used                                                  `$offset = ($page) * $limit;
 $last = ($offset + $limit <$total)?$offset+$limit:$total;
 $pg=printtheme('pager',array('quantity',count($result)));`

drupal 7 pagination


Pulling a Client ID from a String

Question: I am trying to pull a specific part of a string in PHP using regex.  I just need to get the client ID out, but I am struggling.
Here is the code I have so far:
 $matches = array();
 $sentance = "Client ID # 050036598BOB BARKER 11/13/2014";
 $clientID = preg_match_all("/Client ID #([0-9]*)[a-zA-Z]/", $str, $matches);
 print_r($clientID);

The result I am looking for is
  050036598

Comment: You need to print `$matches`, not the boolean `preg_match_all()` returns. So what is wrong with yor current code? Except for the missing space between `#` and `(\d*)` it looks fine
Comment: [Aside from a few wrong variable names, such as `$sentance` and you're asking for `$str`, doing a `print_r` on `$clientID` instead of `$matches` and the fact you forgot a space between `#` and `([0-9]*)` it works just fine.](https://eval.in/240872)
Comment: Thank you both.  The variable names were mistakes when I rewrote it for my testing.  The space is what was killing it.
Answer: You can simply use preg_match() instead and account for whitespace between # and the "id".
$str = "Client ID # 050036598BOB BARKER 11/13/2014";
preg_match("/# *(\d+)/", $str, $match);
echo $match[1]; //=> "050036598"

Pulling a Client ID from a String


Mobile numeric keyboard [0-9] in textarea

Question: Is it possible to open up the mobile numeric keyboard in a textarea box?
The typical pattern="[0-9]*" does not seem to work with a textarea and I can't find any other information on this anywhere else. I am trying to get this working in an angular app, so is there some way to preventDefault() on the default keyboard and somehow trigger the numeric keyboard?
e.g.
<textarea id="searchBox" pattern="[0-9]*" ng-model="searchParams.searchString" rows="3" ng-blur="formatSearch()"></textarea>

Answer: Unfortunately this is not yet possible for textarea. I have searched exhaustively on this and tried many varietions of pattern and types and so on but it just is not supported for textarea.
There are two possible solutions, either you can create your own html5 custom soft keyboard and apply a trick not to open the default keyboard.
Or (more elegant I think) use a normal input with type number or type tel and attach an onkeyup listerer. When enter is pressed, you process the line into your textarea and clean plus refocus the input.
Comment: Thank you for your response. It's a shame we can't use the numeric keyboard with textarea. I will try to figure out a different approach for this. I appreciate your help!
Answer: isn't possible use input?
like
<input name="numbers" type="tel">

and than style the input like a textarea.
i dont have any idea for the textarea.
Comment: Thanks for the response, but unfortunately this isn't an option for what we need. We need a multi-line text box.
Answer: You can use the global attribute inputmode in textarea to alter Android or iPhone keypad.
<textarea inputmode="numeric"></textarea>
MDN Web Docs:
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode
Answer: A textarea can be validated via php but not in html. Below is my way of validating textarea,
$value=$_POST['value from textarea']
if(preg_match("/^[A-Za-z0-9]+$/", $value != 1) {
    echo"oops";
} else {
    echo "success";
}


What regex is \b equivalent to and is there a way to deparse it?

Question: I'm interested in changing the regex word boundary \b to include other characters (for example, a . wouldn't count as a boundary). I understand that it is a boundary between \w and \W characters.
  my $_ = ".test";
  if ( /(\btest\b)/ ){
    print;
    print " $1\n";
  }
  if ( /((?:(?<=\W)|^)test(?:(?=\W)|$))/ ){
    print;
    print " $1\n";
  }

This is what I came up with, and all I'd have to do is change \W to something like [^\w.], but I still want to know how Perl interprets \b in a regular expression. I tried deparsing it like this:
my $deparser = B::Deparse->new("-sC", "-x10");

print $deparser->coderef2text( sub {
          my $_ = ".test";
          if ( /(\btest\b)/ ){
            print;
            print " $1\n";
          }
          if ( /((?:(?<=\W)|^)test(?:(?=\W)|$))/ ){
            print;
            print " $1\n";
          }
       });

I was hoping it would expand \b into what it was equivalent to. What is \b equivalent to? Can you deparse \b or other expressions further somehow?
Answer: \b is functionally equivalent to (?<!\w)(?=\w)|(?<=\w)(?!\w).
\B is functionally equivalent to (?<!\w)(?!\w)|(?<=\w)(?=\w).

The goal of Deparse is to produce a readable representation of Perl's understanding of the code. For example, f() and g(); and g() if f(); compile identically, so Deparse will give the more readable option, g() if f();, for both.
$ perl -MO=Deparse -e'f() and g()'
g() if f();
-e syntax OK

This means that if \b and (?<!\w)(?=\w)|(?<=\w)(?!\w) compiled to the same code, Deparse would still give you \b if it understood compiled regex. Deparse is not what you want.

Maybe you're thinking of Concise. It shows what really gets executed. Notice the use of and in the following even though the original Perl uses if:
$ perl -MO=Concise,-exec -e'g() if f()'
1  <0> enter
2  <;> nextstate(main 1 -e:1) v:{
3  <0> pushmark s
4  <#> gv[*f] s/EARLYCV
5  <1> entersub[t6] sKS/TARG
6  <|> and(other->7) vK/1
7      <0> pushmark s
8      <#> gv[*g] s/EARLYCV
9      <1> entersub[t3] vKS/TARG
a  <@> leave[1 ref] vKP/REFC
-e syntax OK

But like Deparse, Concise knows nothing of the regex program the regex engine created from the string. So this is still not what you want.

However, there is an equivalent of Concise for regex patterns: use re 'debug';.
$ perl -Mre=debug -E'qr/\b/'
Compiling REx "\b"
Final program:
   1: BOUNDU (2)
   2: END (0)
stclass BOUNDU minlen 0
Freeing REx: "\b"

Apparently, \b is implemented as its own operation. For comparison,
$ perl -Mre=debug -E'qr/(?<!\w)(?=\w)|(?<=\w)(?!\w)/'
Compiling REx "(?<!\w)(?=\w)|(?<=\w)(?!\w)"
Final program:
   1: BRANCH (12)
   2:   UNLESSM[-1] (7)
   4:     POSIXU[\w] (5)
   5:     SUCCEED (0)
   6:   TAIL (7)
   7:   IFMATCH[0] (23)
   9:     POSIXU[\w] (10)
  10:     SUCCEED (0)
  11:   TAIL (23)
  12: BRANCH (FAIL)
  13:   IFMATCH[-1] (18)
  15:     POSIXU[\w] (16)
  16:     SUCCEED (0)
  17:   TAIL (18)
  18:   UNLESSM[0] (23)
  20:     POSIXU[\w] (21)
  21:     SUCCEED (0)
  22:   TAIL (23)
  23: END (0)
minlen 0
Freeing REx: "(?<!\w)(?=\w)|(?<=\w)(?!\w)"

Comment: +1. For further information, the non-word boundary `\B` is functionally equivalent to the logical negation of `\b`, that is, the logical negation of `(?<!\w)(?=\w)|(?<=\w)(?!\w)` which -by applying De Morgan's law and simplifying- is equal to `(?<=\w)(?=\w)|(?<!\w)(?!\w)`.
Answer: \b is the zero-width boundary between "a word character" (\w) and "not a word character" (which is something subtly different from "a non-word character" \W). So it would be equivalent to
(?<!\w)(?=\w)|(?<=\w)(?!\w)

Deparsing will not work here because regexes are a separate language directly embedded into the Perl code. You can use re 'debug' to see how regexes are compiled and matched (see the re docs for more info on how to use this).
Comment: Even if Deparse was regex aware, it wouldn't do anything anyway since `\b` has its own regex opcode `perl -Mre=debug -E'qr/\b/'` vs `perl -Mre=debug -E'qr/(?<!\w)(?=\w)|(?<=\w)(?!\w)/'`


Best way to use RandomAccessFile is Java

Question: I am creating a utility which write MSSQL table blob to data disk file using RandomAccessFile. It is too slower because we need to seek the last position always and write the stream contents.. please let me know any other alternative to speedup the randomaccessfile writing.
I have more than 50M records, with current logic it took approx 10 hours.
my code block is something like that:
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
InputStream inputStream = null;

while (rows.hasNext()) {
    Row row = rows.next();
    inputStream = (InputStream) row.getValues()[0];
    offset = randomAccessFile.length();
    byte[] buffer = new byte[8196];
    int count;
    randomAccessFile.seek(offset);
    randomAccessFile.setLength(offset);
    while ((count = inputStream.read(buffer)) != -1) {
        randomAccessFile.write(buffer, 0, count);
    }
}
randomAccessFile.close();

Comment: Btw setLength is exceedingly slow in Java 9 and 10. This is fine in Java 8 and 11.
Comment: Do you need to write in a file from a specific location? Just wanted to understand why you selected RandomAccessFile. you could have used BufferedWriter as well.
Comment: Writing 50 MB of data should take a second. You can test thus by just writing blank data of this size. If it more than this, it's the time to extract the data from the database.
Answer: According to the code you posted, you only need to append to an existing file. This is done easier and more efficient using a buffered writer in append mode.
Thus, use
BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardOpenOptions.CREATE, StandardOpenOptions.APPEND);

instead.
Update after Peter's comment: for an output stream, the whole thing is basically the same, only that Files does not have a nice convenience function for the "buffered" part. Therfore:
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND));

Comment: Writers are for writing text. The OP probably wants a BufferedOutputStream.
Comment: We would need to write binary data too, we don't know what are the data in the tables.
Answer: Currently you are writing roughly 8 Kb (8196 / 1024) of data in each iteration and each iteration does an I/O operation which is blocking and takes time. Try to increase this to at least 1 Mb roughly (10,000,000).
byte[] buffer = new byte[10000000];

Comment: Buffers larger than 32KB can be slower as they don't fit in the L1 data cache.
Comment: yes..I have row which contents 1KB data, so I think current size is okay.


Best known upper bound for $\sigma(n)$

Question: I was looking around on Wikipedia and OEIS and the best I could find relies on RH (Robin's Theorem or Lagrimas's Theorem). Are there any good known bounds that don't rely on RH?
Comment: @WillJagy I meant sure and this estimate for $\sup_{n \le x} \sigma(n)$ follows easily when applying the PNT and the Mertens theorems to $\sigma(\prod_{p \le k} p)$
Comment: @reuns thanks. I just found a paper in English that has the unconditional result, http://projecteuclid.org/download/pdf_1/euclid.em/1175789744   I have the 1984 Robin paper in French, got that through campus library reprint request.  I never learned any a.n.t., I just got interested in this Nicolas survey http://math.univ-lyon1.fr/~nicolas/hcnrevisited.pdf   with superior highly composite and colossally abundant numbers.
Comment: If you meant the asymptotic estimate of $\sup_{n \le x} \sigma(n)$ its second order terms depends on the RH, but its first order term is obtained by the Mertens theorem or the PNT. If you meant the asymptotic estimate of $\sum_{n \le x}\sigma(n)$, its second order terms are related to the [Dirichlet's divisor problem](https://en.wikipedia.org/wiki/Divisor_summatory_function#Dirichlet.27s_divisor_problem).
Comment: @reuns  Robin also proved an unconditional bound on $\sigma(n).$ The criterion that is equivalent to RH  comes from erasing one term in that. I put this in an answer.
Answer: From  Robin we have an unconditional result (1984) that says that for $n \geq 13,$ we have the bound
$$ \frac{\sigma(n)}{n} < \; e^\gamma \log \log n + \frac{0.64821364942...}{\log \log n},$$ with the constant in the numerator giving equality for $n=12.$ Note
$$  e^\gamma  = 1.7810724179901979852365\ldots  $$
This is stated in a paper in English by Briggs as Theorem 1.1.
If you would like to experiment, the easiest sequence of numbers that still gives very large values (almost $1$) of $\frac{\sigma(n)}{n \; e^\gamma \; \log \log n}$ is
$$ A_n = \operatorname{lcm} \{ 1,2,3,4,5, ..., n-1,n \},  $$
where $A_n \neq A_{n-1}$ only when $n$ is a prime or prime power. The very best values come from the sequence of Colossally Abundant numbers, but that is a more difficult computer program.
Let's see, the Riemann Hypothesis is equivalent to the statement that, for $n \geq 5041 = 1 + 7!,$ the number $0.64821364942...$ can be replaced by $0.$
Comment: In a few lines : $N_k = \prod_{p \le k} p$, $\frac{\sigma(N_k)}{N_k} = \prod_{p \le k} (1+\frac{1}{p})$. The PNT gives $\sum_{p \le k} \frac{1}{p} = \log \log k+M+o(\frac{1}{\log^2 k})$ thus
$\log \frac{\sigma(N_k)}{N_k} = \sum_{p \le k} \frac{1}{p}+\sum_{p \le k}\left(\log(1+\frac{1}{p})-\frac{1}{p}\right)$ $ = \log \log k+M+o(\frac{1}{\log^2 k})+C-\sum_{p > k} \left(\log(1+\frac{1}{p})-\frac{1}{p}\right) $
$ =  \log \log k+M+C+o(\frac{1}{\log^2 k})$
and hence $\frac{\sigma(N_k)}{N_k} = \exp(\log \log k+M+C+o(\frac{1}{\log^2 k})) = e^\gamma\log k (1+o(\frac{1}{\log^2 k}))$
Comment: Conclude by using the PNT again to replace $N_k$ by $e^k$

Best known upper bound for $\sigma(n)$


With the metric $(X,d) : X = \Bbb R$ and $d(x,y) = |x| + |y|$ for $x\neq y$ and $A = \{0\}$. Is interior of $A$ empty?

Question: With the metric space $(X,d) : X = \Bbb R$ and $d(x,y) = |x| + |y|$ for $x\neq y$, $d(x,x) = 0$ and $A = \{0\}$. Is interior of $A$ empty?
In usual metric it would be empty but with this metric I conclude that it is $A$ itself.
Def: $ a \in A $ is an interior point of $A$ if $\exists \epsilon > 0: B(a,\epsilon) \subset A$
$B(a,\epsilon) = \{x \in \Bbb R | |x| + |a| < \epsilon\} = \{0\}$
For the condition $B(a,\epsilon) \subset A$ in Def, should it be proper subset or $\{0\} \subset \{0\}$ is okay?
Comment: Please make sure to double-check your question before posting it here. You've already corrected 2 mistakes.
Answer: You are supposed to substitute $a=0$, because you are trying to prove that $0$ is an interior point of $A$.
So, you need to find a positive $\varepsilon$ such that $B(0,\varepsilon) = \{x \in \Bbb R ~:~ |x|+|0|<\varepsilon\} \subseteq A$, which is obviously impossible.
Comment: @Pumpkin yes. Intuitively, $1$ is the only point close to $1$, as other points have distance at least $1$ (actually, $d(1,0) < d(1,1.9)$, so your intuition might need to adapt to this)
Comment: Ok I see now. But then for $A = \{1\}$ it would be possible right? Int A would be  {1}
Comment: I wrote the ball definition wrong x should be in X not in A
Comment: @Pumpkin right, I completely ignored and just copied it, lol
Answer: Your definition of a $\varepsilon$ ball centred at $a$ is incorrect. With your definition every ball around every point would be a subset of $A$. The correct definition, in any metric space $(X,d)$, of a $\varepsilon$ ball centred at a point $a$ is:
$$B(a,\varepsilon)=\{x\in X:d(a,x)<\varepsilon\}.$$
In your case, for any $\varepsilon>0$, $B(0,\varepsilon)=\{x\in \mathbb R:|x|<\varepsilon\}$, which cannot be contained in $\{0\}$.
As for your last question about whether the definition should be $\subseteq$ or $\subsetneq$, I recommend looking at this post.
Comment: @KennyLau The definition the OP uses means the empty set is an $\varepsilon$ ball, which means any set has non-empty interior.
Comment: @KennyLau It wasn't like that when I made this answer, and your answer still has the same error.


DIV saindo da tela

Question: Eu já vi varias vezes uma div meio que saindo da tela, e como não vou saber explicar direito, vou mostrar uma foto de uma exemplo:

Eu imaginei que seria com box-shadow, mas nao consegui fazer.
Nao quero fazer o mesmo design do rapaz, até pq nao vou "roubar" o trabalho dele, mas queria saber como que faz pra ficar assim, saindo da tela.
Link: https://dribbble.com/shots/4150795-Conceptual-Dashboard-UI-Analytics
Answer: Esse efeito usa box-shadow sim, mas tb usa transform:scale(1.2);
Veja nesse Snipper um exemplo:

* {
  box-sizing: border-box;
}
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
body {
  background-color: #3b414d;
  overflow: hidden;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.container div {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: blueviolet;
  margin: 0;
  padding: 0;
}
.container div:nth-child(2) {
background-color: pink;
transform: scale(1.2);
box-shadow: 0 0 20px rgba(0,0,0,.5)
}

Se quiser o efeito apenas quando fizer o :hover basta substituir o .container div:nth-child(2){} por .container div:hover{}

* {
  box-sizing: border-box;
}
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
body {
  background-color: #3b414d;
  overflow: hidden;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.container div {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: blueviolet;
  margin: 0;
  padding: 0;
  transition: all .25s ease-in-out;
  position: relative;
  z-index: 0;
}
.container div:hover {
  background-color: pink;
  transform: scale(1.2);
  box-shadow: 0 0 20px rgba(0,0,0,.5);
  position: relative;
  z-index: 2;
  cursor: pointer;
}

Comment: @Maria faz assim, tira o `display:inline-block;` do `.container div` e na classe `.container` acrescenta `display:flex;` que vai resolver. Mas tudo depende do seu projeto... Onde vão ficar na página, se é responsivo etc. Esse modelo que eu fiz é só um exemplo, não é a solução perfeita para todos os casos...
Comment: isso. mas tem como deixar eles maiores sem acontecer uma quebra? pq quando mudei para .container div {
  width: 300px;
  height: 300px;
} ocorreu uma quebra

DIV saindo da tela


Get array of all entities from entity reference field

Question: On one of my content types I have a taxonomy term reference field that allows for multiple values. Normally if I wanted the term from a field I'd simply do
$node->field_taxonomy_term->entity;
However this doesn't work if there are multiple entities. Normally I would expect getValue() to do the trick but that just gives an array of the ids with target_id as the key. I sort of have a round about way of getting them with this method
<code>    $entity_storage = \Drupal::entityTypeManager()->getStorage('taxonomy');
    $ids = [];
    foreach ($this->field_taxonomy_term->getValue() as $item) {
        $ids[] = $item['target_id'];
    }
    $entities = $entity_storage->loadMultiple($ids);
</code>
But when getting one is as simple as $node->field_name->entity I had a feeling that I'm doing more work than necessary. Is there a simpler way to obtain an array of entities from a field or is what I'm doing the most efficient way to do it?
Answer: I can't say for sure on that specific field but usually there's the referencedEntities() method you can call
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.4.x
So something like this perhaps:
$entities = $node->field_taxonomy_term->referencedEntities();


Getting random verbiage while printing array variable in Java

Question: I'm learning basics of Java and there seems to be an observation I'm not able to get my head around.
Below is the code that is supposed to print the binary implementation of a base10 number. There are no errors or warnings but logical anomalies I'm looking for answers.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Main
{
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int remainder, quotient, i=0;
        int[] binary=new int[n];

        /* Binary division -Extracting the 1's and 0's out of the base10 number and storing it in binary[] */
        while(n!=0){
            remainder=n%2;
            quotient=n/2;
            binary[i]=remainder;
            n=quotient;
            i++;
        }

        int k=i; // For storing the length of array till I want my bits to be reversed since all other bits are initialized to 0.

        /*Reversing the binary[] to get the coreect binary value.*/
        for(int j=0; j<=i; j++){
            int temp=binary[j];
            binary[j]=binary[i];
            binary[i]=temp;
            i--;
        }

        /*Printing out all the bits of binary number. */
        for(int l=1;l<=k;l++){
            System.out.print(binary[l]);
        }

        System.out.println(binary); /*Prints a garbage looking value: For ex- for 25 i get: [I@33909752 */
        scanner.close();
    }
}

Concerns for my code:
1. I am not able to comprehend possible reasoning as to why I am getting random garbage looking verbiage when I try to print the array variable - binary. Is this something expected? If so what is this?
For example:
In my code when I provide an input of 25 I get [I@33909752 while printing the binary variable. I expected something like an [1,1,0,0,1,0,....,0]
2. I get an extra 0 in front of my binary value if I start my for-loop to print the binary from 0 instead of 1
For example:
for(int l=1;l<=k;l++)
{
  System.out.print(binary[l]);
}

Prints 11001 for 25 but if I start the loop from 0, I get 011001. I checked all other places of the code by putting SOPLn statements and nowhere the 0 index of array is getting 0. I wonder why?
Answer:
Don't import arbitrary stuff coming into you mind. You don't use anything from the packages java.io, java.math, java.security, java.text, java.util.concurrent, or java.util.regex. The only thing needing an import in your code so far is java.util.Scanner
You don't need a construct like scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"). If you are going to read another token, which does not happen in you code anyway, the scanner will already skip white-space, including line breaks, by default. There's also scanner.nextLine(), but you don't need it here.
Do not close System.in. While a Scanner created around a resource allocated by yourself should be closed, you are not responsible for System.in.
System.out.println(Object) prints the result of calling toString() on the object. For classes not providing an implementation, like arrays, the method inherited from java.lang.Object produces getClass().getName() + "@" + Integer.toHexString(hashCode()). The int[] array's class name is [I, that's why you see [I@ plus some hex number.
Use System.out.println(Arrays.toString(binary)); instead. But this will print the entire array, including the unused elements.
Instead of modifying an existing variable in a loop, creating the need for a new variable in the outer scope, you should introduce a new changeable, temporary variable in the loop. Further, you have to become familiar with the standard loop idiom, start at index zero and exclude the end index (use < rather than <=).
The loop variable will contain the excluded end index after the loop, when the condition evaluated to false. This logic also applies to your first while loop; afterwards, i will contain the first unused the index or the used length, both interpretations are valid. Subsequent uses must exclude it, using <, which is, as said, the usual pattern. For your reversal loop, this also implies that the end index must be decremented before being used.
Fixing the loop logic will fix your issue with the leading zero.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        int n = scanner.nextInt();
        int remainder, quotient, i=0;
        int[] binary=new int[n];
        /* Binary division -Extracting the 1's and 0's
           out of the base10 number and storing it in binary[] */
        while(n!=0) {
            remainder=n%2;
            quotient=n/2;
            binary[i]=remainder;
            n=quotient;
            i++;
        }
        /*Reversing the binary[] to get the correct binary value.*/
        for(int j=0, k=i-1; j<k; j++,k--) {
            int temp=binary[j];
            binary[j]=binary[k];
            binary[k]=temp;
        }
        /*Printing out all the bits of binary number. */
        for(int l=0; l<i; l++) {
            System.out.print(binary[l]);
        }
        System.out.println();

        System.out.println(Arrays.toString(binary));
    }
}

25
11001
[1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Comment: Java's arrays are always fixed size, so either, you change from using an array to using a `List`, e.g. `java.util.ArrayList`, or just replace the array with a new one of the right length, i.e. after the `while` loop, use `binary = Arrays.copyOf(binary, i);`. Or you predict the right array size upfront, using `32 - Integer.numberOfLeadingZeros(n)`.
Comment: What a stellar answer. To the point and exactly what I needed. On a related note can you comment about ways in which I can make the array size dynamic. I mean there are lots of unused bits in my array and I wonder if we can get rid of them by asking` java` to keep the size of the array to what its needed. I have a python background where a programmer has the liberty to instruct `lists` to be of acceptable size and so I was wondering if we could do something like this in Java?


AR(2) ACF Derivation

Question: Suppose I have the following AR(2) time series process:
$z_t = \delta + \psi_2 z_{t-2} + \epsilon_t$
where $\epsilon_t \sim (0, \sigma^2)$ is a white noise process.
I am hoping to calculate the ACF function for this process. Here are my thoughts thus far:
\begin{align}
Cov[z_t, z_{t-k}] &= Cov[\delta + \psi_2 z_{t-2} + \epsilon_t,\ z_{t-k}] \\\\
&= Cov[\delta,\ z_{t-k}] + Cov[\psi_2 z_{t-2},\ z_{t-k}] + Cov[\epsilon_t,\ z_{t-k}] \\\\
&= \psi_2 Cov[z_{t-2},\ z_{t-k}] \\\\
&= \psi_2\gamma(k-2) \\\\
&= \gamma(k)
\end{align}
Now I know that $\gamma(0) = \sigma^2 \frac{1}{1-\psi_2^2}$ as long as I did my calculations correct. I just found the variance of $z_t$ which is $\gamma(0) = Var[z_t] = \sigma^2 \frac{1}{1-\psi_2^2}$ which I derived by taking the variance of $z_t$ in its $MA(\infty)$ form. Hence,
\begin{align}
Var[z_t] &= Var\left[\frac{\delta}{1-\psi_{2}} +
\sum_{i=0}^{\infty} \psi_2^i \epsilon_{t-2i}\right] \\\\
&= \sum_{i=0}^{\infty}\psi_2^i Var[\epsilon_{t-2i}] \\\\
&= \sigma^2 \sum_{i=0}^{\infty} \psi_2^{2i} \\\\
&= \frac{\sigma^2}{1-\psi_2^2}
\end{align}
So $\gamma(k)$ would then be $\sigma^2 \frac{\psi_2^k}{1-\psi_2^2}$ which can be deduced since we already know $\gamma(0)$.
Then to find $\rho(k)$, which is the ACF, we do the following:
\begin{align} \frac{\gamma(k)}{\gamma(0)} = \psi_2^k = \rho(k)  \end{align}
Is this correct or am I totally jacking something up somewhere along the way?
Comment: Hi: at a glance, it seems correct because it's really an AR(1) except that time starts at $t = 3$ instead of $t=1$. And your result is definitely the autocorrelation of the standard AR(1) where $t$ starts at 1. Maybe you should write down the restriction on $t$ just to be slightly clearer ?
Comment: $t$ starts at 2 actually. But what do you mean by the restrictions on $t$?
Comment: Hi: Yes, if you start at $t=2$, then that's fine but that means your first observation is $z_{0}$. By restriction,  In that case, by restriction  I  just meant that the first observation occurs at $t=2$ which is a little non-standard.
Comment: Just one other thing: Note that you can also just think of it as an AR(1) where the underlying time scale is 2 units of time rather than 1. For me, it's easier to think of it that way.  gunes nicely implied this by  showing that the odd autocorrelations are always zero.
Answer: $\gamma(0)$ is correct and can be calculated in a different (maybe easier) way as well:
$$\begin{align}\gamma(0)&=\operatorname{cov}(z_t,z_t)=\operatorname{cov}(\delta+\psi_2z_{t-2}+\epsilon_t,\delta+\psi_2z_{t-2}+\epsilon_t)\\&=\psi_2^2\gamma(0)+\sigma^2\\&\rightarrow \gamma(0)=\frac{\sigma^2}{1-\psi_2^2}\end{align}$$
And, the relation $\gamma(k)=\psi_2\gamma(k-2)$ is correct, too. It implies the following:
$$\gamma(2)=\psi_2\gamma(0), \ \ \gamma(4)=\psi_2\gamma(2)=\psi_2^2\gamma(0) \dots$$
which means $\gamma(2k)=\psi_2^k \gamma(0)$. For the odd portion, let $k=1$ in the recursive equation:
$$\gamma(1)=\psi_2 \gamma(-1)$$
We know that autocovariance function is symmetric across $k=0$, so $\gamma(-1)=\gamma(1)$. So,
$$\gamma(1)=\psi_2\gamma(1)$$
but since this should hold for all $\psi_2$ (that doesn't violate the stationarity conditions), $\gamma(1)=0$. This would immediately mean $\gamma(2k+1)=0$.
Comment: Thank you for your awesome explanation! Two questions: 1. How exactly did you deduce that $\psi_2^2 \gamma(0) + \sigma^2 \implies \gamma(0) = \frac{\sigma^2}{1-\psi_2^2}$. Also, what exactly would $\rho(k)$ (my ACF) be equal to? Would there be two ACFs? One in the case of the even portion and one in the case of the odd portion? Thank you again!
Comment: 1. Just distribute the covariance over the terms. $\text{cov}(z_{t-2},\epsilon_t)=0$ (past output, current input) and $\text{cov}(z_{t-2},z_{t-2})=\gamma(0)$. 2) You can write it as a partial function, e.g. $\gamma(k)=\psi_2^{k/2}\gamma(0)$ if $k$ is even and $0$ if $k$ is odd.

AR(2) ACF Derivation


Android Keyboard Layout Search

Question: I saw many searchboxes in apps that if click the keyboard layout changes into Search button. How to change the android keyboard layout from Enter to Search if an EditText is click? Just like other search boxes. Thanks
Answer: add
android:imeOptions="actionSearch"
to your EditText in your layout file.
After that you can manage "search" click event by following code:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});

Comment: Thank you for your response.

Android Keyboard Layout Search


Actual job ID of a slurm array job

Question: I sometimes run job arrays in our slurm cluster:
#SBATCH --output=/vol/cluster-data/gprezza/logs/%x_%j.out
#SBATCH --error=/vol/cluster-data/gprezza/logs/%x_%j.err
#SBATCH --array=1-21%5

Once they run, on squeue I see:
1145141_[12-21%5]       cpu    align  gprezza PD       0:00
    1145141_11       cpu    align  gprezza  R       1:42
     1145141_2       cpu    align  gprezza  R    3:58:52
     1145141_1       cpu    align  gprezza  R    4:00:36
     1145141_9       cpu    align  gprezza  R    1:17:44
     1145141_7       cpu    align  gprezza  R    3:14:59

How do I get the actual job id of each job? I need it to check the output and error files. For example job 1145141_1 has as id 1145144 (the output file is at /vol/cluster-data/gprezza/logs/align_1145144.out).
Comment: You can check them with `scontrol`. And you can also change the output and error file names for others easier for you.
Comment: @Poshi do you mind expanding on both points?
Comment: You can expand yourself with `man scontrol` for the first point (look for the `show` command) and for the second point, just use a different name in the `--error` and `--output` parameters of `sbatch`, probably including the job array IDs (more details in `man sbatch`).
Answer: The squeue command accepts a --format parameter for choosing the information that is shown for each job. By default, it is
"%.18i %.9P %.8j %.8u %.2t %.10M %.6D %R"

where the first part %.18i is the job ID.
You can replace that first part with %.18A to get the actual job  ID
So
squeue --format "%.18A %.9P %.8j %.8u %.2t %.10M %.6D %R"

should show what you are looking for.
Note that you can specify the format with env variable SQUEUE_FORMAT to avoid adding it explicitly each time, or define an alias.

Actual job ID of a slurm array job


Metro-style data input form application

Question:
Similar to this question asking about relatively light-weight data entry / editor application development, which would follow Metro design guidelines.
The question is do you know of any samples of a whole app I could look at to see how a (multi-page) forms application might look like? I.e. textboxes, checkboxes, comboboxes in Windows 8 style...

Maybe you know to pinpoint one here?
Answer: The best app I know that showcases some data input is the calendar. Try creating a new appointment. I imagine there are more apps that have input, but I just don't know of any off the top of my head.

Metro-style data input form application


A system of two first order PDEs

Question: In a fluid dynamics problem appears a stream function $f(x,y)$ which is defined by the following system
$$\begin{align}
&\frac{\partial f}{\partial x}=\frac{g'(x)f(x,y)-a_1}{1-g(x)} \\
&\frac{\partial f}{\partial y}=\frac{a_2}{1-g(x)}
\end{align}$$
where $a_1$ and $a_2$ are constants and $g(x)$ some arbitrary function of $x$. I would like to find a general procedure in order to express $f(x,y)$ in terms of the arbitrary function $g(x)$ and the variable $y$, i.e. $f(x,y)=F(g(x),y)$.
Comment: What have you tried? Hint: the RHS of your second equation does not involve $y$. This might be a good place to start?
Comment: Also at the risk of being pedantic, I'd suggest you include whatever assumptions on $g$ you have.
Answer: HINT
Following the hint in the comments, we note the 2nd equation's RHS does not depend on $y$. We integrate both sides to get
$$
f(x,y) = \frac{a_2 y}{1-g(x)} + C(x)
$$
where $C(x)$ is some function independent of $y$, arising from the constant of integration. Can you take it from here (compute $f_x$ and compare to the first equation)?
Answer: First take a look at these steps
$$\eqalign{
  {{\partial f} \over {\partial y}} &= {{{a_2}} \over {1 - g(x)}}  \cr
   f &= {{{a_2}} \over {1 - g(x)}}y + h(x)  \cr
   {{\partial f} \over {\partial x}} &= {{{a_2}g'(x)} \over {{{\left[ {1 - g(x)} \right]}^2}}}y + h'(x)  \cr
  &= {{g'(x)f(x,y) - {a_1}} \over {1 - g(x)}} \cr} $$
and the comparison of the last two equations yields
$${{g'(x)} \over {1 - g(x)}}f(x,y) = {{{a_1}} \over {1 - g(x)}} + {{{a_2}g'(x)} \over {{{\left[ {1 - g(x)} \right]}^2}}}y + h'(x)$$
and finally
$$f(x,y) = {{{a_1}} \over {g'(x)}} + {{{a_2}} \over { {1 - g(x)} }}y + {{1 - g(x)} \over {g'(x)}}h'(x)$$

A system of two first order PDEs


How to speed up node add form with around 50 fields?

Question: I had a node add form with around 50 fields, mostly text with 1 field collection (with another 5 fields) and a few entity and term references.
The page is taking around 30 seconds to load making it unusable.
There are several slow queries (99.28 - DrupalDatabaseCache::getMultiple, 34.21 - views_plugin_query_default::execute, 20.51 - DrupalDefaultEntityController::load, 18.46 - DrupalDatabaseCache::getMultiple, 17.46 - DrupalDatabaseCache::getMultiple.. they go on)
The Cache::getMultiple query has 1087 placeholders, and the EntityController::load has 1084 placeholders.
If a click on the "Add Another Item" on the field collection that takes a further 30 seconds to complete.
What can I do to speed up the load times of the page?
EDIT: I just installed APC which removed all of the caching queries but did not solve the problem - still around 30 second load time. I don't think the slow load times are related to caching. Is taking around 280MB of memory load build the page.
EDIT: Removing the field collection, installing memcache and entitycache has shaved 20 seconds off the load time. However 10 seconds to initially load the page and another 10 seconds per ajax request is still unacceptable. How do webforms perform with a large number of fields? Maybe that would be a better option?
Comment: You could also try memcache for cache bin storage, APC for op-code caching. After that [entitycache](http://drupal.org/project/entitycache) is an easy way to improve entity load performance
Comment: After looking at the XHProf log I removed the field collection and that took 15 seconds off. I'm now using the [multifield](https://drupal.org/project/multifield) module instead despite it being unstable. Installing memcache and entitycache took another 5 seconds off so now I'm down to under 10 seconds.
Answer: Have you considered using multistep forms for your node creation?
Given that you have a lot of fields, you can do it at multiple page loads via various logical steps. There are lots of tutorials for multistep form implementation in Drupal and the example module ships with one.
Comment: I think this is a great suggestion. I've made the form as fast as I can keeping it on one page. If the client is unhappy with the load times then I will suggest this as an alternative.


Alternative to configuration files in Prometheus?

Question: I want to implement a monitoring system in a small organization.
I have experience with Zabbix, but I'm considering Prometheus as it seems there's a big community behind it, and it's pretty much the standard today (please correct me if I'm wrong).
However, I wonder how it is convenient to handle all the configuration of the scrapes and alerting rules in configuration files, rather in a web UI like in Zabbix. I mean, it may be ok for 10-20 alerts, but how can it be manageable with 20 different services and 1000 different alerts, for example? Maybe there's a solution for it that I just missed? In Zabbix it's very convenient to manage everything, since it's UI and also everything is going into groups (host groups, templates, etc.)
I'd appreciate your insights.
Answer: Prometheus is a compelling solution that -- deservedly -- has considerable momentum. For completeness, I urge you to consider other changes that may required by Prometheus as you determine whether it's appropriate for you to switch from your existing solution. This will be one of many changes for which you should be prepared.
I don't know why Prometheus' developers took the path that they did with configuration but I'll give you one benefit of the model. By requiring that configuration is written in (YAML) configuration files, you are able to commit these configurations to your source control and manage changes to these files just as you would with other sources. This is a tenet of "Infrastructure as code" and there are many benefits to this.
Now, it's also true that a UI Console tool could write changes to configuration files for you and you could then manage these files using source control as before. But, this functionality isn't available in the core solution.
One facility that may interest you is that you needn't restart prometheus nor alertmananger when you make changes to their configuration. You can change the configuration and then, POST to the services' /-/reload endpoint and the service will refresh configuration.
See:
https://prometheus.io/docs/prometheus/latest/configuration/configuration/
https://prometheus.io/docs/alerting/configuration/
Also see this useful article that explains how to have Prometheus automatically refresh its configuration when changes are made to a list of targets:
https://www.robustperception.io/using-json-file-service-discovery-with-prometheus
Comment: Thanks for your answer. "Infrastructure as code" is great and I'm going this path in other tools like Ansible and Terraform, but there are some tools that I think it's ok to consider as "blackbox" and just backup their configuration routinely in traditional manners, rather than source control. Anyway, going this path of configuration files, I think that one of the basic features should be the ability to separate the configuration into multiple files with imports and includes, to avoid one huge configuration file.
Comment: It just seems that some features in Prometheus were designed for monitoring a very small system. Another thing that I find hard to manage is searching in all the metrics. In Graphite, for example, you have a tree for that. In AWS CloudWatch, you have namespaces and it's very easy to start looking for metrics for your service. It's a shame, because Prometheus could be a great monitoring tool, but lacks very basic features to support large systems monitoring.
Answer: Zabbix and Prometheus are both powerful monitoring tools. Zabbix is based on host so everything organized on host. You can navigate from hostgroup to host, then navigate from host to metric,alert,dashboard and so on. The web UI of Zabbix is straightforward and easy to learn and use.
Prometheus is base on metric. The advantage of Prometheus is very flexible. Everything is defined in a configure file in YAML format, such as scrape config, alerting rule config and  so on. This is very convenient for teams who follow Observability as Code workflow.
So is there a tool that brings a web UI to Prometheus? Users could manage alerting rules and dashboards in a simple way using webUI. I recommend an easy way to manage prometheus in WebUI using Nightingale project. A typical screenshot may looks like as bellow:

https://n9e.github.io/images/intro/rule-config.png
https://n9e.github.io/images/intro/integrations.png


Allowing users to choose between two sort options in a view

Question: I have a view of user accounts.
I want to allow visitors to the site to choose to sortthis view by login date or by account creation date in a view (Views 3, Drupal 7).
It's easy to expose the sort operator to users, but is there a way to let users select which sort is applied first (creation date or login date)?
I thought about just cloning the view, and then changing the sort on the second view and linking them together, but if possible I would like to avoid duplication.
Comment: You could probably do that with https://www.drupal.org/project/better_exposed_filters to accomplish this, I've combined two sorts together that way before, one selected with Ajax refreshing sort, then having the secondary sort tied in with the same. I would checkout the handbook links on that page for more direction, they have some pretty extensive recipes there that you could use as a base to start from.
Comment: how about sortable headers? I don't know if it goes two levels though
Comment: @Geoff For this view, I'm using Views Fluid Grid to manage the display (the view shows user profiles, and I'm using fluid grid because it works responsively), so unfortunately the sortable table headers won't help me, but that's a good idea.
Comment: the next option I might look at is a custom form inserted into the views header that creates the search url and refreshes the page. This way you could customise the layout and behaviour of the form and set the url appropriately
Answer: You can do that with Better Exposed Filters. I've combined two sorts together that way before, one selected with Ajax refreshing sort, then having the secondary sort tied in with the same. I would checkout the handbook links on that page for more direction, they have some pretty extensive recipes there that you could use as a base to start from.
handbook page for further reference


Limit Google Cloud Platform instance bandwidth

Question: On Google Cloud Platform, is there a way to limit the bandwidth allowed for a specific instance?
I mean specify a limit like 10TB of traffic monthly, or something like that.
Because from what I see there is no way to specify a limit like this.
Any clue?
Answer: Due I haven't found any ways to archive that, i have managed to create a budget limit on the project. In order to alert the administrative office if the customer is going to overtake his limit allowed.
Answer: There isn't any cap or limit of egress traffic for a VM's in GCP.
As you've found out you can set budgeting alerts in your project.
To be more specific however you can set alets for a certain product (refine the scopoe) such as Compute Engine or App Engine etc. Even more - you can set up alerts for a resources with a certain label. If you for example put different labels for a different VM's you can set billing alerts for those. It won't stop them from going over the limit but you will know precisely which VM is generating what cost and set alets with different threshold levels (30,50,80%).
If you go with the labels then creating them (or adding to already existing resources) is easy - just have a look at the documentation on how to manage GCP labels.


Linking taxonomy terms in views

Question: I am using Drupal 8 and I am creating an internship placement system where students sign up and have a skills field (using taxonomy terms).
Employers can create job postings, which have same skills field.
How do I link matching fields (skills) in a view so that when a student logs in they only see jobs related to their skills?
Answer: You need to use views as described below
1. Create a user view (not content view)
2. Add contextual filter user id with default value current logged in user

3. Add relationship on terms referenced from field skills (of user)

4. Add relationship with term from skills

The previous relationship should be autoselected

5. Now you can add content fields to view and the field skills relationship should be autoselected

when a user visits the view page the jobs will be contextually filtered based on their profile selections
Comment: Thanks for the response. Is there a way that i could show the content instead of field in the Format>show area?
Comment: This was a user view so there is no content option (only user).  You can probably start with a content view and do the reverse relations and come to the same result (and be able to use content as SHOW option) but I still think `fields` is more flexible.

Linking taxonomy terms in views