Algorithm - if known $x$ and $y$ value

Question: I am new to this site, so please bear with my bad question-writing skills!
I was given a puzzle, in which I have to work the algorithm being used to generate the $y$ value from the $x$ value. Here are the given 'rules':
The variable $x$ has $2$ digits

if $x = 19, y = 45$
if $x = 10, y = 50$
if $x = 15, y = 25$
EDIT: if $x = 65, y = 55$

What might the algorithm be?
Answer: What are the rules?
If the one's place number is nonzero, multiply it by 5 for the result. If the one's place number is zero, multiply the whole number by 5 for the result.
This can likely be stated in a much better way.
Comment: I'm sorry, but there is a problem with this. I just realised that is x = 65, y = 55
Answer: You can say:
$$
x\equiv 1 \pmod{2} \Leftrightarrow y=5\cdot(x \pmod{10})
$$
$$
x\equiv 0 \pmod{2} \Leftrightarrow y=5x
$$
EDIT: The following is only theorizing.
$$
x > 50 \Rightarrow y=5\cdot(x \pmod{10})+\frac {x-(x \pmod{10})}{2}
$$
Now transform it to a function:
$$
f(x) = \left\{
   \begin{array}{l l}
     5\cdot(x \pmod{10}) & \quad x\equiv 1 \pmod{2}\\
     5x & \quad x\equiv 0 \pmod{2}
   \end{array} \right.
$$
Comment: I suppose it would be helpful if we had one more example of an even x to see if the condition was parity or a zero, but your interpretation seems much more likely.
Comment: I'm sorry, but there is a problem with this. I just realised that is x = 65, y = 55
Comment: @ultimatetechie: Why do you not have written that in the question?
Comment: @Doop I am so sorry for not stating this
Comment: @Zeonatra Because I just asked my friend who gave it to me for that. I can try and get anther number if you want?
Comment: @Doop I can get another number; Which is best do you think (Rules: 2 digit). Should it be even?
Answer: Let $y = a_3x^3 + a_2x^2 + a_1x+a_0.$ Then we have the following system of equations:
$$\begin{align*}
19^3 a_3 + 19^2 a_2 + 19 a_1 + a_0 &= 45, \\
10^3 a_3 + 10^2 a_2 + 10 a_1 + a_0 &= 50, \\
15^3 a_3 + 15^2 a_2 + 15 a_1 + a_0 &= 25, \\
65^3 a_3 + 65^2 a_2 + 65 a_1 + a_0 &= 55,
\end{align*}
$$
forming the linear system
$$\begin{pmatrix}
19^3 & 19^2 & 19 & 1 \\
10^3 & 10^2 & 10 & 1 \\
15^3 & 15^2 & 15 & 1 \\
65^3 & 65^2 & 65 & 1
\end{pmatrix}
\begin{pmatrix}
a_3 \\ a_2 \\ a_1 \\ a_0
\end{pmatrix}
=
\begin{pmatrix}
45 \\ 50 \\25 \\ 55
\end{pmatrix}.
$$
Solving, we find
$$y \approx -0.0219x^3+2.0765x^2-46.491x+329.1989.$$
Comment: I see what you're getting at, but this algorithm isn't going to be as clever as that!
Comment: A polynomial interpolant is like the least clever thing out there ;)

Algorithm - if known $x$ and $y$ value


Max number from arrays in java

Question: I have created a random program with an array with a lot of values and the frequency of each one, inside it, and I would like the program to find the 5 most frequent numbers is there any way I can do that?
`Here is the code I have already written. 2 random arrays, 2 frequencies, find the 5 numbers withe most frequency out of them:
<code>import java.util.Random;
public class ArrayElementsAsCounters {
public static void main(String[] args){
    Random rand = new Random();
    int freq[] = new int[46];
    int freq2[] = new int[21];

    for(int roll=1; roll < 3000000;roll++){
        ++freq[1+rand.nextInt(45)];
        ++freq2[1+rand.nextInt(20)];
    }
    System.out.println("Number\tFrequency");

    for(int number1 =1; number1<freq.length;number1++){
        System.out.println(number1+"\t"+freq[number1]);
    }
    System.out.println("Joker\tFrequency");
    for(int number2 =1; number2<freq2.length;number2++){
        System.out.println(number2+"\t"+freq[number2]);
    }

}
</code>
}
`
Answer: For each value that you have, make them the elements of another array.
This will be the frequency array of the elements.
Now run loop through the original array and each time you encounter an element, add one to its frequency array value.
Then sort the frequency array in descending and starting from the max, print out the first five that are encountered.
Answer: Take a look at MultiSets:
https://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html
You can add all elements into the set and do a sort by count afterwards. Given that the question is broad, I'm just giving guidelines, I'll leave the coding part as an exercise for you to do ;)

Max number from arrays in java


$f(x,y) = \begin{cases} \frac{xy^2}{x^2+y^2} \quad \text{if} \ (x,y)\not=(0,0)\\ 0 \quad \text{if} \ (x,y)=(0,0)\end{cases}$ differentiable?

Question: $$f(x,y) = \begin{cases}  \frac{xy^2}{x^2+y^2} \quad \text{if} \ (x,y)\not=(0,0)\\ 0 \quad \text{if} \ (x,y)=(0,0)\end{cases}$$
Is this two-variable function differentiable at (0,0)?
Comment: @abiessu I think you are wrong. In both case, the value of limit is 0.
Comment: It is possible to make the limit be different numbers from different directions, so no.  Consider $y=x$ vs. $y=\sqrt x$.
Comment: You can consider any line through origin which has a constant slope other than $1$ and other the line $y=x$. Both will give different answers. for example, take $y =2x$.
Answer: In polar coordinates,
$$f=r\cos\phi\sin^2\phi$$
So that the secant of $f$ from the origin in the direction $(\cos\phi,\sin\phi)$ to radius $r$ has slope
$$\frac{\mathrm{d}f}{\mathrm{d}r}=\frac{\Delta f}{\Delta r}=\cos\phi\sin^2\phi\text{.}$$
Therefore $f$ is Gâteaux differentiable at the origin—it has a directional derivative in all directions.
However, there are no constants $f_x$, $f_y$ such that
$$\frac{\mathrm{d}f}{\mathrm{d}r}=f_x\cos\phi+f_y\sin\phi\text{.}$$
That is, the directional derivatives are not linear in the direction. We say, then, that $f$ is not Fréchet differentiable (without further qualification, the Fréchet derivative is "the" derivative, so $f$ is not differentiable at the origin).
Answer: $f(x,y) = \begin{cases}  \frac{xy^2}{x^2+y^2} \quad \text{if} \ (x,y)\not=(0,0)\\ 0 \quad \text{if} \ (x,y)=(0,0)\end{cases}$
Here $$f_x(0,0)= \lim_{h\to 0} \frac{f(h,0)-f(0,0)}{h}=0$$
$$f_y(0,0)= \lim_{k\to 0} \frac{f(0,k)-f(0,0)}{k}=0$$
So the first order partial derivatives with respect to $x$ and $y$ both exist at $(0,0)$.
If the given function is differentiable at $(0,0)$, then by definition
$df=f(h,k)-f(0,0)=Ah+Bk+h\phi+k\psi$ . . . . $(1)$
where $A=f_x(0,0)=0$; $B=f_y(0,0)=0$; and $\phi$, $\psi$ tends to zero as $(h,k)\to(0,0)$.
From $(1)$, $ \frac{hk^2}{h^2+k^2}=h\phi+k\psi$
Putting $k=mh$ and letting $h\to0$, we get
$\frac{m^2}{1+m^2}=\lim_{h \to 0}(\phi+m\psi)=0$
which is impossible for arbitrary $m$.
Hence the given function is not differentiable at $(0,0)$.
Answer: $\frac {\partial f} {dx}=\lim \frac {y^{2}} {x^{2}+y^{2}}$ which does not exist. [Consider limit along $y=0$ and limit along $x=y$]. So $f$ is not differentiable at $(0,0)$.
Answer: The question is quite simple.
$f'_x(0,0)=f'_y(0,0)=0$ ,
Let $x=y=t$ then the function become $F(t)=f(t,t)=\frac{t}{2}$. The differentiation is $F'(t)=\frac{1}{2}\ne 0$ then it is not differentiable.
Answer: Another way would be to answer the original question by definition.
For contradiction, assume that the function is differentiable at $(0,0)$. In virtue of the fact that $f(0,0)=f'_x(0,0)=f'_y(0,0)=0$, it suffices to show that
$$
f(h_x,h_y)=f(0,0)+f'_x(0,0)\cdot h_x+f'_y(0,0)\cdot h_y+\varepsilon (h_x,h_y)
$$
with $\frac{\varepsilon (h_x,h_y)}{\sqrt{h_x^2+h_y^2}}\to 0$ as $(h_x,h_y)\to (0,0)$. Since the first three summands on the RHS vanish, we obtain $\varepsilon(h_x,h_y)=f(h_x,h_y)$. Consequently,
$$
\frac{\varepsilon (h_x,h_y)}{\sqrt{h_x^2+h_y^2}}
=\frac{h_x^2\,h_y}{\sqrt{\left (h_x^2+h_y^2\right )^3}}
$$
which is a non-constant homogeneous function of degree $0$. Therefore, $\frac{\varepsilon (h_x,h_y)}{\sqrt{h_x^2+h_y^2}}\,{\color{red}\not{\!\!{\color{red}\to}}}\,0$ as $(h_x,h_y)\to (0,0)$ and $f(x,y)$ cannot be differentiable at $(0,0)$.


Render Failed when ListVieWebPart sorted by more than 2 columns

Question: Does anyone know if it's possible have  a sharepoint lsit view sort by more than 2 columns. Wned I go to modify the view in the UI I'm only allowed to enter two sort fileds. I tried to do it in the Source like this:
> <Query>
>           <GroupBy Collapse="TRUE" GroupLimit="100">
>             <FieldRef Name="Category" />
>             <FieldRef Name="SubCategory" />
>             <FieldRef Name="Topic" />
>           </GroupBy>
>           <OrderBy>
>             <FieldRef Name="Category" />
>             <FieldRef Name="SubCategory" />
>             <FieldRef Name="Topic" />
>           </OrderBy>
>         </Query>

I get an error on the page:

Answer: I just used the Caml Query Builder from U2U and the query below runs fine against my 2010 server.  I don't have a 2007 server to test it against so I can't gurarantee it will work for you.  Get the tool though, it will help a LOT!
http://www.u2u.be/Res/Tools/CamlQueryBuilder.aspx
UPDATE: New tool for SharePoint 2010
http://karinebosch.wordpress.com/2012/05/12/caml-designer/
<Query>
  <OrderBy>
    <FieldRef Name="ID" Ascending="True" />
    <FieldRef Name="_DCDateCreated" Ascending="False" />
    <FieldRef Name="_UIVersionString" Ascending="True" />
    <FieldRef Name='Created' Ascending='True' />
  </OrderBy>
</Query>


java.lang package in java

Question: Since java.lang package is automatically imported in all java programs by compiler, why is it necessary to write import java.lang.annotation; statement at the top of the program while using annotations in the program?
Answer: Because the java.lang.annotation package isn't the same as the java.lang package. They're simply different packages.
Imagine if importing one package imported all the packages "under" it - then
import java.*;

would import almost everything in the standard libraries - but that's not the way it works. An import statement of
import foo.*;

simply imports all the types in the foo package - it doesn't import anything in any other packages which happen to start with foo..
Answer: Because java.lang automatic import is just for it's classes and interfaces whose package belong it is java.lang.
annotation is a sub-package inside java.lang and this automatic behaviors don't propagate to sub-package only immediate classes of java.lang
Comment: I got it. Thanks :)

java.lang package in java


Timezone and summertime CodeIgniter

Question: I search the better solution for view the local time for all users of my website.
I got a problem with summer time, actually i got this function if you got a better way help me :
function timezone_by_offset($offset) {

 $abbrarray = timezone_abbreviations_list();
    $offset = $offset * 60 * 60;

    foreach ($abbrarray as $abbr) {
        foreach ($abbr as $city) {
            if ($city['offset'] == $offset && $city['dst'] == TRUE) {
                return $city['timezone_id'];
            }
        }
    }
    return 'UTC'; // any default value you wish
}
echo timezone_by_offset(1) . '
';
echo (date_default_timezone_set(timezone_by_offset(1)) == TRUE ? 'Valid'. date('Y-m-d H:i:s') : 'Not Valid'). '
';

SOLUTION :
<?php
 function get_timezones()
 {
    $o = array();
    $t_zones = timezone_identifiers_list();
    foreach($t_zones as $a)
    {
        $t = '';

        try
        {
            //this throws exception for 'US/Pacific-New'
            $zone = new DateTimeZone($a);

            $seconds = $zone->getOffset( new DateTime("now" , $zone) );
            $hours = sprintf( "%+02d" , intval($seconds/3600));
            $minutes = sprintf( "%02d" , ($seconds%3600)/60 );

            $t = $a ."  [ $hours:$minutes ]" ;

            $o[$a] = $t;
        }

        //exceptions must be catched, else a blank page
        catch(Exception $e)
        {
            //die("Exception : " . $e->getMessage() . '
');
            //what to do in catch ? , nothing just relax
        }
    }

    ksort($o);

    return $o;
}

$o = get_timezones();
?>

<select name="time_zone">
<?php
    foreach($o as $tz => $label)
    {
        echo "<option value="$tz">$label</option>";
    }
?>
</select>

Best Regards.
Answer: UPDATE 3
PART 1 - Finding correct timezone
If you are looking for a timezone_name with help of its offset and HAS daylight saving you set the the third parameter of timezone_name_from_abbr() to true, otherwise to false. If you set it to 1 and the offset + daylight saving does not give valid timezone_name it will return false. In such cases you can turn it back to false.
Example
$tz = timezone_name_from_abbr(null, $offset * 3600, true);
if($tz === false) $tz = timezone_name_from_abbr(null, $offset * 3600, false);

PART 2 - Get local date/time accoring to DAYLIGHT SAVINGS
You do not have to do anything here, once timezone is set PHP date function automatically sets daylight savings according to your timezone and CURRENT date. So
function print_according_to_offset($offset)
{

    $tz = timezone_name_from_abbr(null, $offset, true); //If a ofset with daylight savings is found
    if($tz === false) $tz = timezone_name_from_abbr(null, $offset, false); //otherwise
    if($tz === false) // If no timezone is still found
    {
        echo 'Invalid Offset
';
        return;
    }
    $otherTZ  = new DateTimeZone($tz);
    $datetime = new DateTime; // current time = server time
    $datetime->setTimezone($otherTZ);
    echo $tz . '
';
    echo $datetime->format('Y-m-d H:i:s') .'

';
}

print_according_to_offset(19800);

UPDATE 2
<?php
$timezone = '+0:00';
$timezone = preg_replace('/[^0-9]/', '', $timezone) * 36;
$timezone_name = timezone_name_from_abbr(null, $timezone, true);
date_default_timezone_set($timezone_name);
echo date('D d M Y H:i:s');
?>

More information
UPDATE
CI function and improved code
function print_according_to_offset($offset)
{
    $user_timezone =  timezone_name_from_abbr("",$offset,0);
    $otherTZ  = new DateTimeZone($user_timezone);
    $datetime = new DateTime; // current time = server time
    $datetime->setTimezone($otherTZ);
    echo $datetime->format('Y-m-d H:i:s') .'
';
}

print_according_to_offset(14400); //EXAMPLE

Dont expect us to do everything for you, edit the function and return $otherTZ if you need to get timezone only.
Old Post
I think this is what you need.
$offset = 3600 ; //your offset
$my_timezone =  timezone_name_from_abbr("",$offset,0);

date_default_timezone_set($my_timezone);
echo date('Y-m-d H:i:s');

More info
Comment: The timezone is not fix, my users on my website is international, i use codeigniter framework and i got a function for get timezone (UTC+1, UTC+2, UTC+3, etc) but i don't know how do this corrrectly
Comment: It is in php and CI is based on php. It will definitely run with CI, all you need is to set the offset. But I have updated the solution so you can implement easily with CI
Comment: so your system does the same thing as me except that my problem is offset, I can't know what has offset corresponds to UTC +1 for example
Comment: I thought you had the found the correct offset. I have updated my post, it should work now.
Comment: Ok but the problem with this way is for the summer time and winter time, i know in west european the time is UTC +1 in winter and UTC +2 in summer and i don't know how do that and your function doestn't work correctly cause the summer time is not take for all country in the world and i can't do UTC -1, UTC -2, etc
Comment: I have found better solution of you, but a problem persist for convert a date in my database with timezone user got

Timezone and summertime CodeIgniter


Does Tchaikovsky's Sleeping Beauty modulate to the relative minor?

Question: There's a part of Tchaikovsky's Sleeping Beauty that I like. And I was wondering if I'm right as far as the theory goes:
Measures 156-159 is in the relative key of G minor, and ends on this key.

Measures 172-176 is in the given key of B-flat major, and ends on this key.

Here's what it sounds like. I'm mainly talking about from time 2:38 (minor) vs 2:55 (major)

I'm just wondering if I'm right that 2:36-2:38 is a modulation to the relative key of G minor and how do you know? That part just made me sad and I also noticed it ended on a Gm.
Answer: While it's true this entire movement is in B♭, this portion is really in the key of E♭ starting at the pick-up to m. 145 (2:24) until the return to B♭ around m. 177 (2:56). Notice all of the A♭s effectively turning the key signature of two flats into one with three (and thus E♭ major).
With that said, the music definitely cadences in G minor in m. 159 (2:38). But to my ears, this is more a tonicization than a modulation. What's the difference? We typically say that a modulation reaches a cadence in a new key, and this one does! But remember that so much of a cadence is the preparation; here, we really just have a V–i in G minor. A truer preparation (and therefore a stronger cadence creating a bona fide modulation) could have used a predominant that led into this dominant. To me, the E♭ chord in m. 156 sounds too much like the current tonic to be understood as a predominant setting up a G-minor cadence. Furthermore, the music immediately returns back to E♭, quickly removing any status of "tonic-ness" that G could have had. Really, this G-minor cadence is just a way to end this phrase with a perfect authentic cadence (PAC) that isn't the current tonic.
And speaking of cadences: notice that there's never a PAC in this current tonic of E♭! We only receive weak IACs in m. 151 (2:30) and m. 167 (2:47). This really keeps the momentum up to push us forward into the return of the opening material in B♭.
Comment: I like to use terms "cadence" and "cadential harmony" to try distinguishing this type of progression that _looks like a cadence_ in terms of treble and bass notes matching the definition, but not really having the structural function. I'm not sure if "cadential harmony" is an excepted term to convey that meaning.


Apache Jmeter + Random Double

Question: Is it possible to generate random double numbers in JMeter?
I tried to use the Random in the config element where i have defined the
Minimum value: 47.9999  (RND1)
Maximum value: 30.9999  (RND2)

Then in the selected Prepared Selected Statement i placed this values:
Parameter values: ${RND1},${RND1},${RND2}
Parameter types: DOUBLE,DOUBLE,DOUBLE

But it seems not work, because i receive an error:

Response message: java.sql.SQLException: Cannot convert class
  java.lang.String to SQL type requested due to
  java.lang.NumberFormatException - For input string: "${RND1}"
Answer: Looks like ${RND1} is not expanded to it's value in your JDBC Request because it wasn't initialized Random Variable config item - because the last one is to generate only integer values (as well as jmeter's __Random function).
To generate random double values in defined range you can use schema like below:
1. Define MIN and MAX range values as variables in User Defined Variables

RND1    37.9999
RND2    41.9999

2. Generate random double value in range RND1..RND2 using e.g. Beanshell Sampler:

Parameters: ${RND1},${RND2}
Script (java code):

import java.util.*;

String [] params = Parameters.split(",");

double rangeMin = Double.valueOf(params[0]);
double rangeMax = Double.valueOf(params[1]);
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();

vars.put("RND",randomValue.toString());

//System.out.println(randomValue);

Adding Debug Sampler, with Jmeter variables = true let you see generated values for debugging purposes.
3. Refer generated random value as ${RND} for further use (in JDBC Request in your case)

Apache Jmeter + Random Double


Two continuous distributions with same 1% & 5% quantiles however  distributions are notably different in shape, location etc?

Question: Previously I asked this question to R-help (finance group) however, could not get a satisfactory reply (probably this is not directly related to R.) Here is my question:
Is there any possible way to get 2 continuous distributions (defined on the real line) such that, both distributions have same 1% & 5% quantiles (or, any one of these two. However to me this is a weak condition!), however those distributions are notably different in shape, location etc.
Can somebody please point me any example of such 2 distribution?
Comment: I have noticed that you have not accepted any answers to your previous questions. Consider accepting some of them if you find them helpful. This will motivate responders :).
Comment: By $1\%$ quantiles, do you mean each percentile from the first through $99$th?
Answer: Take two distribution functions $F_1$, $F_2$ (increasing functions from $\mathbb{R} \to [0,1]$...) such that $F_1(0.01)=F_2(0.01)$ and $F_1(0.05)=F_2(0.05)$. There are infinitely many possibilities !
For instance you can fix some values for the $1\%$ and $5\%$ quantiles and use the optim() R function to determine the parameters of a normal distribution which fits these values and on the other hand determine the parameters of a log-normal distribution which fits these values.
Answer: Would you consider it a notable difference if one distribution has a negative mean, and the other has a positive mean? This difference may be critical in some situations.
Let $X$ be the constant $-1$. $E[X] = -1.$
Let $Y$ be $-1$ with probability $99.5\%$, and $399$ with probability $0.5\%$. You can think of $Y$ as the net value of a raffle ticket you bought for $\$1$ for a $\$400$ prize. $E[Y] = 1$. If you take gambles like this repeatedly, you will win in the long run with high probability.
These are not continuous, but you can make slight adjustments to make them continuous. Let $X'$ have density $1/2$ from $-2$ to $0$, and let $Y'$ have density $1/2$ from $-2$ to $-1/100$ and from $400-1/100$ to $400.$ These exhibit the same behavior.
More subtly, you can make the difference between a winning and a losing gamble occur between, say, the $55$th and $60$th percentiles. Suppose you risk $3$ to gain $4,$ e.g., in a poker game you call a $\$3$ overbet into a pot of $\$1$ on the last round. If you lose at most $4/7 \approx 57\%$ then you have a winning gamble. The $5\%$ quantiles can't see the difference between losing $56\%$ of the time (a good gamble) and losing $59\%$ (a bad gamble). This example can also be made continuous.


Twig template suggestions for paths such as page--node--page-url

Question: using D8, I'd like a twig template for a page I've created based off the path of the page and not node %. I look in my twig suggestions and all I see are:
page--node--8.html.twig
page--node--%.html.twig
page--node.html.twig
page.html.twig

As template suggestions. However, as I'm working in multiple environments and don't know what the node number will be when I actually create this page I'd like to just base it off the path I've set for the page which is '404-error'. Anyone know how to do that?
I'm imagining something like page--node--404-error.html.twig
However that doesn't seem to work (I tried it).
Comment: The only available template suggestions are the ones that are defined. If you disable caching and enable twig debug, you can view what the suggested templates are in the source code of the page. https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
Comment: After that, you would have to do some logic for example in hook_preprocess_page, check if the current request is a node object, and if so, add on to the template suggestion list with 'page__node__' and add the path. I caution you here though, the paths may be too long to exist as a filename depending on what you're trying to do.
Answer: You can add suggestions for the page template in a hook:
mytheme.theme:
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

This is an example how to add a suggestion with the path for any page. You can narrow it down to the pages you are interested in and if necessary check for paths that are too long.


To check whether my code is correct or not

Question: void addEntry(Integer newEntry)
throws SimulationException
Adds a new entry to the log.
Existing entries are shifted along one place in the window accordingly.
Parameters:
newEntry - the new value to be added to the log
Throws:
SimulationException - if the given value is not in the range 0 to maxEntry, inclusive
how does the code look like ? does it look like this ?
public void addEntry(Integer newEntry) throws SimulationException{

    }

Comment: And what is the concrete question?
Comment: -1 See Santiago's Answer
Answer: That's fine. Now, you hardly want to log in to Stack Overlflow every time you need to check if some invocation is right :) learn to use:
a) the Java compiler. If you try and compile code with erroneous syntax, the compiler will tell you where you made your mistake! Learn to use and interpret the outputs of the compiler.
b) an advanced Java development environment, such as Eclipse. Actually, I've no idea how can someone code in Java without Eclipse. For me, it's almost part of the language.
Cheers!
Comment: i'd say the same goes for Maven, Idea, Log4J, and lots of other Java-goodies =)
Answer: class Square {

    public static void main(String args[]) {

        int n = 289, r;
        r = sqrt(n);
        if (n==r) {
            System.out.println("Perfect Square");
        } else {
            System.out.println("Not a Perfect Square");
        }
    }
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Can I host Drupal alongwith Google App Engine?

Question: I am new to Drupal as well as Google App Engine. I want to create a scalable website with few specialized apps in Google app engine and integrate with Drupal. Given both the platforms are extensively used, it seems to me that they should be supporting each other. However, I checked both Google app engine and Drupal website but could not figure out if they support each other. So my question is , is there any way I can host Drupal with Google app engine? Can they work together in the same platform?
Answer: Google App Engine now supports PHP, yes you can.
But Drupal technically is supposed to run on an Apache server (.htaccess rewrites, restrictions and options) with normal email servers that can be handled using normal PHP's mail(), and PDO, you will need to take care of providing alternatives for the services.
Mainly, GAE has limitations in emails, SQL, and writable file system.
Here is a link to a post that helped me a lot: http://blog.boombatower.com/drupal-google-app-engine


PhoneGap and Zxing QrCode - building issues

Question: I currently encounter a problem with installing ZXingWidget for a
PhoneGap project.
I followed both "PhoneGap Plugins" and ZXingWidget installation
guides, but my project building fails.
Most of my errors (17) look like that :

path/project/Plugins/BarcodeScanner.mm:8:0 In file included from
path/project/Plugins/BarcodeScanner.mm
path/project/Plugins/BarcodeScanner.h:11:0   In file included from
path/project/Plugins/BarcodeScanner.h
../zxing-1.6/iphone/ZXingWidget/Classes/QRCodeReader.h:10:0 In file
included from ../zxing-1.6/iphone/ZXingWidget/Classes/QRCodeReader.h
../zxing-1.6/iphone/ZXingWidget/Classes/FormatReader.h:22:0 Zxing/
common/Counted.h: No such file or directory in ../zxing-1.6/iphone/
ZXingWidget/Classes/FormatReader.h

That's mean my PhoneGap project finds "BarcodeScanner.mm",
"BarcodeScanner.h" and "QRCodeReader.h" but it is not able to reach
"FormatReader.h" ?
I check again and again the installation guides step by step, I think
I put well the relative path to ZXingWidget classes in the Project
Settings, but I don't understand where I'm wrong.
I will appreciate any help.
SOLUTION
I forgot to include the Zxing cpp source in the PhoneGap project.
As the "zxing/iphone/ZXingWidget/Classes" directory, the "cpp/core/src/" directory has to be included (the "recursive search" box doesn't need to be checked.)
In addition, the following iOS frameworks: AVFoundation, AudioToolbox, CoreVideo, CoreMedia and libiconv have to be added to the project.
Better explanations :
http://www.google.com/url?sa=D&q=http://code.google.com/p/zxing/source/browse/trunk/iphone/README%3Fspec%3Dsvn1651%26r%3D1651
Comment: go ahead and write your solution as the answer to your question.
Comment: Please move your solution down to an answer so we can get this off the unanswered list.  Thank you.
Comment: So this phoneGap solution is working for you?
Answer: SOLUTION as posted by craymond.
I forgot to include the Zxing cpp source in the PhoneGap project. As the "zxing/iphone/ZXingWidget/Classes" directory, the "cpp/core/src/" directory has to be included (the "recursive search" box doesn't need to be checked.) In addition, the following iOS frameworks: AVFoundation, AudioToolbox, CoreVideo, CoreMedia and libiconv have to be added to the project.
Better explanations : http://www.google.com/url?sa=D&q=http://code.google.com/p/zxing/source/browse/trunk/iphone/README%3Fspec%3Dsvn1651%26r%3D1651


Calculate the amount of days between two dates in ms word

Question: I have a Word document with two mergefields, each containing a date
{ MERGEFIELD myObj.startDate \* MERGEFORMAT }--> outputs 01.01.2014
{ MERGEFIELD myObj.endDate \* MERGEFORMAT } --> outputs 31.01.2014
Now I would like to calculate how many days there are between those two dates, so I have to "substract" startDate from endDate, e.g. 31.01.2014 - 01.01.2014 --> 31
Unfortunately this doesn't work:
{ { MERGEFIELD myObj.endDate \* MERGEFORMAT } - { MERGEFIELD myObj.startDate \* MERGEFORMAT } }
Does anyone know if it's even possible, and if so, how?
Comment: Date differences are also discussed in http://stackoverflow.com/questions/20353619/word-create-formula-to-subtract-dates-in-word/20361233#20361233
Answer: The solution below was taken from a document posted to the Windows Secrets forum by Paul Edstein. It contains a trove of information on how to perform date calculations in Word field codes and can be found in this thread:
Microsoft Word Date Calculation Tutorial
Because Word field codes do not copy and paste easily, I have inserted a screen cap of the code below. I suggest that you become a member of the free Windows Secrets forum so you can download this document and copy the field codes from Mr. Edstein's original document into your own document as this will be easier than keyboarding the text and creating the field code brackets manually (CTRL-F9 in Word).
The following code should work with your date format of DD.MM.YYYY. If you bookmark your myObj.startDate and myObj.endDate field codes within your document using the StartDate and EndDate bookmark names, the code below will work as is. Because the SET command is designed to work with bookmarks, this solution will probably not work if you replace the EndDate and StartDate bookmarks from this example with your MERGEFIELD field codes. However, I have not experimented with this, so I do not know if the object model has this flexibility.
Comment: Update: The tutorial can also be found at: https://www.msofficeforums.com/word/38719-microsoft-word-date-calculation-tutorial.html and http://www.gmayor.com/downloads.htm#Third_party. It is a valuable resource. Anyone trying to do date calculations in Word should keep a copy on their computer.


In MySQL, why is it safe to turn off innodb_support_xa for single threaded updates?

Question: In MySQL's docs the following is said about the innodb_support_xa option:

Enables InnoDB support for two-phase commit in XA transactions, causing an extra disk flush for transaction preparation. This setting is the default. The XA mechanism is used internally and is essential for any server that has its binary log turned on and is accepting changes to its data from more than one thread. If you turn it off, transactions can be written to the binary log in a different order from the one in which the live database is committing them. This can produce different data when the binary log is replayed in disaster recovery or on a replication slave. Do not turn it off on a replication master server unless you have an unusual setup where only one thread is able to change data.
For a server that is accepting data changes from only one thread, it is safe and recommended to turn off this option to improve performance for InnoDB tables. For example, you can turn it off on replication slaves where only the replication SQL thread is changing data.

However, from my understanding from reading on the infamous group commit bug, 2PC is used to guarantee that the transaction log and the binlog contain the same set of transactions, while the prepare_commit_mutex is responsible for ensuring the same order.
With prepare_commit_mutex, the writing to the transaction log and the binlog are already serialized, then what's the difference between multi-threaded and single-threaded updates?
On the other hand, even if there is only one thread that can change data, without 2PC, if a crash occurs after a transaction is written to the binlog, but before it's written to the transaction log, how is Innodb going to deal with this situation in recovery? In theory it can simply execute the outstanding transaction in the binlog, just as what the slaves do, but I doubt Innodb actually does that, because otherwise why do we need 2PC at all?
I'm not familiar at all with the internals of MySQL, so please forgive me if I'm terribly wrong. Thanks!
Answer: To begin with...
http://yoshinorimatsunobu.blogspot.com/2009/08/great-performance-effect-of-fixing.html
Before InnoDB Plugin 1.0.4, it was like:
obtain mutex
  write innodb log and fsync, for prepare-phase (skip if innodb_support_xa=0)
  write binlog (fsync as appropriate if sync_binlog > 0)
  write innodb log and fsync, for commit-phase
release mutex

On and after InnoDB Plugin 1.0.4 (and MySQL 5.5), it is now:
write innodb log and fsync, for prepare-phase (skip if innodb_support_xa=0)
obtain mutex
  write binlog (fsync as appropriate if sync_binlog > 0)
  write innodb log, for commit-phase
release mutex
fsync innodb log, for commit-phase

As you can see, in the new version, nothing (except in case sync_binlog > 0) is fsync'd in the critical section. That way, group commit now works and ensures far better concurrent throughput.
For instance, with the previous "broken" version, if you had 100 threads concurrent commits, all fsyncs were serialized and you would get 100 fsyncs for prepare and another 100 fsyncs for commit. Therefore group commit was completely broken.
Now with the newer implementation, fsyncs are grouped depending on the concurrency of transactions, while ensuring operation ordering between innodb log and binlog. It also means that if there's only one thread, there's no performance gain.
As to your question that, when crash occurs after a transaction is written to the binlog, but before it's written to the transaction log - I'm on the same page as you.
If the server crashed before the final step, there's a slight chance that you have a discrepancy between innodb log and binlog (either one could be ahead of the other), but it is guaranteed that you have all the information on what to examine in the innodb log, as it is recorded in the prepare-phase.
However, what to do with the uncommitted is still nondeterministic. For instance, unless sync_binlog = 1 there's a chance that a slave received the data but not fully fsync'd the binlog on the master yet. You can't just redo the failed transaction as it may have already run on one of the slaves.
Which also means, the binlog could be shorter than the innodb log, returning "The binary log [file_name] is shorter than its expected size." as described in the official doc, and you have to rebuild the slave from scratch. Not very human friendly.
http://dev.mysql.com/doc/refman/5.1/en/binary-log.html
As consistency in terms of operation ordering is guaranteed independent of the innodb_support_xa setting (which contradicts what's said in the official doc on innodb_support_xa, maybe because it was written about the stock innodb 5.0.3 far before the concurrency fix), and consistency between innodb log on the master and relay log on the slave is not strictly guaranteed even with innodb_support_xa, I don't see any point in using innodb_support_xa. It's scary to not follow the official recommendation, though, however it seems stale and wrong in many points.
I'm wondering if there's any correlation between the innodb_flush_log_at_trx_commit setting and the innodb_support_xa behavior when the former is set to 2 or 0.
One practical way of thinking is that, failover to the slave is safe - after all, the failed transaction was something that you wanted to get done - but never fail-back to master, as there might be some discrepancy in the data. You need to fully copy the data from the slave, before you make the master a new slave. In other words, when the master crashed, trust the slave from then on - that way, you don't need to mess with innodb log for crash recovery.
Also note that MySQL 5.5 supports semi-synchronous replication, along the same line as "trust the slave" - thought you might be interested.
http://dev.mysql.com/doc/refman/5.5/en/replication-semisync.html
Comment: @Sebas comment is a little vague, according to MySQL docs: "innodb_support_xa is deprecated and will be removed in a future MySQL release. InnoDB support for two-phase commit in XA transactions is always enabled as of MySQL 5.7.10" So it is deprecated, but only because it will always be on.


Variable importance assessed by MR vs. by Spearman's rank-order coefficient

Question: I am looking for an answer to the following questions:

Consider a multiple linear regression model with 2 IVs ($X_1$ and $X_2$). Now, suppose that there is a strong monotonic relationship between $X_1$ and the DV (using the Spearman rank coefficient), and that a weak relationship exists between $X_2$ and DV. Does this mean that $X_1$ will have the highest beta weight ($\beta_{X_1} > \beta_{X_2}$)?
For example, if we say that IV1 has more predictive power than IV2 and so on, how can we interpret this statement in term of monotonicity between each IV and the DV?
Answer: It is not necessarily true that the ordering of Spearman's rank coefficient will be the same as the ordering of the betas returned by a multiple regression model fit.  There can be several reasons for this, here are a few that I can think of quickly (there may well be more):
Range restrictions:
A restricted range will not affect (on average--i.e., the expected value of) the estimated slope of a variable (although it will its significance), but it will strongly affect the correlation (either Spearman's or Pearson's).  Thus, by adjusting the ranges of $X_1$ and $X_2$, it is possible to flip the orderings back and forth.  Here's an example where $X_1$ ranges from 0 to 10, and $X_2$ ranges from 0 to 3:
x1   0         5       10         0        5       10        0         5        10
x2   0         0        0         1.50     1.5      1.5      3         3         3
y  -48.09667 -12.12629 17.93941 -57.59159 12.30414  6.521197 4.300887 58.36051 -55.91287

rho(x1,y) = 0.3689324;     rho(x2,y) = 0.05270463
beta_x1   = 2.331171;      beta_x2   = 5.448008

Multicollinearity:
If your covariates are correlated with each other ($r(X_1, X_2)\ne0$) all kinds of counter-intuitive results can occur.  Perhaps one of the most counter-intuitive is the suppressor effect (you can read about it at the bottom of this page--but read the whole page, it's worth your time).  Here's an example where $X_1$ acts as a suppressor:
x1 -0.029557 0.606060 1.8436 -1.20882  0.46996  0.22534  0.23217 -1.35094 -0.787902
x2  0.165287 0.086891 2.2664 -0.69033  0.23273  0.18010 -0.32480 -1.36021 -0.556156
y   0.432622 0.223160 1.1213  0.42582 -0.94566 -1.00691  0.15683 -0.54717  0.056125

rho(x1,y) =  0.2333333;        rho(x2,y) = 0.1
beta_x1   = -0.593140024;      beta_x2   = 0.874374951

MR betas are linear relationships, Spearman's rho isn't necessarily:
The rectilinear line of best fit can have a very shallow slope (i.e., small beta weight) if the true function is curvilinear, whereas Spearman's correlation coefficient is completely unaffected by this.  Here's an example of a situation where $Y$ is related to the log of $X_2$:
x1 3        6        9        3       6        9        3        6        9
x2 3        3        3        6       6        6        9        9        9
y  1.942158 4.222256 4.672984 4.85704 5.061267 5.381291 4.154654 5.875549 7.183006

rho(x1,y) = 0.6324555;     rho(x2,y) = 0.5797509
beta_x1   = 0.3490794;      beta_x2  = 0.3542117

(I don't know if the latter two examples are 'fair', in that they rely on a misspecification of the multiple regression model--that is, the model that was fit was not the true data generating process--but we probably never fit the model that exactly mirrors the true data generating process in real life, and these are cases where the orderings flip.)
Thus, the answers to your two questions are: No, having a higher Spearman rank coefficient does not mean that it will have the highest beta weight; and we cannot interpret orderings of beta weights in terms of orderings of monotonicity between the IV and DV.
Comment: *(In passing, I should note that your question refers to the "importance" and "predictive power" of variables in ways that suggest you see these terms as related to the betas found in a multiple regression analysis. I believe that this is a mistaken assumption--albeit a very common misunderstanding. Unfortunately, it would take quite a bit to explain why, and I'm guessing that it is peripheral to your real question, so I won't address these issues here. However, if you are interested in these issues, ask another question and I'll be happy to explain it.)*


Unable to start a script at startup ubuntu

Question: I am trying to execute one script at startup on ubuntu 16.04 LTS desktop. I have added my script to /etc/init.d location. But after restart I am unable to see my script running using
pidof -s pgd

Once I execute this command sudo service run_pgd start it started with a pid. I want this script to be executed in the background.
I have achieved the same thing by adding the script in rc.local it was working fine. But I am having issue in /etc/init.d location This is the script file
#!/bin/bash

###
# Configuration section
#

# Specify full path to directory with pgd executable and config files here:
# For example: PGD_DIR="/usr/local/Neurotechnology/Activation"
PGD_DIR="/opt/Neurotec_Biometric_10_0_SDK/Bin/Linux_x86_64/Activation"

#
# End of Configuration section
###

# If PGD_DIR is not set use the directory of current script
if [ ! "${PGD_DIR}" ]
then
    PGD_DIR=`dirname "$0"`

    # If we were called through relative path, make absolute one
    if [ "${PGD_DIR:0:1}" != "/" ]
    then
        PGD_DIR="$PWD/$PGD_DIR"
    fi
fi

NAME=pgd
PROGRAM="${PGD_DIR}/${NAME}"
if [ "`uname -s`" = "Darwin" ]
then
    LOG=/Library/Logs/pgd.log
else
    LOG=/tmp/pgd.log
fi

###
# Common routines section
#

echo_()
{
    echo "run_pgd.sh:" "$*"
}

get_pid()
{
    if which pidof &> /dev/null
    then
        echo `pidof -s $NAME`
    else
        ps axc|awk "{if (\$5==\"$NAME\") print \$1}"
    fi
}

start_pgd()
{
    echo_ "starting $NAME..."
    PRESERVE_DIR="$PWD"
    cd "$PGD_DIR"
    "$PROGRAM"
    cd "$PRESERVE_DIR"
    sleep 1
    if [ -s "$LOG" ]
    then
        echo_ "$NAME run log ($LOG):"
        echo  "----------------------------------------"
        cat   "$LOG"
        echo  "----------------------------------------"
    fi
}

stop_pgd()
{
    PID=`get_pid`
    if [ $PID ]
    then
        echo_ "stopping $NAME..."
        kill $PID
        echo_ "$NAME (pid=$PID) was sent a signal."
    else
        echo_ "$NAME processs not running!"
        exit 1
    fi
}

###
# Body...
#

if ! test -d "$PGD_DIR"
then
    echo_ "Wrong PGD_DIR variable value specified: $PGD_DIR"
    echo_ "Please point it to correct place with $NAME application."
    echo_ "Please also ensure that needed configuration files are there."
    exit 1
fi
if ! test -f "$PROGRAM"
then
    echo_ "$PROGRAM application not found!"
    exit 1
fi
if ! test -x "$PROGRAM"
then
    echo_ "$PROGRAM application not runable!"
    exit 1
fi

case "$1" in
  start)
    PID=`get_pid`
    if [ $PID ]
    then
        echo_ "$NAME is already running (pid: $PID)"
        exit 1
    fi

    [ ! -f $LOG ] || rm $LOG
    start_pgd
    ;;
  stop)
    stop_pgd
    ;;
  restart)
    stop_pgd

    sleep 4

    if [ `get_pid` ]
    then
        echo_ "$NAME has not stopped!"
        echo_ "restart failed."
        exit 1
    fi

    [ ! -f $LOG ] || rm $LOG
    start_pgd
    ;;
  log)
    PID=`get_pid`
    if [ $PID ]
    then
        echo_ "$NAME is running with pid: $PID"
    else
        echo_ "$NAME processs not running!"
    fi

    if [ -s "$LOG" ]
    then
        echo_ "log ($LOG):"
        echo  "----------------------------------------"
        cat   "$LOG"
        echo  "----------------------------------------"
    else
        echo_ "log file (\"$LOG\") is empty."
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|log}"
    exit 1
esac

exit 0

Is there something wrong with my script ? What are the required changes do I need to make to execute this script at startup ? I want this script to be executed even if the system reboots after crash or any failure.
Regards
Answer: Scripts in /etc/init.d are not executed at startup by default. This is just the location where startup scripts are (or, by now, were) located.
After placing your script there you need to create symlinks in /etc/rc[1-6].d.
You can do that manually, or by running:
update-rc.d


Combining multiple contingency tables

Question: I have images that are evaluated by different experts. Basically, each expert look at the same pictures and saying whether a feature in the image exists or not. We have some images from diseased and normal people. The idea is to find whether a particular feature of the image is associated with disease. IF there were only a single expert we would be able to do a Fisher's exact test. But there are multiple experts so we need a way to combine multiple contingency tables to get a single p value. By digging internet, I found that "Cochran-Mantel-Haenszel statistics" does something similar to this. However, I still have questions whether this is the appropriate test. Any suggestions?
Comment: Do all the experts evaluate all the images?
Answer: I think you can simplify this if you stop thinking of it as a collection of contingency tables, and re-envisage it as a simple linear model (with binomial response ie logistic regression).

The response variable is whether the image is actually from someone with a disease (I presume you have this information, and also that the experts did not know this in advance, as otherwise the whole exercise seems a bit pointless).
The explanatory variable is how many experts (or perhaps what proportion of experts) rated the image as having the feature you're interested in.  If there are actually multiple features, you can have as many of these explanatory variables (and indeed interactions) as you want.

Then you can just fit this as a logistic regression model, or possibly as a generalized additive model with a binomial response if you want to allow for non-linearity between the "proportion of experts who saw the feature" and the response.
Alternatively (but same basic idea), you could use a similar approach but make the "number of experts who saw the feature" an ordered categorical explanatory variable.  This would make sense if you think (for example) there is a radical discontinuity between 0, 1 or 2 experts who see the feature rather than a smooth progression of "the more who see it, the more likely it is to be there.".
Comment: I'm really unclear what is in the contingency tables.  If you don't have information on how many experts rated it as existent or non existent, what actually do you have?
Comment: Thats a good idea, I will definitely try this if i am able to get the appropriate data. However, I think I only have the contingency tables and it might take a while to get the actual assesment on the image level so my first go is a contingency table approach. So I want to ask whether there is at least statistically something wrong with the contingency table approach and the CMH test?
Comment: I don't know the CMH test so can't help on that.  But do you mean (by "actual assessment on the image level") that you don't know which images actually were associated with disease?  If so I don't think you can solve your problem by any means.
Comment: Thanks Peter, the person that collected the data unfortunately only have the contingency tables not the actual assesment the experts  made. I can not calculate for a given image how many experts rated it as existent or non existent.

Combining multiple contingency tables


Show block only on "Page Not Found"?

Question: Using a Block's visibility setting of Show block on specific pages: Pages on which this PHP code returns TRUE (experts only)...

...what PHP would I write that returns TRUE so that the block only shows on "Page Not Found" pages?
Answer: Can I recommend not doing it with PHP?
I would suggest making a page (via Admin->Content->Add Content), this assumes that you have the node module installed.
And then set that page as your "Default 404 (not found) page" in Admin->Configuration->System->Site Information
And then you can use that page's path in the block set up, but list under "Only the listed pages"
Comment: That was my first try! Seems simple, right? Doesn't work. When you hit an incorrect URL the Page Not Found page is shown, BUT it doesn't redirect. It retains the incorrect URL. So using its path in the block setup doesn't work… nor does using its node path ("/node/123").
Comment: Instead of adding new node create a panel page. It works! I tried it a month ago!
Comment: Well, I am surprised by that, as drupal_deliver_html_page() https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_deliver_html_page/7.x is called and it sets/executes `menu_set_active_item($path);` and `$return = menu_execute_active_handler($path, FALSE);` using the 404 path you have set in config - and I thought blocks are also invoked from this.  So with your 404 page set, your should be able to do compare your 404 path with  `menu_get_active_trail();` with php
Comment: @rjl Well, you seemed pretty confident that this should work, so I double-checked the path option by adding both the aliased path and the node path to the *Only listed pages* box… and **IT WORKED!** I'm at a loss though; I literally spent an hour on this earlier trying every possible way to make this work using the path, and got nowhere. The only thing I did differently this time is use both path options at the same time… which I don't think has anything to do with it. *Sigh…* must be the Drupal gremlins hard at work again. Anyway, thanks for prompting me to try again!
Comment: I am wondering if those gremlins may have been a caching issue, anyway I am glad it worked!

Show block only on "Page Not Found"?


How do I get the logo path?

Question: I have a custom logo and I have tried to get his path in this way theme_get_setting('logo_path'), but no expected result.
I am using the code in a custom block, in input PHP.
Comment: Where are you using this code? Have you tried `theme_get_setting('logo_path', 'THEME_NAME')`, replacing THEME_NAME with the name of your theme?
Answer: logo_path seems to only be set if you override the theme's default logo via its theme settings. To get the default logo, use theme_get_setting('logo').
Comment: Thanks, that's exactly what I was looking for! Use `` in a PHP code block to show the logo in your own block.
Comment: But why the result of `theme_get_setting('logo')` is empty string ? I have set my custom logo in `/admin/appearance/setting`
Comment: Why when Logo is deactivate from theme `TOGGLE DISPLAY -
Enable or disable the display of certain page elements.` the  `theme_get_setting('logo')` has no results. Why ?
Answer: global $base_url;
drupal_theme_initialize();

if (!$logo = theme_get_setting('logo_path')) {
    $logo = theme_get_setting('logo');
}

if (!empty($logo)) {
  // [1]
  // Remove the base URL from the result returned by theme_get_setting('logo').
  // If you don't need the relative path, you can remove this code.
  if (strpos($logo, $base_url) === 0) {
    $logo = drupal_substr($logo, drupal_strlen($base_url));
  }
  // [1]
  // …
}

The call to drupal_theme_initialize() is not strictly necessary, and it doesn't do anything if the global variable $theme is already initialized.
The code is removing the base URL because the value reported from theme_get_setting('logo') is an absolute path; if you don't need a relative path to access the file, then the part between // [1] can be removed.
When the logo has been disabled in the theme settings, theme_get_setting('logo') doesn't return anything.
Comment: I replaced the code in `[1]` with `$logo = file_create_url($logo);` in order to get the full URL path of the logo (with the http://).

How do I get the logo path?


Como fazer animação de mudança de vídeos com clique do mouse

Question: Estou com uma dúvida, não sei nem como pesquisar o que eu quero.
A ideia seria clicar na imagem do Vídeo 1 e o Vídeo e o Titulo mudassem sem sair da página, assim pro 2 e 3. Tomei uma surra em uns códigos mas esse na verdade não sei nem como pesquisar.
Comment: Provavelmente o que procura e uma *Single Page Application* que muda dinamicamente o video sem ter de recarregar a pagina. Umas das frameworks usadas para produzir SPAs e o [tag:AngularJs]
Comment: você já usa jQuery ou outra frame em JS, como Angular? Ou apenas está trabalhando com css/js puro? Tem alguma restrição de usar algum deles?
Comment: No click do video você pode alterar o src do video para o video que voce precisa e colocar o titulo também.
Answer: Podes fazer isto da seguinte maneira:

function mostraDiv(num) {
    document.getElementById('div1').style.display='none';
    document.getElementById('div2').style.display='none';
    document.getElementById('div3').style.display='none';
    document.getElementById('div'+num).style.display='block';
}
.hiddenEl{display:none;}

    <button class="imagens" onclick="mostraDiv('1')">Mostra Div 1</button>
    <button class="imagens" onclick="mostraDiv('2')">Mostra Div 2</button>
    <button class="imagens" onclick="mostraDiv('3')">Mostra Div 3</button>

Sou a div1

Sou a div2

Sou a div3

Depois basta fazeres as modificações à tua medida, trocando os botões por divs e inserindo imagens dentro delas como thumbnails de preview do vídeo que o usuário irá ver, ao clicar no botão/imagem pretendida e também popular as divs com o conteúdo (títulos, vídeos etc).
Eu criei aqui um exemplo no JSFiddle simples mas bem elaborado de como isto irá funcionar com os respetivos títulos e vídeos para cada botão, para teres uma ideia.


How to link taxonomy term with current loaded NID?

Question: I want to link taxonomy term with current loaded node
I am using
<code>$nid = arg(1);
$term=taxonomy_term_load($tid)
print $term;
</code>
but noting happened.
Please tell what is the correct way
Comment: please check this http://drupal.stackexchange.com/questions/8722/how-do-i-get-a-list-of-all-taxonomy-terms-assigned-to-a-node
Comment: Get the **taxonomy ID - tid** using **db_select** and **node ID**. And then load the **taxonomy_term_load($tid)**, Which taxonomy field you want from the node?
Comment: i have differ kind of term and every term is linked with page for example term A has page 1 and its child term b has page 2 when i am click page 1 it go to page 1 not term A and same as when i am click page 3 it go to page 3 not to term b these data are shown in first side bar block all data are custom code
Comment: You want to say that you have 2 pages, PAGE 1 has associated with term A and PAGE 2 with term B(which is the child of term A). And when you click on  PAGE 1 of course it will redirect to PAGE 1 only. Are you trying to redirect to term A? And when you click to PAGE 3, why it should redirect to term B? There is not association with PAGE 3. Can you explain it in more details?
Comment: oh sorry its no page 3 its page 2
Answer: <code>$nid = arg(1);
$node = node_load($nid);
//field_taxonomy is the taxonomy field used in the node
$tid = $node->field_taxonomy['und'][0]['tid'];
$term=taxonomy_term_load($tid)
print $term;
</code>
Answer: In Drupal 6 and Drupal 7, taxonomy and node ids' are linked in term_node and taxonomy_index tables respectively. To programmatically link nid and tid, load the node and enter tid in it under hook_node_presave()
Create a new taxonomy object, if not already exist
<code>$taxonomy = new stdClass();
$taxonomy->vid = xxx; // id of the vocabulary term
$taxonomy->name = 'abc'; // name of the term
$new_term = taxonomy_term_save($term);
$tid = $new_term->tid; // This will get you tid of new term
                       // that is created or use taxonomy_term_load() if you have tid
</code>
Attach this tid in the node
<code>$node->taxonomy_field_name_in_the_node['und'][]['tid'] = $tid;
</code>
submit this node.


automatic resolve member function with const postfix

Question: Inside my class I have 2 algorithms that should be applied depending if container supports lower_bound.
template <class T>
class SmartContainerHandler{
....
template <class Q=T>
typename std::enable_if< std::is_member_function_pointer<decltype(&Q::lower_bound)>::value >::type
foo_impl(int k, double _ = 0)
{
    auto r = _t.lower_bound(k);
    std::cout << "has lower_bound" << (r == _t.end() ? -1 : *r) << std::endl;
}
template <class Q=T>
typename std::enable_if<! std::is_member_function_pointer<decltype(&Q::lower_bound)>::value >::type
foo_impl(int k)
{
    std::cout << << "no lower_bound, just a key:" << k <<  std:: endl;
}

For example I would like to instantiate either with  SmartContainerHandler<std::set<int> > or SmartContainerHandler<std::vector<int> >
My problem that lower_bound has 2 signatures
template< class K > iterator lower_bound(const K& x);
template< class K > const_iterator lower_bound(const K& x) const;

(just try to compile this without success auto m = &std::set<int>::lower_bound)
In my particular case I don't care about const signature, but in sake of more generic question: How to check method exists if provided 2 or more signatures?
Comment: Do you want a way to distinguish no-overload / one-overload / two-overloads (e.g., const / non-const)? Or simply a way to distinguish no-overload / one or more overloads?
Comment: @Holt The best for me - let the compiler provide best overload. But  I understand that from expression`&Q::lower_bound` it is impossible. So const/non-const is a good way to specify correct choice.
Answer: You can simply rely on expression SFINAE here, something like:
template <class Q=T>
auto foo_impl(int k, double _ = 0)
    -> decltype(std::declval<Q&>().lower_bound(k), void())
{
    auto r = _t.lower_bound(k);
    std::cout << "has lower_bound" << (r == _t.end() ? -1 : *r) << std::endl;
}

void foo_impl(int k, ...)
{
    std::cout << << "no lower_bound, just a key:" << k <<  std:: endl;
}

The first foo_impl overload will be discarded if std::declval<Q&>().lower_bound(k) is not a valid expression.
Comment: Looking promising but doesn't work. Here is my sandbox http://coliru.stacked-crooked.com/a/1991cace8871b95b that twice prints `no lower_bound, just a key:6
no lower_bound, just a key:6`
Comment: @Dewfy It only requires minor tweaks: http://coliru.stacked-crooked.com/a/6b644b93488a04da
Comment: @VittorioRomeo super!


PHP e Javascript - Ajustando busca em tabela MySQL (Doctrine Query)

Question: Estou fazendo na minha página do meu cliente, que assumi de outro desenvolvedor, uma seção pra buscar eventos cadastrados no banco de dados MySQL. Como está essa página:

    BUSCA DE EVENTO

Digite o número do evento:

            <input name="buscaNumero" id="buscaNumero" class="validate[required]" title=""></input>

        <input id="buscaNoBanco" name="buscaNoBanco" type="button" class="textDescricaoSobre font13" value="Buscar Evento" onclick="buscaBanco(document.getElementById('buscaNumero').value);" style="cursor: pointer; width: 93px;" />

        RESULTADO DA BUSCA

        Código:

        Modelo:

        Evento:

        Local:

        Data e Hora:

        Carga Horária:

        Conteúdos Abordados:

        Indicadores de Performance:

        Materiais:

        Facilitadores:

        Lista de Presença:

    VOLTAR AO MENU INICIAL

A função buscaBanco foi definida assim:
function buscaBanco(numero){
    if (numero == '') {
        alert('Nenhum resultado encontrado!');
        $('#resultadoBusca').hide();
    }
    else {
        // Executa a consulta SQL. Se houver resultado, mostra na tela
        $('#resultadoBusca').show();
        <?php
            // class_exists('Servico') || include_once CLASS_PATH . 'Servico.class.php';
            $data['evento'] = Servico::getRetornosEventos();
            $event = $data['evento'];
        ?>
        document.getElementById('resultCodigo').textContent = <?php echo $event['id'] ?>
        document.getElementById('resultModelo').textContent = <?php echo $event['modelonome'] ?>
        document.getElementById('resultEvento').textContent = <?php echo $event['evento'] ?>
        document.getElementById('resultLocal').textContent = <?php echo $event['localevento'] ?>
        document.getElementById('resultData').textContent = <?php echo $event['dataevento'] ?>
        document.getElementById('resultHora').textContent = <?php echo $event['horaevento'] ?>
        document.getElementById('resultCarga').textContent = <?php echo $event['cargahoraria'] ?>
        document.getElementById('resultConteudos').textContent = <?php echo $event['conteudos'] ?>
        document.getElementById('resultIndicadores').textContent = <?php echo $event['indicadores'] ?>
        document.getElementById('resultMateriais').textContent = <?php if($event['chkapostila']=='1'){ echo "Apostila"; } else { echo "Nenhum"; } ?>
        document.getElementById('resultFacilitadores').textContent = <?php if($event['facilitadores']=='Externos'){ echo $event['externosnomes']; } else { echo $event['internosnomes']; } ?>
        document.getElementById('resultLista').textContent = <?php echo $event['listapresenca'] ?>
    }
}

E a função getRetornosEventos() que fica no arquivo servico.class.php  (com doctrine query) funciona assim:
public static function getRetornosEventos(){
    return self::$evento = self::setRetornosEventos();
}

public static function setRetornosEventos(){
    $sql = Doctrine_Query::create()
    ->select('e.id,u.nome AS usuarionome,
             (CASE WHEN modelo = 1 THEN "Sala de Aula"
                   WHEN modelo = 2 THEN "On The Job"
                   WHEN modelo = 3 THEN "Palestra"
                   WHEN modelo = 4 THEN "Workshop"
                   WHEN modelo = 5 THEN "Programas Institucionais"
                   WHEN modelo = 6 THEN "Outro" ELSE modelo END) as modelonome,
             (CASE WHEN programa = 1 THEN "Eu Faço Parte"
                   WHEN programa = 2 THEN "PDG"
                   WHEN programa = 3 THEN "PDL Unidades"
                   WHEN programa = 4 THEN "PDL Corporativo"
                   WHEN programa = 5 THEN "Jeito de Ser" ELSE programa END) as programa,
              outromodelo,evento,localevento,DATE_FORMAT(dataevento, "%d/%m/%Y") as dataevento,horaevento,
              cargahoraria,conteudos,indicadores,chkapostila,chkcopia,chkoutro,chknenhum,outromaterial,
             (CASE WHEN facilitadores = "E" THEN "Externos"
                   WHEN facilitadores = "I" THEN "Internos" ELSE facilitadores END) as facilitadores,
              externosnomes,externosempresas,internosnomes,internosempresas,listapresenca')
    ->from('WtEducEventos e')
    ->addFrom('WtUsuario u')
    ->where('e.usua_id = u.id')
    ->addWhere('e.id = ' . $_POST['buscaNumero']);
    $data = $sql->fetchArray();
    return $data;
}

Porém, a página fica desconfigurada e aí não possível nem testar a busca. O que pode estar errado? Algum ponto-e-vírgula faltando na função buscaBanco? A declaração Class_Exists (normalmente fica nos arquivos de Controller) é obrigatória nesse caso? Ou de repente algum erro em misturar o PHP em script de java ou até mesmo com a consulta SQL (doctrine query).
Aceito ajudas e sugestões.
Answer: Está faltando aspas na função buscaBanco. Do jeito que está, vai acusar erro de sintaxe.
function buscaBanco(numero){
    if (numero == '') {
        alert('Nenhum resultado encontrado!');
        $('#resultadoBusca').hide();
    }
    else {
        // Executa a consulta SQL. Se houver resultado, mostra na tela
        $('#resultadoBusca').show();
        <?php
            // class_exists('Servico') || include_once CLASS_PATH . 'Servico.class.php';
            $data['evento'] = Servico::getRetornosEventos();
            $event = $data['evento'];
        ?>
        document.getElementById('resultCodigo').textContent = "<?php echo $event['id'] ?>"
        document.getElementById('resultModelo').textContent = "<?php echo $event['modelonome'] ?>"
        document.getElementById('resultEvento').textContent = "<?php echo $event['evento'] ?>"
        document.getElementById('resultLocal').textContent = "<?php echo $event['localevento'] ?>"
        document.getElementById('resultData').textContent = "<?php echo $event['dataevento'] ?>"
        document.getElementById('resultHora').textContent = "<?php echo $event['horaevento'] ?>"
        document.getElementById('resultCarga').textContent = "<?php echo $event['cargahoraria'] ?>"
        document.getElementById('resultConteudos').textContent = "<?php echo $event['conteudos'] ?>"
        document.getElementById('resultIndicadores').textContent = "<?php echo $event['indicadores'] ?>"
        document.getElementById('resultMateriais').textContent = "<?php if($event['chkapostila']=='1'){ echo "Apostila"; } else { echo "Nenhum"; } ?>"
        document.getElementById('resultFacilitadores').textContent = "<?php if($event['facilitadores']=='Externos'){ echo $event['externosnomes']; } else { echo $event['internosnomes']; } ?>"
        document.getElementById('resultLista').textContent = "<?php echo $event['listapresenca'] ?>"
    }
}


Programmatically resize images uploaded

Question: When uploading images to D8 programmatically the setting for Maximum image resolution will be ignored and images will not be scaled down. Some of the images i have to upload are even larger then 10MB.
I am currently using this code.
$file_type = explode('.', $image)[1];
$data = file_get_contents($image);
$path = 'public://images/';

if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {

  $file = file_save_data($data, $path . md5($image) . '.' . $file_type, FILE_EXISTS_REPLACE);

  $node = Node::create(array(
    'type' => 'image',
    'title' => $image,
    'field_image' => array(
      'target_id' => $file->id(),
    ),
  ));
  $node->save();

}

I've tried to work with ImageStyle::load('max_2600x2600'), but that will only create a style in styles directory.
It would be possible to use a custom shell command but i would love to use the Drupal 8 way. How to make sure original images will get resized?
Answer: You can Use Image style before save the node.
$original_image = 'public://images/image.jpg';

// Load the image style configuration entity.
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('max_2600x2600');

$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);

Here some links may helps you
Drupal 8 - Create an Image and ImageStyle Programmatically
Drupal 8 images with image style
Flexible image style system
Comment: My image does not come from **public://** but from directory outside of Drupal provided for FTP uploads. You pointed me into the right direction and i've finally managed to resize images while importing them.
Comment: now your issue has been fixed right?
Comment: Yes thanks allot! But the code in your example is not the code that helped me, since it will not create a new image outside of **public://** and i want to create a file with **fid** to attach to the node. I'm using $style->createDerivative($original_image, 'temporary://filename.jpg'); to create a resized image in temporary directory and attach this file to the node and have it imported correctly.
Comment: Nice to here you. Actually this code is how to resize images programmatically using image style. Great job :)
Answer: I ran into the same thing. This code ended up working for me
      use Drupal\file\Entity\File;
      use Drupal\image\Entity\ImageStyle;
      use Drupal\node\Entity\Node;

      $fileName = 'example.jpg';
      $destination =  "public://images/" . $fileName;
      $temporaryFile = 'temporary://' . $fileName;
      file_save_data($photoData, $temporaryFile, FILE_EXISTS_REPLACE);

      $style = ImageStyle::load('thumbnail');
      $style->createDerivative($temporaryFile, $destination);

      $file = File::create([
        'uid' => 1,
        'filename' => $fileName,
        'uri' => $destination,
        'status' => 1,
      ]);
      $file->save();

      if ($file) {
          $node->get('field_photos')->appendItem([
              'target_id' => $file->id(),
              'alt' => 'Alt text goes here',
          ]);
      }

      ...

      $node->save();

Programmatically resize images uploaded


When does the law of large numbers fail?

Question: The question is simply what is stated in the title:  When does the law of large numbers fail?  What I mean is, in what cases will the frequency of an event not tend to the theoretical probability?
Answer: There are two theorems (of Kolmogorov) and both require that the expected value be finite. The first holds when variables are IID, the second, when sampling is independent and the variance of the $X_n$ satisfies
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} < \infty$$
Say that all $X_n$ have expected value 0, but their variance is $n^2$ so that the condition obviously fails. What happens then? You can still compute an estimated mean, but that mean will not tend to 0 as you sample deeper and deeper. It will tend to deviate more and more as you keep sampling.
Let's give an example. Say that $X_n$ is uniform $U(-n2^n , n2^n)$ so that the condition above fails epically.
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} = \sum_{n=1}^\infty \frac{n^2 2^{2n+2}}{12}\frac{1}{n^2} = \frac{1}{3} \sum_{n=1}^\infty 4^n = \infty.$$
By noting that
$$\bar{X}_n = \frac{X_n}{n} + \frac{n-1}{n}\bar{X}_{n-1},$$
we see by induction that the computed average $\bar{X}_n$ is always within the interval $(-2^n, 2^n)$. By using the same formula for $n+1$, we also see that there is always a chance greater than $1/8$ that $\bar{X}_{n+1}$ lies outside $(-2^n, 2^n)$. Indeed, $\frac{X_{n+1}}{n+1}$ is uniform $U(-2^{n+1},2^{n+1})$ and lies outside $(-2^n, 2^n)$ with probability $1/4$. On the other hand, $\frac{n}{n+1}\bar{X}_n$ is in $(-2^n, 2^n)$ by induction, and by symmetry it is positive with probability $1/2$. From these observations it follows immediately that $\bar{X}_{n+1}$ is greater than $2^n$ or smaller than $-2^n$,
each with a probability larger than $1/16$. Since the probability that $|\bar{X}_{n+1}| > 2^n$ is greater than $1/8$, there cannot be convergence to 0 as $n$ goes to infinity.
Now, to specifically answer your question, consider an event $A$. If I understood well, you ask "in what conditions is the following statement false?"
$$ \lim_{n \rightarrow \infty} \frac{1}{n}\sum_{k = 1}^{n} 1_A(X_k) = P(X \in A), \; [P]\;a.s.$$
where $1_A$ is the indicator function of the event $A$, i.e. $1_A(X_k) = 1$ if $X_k \in A$ and $0$ otherwise and the $X_k$ are identically distributed (and distributed like $X$).
We see that the condition above will hold, because the variance of an indicator function is bounded above by 1/4, which is the maximum variance of a Bernouilli 0-1 variable. Still, what can go wrong is the second assumption of the strong law of large numbers, namely independent sampling. If the random variables $X_k$ are not sampled independently then convergence is not ensured.
For example, if $X_k$ = $X_1$ for all $k$ then the ratio will be either 1 or 0, whatever the value of $n$, so convergence does not occur (unless $A$ has probability 0 or 1 of course). This is a fake and extreme example. I am not aware of practical cases where convergence to the theoretical probability will not occur. Still, the potentiality exists if sampling is not independent.
Comment: Are you two discussing the same law?  The question asks about *frequencies of events* while this reply seems to focus on the sampling distribution of a *mean*.  Although there is a connection, it hasn't yet appeared explicitly here as far as I can tell.
Comment: If they are identically distributed, but not independent, the limit in question may not exist at all.
Comment: One comment. On wikipedia (lnl page) i have read that the non finiteness of variance only decelerate the convergence of the mean value. Is different from what you states?
Comment: @whuber True. I focused too much on the title of the question. Thanks for pointing. I updated the answer.
Comment: @gui11aume i don't understand "We see that the condition above will hold, because the variance of an indicator function is bounded above by 1/4.". What does it means?
Comment: It is not clear what $1_A(X_k)$ means or how it relates to $P(A)$. If the $X_k$ are **iid** (that is, not *just* independent), then we might interpret the former as $1_{(X_k \in A)}$ and the latter as $P(X_1 \in A)$, but otherwise...
Comment: Thanks for the recent edit. I'd still suggest you clarify that the limiting statement only makes sense if the $X_k$ are iid and also that the right-hand side should be $P(X \in A)$ and not $P(A)$.
Comment: @cardinal, yup! I was thinking about the meaning of the terms in non IID case but could not come with anything satisfactory.
Comment: @cardinal, after giving it a thought, I think that they just need to be identically distributed for the formula to make sense. I edited accordingly because it fits better with what comes after.
Comment: @emanuele I edited the answer to clarify. 1/4 is the max variance of a Bernouilli 0-1 variable (its variance is $p(1-p)$).
Comment: can someone make a demo/simulation in R that shows when the law of large number of fails?
Comment: `n=1; x=c(); while(TRUE) { n = n+1; x = c(x, runif(n=1, -n*2^n, n*2^n)); print(mean(x)) }`


Service Discovery Eureka Netflix

Question: eu tenho uma arquitetura SOA com duas stacks diferentes uma com java e outra com ruby, tenho um microservice usando spring boot e outro rails, e estou tentando configurar um Service Discovery com Eureka para projetos java especialmente com Spring Boot é muito fácil de se registrar no Service Discovery porém para outra lang sem ser java não achei solução?
Então é possível registrar no Eureka sem ser um projeto java? se sim, como?
Answer: Achei a solução:
Você registra seu micro serviço via REST.
https://github.com/Netflix/eureka/wiki/Eureka-REST-operations
Exemplo de json:
{
    "instance": {
        "hostName": "rails-checkin",
        "app": "rails-checkin",
        "vipAddress": "com.automationrhapsody.eureka.app",
        "secureVipAddress": "com.automationrhapsody.eureka.app",
        "ipAddr": "127.0.0.1",
        "status": "UP",
        "port": {"$": "3000", "@enabled": "true"},
        "securePort": {"$": "3000", "@enabled": "true"},
        "healthCheckUrl": "http://rails-checkin:3000/checkins",
        "statusPageUrl": "http://rails-checkin:3000/checkins",
        "homePageUrl": "http://rails-checkin:3000/",
        "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
        }
    }
}

Service Discovery Eureka Netflix


How do I automatically add links on the right sidebar in drupal 7?

Question: Let's say I have a few articles about weight training. How do I populate the right sidebar blocks with related links to current article?
Answer: I've just implemented related content using views following this tutorial. If you prefer using a module you got even more choices.
Comment: Awesome! It works! Now all related articles are displayed on the sidebar of any article! Thanks a ton!
Comment: hmmm my drupal 7 version doesn't have the views section.
Comment: Ah I think I need to install the views module


Update between two tables when there is no relation between them

Question: I need a SQL statement which fills the null values from the second column of #T1 table with values from #T2(C1).
There is no foreign key or match between the columns of those two tables.
Sample:
T1 (C1, T2C1)
A1, 1
A2, null
A3, null
A4, 4
A5, null
-------------
T2 (C1)
a
b

After update, the T1 will look like:
A1, 1
A2, a
A3, b
A4, 4
A5, null

I found two approaches:
Using CTE
create table #T1 (C1 varchar(10), T2C1 varchar(10))
create table #T2 (C1 varchar(10))

insert into #T1 values ('A1', '1')
insert into #T1 values ('A2', null)
insert into #T1 values ('A3', null)
insert into #T1 values ('A4', '4')
insert into #T1 values ('A5', null)

insert into #T2 values ('a')
insert into #T2 values ('b')

;with t2 as
(
select C1, row_number() over (order by C1) as Index2
from #T2
)
,t1 as
(
select T2C1, row_number() over (order by C1) as Index1
from #T1
where T2C1 is null
)
update t1
set t1.T2C1 = t2.C1
from t2
where t1.Index1 = t2.Index2

select * from #T1

drop table #T1
drop table #T2

With Derived Tables
create table #T1 (C1 varchar(10), T2C1 varchar(10))
create table #T2 (C1 varchar(10))

insert into #T1 values ('A1', '1')
insert into #T1 values ('A2', null)
insert into #T1 values ('A3', null)
insert into #T1 values ('A4', '4')
insert into #T1 values ('A5', null)

insert into #T2 values ('a')
insert into #T2 values ('b')

update #T1
set T2C1 = cj.C1
from #T1
join (select T2C1, row_number() over (order by C1) as Index1, C1
   from #T1
   where T2C1 is null) ci on ci.C1 = #T1.C1
join (select C1, row_number() over (order by C1) as Index2
  from #T2) cj on ci.Index1 = cj.Index2

select * from #T1

drop table #T1
drop table #T2

My question is, can I achieve this without using windowing functions and with no cursors?
Update

@Damien_The_Unbeliever correctly points that to do this kind of update it is not possible without defining an ordering on tables, actually I think exactly said is without properly identify and link the rows from target table.

@Bogdan Sahlean has found another way, using table variables and IDENTITY column, which I'm happy with this solution, it's another way
However, in the real application I will still use the windowing functions

Thanks all
Comment: There is no inherent ordering to tables, and you're trying to impose one. I don't see how you'd do it without a window function or cursor.
Comment: I'm living with the fact maybe I'm missing something, I know that the only join between those tables will be a cartesian product, N x M where M > 1
Answer: 1.I suppose you have a pk in target table (#T1).
2.Instead of ROW_NUMBER this solution uses IDENTITY(1,1) columns and two table variables.
3.I didn't tested this solution.
DECLARE @t2_count INT = (SELECT COUNT(*) FROM #T2);

DECLARE @Target TABLE
(
     MyId INT IDENTITY(1,1) PRIMARY KEY
    ,T1_pk INT NOT NULL UNIQUE
);
INSERT  @Target (T1_pk)
SELECT  TOP(@t2_count) pk
FROM    #T1
WHERE   T2C1 IS NULL;

DECLARE @Source TABLE
(
     MyId INT IDENTITY(1,1) PRIMARY KEY
    ,C1 VARCHAR(10) NOT NULL
);
INSERT  @Source (C1)
SELECT  C1
FROM    #T2;

UPDATE  #T1
SET     T2C1 = src.C1
FROM    #T1 t
INNER JOIN @Target trg ON t.pk = trg.T1_pk
INNER JOIN @Source src ON trg.MyId = src.MyId;

Answer: I agree with Damien, anyway when you will rely on the engine and make a premise that the table is ordered by the C1 column (which depends only on the DB and you can not rely on that  ) the you could issue an update statement which will update all the rows
declare @a int
set @a = 0

update #t1
set t2c1 = @a,
@a = @a+1

But I wouldn't do that.
Comment: It doesn't really matter the order. In the real application, the scenario is this: I have a list of barcodes in a CSV file, which I put it in table, using bulk insert. Then for each product stock, that hasn't already a barcode (here the null condition) I assign a barcode. The order in which the barcodes are assigned it doesn't matter, the only condition is to keep the list unique.
Answer: I would use a CTE along with ROW_NUMBER:
WITH cte_t1 AS
(
  SELECT
   T2C1
  ,ROW_NUMBER() OVER (ORDER BY C1) AS id
  FROM T1
  WHERE T2C1 IS NULL
)
,cte_t2 AS
(
  SELECT
   C1
  ,ROW_NUMBER() OVER (ORDER BY C1) AS id
  FROM T2
)
UPDATE t1
  SET t1.T2C1 = t2.C1
  FROM cte_t1 AS t1
  INNER JOIN cte_t2 AS t2
    ON t1.id = t2.id
;

The ROW_NUMBER creates an identifier based on the order the columns are in (which I am assuming is what you are looking for, but note that SQL does not have an order instead this query is relying on the physical order of the records which is not a good idea but it looks like that is what you are dealing with).  We then join on this identifier and update the records in T1 with the values in T2.
I have placed this solution on SQL Fiddle.
If you can look into create new tables with some type of identifier that links them together, then you would not have to rely on the physical order of the records.
Comment: Please check the comment posted by Damian. I don't have a specific order on the tables. The order is as how they physically are in the table.


How to define train and test sets in financial time series for estimating machine learning parameters

Question: After reading some material, I found few options for defining train and test sets:

Just splitting with no change.
Accumulating/moving window of train set.
Leave a relatively small (warming) period between test and train sets, and then use window again (including the warming period).

What should be the most accurate way for applying machine learning algorithms and parameters estimation?
Comment: Obviously just splitting the data randomly as you normally would in supervised ML is a bad idea for time series. I've used essentially the same approach described at the end of [this blog post](http://robjhyndman.com/hyndsight/crossvalidation/) successfully in the past, but with a step size larger than 1 to save computing time. The [paper](http://projecteuclid.org/euclid.ssu/1268143839) linked at the bottom was also helpful.
Comment: @Memming, you may consider an entire daily data of an asset (say 20 years). The data is highly correlated and up/down trend prediction. Thanks!
Comment: The answer would depend on how much data you have, how many things are you trying to estimate, how correlated your data is, and how nonstationary the data might be.
Comment: Thanks alto. Actually, thats exctly what i did but wasn't sure about it. Can the same approach be used for feature selection as well?
Answer: If you're still looking for insight regarding financial time series & machine learning, you might want to check out this article from the Journal of Economic Perspectives, which gives a great overview of various ML methods pertaining to Economics/Finance.
Essentially, the main problem you have is that most traditional machine learning techniques deal with cross-sectional data "where independently distributed data is a plausible assumption" (quoted from said article). However, since with Financial Time Series you, by and large, can't make that assumption, you're better off taking a totally different approach than the 'ole Training/Test set split-'em-up. Your best bet--as mentioned in that article (Seriously, it's really good)--may be to read up on Bayesian Structural Time Series (BFTS) (briefly mentioned in that article that you should be reading by now and described in more detail here and, well, I don't have the reps for a third link...).
Now, if you're just looking to do some run-of-the-mill Time Series estimation you can settle for the choose-the-model-with-the-lowest-out-of-sample-RMSE approach. However, that may cause you to forfeit all your "Machine Learning" name-dropping privileges. Just a warning...
Good luck!
Comment: Hi Steve. I'm already using the idea mentioned in the link in @Alto's above answer. It's quite simple and intuitive (and works!). I will read the article, but i guess studing a completely new method should take a while. Thanks!
Comment: Hey, I'm just glad you still care (after all, your original post was a couple months ago...). Definitely check out that first article--it's by Hal Varian, who is now the chief economist at Google (plus, **JEP** articles tend to be much more readable than your typical Economics fare).
Answer: Generally cross-validation is one of the methods to evaluate a model by splitting data into train and test data sets. Leave-one-out cross-validation splits the dataset, say n datapoints as (n-1) for train data and test on nth datapoint. this process is repeated until each data point serves as a test datapoint. This ensures fairness in splitting the training data and rigorous evaluation of the model.
Comment: If you blindly apply normal CV methods when working with highly correlated data, like things with temporal/spatial characteristics, you're going to have a bad time (and likely be highly overoptimistic about true model performance).


Derivation of Family of Circles Meeting at Two Points

Question: We know the formula of "family of circles intersecting at two points" as follows:
$$x^2 + y^2 + D_1 x + E_1 y + F_1 + \lambda (x^2 + y^2 + D_2 x + E_2 y + F_2) = 0, \qquad \lambda \setminus \{-1\} \in \mathbb{R}$$
I could not find any rigorous derivation of the formula, which might involve theorems (linear independence, orthogonality of vectors by dot product) from linear algebra, vector algebra, etc., other than simply multiplying one of the circle equations known to intersect at two points by $\lambda$.
Question: How can we can derive the formula in a more rigorous way if possible?
Answer: You forgot to allow $\lambda=\infty$ to correspond to the circle $x^2+y^2+D_2x+E_2y+F_2=0$ as a candidate.  A more convenient way is the affine linear combination $\lambda C_1+(1-\lambda)C_2=0$, $\lambda\in\mathbb{R}$ (the degenerate case $\lambda=\infty$ then corresponds to the radical axis).
An algebraic proof: A general circle is given by $x^2+y^2+Dx+Ey+F=0$, so in terms of coefficients, it makes sense to start by looking at the linear map
$$
\begin{pmatrix}
x(P_1)^2+y(P_1)^2 & x(P_1) & y(P_1) & 1\\
x(P_2)^2+y(P_2)^2 & x(P_2) & y(P_2) & 1\\
\end{pmatrix}\colon\mathbb{R}^4\to\mathbb{R}^2
$$
which obviously has rank 2.  We are given the kernel containing both
$$
\begin{pmatrix}
1\\D_1\\E_1\\F_1
\end{pmatrix} \text{ and }
\begin{pmatrix}
1\\D_2\\E_2\\F_2
\end{pmatrix}
$$
so every element of the kernel is a linear combination of them (since the kernel has dimension $2$).  Now scalar multiplication doesn't change the circle, and obviously the zero vector doesn't give a circle.  So projectivising gives
$$
\lambda
\begin{pmatrix}
1\\D_1\\E_1\\F_1
\end{pmatrix}+
(1-\lambda)\begin{pmatrix}
1\\D_2\\E_2\\F_2
\end{pmatrix}
$$
i.e.,
$$
\lambda(x^2+y^2+D_1x+E_1y+F_1)+(1-\lambda)(x^2+y^2+D_2x+E_2y+F_2)=0
$$
Answer: A circle is a conic such that the quadratic coefficients are proportional to $1,0,1$.
If you consider the equations of two circles having two common points, any linear combination describes a conic passing through these points. And the quadratic coefficients are proportional to $1,0,1$.
Note that there is a non-trivial linear combination such that the quadratic coefficients vanish. In this case, you get the equation of a line, still by these two points.


$ \frac{\pi}{4} = \frac{3}{4} \times \frac{5}{4} \times \frac{7}{8} \times \frac{11}{12} \times \cdots$ (just primes in the numerator)

Question: How to prove the following equality?
$$ \frac{\pi}{4} = \frac{3}{4} \times \frac{5}{4} \times \frac{7}{8} \times \frac{11}{12} \times \frac{13}{12} \times \frac{17}{16} \times \frac{19}{20} \times \frac{23}{24} \times \frac{29}{28} \times \frac{31}{32} \times \cdots$$
I've seen this formula on Wikipedia.
The numerators are the odd primes; each denominator is the multiple of four nearest to the numerator.
Thanks.
Comment: Perhaps I'm missing something obvious, but how are you determining the denominators?
Comment: This is evaluating the $L$-function of the nontrivial character mod 4 at $s = 1$ through its Euler product, which is a lot more subtle to justify than evaluating the series for that $L$-function at $s = 1$.
Comment: It looks like it's $d = p \pm 1$ such that $d \mod 4 = 0$.
Comment: It looks very much like [this question](http://math.stackexchange.com/q/372615/73025).
Comment: @PeterTamaroff It is very close and can be solved using the same techniques but the identity itself is not the same. In my link, it was $p\pm1$ if $p\equiv\pm1\mod 4$ (note the sign difference). For example, in that identity $31$ would be divided by $30$, not by $32$.
Comment: Hmm, the numerators are the primes, and the denominators are $p\pm 1$. Remains to see what rule they follow.
Comment: It is $\mod 4$.
Comment: @Cortizol What? I mean, $\mod 4$, we have the primes $-1,1,-1,-1,1,\ldots$. Then just reverse the signs.
Comment: @O.L. I'm closing as a duplicate.
Comment: @PeterTamaroff Although I have voted to close, after a more detailed examination it turns out to be not completely the same problem. Please leave it open! however, the author should explain the denominator $p_k+(-1)^{?}$.
Comment: @O.L. But the denominator follows the rule $p\pm1$ if $p\equiv \mp 1\mod 4$.
Comment: @O.L. Ah, I see.
Answer: Your product is nothing but
$$\lim_{n \to \infty}\prod_{\overset{p_k \leq n}{p_k \equiv -1 \pmod4}} \left(1+\dfrac1{p_k}\right)^{-1} \prod_{\overset{p_k \leq n}{p_k \equiv 1 \pmod4}} \left(1-\dfrac1{p_k}\right)^{-1}$$
Now recall that
$$\left(1-\dfrac1r\right)^{-1} = \sum_{k=0}^{\infty} \dfrac1{r^k}$$
Make use of the above to note that
$$\lim_{n \to \infty}\prod_{\overset{p_k \leq n}{p_k \equiv -1 \pmod4}} \left(1+\dfrac1{p_k}\right)^{-1} \prod_{\overset{p_k \leq n}{p_k \equiv 1 \pmod4}} \left(1-\dfrac1{p_k}\right)^{-1} = \lim_{m \to \infty} \sum_{\ell=0}^m \dfrac{(-1)^\ell}{2\ell+1} = \dfrac{\pi}4$$
The last step makes use of the fact that
$$4\ell+1 = \prod_{\overset{q_k \equiv 1 \pmod4}{k=1,2,\ldots,n_1}} q_k^{a_k} \prod_{\overset{p_j \equiv -1 \pmod4}{j=1,2,\ldots,n_2}} p_j^{b_j}$$
such that $\displaystyle \sum_{j=1}^{n_2}b_j = \text{even}$ and
$$4\ell-1 = \prod_{\overset{q_k \equiv 1 \pmod4}{k=1,2,\ldots,n_1}} q_k^{a_k} \prod_{\overset{p_j \equiv -1 \pmod4}{j=1,2,\ldots,n_2}} p_j^{b_j}$$
such that $\displaystyle \sum_{j=1}^{n_2}b_j = \text{odd}$.
Comment: The main thing to note is $$(1 \pm 1/p)^{-1} = 1 \mp 1/p + 1/p^2 \mp 1/p^3 + \cdots $$ If you multiply out the product, you can see each odd number $x$ appears exactly once in the form $1/x$ (with an appropriate sign). (the prime factorization of $x$ tells you which term to take from each factor to make $1/x$)
Comment: Care to elucidate on the derivation of the final line?
Comment: @nbubis I have updated the post clarifying the last line.
Answer: As I mentioned in my comment yesterday, this question is very similar to this one, except that here we want to prove the identity
\begin{align*}
\dfrac{\pi}{4}=\prod_{k=2}^{\infty}\left(1+\dfrac{(-1)^{\frac{p_{{k}}+1}{2}}}{p_{k}} \right )^{-1},
\end{align*}
which turns out to be even simpler.
So I almost literally reproduce the relevant half of my previous solution:

Decompose the product on the right as
$$B=\prod_{\text{primes}\; p\\ \text{ of  the  form }4k+1}\left(1-\frac{1}{p}\right)^{-1}\prod_{\text{primes}\; p\\ \text{ of  the  form }4k+3}\left(1+\frac{1}{p}\right)^{-1}.\tag{1}$$
Consider an odd integer $n=2m+1$. It is easy to understand that if primes of the form $4k+3$ appear in its prime number decomposition an even number of times, then $n$ is of the form $4K+1$ [since $(4k_1+3)(4k_2+3)=1\; \mathrm{mod}\;4$]. If the number of such appearances is odd, then $n$ is of the form $4K+3$.
Rewrite (1) (expanding its factors into geometric series) as
$$B=\sum_{m=0}^{\infty}\frac{(-1)^{r(m)}}{2m+1}$$
where $r(m)$ counts the number of appearances of primes of the form $4k+3$ in the decomposition of $2m+1$. But then Step 2 allows to write $(-1)^{r(m)}=(-1)^m$, so that
$$ B=\sum_{m=0}^{\infty}\frac{(-1)^{m}}{2m+1}=\frac{\pi}{4}.$$
Answer: Let $L(s,\chi)$ be the $L$ function for the non principal modulo $4$ Dirichlet
character
$$\frac{\pi}{4}=L(1,\chi)=\prod_{p}\frac{p}{p-\chi(p)}=\prod_{p\equiv 1 \text{mod 4}}\frac{p}{p-1}\prod_{p\equiv 3 \text{mod 4}}\frac{p}{p+1}$$


Is carrying the ball with your mouth legal in soccer?

Question: I have an old deflated soccer ball that I play with my dog. Often he will give up on kicking it and pick it up with his mouth. I say this is cheating. He insists it is not.
This got me thinking: If in a regulation game a player managed to somehow grab the ball with his mouth and carry it down the field, would this be against the rules? If so, what would the call be?
Let's assume for the sake of this question that neither the ball nor the player are breaking any rules on their own (e.g. the ball is properly inflated).
Answer: There was a similar question about squeezing the ball between two feet and hopping across the field. The answer that @studro gave there applies here as well. The questions though are not duplicates.
An indirect free kick can be awarded to the opposing team because of LOTG 12.2 as already mentioned by @Joe

Playing in a dangerous manner
Playing in a dangerous manner is any
action that, while trying to play the ball, threatens injury to
someone (including the player themself) and includes preventing a
nearby opponent from playing the ball for fear of injury.

or the referee may decide to caution the player for unsporting behaviour. Trying to grab the ball with your mouth/teeth and to game the system can be considered a lack of respect to the game. From LOTG 12.3

Cautions for unsporting behaviour
...

shows a lack of respect for the game

...
Answer: Barring anything better, I would suggest that the following line from the FIFA Laws of the Game (12.2) would apply:

Playing in a dangerous manner

Playing in a dangerous manner is any action that, while trying to play the
ball, threatens injury to someone (including the player themself) and includes
preventing a nearby opponent from playing the ball for fear of injury.

Holding the ball in your mouth would prevent a nearby opponent from playing the ball for fear of injury (to the player holding the ball), I imagine...