Solving a Binomial Expansion Question

Question: I have a question which asks to find the coefficient of x and the constant term, for $f_n(x)$ given that
$f_1(x) = (x - 2) ^ 2$ and
$f_{n+1}(x) = (f_n(x) - 2) ^ 2, n >= 1$
Now I tried to derive the values like solving for $f_2$ and $f_3$ , but its getting too long. What is a shorter way to solve these problems?
I guess that the constant term would be $4$ or $4^{(n-1)!}$ but I am not sure.
I was proceeding like this,
$f_2 = (f_1 - 2) ^ 2 $
so for $-4 * f_1$ the constant term would be -16
and for $f_1^2$ it will be 16 for $2^4$ and $2*f_1$ would be 4 . so in total that's +4 .. so it could be 4 or $4^{0!}$.
Comment: Experimenting with $f_1$, $f_2$ and $f_3$ would yield *very natural* conjectures. Did you do that? For example, $f_1(x)=4-4x+$higher terms hence $f_2(x)=(2-4x)^2+$higher terms$=4-16x+$higher terms hence $f_3(x)=(2-16x)^2+$higher terms$=\ldots$
Answer: At $f_2$, const term is $(2^2-2)^2=2^2=4$, So, for $f_3$, you get the same thing, and this goes on for every $n$ .
Now the constant term being fixed, notice $x$ ca be formed only by multiplying a constant term with a $x$ containing term.So we need only to consider the $2\times (term\ with \ x) \times 2$ while squaring.n So, notice the sequence..
$$f_1\ ->(-2)$$
$$f_2\ ->2\times (-2)\times 2=(-2)\times 2^2$$
$$f_3\ ->2\times (-2)2^2\times 2=(-2)\times 2^4$$
$$f_4\ ->2\times (-2)2^4\times 2=(-2)\times 2^6$$
$$\vdots$$
$$f_n\ ->2\times (-2)2^{2n-4}\times 2=(-2)\times 2^{2n-2}$$
Comment: ok, thanks. I was doing it complex way. :P
Comment: @shortCircuit Do upvote if you liked my answer
Comment: I need 15 points to upvote.

Solving a Binomial Expansion Question


PDO nao retorna erro mesmo em um bloco try catch

Question: Estava tentando cadastrar em um banco mysql utilizando PDO. Não cadastrava mas mesmo assim eu nao tinha um retorno de erro apesar do bloco try catch. Descobri mais tarde que o erro era o tamanho da coluna telefone, no banco era 11, mas estava passando uma string com tamanho 13. Como Fazer a impressao do erro neste caso ja que o try catch não faz isso?
<?php
function save($dados){
    try{
        $pdo = new PDO("mysql:host=127.0.0.1; dbname=projetocadastro;", "root", "123456");
        $sql = 'INSERT INTO tb_clientes(nome, cpf, telefone, email, nascimento, estado, cidade, bairro, rua, numero) VALUES (:nome, :cpf, :telefone, :email, :nascimento, :estado, :cidade, :bairro, :rua, :numero);';
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':nome', $dados['nome']);
        $stmt->bindValue(':cpf', $dados['cpf']);
        $stmt->bindValue(':telefone', $dados['telefone']);
        $stmt->bindValue(':email', $dados['email']);
        $stmt->bindValue(':nascimento', $dados['dtnasc']);
        $stmt->bindValue(':estado', $dados['estado']);
        $stmt->bindValue(':cidade', $dados['cidade']);
        $stmt->bindValue(':bairro', $dados['bairro']);
        $stmt->bindValue(':rua', $dados['rua']);
        $stmt->bindValue(':numero', $dados['numero']);
        $stmt->execute();
    }
    catch (PDOException $e){
        echo $e->getMessage();
    }finally{
        $pdo = null;
    }
}
save($_POST);
?>

Answer: Altere o error mode da sua classe PDO para PDO::ERRMODE_EXCEPTION:
$pdo = new PDO(
    "mysql:host=127.0.0.1; dbname=projetocadastro;",
    "root",
    "123456",
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

Comment: Pode remover essa aspas solta na penultima linha?
Comment: Pode, foi um erro de digitação


CSS frustration: How to center floating images of different widths inside LI tags?

Question: I'm working on a webpage that has a javascript image rotator, but it needs to be able to handle images of different sizes.
The code that I'm using as a base has a DIV outside floating LIs which contain the images, but no matter what I try I can't seem to get the images to all be centered.  The only one that's centered is the one that's the full 800px wide.
I have a feeling it's something to do with float, position, or display, but I've been messing around for hours with no luck.
Here's my site:
Here's where I borrowed the image rotator code from:
http://www.serie3.info/s3slider/ (code) http://www.serie3.info/s3slider/demonstration.html (demo)
Thanks for any help you can provide!
Answer: Add:
left: 0;
padding: 0;

to the #slider1Content style.
Then delete the float: left;  from the .slider1Image style.
Note that the source CSS contains this warning: "important to be same as image width" on several dimensions.  Since this CSS isn't sized for each image, you'll have that white margin around each picture.
If you desire to reset those key dimensions dynamically (I think the site looks OK without this), then that is a separate question that has been answered here on SO before.
Comment: Thanks, this does the centering, although the white margin is a bit annoying so I went with Brandon's version below.
Answer: This works as well (In Firefox and Safari, haven't tried IE). Save as a .html for an example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta name="description" content="A picture and caption that you can change for everyone in the world to see.">
    <meta name="keywords" content="pic and words, pic words, caption">
    <title>Pic and Words</title>
    <link href="http://picandwords.be-better.net/styles.css" rel="stylesheet" type="text/css">

Pic and Words

                        "Somewhere down Baja on the way to Cabo."

                        "Drunk dude on a bike"

                        "Do not want!"


Difference between shift adder and Serial Adder

Question: Is shift adder and serial adder are same? I tried Google but I cannot understand difference. I have to use it in VHDL.
Thanks
Comment: A shift adder is used to implement multiplication by shifting a multiplicand. A serial adder is also known as a bit-serial adder or binary serial adder.
Answer: Serial binary adder:
The serial binary adder or bit-serial adder is a digital circuit that performs binary addition bit by bit. For example to add 1010 + 0100, we will start from LSB.
0 + 0 --> 0
1 + 0 --> 1
0 + 1 --> 1
1 + 0 --> 1

And your final answer is 1110.
Shift Adder: Is used for multiplication. For example if we want to multiply 10 and 10, we will start from LSB.
10 * 0 --> 00
10 * 1 --> 10

First partial product is shifted to right before added to second partial product. For getting the result.
 000
+10
-------
 100


AWS client VPN endpoint - some client ip's do not allow access to resources

Question: I am using AWS client VPN endpoint with 2 VPC's:

VPN VPC (10.100.0.0/16)
App VPC (10.200.0.0/16)
VPC peering between the 2 VPC and Route table rules to communicate both.

My resources in the 'App VPC' are hosted in subnets that have route rules to the peering connection to the 'VPN VPC'.
The Security Group used by the resources in 'App VPC' allows traffic from 10.100.0.0/16
The problem is when I connect to the VPN and I get assigned IP's such as 10.100.20.132, 10.100.20.162, 10.100.20.165, 10.100.20.167 it is not able to reach the resources.
But when I get assigned IP's such as 10.100.20.2, 10.100.20.3, 10.100.20.6, 10.100.20.34 it does work.
I ran a few reachability Analyzer to validate traffic from the VPN is able to reach the resources which always shows success with the trace:
'VPC peering' -> 'NACL' -> 'SG(10.100.0.0/16)' -> 'ENI' - 'Instance'
Network is not my field, any insight on where to look is appreciated.
Comment: My first thought is routing. Can you please edit your question to include screenshots of the route tables for the applicable subnets in both VPCs. I'd also suggest you have a look at NACLs and Security Groups, but I would look at routing first.
Answer: My mistake was in the routing tables from the 'Associations' subnets.
I have 2 subnets, for one I did add the route for CIDR block of the 'App VPC' in the Route Table:
Subnet 1

10.200.0.0/16 -> VPC peering(VPN to APP)
10.100.0.0/16 -> local
0.0.0.0/0 -> igw

But I forgot to do it in the Route Table of the second Associated subnet.
Subnet 2

10.100.0.0/16 -> local
0.0.0.0/0 -> igw

I just added the missing route and it worked.


Selenium: unable to switch window

Question: I am trying to switch to another pop-up window,but is giving some sort of error. I am not able to figure out why the code in not working for switching the window
Error it is giving is
java.lang.NullPointerException: null value in entry: name=null
Here is the code....
String parentWindowHandle = driver.getWindowHandle();
        System.out.println("parentWindowHandle......"+parentWindowHandle);
        //click on "register"

        Actions act = new Actions(driver);
            act.click(driver.findElement(By.id("ctl00_ContentPlaceHolder1_btnRegisterMe")));
        act.perform();

        sleep(26000);
        String popUpWindowHandle=null;
        Set<String> openWindowsList = driver.getWindowHandles();
        for (String windowHandle : openWindowsList) {
             System.out.println("windowHandle......"+windowHandle);
            if (!windowHandle.equals(parentWindowHandle))
                {popUpWindowHandle = windowHandle;

              break;}
        }
                // Switching control to newly opened window

        driver.switchTo().window(popUpWindowHandle);

Comment: your issue is coming from `windowHandle.equals(parentWindowHandle)`.  My guess is that `parentWindowHandle` is not initialized.
Comment: ya i hv initialize parentWindowHandle, but forgot to put that code here.have a look at the code which i hv reposted....
Answer: If you are able to print window handles then try
if (!windowHandle.equalsIgnoreCase(parentWindowHandle)){
            popUpWindowHandle = windowHandle;
            break;
}

instead of
if(!windowHandle.equals(parentWindowHandle)){}

Comment: thanx 4 the help .... its working with if(!windowHandle.equals(parentWindowHandle)){}
Comment: Can you share what was the actual problem and what you did to fix?
Comment: i have increased the sleep time from 5sc to 26sc......actually the problem was window switch code was executing before opening of new pop-up window....

Selenium: unable to switch window


Angularjs: Dependency injection. "is not a function" error

Question: I'm having my first go at dependency injection. My goal is to eventually just enable some simple communication between two controllers. I'm not even getting far enough to even worry about handling the communication with the second controller. I'm getting an "is not a function error" for ContactMessages.AddNewContact(response.data);
When I use self.ContactMessages.AddNewContact(response.data); I get "Cannot read property 'AddNewContact' of undefined"
I just want to invoke the AddNewContact function of the ContactMessages factory.
This should be a fairly basic procedure.

    <form name="frmAddContact" noValidate>
        <input placeholder="Contact Email" type="email" ng-model="ActCtrl.newContact.Email" required></input>
        <select ng-model="ActCtrl.newContact.Type"  required>
            <option value="">Contact Type</option>
            <option value="COLLEAGUE">Colleague</option>
            <option value="FRIEND">Friend</option>
            <option value="FAMILY">Family</option>
        </select>
        <select ng-model="ActCtrl.newContact.Frequency"  required>
            <option value="">Contact Frequency</option>
            <option value="ANY">Any Time</option>
            <option value="WEEKLY">Weekly</option>
            <option value="MONTHLY">Monthly</option>
            <option value="QUARTERLY">Quarterly</option>
            <option value="YEARLY">Yearly</option>
        </select>

            <button ng-click="ActCtrl.AddContact()" ng-disabled="frmAddContact.$invalid" >Add Contact</button>

    </form>

Comment: I've isolated the issue to the inability to call ContactMessages.AddNewContact from inside the $http request. I can call   said function from inside AddContact.
Answer: Hi change your Factory like this
app.factory('ContactMessages', [
    function () {
        var o = {};

        o.AddNewContact = {};
        return o;
    }
]);

for refrence https://plnkr.co/edit/sYSJ5ZOVQUX0ctir2EmM?p=preview
Comment: Made the changes as suggested. This results in the same error messages as before.
Comment: var self = this; u have to move on top not inside the this.AddContact=function()  , before the  this.newContact move your var self = this;


Can I have Zscore result calculated within specific range?

Question: I dont fully understand Zscore,
I need to standardise raw data to use them for further uses, so I though about using Zscore. When I calculated it, some of the results I got are greater than 1 and I wonder if I can control these result without ruining the standardisation .
Is it possible to calculate zscore and ensure result range between 1 and -1? or i have to use other methods
Comment: This is called [normalization](https://stats.stackexchange.com/search?q=normalize+0+1).
Answer: The normal  distribution has two parameters: the mean and the variance.  The z-score is the name of the normal distribution with a mean of zero and a variance of 1.  The possible values of this distribution cover the entire set of real numbers.  About 68% are within the range (-1, 1).  If when you standardized you obtained about 68% of your transformed values between -1 and 1, then that is what you should expect if your distribution is normal.
If your distribution is not normal, and if you are referencing dividing observations by their standard deviation, then the z-score you calculated is a count of how many standard deviations each number is from the mean of your distribution.  If a number is more than 1 standard deviation from the mean,then it will have a z-score of greater than 1 or less than -1.
Comment: My answer does not help you. I was confused by your mention of Zscore.
Comment: It is likely the question refers to the process of standardizing a set of numbers and so has little to do with Normal distributions or their properties.
Comment: what i'm trying to do is the standardise raw data and  convert them to numbers between 1 and -1 for AI training and yes most of the data between 1 and -1 but I cannot have any data outside this range. is there a way to get all data between this range using SD
Comment: How about this.  You are able to determine of a number is negative or positive.  Take the positive numbers and calculate the empirical cumulative density.  Then do the same for the absolute value of the negative numbers, then add the negative sign back in.
Comment: okay if its called normalisation can i normalise the Zscore value?  so after calculating zscore, i do something like .8*(zscore)+.1 to have all the result of specific range. will this mess with the concept of zscore
Comment: Now there is a link to the accepted way to do this,but, in my opinion, you have to use a method that does not reduce the amount of information in your data.  If you have a few large or very negative values, you might want to plot the distribution of your data after the transformation to see if it looks right.


How to enable boolean fields?

Question: I installed the minimal setup when installing Drupal, and I want a boolean field in one of my Content Types. But this is not enabled. I found this Boolean module, but it only has 859 installs (as of 6th Jan, 2014), so I doubt I need to install that. So how can I enable 'Boolean' as one of the field types?
Answer: You need to enable the List module, which also gives you the List, List (numeric) and List (text) field types.

How to enable boolean fields?


PHP Code deleting data from MySQL database

Question: Hi I am creating a movies system that you can add edit and delete movies from. I have a webpage a that displays all data from the MySQL database and a edit.php which you enter the movie ID and change the values, thing is when you click Update it removes the data from the mysql database(all but the ID). Here is the code:

<?php

session_start();
error_reporting(error_reporting() & ~E_NOTICE);
$username = $_SESSION['username'];

if ($username)
  {
    echo "
Welcome $username. Logout.
";
  }
else
  {
    echo "
Login or Sign up!
";
  }
echo "Home | Add a movie | Movies list";
echo "
";
echo "
";
echo "
";
echo "If you made a mistake here you can change the information you entered. ";
echo "
";
echo "
";

if(isset($_POST['update']))
  {
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $conn = mysql_connect($dbhost,$dbuser,$dbpass);
    if(! $conn)
      {
        die('Something went wrong show this to dylan:'.mysql_error());
      }

    $id = $_POST['id'];
    $moviename = $_POST['name'];
    $movieage = $_POST['age'];
    $moviedate = $_POST['date'];
    $moviedescrip = $_POST['description'];

    $sql = "UPDATE movies " .
      "SET name = '$moviename', " .
      "age = '$movieage', " .
      "date = '$moviedate', " .
      "description = '$moviedescrip' " .
      "WHERE id = $id";

    mysql_select_db('movie_system');
    $retval = mysql_query( $sql, $conn);
    if(! $retval )
      {
        die('Sorry, could not update the data show this to Dylan: '.mysql_error());
      }

    echo "The values have been changed!";
    mysql_close($conn);
  }
else
  {
    ?>
    <form method="post" action="<?php $_PHP_SELF ?>">

      Movie ID:
      <input name="id" type="text" id="id">

      Movie name:
      <input name="moviename" type="text" id="name">

      Movie age rating:
      <input name="movieage" type="text" id="age">

      Date avilable on DVD:
      <input name="moviedate" type="text" id="date">

      Description from back of case:
      <input name="moviedescrip" type="text" id="description">

      <input name="update" type="submit" id="update" value="Update">

      </form>
      <?php
      }
?>

I also asked another question helping me get the code for edit.php:
Here
Comment: Do not use the html tag, like in `echo "";`. It is meant for the entire page.
Comment: You might try outputting your `$_POST` variables before the query to see if they are posted correctly. `echo"";print_r($_POST);echo"";` Also try outputting your query to see if it's correct: `echo "".$sql."";`
Comment: I put it at the top of the webpage and it says this:Array
(
)
Comment: @Joop Edden - What do you mean?
Comment: He means you should only have 1 `` opening tag, it should wrap the entire page, not every line of code
Comment: Please be aware that the `mysql_` set of functions are deprecated and are likely to disappear from future versions of PHP (try looking up mysqli for a similar interface which will remain supported). Also, as you are plugging the form fields straight into the SQL, you open yourself up to what are known as "SQL injection" attacks; someone could deliberately pass you values which would wipe out *all* of your database entries! See http://www.php.net/manual/en/security.database.sql-injection.php for an explanation.
Answer: The input names don't match what you're retrieving with $_POST.
<input name="moviename" type="text" id="name">

doesn't match:
$moviename = $_POST['name'];

it should be:
$moviename = $_POST['moviename'];

id DOES match in both places, which is why the update is successful.
Comment: So what sould the code be then? Thanks for the reply by the way!
Comment: It's in my answer: $moviename = $_POST['moviename'];   (similar change for the others)


Proving positive definiteness for a symmetric matrix

Question: Let A be an $n\times p$ matrix with rank $p$. I want to prove that $X = A^TA$ is a positive definite matrix.
I know that for any symmetric matrix to be positive definite, all of its eigenvalues must be strictly positive.
So I need a way to show that $X$'s eigenvalues are all positive, or perhaps any other method to proof that $X$ is positive definite.
Comment: matrix $Z$ is positive definite if $x^TZx>0$ for any vector $x$ ... plug in $Z=A^TA$ and you'll find that you're looking at the norm of a vector $Ax$ which is always greater than zero
Answer: As suggested above by phdmba7of12, we consider the quadratic form
$$x^T X x = x^T (A^T A)x = (Ax)^T (Ax) = (Ax, Ax) = \lVert Ax \rVert^2 \geq 0.$$
Since $A$ has rank $p$, the only solution of $Ax = 0$ is the trivial solution. Hence,
$$x^T X x = 0 \iff x = 0.$$
Hence, we have varified the definition of positive definiteness.
Answer: It is straightforward to show that $A^TA$ is positive semi-definite by showing $x^TA^TAx \geq 0$ for all $x \in \mathbb{R}^{p}$, therefore $A^TA$'s all eigenvalues are non-negative.
Now using the fact $\mathrm{rank}(A^TA) = \mathrm{rank}(A) = p$, hence as an order $p$ matrix, $A^TA$ is non-singular. Therefore $A^TA$ doesn't have zero eigenvalues.
Combining these two arguments together, we see that all eigenvalues of $A^TA$ are positive, thus $A^TA$ is positive definite.


Embed Protected PDF

Question: Wondering if anyone has done this in Drupal 7.
I have a set of PDFs which need to be protected (i.e. restrict access). However, they also need to be displayed on a webpage (via the EMBED tags) for those users who have been authenticated.
What I have seen done in other systems is:
The PDFs are stored in a protected directory (e.g. PRIVATE)
There is also a PUBLIC directory
When the PDF is requested by an authenticated user, the PDF is copied from the PRIVATE directory to the public under an MD5 (with SALT) hashed name, and the filename is returned to the viewer.
Does this make sense, and has anyone done this in Drupal?
Answer: Set the download method to private and implement hook_file_download().
Comment: Forgive me if I'm wrong, but won't that affect an immediate download?  I want the PDF to be displayed via the  tags.
Comment: `hook_file_download()` is invoked regardless of how the HTTP request was initiated (whether via  tag, following a link, or entering the URL of the file in the address bar of the browser). Change the headers if the ones that Drupal generates do not suit your needs. Add URL arguments to the URL in the  tag, if you want to send different headers only in the  scenario. These URL arguments can then be evaluated by your `hook_file_download()`.

Embed Protected PDF


Remove attribute ID from site-logo (Panels Page Elements)

Question: I use a module panels everywhere with Omega 4. I try to put a site-logo in header and footer but Logo Page Element from Panels takes site-logo and render it with ID. So I have same ID twice in my page.
Header

Footer

How I can remove ID or render element with my markup?
How I can create own element for panels?

Thank you
Comment: Could you please make title more unique? Each and every question about panels page elements here was asked because someone had problems, right? Ideally, title should be a question in it's own right, and body used only to provide details, context etc. Now I don't ask you to be ideal ;) but maybe few steps in that direction? :)
Comment: Ok, i think now is better :)
Comment: it attracted someone who could answer. Definite proof it's better :)
Answer: This logo is created in ctools_page_logo_content_type_render function. Unfortunately we can't alter code of this function.
As a solution you may create your custom Ctools content type plugin, that will return logo without 'id' attribute. You can find more information about Ctools plugins here.


use custom Go packages

Question: I have written some custom packages which I am struggling to reuse.
My code is structured as follows:
$GOPATH/src/github.com/myusername/myfirstrepo/

In myfirstrepo I have 2 different packages:
myfirstrepo
   |--somefolder1/package1
   |--somefolder2/package2

Now I'd like to import my package1 in package2, I know I can use my published code on github using go get but I'd like to know if it's possible to use something similar to npm:
import "./../somefolder1/package1"

Obviously I've tried this and it doesn't work.
How can I simply do this?
Answer:
Now I'd like to import my package1 in package2, I know I can use my published code on github using go get

It doesn't have to be published on github.
The import path just has to be a valid path within your workspace ($GOPATH)
import "github.com/myusername/myfirstrepo/somefolder1/package1"

Relative paths are not the best practice (unless you really need to access your functions without classifier).

use custom Go packages


Finding the dimension of vector space

Question: Let $J=
        \begin{pmatrix}
        0 & 1 & -9 \\
        -1 & 0 & 4 \\
        9 & -4 & 0 \\
        \end{pmatrix}
$, $V=\{A \in M_{3 \times 3}(\mathbb R)|AJ=JA^T \}$.
Find the dimension of V. Justify your answer.
I already know the answer of this question: the dimension of $V$ is 6.(This is not sure, since I solved it a long time ago.) I solved this question by letting $A=
        \begin{pmatrix}
        a_1 & a_2 & a_3 \\
        b_1 & b_2 & b_3 \\
        c_1 & c_2 & c_3 \\
        \end{pmatrix}
$ and just substituting into $AJ=JA^T$, but this solution is somewhat messy, since it includes system of linear equations with 9 variables.
Is there more elegant solution for this problem without having to deal with such complicated equations?
Answer: Notice that $J^T = -J$. For every $A \in V$ it holds $AJ = JA^T = -J^TA^T = - (AJ)^T$.
Therefore $AJ$ is antisymmetric and we have
\begin{equation}AJ=
\begin{pmatrix}
b_1 - 9 c_1 & b_2 - 9 c_2 & b_3 - 9 c_3\\
4 c_1 - a_1 & 4 c_2 - a_2 & 4 c_3 - a_3\\
9 a_1 - 4 b_1 & 9 a_2 - 4 b_2 & 9 a_3 - 4 b_3\\
\end{pmatrix}
\end{equation}
For $AJ$ to be antisymmetric the following system should be satisfied
\begin{align}
9a_2 -a_3 +4c_3 -4b_2 &= 0\\
9a_1 -4b_1+b_3-9c_3 &= 0\\
-a_1 +b_2 +4c_1-9c_2 &=0
\end{align}
EDIT: The diagonal elements should equal zero
\begin{align}
b_1 - 9c_1 &=0\\
-a_2 +4c_2 &=0\\
9a_3 -4b_3 &=0
\end{align}
Solving this system will give you the dimension of $V$.
Comment: aren't there the conditions for the diagonal to be 0?
Comment: yep, you're right I forgot those.

Finding the dimension of vector space


Como instanciar uma Activity com campos de EditText sem ficarem selecionados automaticamente?

Question: Desenvolvendo uma aplicação Android, deparei com um problema, eu tenha uma Activity onde há campos de edição(EditText) no xml, e quando instancio ela, o primeiro campo EditText, fica selecionado e o teclado aparece pra preencher, e eu não queria que o teclado aparecesse, e q não selecionasse o campo automaticamente, basicamente to montando uma Activity inicial igual a de login do app da Evernote. E se tiver como passa os esquema de fazer aquela Activity com as TabLayout, ViewPager, e o parallax que ele faz melhor.
Answer: Uma forma simples é no AndroidManifest.xml declarar a activity desta forma:
<activity android:name=".MainActivity"
          .....
          android:windowSoftInputMode="stateHidden"
          >

Answer: Por padrão o android sempre marca o que contem o input com <autofocus/> ou o primeiro, uma solução é no onCreate inserir o seguinte trecho:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(seuInputText.getWindowToken(), 0);

Answer: Mude o foco para seu Layout, como no exemplo abaixo, retirado do SOen:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >


How to insert a blank line in php for each group from select query

Question: I am using PHP to export a text file from a query. The selection result is as follows
Account   student_no
001        stu_001
           stu_001

001        stu_002
           stu_002

Which I selected by (select * from payment group by account,student_no asc, so my question is I need to insert a blank line between each group (i.e. 001   stu_001, 001 stu_002) for the export text file. So how can I do that in PHP.
Answer: First ORDER the results by account and then
$previousAccount="";
foreach($records as $record)
{
   $account=$record["account"];
   if($account!=$previousAccount)
  {
   $output.=PHP_EOL;  // or echo or fwrite etc
  }
  $previousAccount=$account;
...
...
...
...
}

Comment: You should use `PHP_EOL` instead of "\n"
Answer: Assuming you build up your output in a string, just add \n between double quotes:
$output_string = 'This line is followed by a new line'. "\n";
$output_string .= 'And I add another line'. "\n";

Answer: Use this tab to define where and how many blank lines you want PhpStorm to retain and insert in your code after reformatting. For each type of location, specify the number of blank lines to be inserted. The results are displayed in the Preview pane....Code Style. PHP
Comment: What was that? really
Answer:  $output = sprintf( "%20s %20s \n", "Account","student_no" );    // Print Account   student_no
 foreach($record as $row){
      $output .= sprintf( "%20s %20s",$row['account'], $row['student_no'] ) . "\n";
 }

http://pastebin.com/qrBZzywh


Como faço para adicionar uma coluna nova entre 2 colunas no PostgreSQL?

Question: Como eu faço para adicionar uma coluna nova entre duas colunas já existentes em minha base de dados no PostgreSQL?
No MySQL eu utilizo a função AFTER para adicionar uma coluna depois de uma outra, e no PostgreSQL? Como eu faço isso?
SQL
ALTER TABLE nota ADD hota_utc VARCHAR(2) AFTER hora_entrada_saida;

Comment: O `AFTER` é uma instrução somente do MySQL.
Answer: Não é possível. A solução é criar uma nova tabela com a nova estrutura com as colunas do jeito que você quer, copiar os dados para ela e depois de apagar a antiga, renomear a nova para tomar o lugar da antiga.
Em geral considera-se irrelevante a ordem das colunas.
Tem uma explicação de como proceder na wiki do produto.
Coloquei no GitHub para referência futura.
Comment: Ok @bigown. Muito obrigado!
Comment: Na verdade é possível, eu já pesquisei sobre o assunto em inglês, e achei respostas que mencionavam ser possível alterando os contadores internos no núcleo de gerecimento do postgres, em `information_schema` na tabela desejada, contudo o gerecimento para isto é tao grande que não é recomentado se fazer, além de em caso de erro poderia geraria complicações não só na tabela atual como em outras não desejadas. concluindo, é possível, mas é melhor fazer como o @bigown falou.
Comment: Não é possível de um jeito natural. Gambiarra sempre dá para fazer.
Comment: Atravessar a rua só para tentar escorregar numa casca de banana de outro lado ...


How can I get hold of the Composer object?

Question: I'm trying to get the file location of something in an installed package.
https://stackoverflow.com/questions/15714809/get-filesystem-path-of-installed-composer-package says I can get that from the Composer object.
But in Drupal, how do I get the Composer object?
Comment: The comments in the linked question contain the answer - that object is available to Composer plugins/scripts/installers, not in the application. There are other answers with alternatives though
Answer: Usually, I'm doing this using ReflectionClass.
Take this example: to load the cacert file which comes inside one of composer packages:

First, locate any class in that package using ReflectionClass.
Secondly, get the package path using dirname bypassing the file name.

Code example:
// Load certificate file.
$reflection = new \ReflectionClass(\GSRequest::class);
$packagePath = dirname($reflection->getFileName());
$gsRequest::setCAFile(realpath($packagePath . '/cacert.pem'));


How do I find the number of sublists (from every level) of a list in LISP?

Question: Eg. for list (A 1 (B 2) (1 C 4) (D 1 (6 F)) ((G 4) 6)) => 6
Comment: Correct it in your question instead of just commenting.
Comment: It would be great if you put some effort into finding an answer and show what you've done.
Comment: sorry...the answer should be 7 because the list itself is a sublist
Answer: A quick answer would be this:
<code>(defun count-sublists (list)
  (if (listp list)
      (1+ (loop for el in list
             sum (count-sublists el)))
      0))
</code>
Just loop over the elements and recursively count all lists.


Declare var before assigning multiple values in Javascript?

Question: In Javascript, which format of var declarations is better:
function test1() {
  switch(type) {
    case 1:
        var test = "Hello One"
      break;
    case 2:
        var test = "Hello Two"
      break;
  }
}

Or:
function test2() {
  var test;

  switch(type) {
    case 1:
        test = "Hello One"
      break;
    case 2:
        test = "Hello Two"
      break;
  }
}

In test2(), there is 1 extra line of code to declare test as a var before assigning a value, but this saves having to declare var test twice. Is either way better than the other?
Comment: possible duplicate of [javascript var declaration within loop](http://stackoverflow.com/questions/2731123/javascript-var-declaration-within-loop) __because the answer explains what's happening here.__ (I'm sure there are dozens of other questions about hoisting.)
Comment: Well, actually I was asking more about the syntax of it, more than what was going on with the scoping. It's nice to learn about the term "javascript hoisting" though!
Comment: I get that, but the explanation of what's happening explains why one syntax is preferred. You sort of can't ask one without the other.
Answer: javascript does not have block scope, so declaring variables in a switch block does not work like you would expect.
furthermore, due to variable hoisting, all variable declarations in a function block are hoisted to the top by the interpreter and your code would look like this:
function test1() {
  var test;
  var test;

  switch(type) {
    case 1:
        test = "Hello One"
      break;
    case 2:
        test = "Hello Two"
      break;
  }
}

After performing the hoist, it is easy to see why the first block is incorrect.
Comment: @Mathletics Yes, see [EMCAScript 10.5](http://www.ecma-international.org/ecma-262/5.1/#sec-10.5), step 8: for each VariableDeclaration with some identier `dn`, the interpreter checks if a variable with identifier `dn` is already declared in-scope, and only acts if it does not yet exist.
Comment: Could you clarify what you mean by "incorrect" in your final sentence? Both examples are valid and behave identically. (I'm not disagreeing with anything you're saying in this answer, but I think it would be helpful to use a more precise term than "incorrect" -- perhaps "less clear"?)
Comment: @apsillers "incorrect" meaning a bad practice that static analysis tools (jslint, jshint, resharper, etc) will flag
Comment: @apsillers is it really _valid_? (Is there a spec line stating that declaring the same variable more than once is acceptable, or is it just ignored in implementation?)
Comment: @apsillers perfect, that's what I wanted to see. Thanks!
Comment: @jbabey Thanks, that's a good example of something "going wrong" with the first.
Answer: IMO the second should be preferred.
It's more communicative, and closer to what's actually happening (e.g., variable hoisting).
I'm also not a fan of hiding variable declarations inside what look like scopes but aren't.
Answer: Your first code is wrong; you've declared the same variable multiple times.
JSHint will complain about it.
Comment: The parser won't, though.


Generating unique random value in Numpy

Question: I tried to generate large numbers of unique random values using np.random.randint but it returned few duplicates values.
I have following dataset
District    Prefix  Quota
A           98426   783
A           98427   223
A           98446   127
A           98626   51
B           98049   167
B           98079   153
B           98140   120
B           98159   139
B           98169   182
B           98249   86
B           98426   588
B           98446   96
C           98049   104
C           98060   68
C           98149   65
C           98150   68
C           98159   86
C           98160   80
C           98169   113

Code to reproduce:
import pandas as pd
df = pd.DataFrame([
    ['A', 98426, 783],
    ['A', 98427, 223],
    ['A', 98446, 127],
    ['A', 98626, 51],
    ['B', 98049, 167],
    ['B', 98079, 153],
    ['B', 98140, 120],
    ['B', 98159, 139],
    ['B', 98169, 182],
    ['B', 98249, 86],
    ['B', 98426, 588],
    ['B', 98446, 96],
    ['C', 98049, 104],
    ['C', 98060, 68],
    ['C', 98149, 65],
    ['C', 98150, 68],
    ['C', 98159, 86],
    ['C', 98160, 80],
    ['C', 98169, 113]
],
    columns=['District', 'Prefix', 'Quota'])

I had to create a unique random number and add it to the prefix. the number of random values is given in Quota
np.random.seed(1)  # for repeatability
random=df.Prefix.repeat(df.Quota)*100000 + np.random.randint(0, 99999, df.Quota.sum())

I thought np.random.randint gave unique numbers but while generating around 18000 numbers, it gave around 200 duplicate number.
eventually I tried random.sample and problem was fixed. but I want to generate unique numbers using np.random.randit because I can change seed in np.random.seed(n) and can create another set of unique numbers different from first set by changing seed.
Answer: You won't be able directly with np.random.randint, since it doesn't offer the possibility to randomly sample without replacement. But np.random.choice does. And by specifying a random seed, you can reproduce the generated sequence, which will consist on a random, uniformly sampled distribution array within the range range(99999):
np.random.seed(2)
numbers = np.random.choice(range(99999), size=df.Quota.sum(), replace=False)
random = df.Prefix.repeat(df.Quota)*100000 + numbers

len(random)==random.nunique()
# True

Comment: thanks it worked but the values generated by np.random.seed(1) and np.random.seed(2) have duplicated values. np.random.seed(1) gives unique set and so does np.random.seed(2). but merging both values gives duplicate values
Comment: Yes, that is expectable though right @YubrajBhusal ? You're generating independent sequences, why should it guarantee that these *also* have no repeated samples? `np.random.choice` has no idea of the previously generated sequence, regardless of the random seed
Comment: how do you suggest I can create a sets of number which will be unique from previous set?
Comment: What you can do... is generate an even larger array, o size say `df.Quota.sum()*10`, and split that into 10 different arrays, which will be unique @YubrajBhusal
Comment: how can  can I group by "prefix" column and create random number among them, so that each prefix will have chance to get random number from 0 to 99999. the above code creates random number total of "Quota" column and add prefix to them. by doing that not all prefix gets chance to get random number from 0 to 99999. I want to put np.random.choice on prefix, so that every other prefix gets chance to get random number from 0 to 99999. thanks in advance

Generating unique random value in Numpy


Extreme point and affine map

Question: The problem in Conway's Functional analysis book :

I know that
$x$ is called an extreme point of $A$ if $x_1, x_2\in A$ and $x=\frac{1}{2}(x_1+x_2)$ imply $x_1=x_2$.
And if $T$ is an affine map, then $T(\frac{1}{2}(x_1+x_2))=\frac{1}{2}T(x_1)+\frac{1}{2}T(x_2)$.
But I don't know how to solve this problem.
Comment: Hint: If $y = \frac{y_1+y_2}{2}$ and $y_1 = y_2$, then $y_1 = y_2 = y$.
Comment: @PrahladVaidyanathan I already know that.. Could you give me more hint?
Answer: Let $x$ be an extreme point of $T^{-1}(y)$ and $x = \frac{1}{2}(x_1+x_2)$ for some $x_1,x_2 \in K$. Then
$$y = T(x) = \frac{1}{2}(T(x_1) + T(x_2)).$$
As $y$ is an extreme point of $T(K)$, this implies that $y = T(x_1) = T(x_2)$. But then $x_1,x_2$ are elements of $T^{-1}(y)$ and since $x$ is an extreme point of $T^{-1}(y)$ we have $x = x_1 = x_2$.
Comment: Thank you for very nice answer.

Extreme point and affine map


how to create a pie chart with pyqt in python

Question: Trying to create a pie chart shape but for some reason I can't get it to join together correctly. When I run my code It creates a lot of segments on top of each other.
Here is my code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, random

app = QApplication(sys.argv)
scene = QGraphicsScene()
families = [1,2,3,4,5,6,7]
total = 0
colours = []
set_angle = 0
count1 = 0
total = sum(families)
for count in range(len(families)):
    number = []
    for count in range(3):
        number.append(random.randrange(0, 255))
    colours.append(QColor(number[0],number[1],number[2]))

for family in families:
    angle = round(family/total*16*360)
    ellipse = QGraphicsEllipseItem(0,0,400,400)
    ellipse.setPos(0,0)
    ellipse.setStartAngle(set_angle)
    ellipse.setSpanAngle(angle)
    ellipse.setBrush(colours[count1])
    set_angle = angle
    count1 +=1
    scene.addItem(ellipse)
view = QGraphicsView(scene)
view.show()
app.exec_()

Answer: Digging this thread as it might help others.
@Barry's answer is almost correct, but needs a few adjustments.
Indeed, to have a perfect round shape to your ellipse, you need to change the line:
set_angle = angle

to
set_angle += angle

This way, the set_angle (which is the starting angle of our "pie chunks") is always the last angle drawn on the canvas.
Also, the line:
angle = round(family/total*16*360)

could be written like this (for readability's sake):
angle = round(float(family*(16*360))/total)

So a working example would be (using Python3 & PyQt5):
from PyQt5.QtWidgets import QGraphicsScene, QApplication, QGraphicsView, QGraphicsEllipseItem
from PyQt5.Qt import QColor
import sys, random

app = QApplication(sys.argv)
scene = QGraphicsScene()

families = [1,2,3,4,5,6,7,8,9,10]
total = 0
set_angle = 0
count1 = 0
colours = []
total = sum(families)

for count in range(len(families)):
    number = []
    for count in range(3):
        number.append(random.randrange(0, 255))
    colours.append(QColor(number[0],number[1],number[2]))

for family in families:
    # Max span is 5760, so we have to calculate corresponding span angle
    angle = round(float(family*5760)/total)
    ellipse = QGraphicsEllipseItem(0,0,400,400)
    ellipse.setPos(0,0)
    ellipse.setStartAngle(set_angle)
    ellipse.setSpanAngle(angle)
    ellipse.setBrush(colours[count1])
    set_angle += angle
    count1 += 1
    scene.addItem(ellipse)

view = QGraphicsView(scene)
view.show()
app.exec_()

Hope it helps.
Comment: hi @ekhumoro could you explain why you multiply 360 by 16 ?
Answer: The problem is related to integer division, check this line: angle = round(family/total*16*360), it could be fixed setting total = float(sum(families)) or putting this line from __future__ import division at the start of your code, both solutions are valid.
Answer: as xndrme said you need
from __future__ import division

Your segments however will still be on top of each other because they all have the same starting angle.
set_angle = angle

should be
set_angle = angle + angle


Symfony Cache TagAwareAdapter problem with saving and then getting cacheItem

Question: Symfony's FilesystemTagAwareAdapter() lets me get, assign a value to, and save a cacheItem, and then retrieve the saved item with another get. But if I also tag the new item before saving, I cannot retrieve the saved item with another get.

when I run the following:

<code>$this->cache = new \Symfony\Component\Cache\Adapter\FilesystemTagAwareAdapter();
$thingItem = $this->cache->getItem('thing');
$thingItem->set('thingValue');
// $thingItem->tag('msc');
$this->cache->save($thingItem);
$retrieved = $this->cache->getItem('thing')->get();
</code>
The value of $retrieved is "thingValue".

If I uncomment the "$thingItem->tag('msc');" line and run the code again, the value of $retrieved is null.

I would expect the value of "$retrieved" to be "thingValue" in both cases.
Can anyone explain the inconsistent behavior?
Edit:
This is on php 8.1 and windows 10.
The inconsistent behavior occurs in a phpunit TestCase test in a Symfony project I am working on.
I find that the inconsistent behavior does not occur in a function test using Symfony's KernetTestCase with $this->cache = static::getContainer()->get('cache.app.taggable');
Comment: I cannot reproduce your bug. Btw, you mix `$this->cache` and `$cache`. Do you mistakenly have two instances of the cache?
Comment: I removed all `this->` from the code and tried to reproduce the error, failed, I got "thingValue" - also with the `->tag()` call. the comment by simon.ro is on point, I guess ;o)
Comment: I have set every cache reference to $this->cache and added reference to php version and o/s. I'm wondering if Windows is blocking something cache tries to do in the default tmp directory when adding a tag?
Comment: the tagging by default works via symlinks in an extra tag directory. if the OS doesn't allow symlinks, the cache entry will be removed: https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Cache/Adapter/FilesystemTagAwareAdapter.php#L149-L150
Comment: Thank you simon.ro and Jakumi. I have added a note that the inconsistency occurs when the code is run in a unit test but does does not occur in a functional test. So I guess my "fix" is to test the service in which I use the cache in a functional test. I still wonder why it does not work in the unit test, though.
Answer: Solved!
It appears that the cache.app.taggable that symfony creates in a Windows environment is not a FilesystemTagAwareAdapter. It is a TagAwareAdapter wrapped around a TraceableAdapter wrapped around a FilesystemAdapter().
So if I create my cache this way:
<code>$this->cache = new TagAwareAdapter(new TraceableAdapter(new FilesystemAdapter());
</code>
The code works as expected in a phpunit test!


If $a_n=n\left(1-\frac{1}{n}\right)^{n[\log n]}$, prove $1\leqslant \liminf a_n$ and $\limsup a_n\leqslant e.$

Question:
Prove that:
  $$\limsup n\left(1-\frac{1}{n}\right)^{n[\log n]} \leqslant e$$
  and
  $$\liminf n\left(1-\frac{1}{n}\right)^{n[\log n]} \geqslant 1.$$

Attempt. Since for $n>2$:
$$1<[\log n]<\log n+1\leqslant n,$$ we would get:
$$n\left(1-\frac{1}{n}\right)^{n[\log n]}\leqslant n\left(1-\frac{1}{n}\right)^n \to +\infty,$$
$$n\left(1-\frac{1}{n}\right)^{n[\log n]}\geqslant n\left(1-\frac{1}{n}\right)^{n^2} \to 0,$$
so the above estimates are not convenient.
Thanks for the help.
Answer: First, note that $\log n-1 < [\log n] \leq \log n$. Now, $0<1- \frac{1}{n}<1$, so we have
$$ n \left( 1- \frac{1}{n} \right)^{n \log n} \leq n \left( 1- \frac{1}{n} \right)^{n [\log n]} < n \left( 1- \frac{1}{n} \right)^{n (\log n - 1)}. $$
We now want to use the fact that $\left(1- \frac{1}{n}\right)^{n} \to e^{-1}$ as $n \to \infty$ to simplify the above inequalities. To make the computation easier, write this as $n\log(1- \frac{1}{n}) \to -1$, which can be sharpened to $n\log(1- \frac{1}{n}) = -1 - \frac{1}{2n} + O\left( \frac{1}{n^2} \right)$ using the Taylor series for $\log(1-x).$
Now,
$$\log \left(n \left( 1- \frac{1}{n} \right)^{n \log n} \right) = \log n \left( 1 + n \log \left(1 - \frac{1}{n} \right) \right) = \log n\left(- \frac{1}{2n} + O\left( \frac{1}{n^2}\right) \right) \to 0$$
as $n \to \infty$, and similarly
$$ \log \left( n \left( 1- \frac{1}{n} \right)^{n (\log n - 1)} \right) = \log n \left( 1 + n \log \left(1 - \frac{1}{n} \right)  \right) - n \log\left( 1- \frac{1}{n} \right) \to 1$$
as $n\to\infty.$ Taking the exponentials of both of these inequalities gives the desired result.
Answer: Actually, the correct inequalities for $n>1$ are:
$\log n-1<[\log n] < \log n$, (noting that $\log n$ is never an integer for $n>1$, or you can use less or equal in the right one as it doesn't really matter ) so you get $n\left(1-\frac{1}{n}\right)^{n[log n]} < n\left(1-\frac{1}{n}\right)^{(n\log n -n)}$ and the limit of RHS is obviously $e$, since $n\left(1-\frac{1}{n}\right)^{n\log n}$ converges to $1$ (by taking logarithms and using that $\log (1-\frac{1}{n}) = -\frac{1}{n} + O(\frac{1}{n^2})$, so multiplying by $n\log n$ you get just an $O(\frac{\log n}{n})$ which converges to $0$ hence the claim).
The other limit is now obvious since $n\left(1-\frac{1}{n}\right)^{n[log n]} > n\left(1-\frac{1}{n}\right)^{n\log n}$ which converges to $1$ as noted above.


Complex function question

Question: The question is as follows:
Define a function $f:\mathbb C→\mathbb C$ such that $∣\{z∈\mathbb C:f(z)=0\}∣=5$ and $∣\{z∈\mathbb Q:f(z)=0\}∣=1$.
How do I go about solving something like this? I'm thinking the function in question has to be rational and complex on order to satisfy the two statements. But how the heck do I get two different moduli?
Comment: Perhaps it is a cardinality/counting function rather than a modulus/magnitude  function
Answer: I think that $∣\{z\in\mathbb C:f(z)=0\}∣=5$ and $∣\{z\in \mathbb Q:f(z)=0\}∣=1$ mean respectively that the cardinality of the set $\{z\in\mathbb C:f(z)=0\}$ is $5$ and the cardinality of the set $\{z\in \mathbb Q:f(z)=0\}$ is $1$, that is $f$ has $5$ distinct complex zeros with exactly one of them in $\mathbb{Q}$. Let $f$ be a polynomial of degree five with one root in $\mathbb{Q}$ and four distinct roots in $\mathbb{C}\setminus\mathbb{Q}.$ For example $f(z)=z(z^4+1)$. Are you able to find another one?
Comment: Argh drat, it's cardinality! That makes perfect sense now thank you! What a dumb mistake :/
Answer: Take $4$ distinct irrational numbers $a$, $b$, $c$, and $d$ and define$$f(z)=z(z-a)(z-b)(z-c)(z-d).$$

Complex function question


Preciso de ajuda porque não entendo por que meu código não está realizando a filtragem por data. ASP.NET [Resolvido]

Question: Quando eu faço a filtragem, nenhum valor é retornado para mim
my view index page
Acho que o problema está no meu índice ActionResult, mas não sei o que é, porque acho que as referências estão corretas. O que sei no meu controlador de índice é converter a variável DataTime em String
My Model
public Nullable<System.DateTime> Data_Registo { get; set; }
public Programa()
    {
        Data_Registo = DateTime.Now;
    }

My Controller:
public ActionResult Index(string startdate = null, string enddate = null)
    {
        if (startdate != null && enddate != null)
        {
            //this will default to current date if for whatever reason the date supplied by user did not parse successfully

            DateTime start = DateManager.GetDate(startdate) ?? DateTime.Now;

            DateTime end = DateManager.GetDate(enddate) ?? DateTime.Now;

            var rangeData = db.Programa.Where(x => x.Data_Registo >= start && x.Data_Registo <= end).ToList();

            return View(rangeData);
        }
        return View(db.Programa);
    }

    public class DateManager
    {

        static bool IsMonthAssigned { get; set; }

        public static DateTime? GetDate(string d)
        {
            char[] splitsoptions = { '/', '-', ' ' };
            foreach (var i in splitsoptions)
            {
                var y = 0;
                var m = 0;
                var day = 0;
                if (d.IndexOf(i) > 0)
                {
                    try
                    {
                        foreach (var e in d.Split(i))
                        {

                            if (e.Length == 4)
                            {
                                y = Convert.ToInt32(e);

                                continue;
                            }
                            if (Convert.ToInt32(e) <= 12 && !IsMonthAssigned)
                            {
                                m = Convert.ToInt32(e);
                                IsMonthAssigned = true;
                                continue;
                            }
                            day = Convert.ToInt32(e);

                        }

                        return new DateTime(y, m, day);
                    }
                    catch
                    {

                    }
                }
            }
            return null;

        }

        public static DateTime? GetDate(string d, bool custom)
        {
            CultureInfo culture = new CultureInfo("en-US");

            string[] dateFormats =
            {
            "dd/MM/yyyy", "MM/dd/yyyy", "yyyy/MM/dd", "yyyy/dd/MM", "dd-MM-yyyy", "MM-dd-yyyy", "yyyy-MM-dd",
            "yyyy-dd-MM", "dd MM yyyy", "MM dd yyyy", "yyyy MM dd", "yyyy dd MM", "dd.MM.yyyy", "MM.dd.yyyy",
            "yyyy.MM.dd", "yyyy.dd.MM","yyyyMMdd","yyyyddMM","MMddyyyy","ddMMyyyy"
        };//add your own to the array if any

            culture.DateTimeFormat.SetAllDateTimePatterns(dateFormats, 'Y');

            if (DateTime.TryParseExact(d, dateFormats, culture, DateTimeStyles.None, out var date))
                return date;

            return null;

        }
    }

My View
@using (Html.BeginForm("Index", "Programas", FormMethod.Get))
{
<fieldset>
    <legend>Search criteria</legend>
    @Html.Label("StartDate", "Start Date:")
    <input class="startdate" id="startdate" name="startdate" type="date" value="">
    @Html.Label("enddate", "End Date:")
    <input class="startdate" id="enddate" name="enddate" type="date" value="">
    <input type="submit" value="Apply" />
</fieldset>
}

(UPDATE)
Tentei criar uma entrada direta, mas os dados não são carregados do banco de dados
        public ActionResult Index(DateTime? start, DateTime? end)
    {

            var programas = db.Programa.Where(x => x.Data_Registo >= start && x.Data_Registo <= end).ToList();

        return View(programas.ToList());

    }

Thanks for help
Comment: Qual é exatamente a sua pergunta? se o banco de dados não está retornando nenhum registro, como você esperar ter algo para exibir?
Comment: A minha base de dados não retorna nenhum registo depois de aplicar o filtro. A pergunta é o que pode estar errado para não retornar nenhum registo? Nota: antes do filtro a BD é carregado certa, só depois de aplicar o filtro é que não retorna nada.
Comment: Faça a consulta na mão, tente outros parâmetros com um range maior. Você pode estar tendo problema de achar resultados por conta da hora junto do da data
Answer: Finalmente consegui! nada como simplificar
Deixo o código abaixo para quem necessitar de criar uma procura entre datas.
    public ActionResult Index(string startdate = null, string enddate = null)
    {
        if (startdate != null && enddate != null)
        {

            DateTime start = Convert.ToDateTime(startdate);

            DateTime end = Convert.ToDateTime(enddate);

            var rangeData = db.YourTable.Where(x => x.YourColumn >= start && x.YourColumn<= end).ToList();

            return View(rangeData);
        }
        return View(db.YourTable.ToList());
    }


Intersections of two cones with parallel axes

Question: In mathpages, "On the Ellipse", the author starts, as usual, by considering an intersection of a plane and a cone. But, in order to derive further properties of the ellipse, he immediately states after that

By symmetry, the locus of intersection between the cone and the plane is also the locus of intersection of two right cones with parallel axes offset from each other, as shown in the figure below.

Why should this be the case, a-priori?
Is there any reason to think, without any derivations\algebra, that it should be symmetric about this axis? Or vice versa, that the intersections of two right cones with parallel axes should be planar - without any proof or calculations?
The author doesn't regard this point anywhere in this page.
Any help is appreciated.
Comment: If the apex is at the origin the equation of a right circular cone is $$\frac1{\sqrt2}=\cos(\frac{\pi}{4})=\frac{n_x x+ n_y y+n_z z}{\sqrt{x^2+y^2+z^2}},$$ where $[n_x, n_y, n_z]$ is the unit normal vector along the axis. This means that if you have two translated to different apexes the intersection will be contained in a plane, just by the fact that the quadratic terms cancel.
Comment: Equivalently, why is the intersection of these two cones contained within a plane?
Comment: Those are oblique cones, not right cones, since the altitudes are not perpendicular to the elliptical base.
Answer: Look from the front so the picture is in 2D.
Imagine translating each of the two edges of down-cone, so that they connect with the edge's intersection with the vertical side of the cylinder. This way you constructed a parallelogram. Therefore, you see the angle of the up-cone and the down-cone (in 3D, solid angle) must be equal - that they are really from the same cone. Now the symmetry about the axis is simple from trigonometry.
Comment: Succinct way: notice the parallelogram
Comment: Do you mind explaining a bit further about the symmetry about the axis?
Comment: From the diagram, you can see the two axis are the same distance from the side (or the center) of the cylinder. And as the axis of the 2 cones are parallel, you could imagine flipping the picture up to down, and then right to left, and you get the exact same picture.
Comment: Why should the upper (constructed) cone should be a  right cone, and not some other wonky symmetric shape?
Answer: Just an idea.
Suppose the plane is passing through the origin and cutting the upper right cone with apex $(0,0,T)$ at an ellipse $E$. Reflect the cone about $xy$-plane obtaining a lower cone. Then translate the lower cone so that it passes through $E$.


Show that $H \cap gK$ is either empty or is equal to the coset of $K \cap H$ in $H$ for subgroups $H,K <G$ and $g \in G$

Question: Problem Statement

Suppose $H,K < G$ are subgroups of a group $G$. Prove that for all $g \in G$, $H \cap gK$ is either empty or is equal to a coset of $K \cap H$ in $H$.

A quick question to get out of the way: The phrase term "Coset of $K \cap H$ in $H$" what exactly does this term suggest, in symbols? Because in reference to cosets I've only been exposed to the term "left coset (of $H$) by $g$" which is, of course $gH$. So, does this term mean that $h(K \cap H)$? Or potentially does it mean, $K \cap gH$? I'm a bit confused on the terminology here so some clarification would go a long way to helping decipher how to approach this problem.

Conceptually then, I believe this is what I know and what I want to show to prove the above:
$H \cap gK = \emptyset$ when $H$ and $gK$ share no elements in common. So, suppose that $H \cap gK$ is nonempty. That is, $f$ is any element such that $f \in H \cap gK$. This means that $f \in H$ and $f \in gK$.
Now, we want to show that the inclusion of an arbitrary element $f$ in the intersection of a subgroup $H$ and a coset of another subgroup $gK$ with an element of the group implies that that arbitrary element is also an element of a coset of $K \cap H$ in $H$ (whatever that means exactly.) And, conversely, that an element of a coset of $K \cap H$ in $H$ implies that it is an element of $H \cap gK$. So that we show containment in both directions. Correct?
Comment: It means: $h(H\cap H)$
Comment: $H\cap K$ is a subgroup of $H$. So as any subgroup it has cosets, which are subsets of $H$ of the form $h(H\cap K)$ where $h\in H$. This is exactly the definition you know, just instead of "$G$ and $H$" we use "$H$ and $H\cap K$".
Comment: @NumericalDisintegration It is not clear what is $h$ in your comment though. You can start by assuming the intersection is not empty, so there is some element $h\in H\cap gK$. (for a fixed $g$) Now show that $H\cap gK$ equals the coset $h(H\cap K)$ for this specific $h$. Now try to show a two sided inclusion between sets.
Comment: @Mark Thank you for the clarification, that makes sense. Now, if you don't mind me asking, for the first containment can I say that since $f \in H \cap gK$ that means that $f \in H$ and $f \in gK$ and that implies $f \in h(H \cap K)$ since $h(H \cap K)$ is the set of products of an element $h \in H$ with all elements that are in both $H$ and $K$...

...actually, I'm not quite seeing where I should be making the connection here: Obviously since $f \in H$ then if it were just $hH$ that'd make sense... but it'd also be trivial since $hH = H$. I'm having trouble intuiting the coset elements
Answer: A coset of $K\cap H$ in $H$ means $h(K\cap H)$ for some $h\in H$. Therefore we want to show that if $H\cap gK\neq \varnothing$ for $g\in G$, then $H\cap gK=h(K\cap H)$ for some $h\in H$.
Let $g\in G$ and suppose that $H\cap gK\neq \varnothing$. There exists $x=h=gk$ for some $h\in H$ and $k\in K$. The natural guess is that $H\cap gK=x(K\cap H)$.
First note that $g=xk^{-1}$. Hence $gK=xk^{-1}K=xK$. Also $xH=H$ as $x\in H$. Therefore
$$x(K\cap H)=x(H\cap K)=xH\cap xK=H\cap gK$$
as claimed.


Does Exchange 2007 license allow Exchange 2003 to be installed and used?

Question:
Possible Duplicate:
Can you help me with my software licensing question?

Does having Exchange 2007 license allow me to install Exchange 2003 and use it instead? (for example if system is 32 bit only and Exchange 2007 is x64 so can't be installed).
Answer:
STANDARD LICENSING DISCLAIMER:
While SF can give you a decent idea, and more often than not a very good answer, the best place to ask these types of questions is to ask you licensing representative from Microsoft.

I believe that if you bought the license via one of the open license programs you have downgrade rights (possibly only applicable with Software Assurance as well)
The Downgrade Rights Page may contain useful information (I didn't read it through too thouroughly)
Comment: +1 for "ask your representative". MS licensing is unfortunately ridiculously complicated.
Comment: I wouldn't call MS Licensing "ridiculously complicated" but it is an acquired taste. At least they've started standardizing the different products by line. Now if they'd just make it the same for the 3 different ways of buying licenses, we'd be set.
Answer: It depends on how you get it. If you just buy Exchange 2007, so long as the previous version is supported, you can use previous versions. Note that your licenses must match. If you licensed 2007 server, you can't use 2003 CALs, even if you're install 2003. You do have to call MS and get keys to install 2003 though, and that'll be a fun call.
If you get Exchange through Small Business Server (or some packaged deal like it) then no.


Calculate z-score from odds-ratio

Question: I want to calculate the z-score for a distribution for which I know the odds-ratio, and the p-value. I also know the upper and lower 95% confidence limits for the odds-ratio. An example with two-data points is shown here.
OR       OR_95    OR_95U   p-value
0.997804 0.970573 1.025798 0.876215
1.039562 1.010116 1.069866 0.00815

Comment: "Z score" of what?  (By "distribution" surely you mean *data*, so what you have is an *estimated* odds ratio (and its p-value).) And what is the second row of statistics you show?  A second example?
Answer: Odds ratios standard errors, CIs, etc are calculated on the log of the odds.
Here's some R code. First we'll take the log of the odds:
OR <- 0.997804
ORL95 <- 0.970573

logor <- log(OR)
logorl95 <- log(ORL95)

Then calculate the difference between the odds ration and the lower (or upper, it doesn't matter, they're the same) confidence limit.
diff <- logor - logorl95

The confidence limit is 1.96 * se, so:
seor <- diff / 1.96

z is estimate / se.
z <- logor / seor
z

Let's calculate p, just to make sure we didn't make a foolish mistake along the way:
(1 - pnorm(abs(z))) * 2

Here are the important bits of the output:
> z
[1] -0.155723

> (1 - pnorm(abs(z))) * 2
[1] 0.8762514

Comment: In case you want more detail, this is covered in Agresti's *An Introduction to Categorical Data Analysis*.
Comment: Thanks! Does it matter if the odds-ratios are greater than or less than 1? For the second data point I know the Z is 2.185, however when I try to follow the directions you stated above, the answers do not seem to match. Am I misunderstanding something?
Comment: I'm not sure if you're misunderstanding, but that Z is not correct. If Z is 2.185 then p is not 0.008. A z of 2.185 gives  p of 0.029.  (Zs of [about] 2, 2.5 and 3.3 give ps of [about] 0.05, 0.01, 0.001.)

Calculate z-score from odds-ratio


Migração com Caracteres Estranhos?

Question: Os dados são de um banco Firebird e mesmo abrindo com ferramentas oficiais os caracteres não vêm no "formato" br, por exemplo:
ÁGUA vem µGUA
PÃO  vem PÆO

Encontre um site que ao informar um caractere especial, por exemplo µ ele me retorna o valor do caractere em decimal, octal, etc:

Site: http://unicodelookup.com/#µ/1

No exemplo acima o site retorna o valor decimal 181 para o caractere µ. Se utilizarmos o atalho ALT+181 ele retorna Á que é exatamente a letra que este código representa no primeiro exemplo acima. Tentei utilizar var characters = Encoding.ASCII.GetChars(new byte[] { 181 }); mas retonra ? ao invés do Á.
Minha pergunta é:
Exite alguma função que simule o código gerado por ALT+181 para retornar um caractere?

Aceito resposta em c# ou vb6
Comment: Adicionei a tag firebird, porque me parece um problema que possa ser resolvido no próprio banco ou durante a conexão, não tenho certeza ainda.
Answer: Você pode efetuar um Backup e um Restore do seu banco de dados utilizando os seguintes comandos do Gbak para correção de UNICODE.
-FIX_FSS_D(ATA)       fix malformed UNICODE_FSS
-FIX_FSS_M(ETADATA)   fix malformed UNICODE_FSS metadata

Segue um exemplo do comando de restore.
"C:\Program Files (x86)\Firebird\Firebird_2_5\bin\gbak.exe" -se service_mgr -c -v -user sysdba -password masterkey "d:\base de dados\teste.fbk" "d:\base de dados\teste.fdb"-fix_fss_m win1252 -FIX_FSS_D win1252

Para mais informações sobre os comandos acesse

https://www.firebirdsql.org/pdfmanual/html/gbak-cmdline.html
Comment: @rubStackOverflow Se a resposta lhe foi útil, se puder marque-a como aceita `√`, assim quando outros usuários visualizarem sua questão verão que já tem uma resposta correta e aceita por você.

Migração com Caracteres Estranhos?


Migrating multiple values into a single file field in Drupal 7 with Migrate 2.2

Question: I have a file field that can have multiple downloadable files for an image node type. These images will have several versions (psd, jpg, eps) that will be downloadable. I would like to be able to append multiple values to this field. How would I do that when they are coming from multiple source columns (i.e. eps_filename, jpg_filename, psd_filename)?
I found related documentation here: http://drupal.org/node/1012810 But that documentation is for taxonomy terms where the details of the value can simply be a string with a separator. For this I am using MigrateFileFieldHandler::arguments(), so I can't just give it a separator.
Further what I would like to do is also be able to come back later and append more files to the migrated nodes. This is because the larger files will take longer to get on the server, so their smaller counterparts (jpg, png, etc) will be loaded first and then adding the eps files later. Now I already figured out how to update the previously migrated nodes using systemOfRecord. But I am not sure how to append to a multi-value field.
I am using Drupal 7 and the Migrate module version 2.2. Here is some sample code I am using for migrating the data initially into the file field.
<code>$jpg_arguments = MigrateFileFieldHandler::arguments(NULL,
  'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_file', 'jpg_uri')
     ->arguments($jpg_arguments);
</code>
I suspect the trick is using the prepareRow() function. But so far I have not been able to get that to execute yet.
Any ideas? I really appreciate any help.
Thanks!
Comment: No answers yet. Bummer.
Answer: I think what you need is prepareRow. Here is code from the migrate baseball example where multiple fields are merged into a single array field.
<code> function prepareRow($row) {
    // Collect all the batters into one multi-value field.
    for ($i=1; $i <= 9; $i++ ) {
      $key = "visiting_batter_$i";
      $visiting_batters[] = $row->$key;
      $key = "home_batter_$i";
      $home_batters[] = $row->$key;
    }
    $row->visiting_batters = implode(',', $visiting_batters);
    $row->home_batters = implode(',', $home_batters);
    $row->title = "$row->home_team vs. $row->visiting_team. " . gmdate('M d, Y', strtotime($row->start_date));
  }
</code>
(from the file migrate_example_baseball.migrate.inc)
However I have been having mixed results with prepareRow in my own code, so while this looks straight forward I can't guarantee that it will work.
Comment: I gave you an upvote for giving it a good go. Thanks!
Answer: hmmrr. It might be easier not to do this in 1 pass ... but a 2 step migration. Create your new parent record in 1 migration task, then back-fill in your N file_fields with the new node or entity id as a second migration task.
furthermore, while you've looked into System of Record -- my understanding of this feature is it only works for DB schemas which are 1:1 between your old DB and the new DB schema. Eg, a multiple value field entry cannot be inspected because could be N-fields in a row in an old DB and for instance N-rows crossreferenced to a parent row id in the new DB.
I have used the "Query in Prepare" method, I tried the group_concat version too .... so that's my 2 cents on the matter.
Comment: I gave you an upvote for giving it a good go. Thanks!
Answer: Actually I figured this out last month, but just got back to commenting here. The solution was far more complex than what anyone has suggested. I actually had to extend the MigrateDestinationNode class and create my own import function that is a modified version of the one used in that class. I will paste the source code below.
Essentially what I had to do was modify the import where it tries to do an update on the existing node when the System of Record is set to destination to check for the field type that I am saving the file to and merge the file field data of the file that is already on the node with the one I am adding.
I also had to make sure that I used this new extended class as the destination and set the System of Record to Migration::DESTINATION.
Here is the code:
<code><?php
class ImageAssetNodeAddEPSMigration extends BasicClientMigration {
  public function __construct() {
    parent::__construct();

    //This allows us to update the existing record.
    $this->systemOfRecord = Migration::DESTINATION;

    $this->description = t('Image Asset Files - Adding the EPS files');
    $this->dependencies = array('ImageAssetNode');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'destid1' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Node ID.',
          'alias' => 'an',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    // We get the data from the database for this.
    $query = db_select('migrate_map_imageassetnode', 'an')
        ->fields('an', array('destid1'));
    $query->innerJoin('migrate_client_image_asset_node', 'ta', 'an.sourceid1 = ta.fcid');
    $query->fields('ta', array('eps_psd_filename', 'eps_psd_name', 'eps_psd_uri', 'fcid') );

    // Passing the cache_counts option means the source count (shown in
    // drush migrate-status) will be cached - this can be very handy when
    // dealing with a slow source database.
    $this->source = new MigrateSourceSQL($query, array(), NULL,
      array('cache_counts' => TRUE));

    // Set up our destination - nodes of type migrate_example_beer
    $this->destination = new MigrateDestinationNodeExtended('media_images');

    /*
      Assign mappings TO destination fields FROM source fields. To discover
      the names used in these calls, use the drush commands
      drush migrate-fields-destination ImageAssetNode
      drush migrate-fields-source ImageAssetNode
    */

    // Mapped fields
    $this->addFieldMapping('nid', 'destid1')
         ->description(t('The original node id.'));

    // Copy an image file, write DB record to files table, and save in Field storage.
    // Note we specify the source query fields that will map to the file alt/title/description
    // values.

    $eps_arguments = MigrateFileFieldHandler::arguments(NULL,
      'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'eps_psd_name'),
      array('source_field' => 'eps_psd_filename'), array('source_field' => 'eps_psd_filename'), NULL, TRUE);

    $this->addFieldMapping('field_file', 'eps_psd_uri')
         ->arguments($eps_arguments);

    // Add fields that are mapped via argument
    #$this->addFieldMapping(NULL, 'eps_psd_uri');
    $this->addFieldMapping(NULL, 'eps_psd_filename');
    $this->addFieldMapping(NULL, 'eps_psd_name');

    // No unmapped source fields
    $this->addUnmigratedSources( array('fcid', 'jpg_uri', 'jpg_filename', 'jpg_name', 'category_tid') );

    // Unmapped destination fields
    $this->addUnmigratedDestinations( array('is_new', 'name', 'created', 'changed',
      'status', 'promote', 'revision', 'language', 'sticky', 'uid', 'revision_uid',
      'title', 'body', 'field_image', 'field_keywords', 'field_download_count',
      'field_images_category', 'field_media_status', 'field_media_audience',
      'field_roles_download', 'field_roles_share', 'field_roles_view', 'path', 'comment',
      'bookmarks', 'cart', 'download', 'pathauto') );
  }
  /*
  public function prepare(&$node, &$row) {

  }*/

  public function prepareRow($current_row) {
    //If the file does not exist then skip it.
    if (!file_exists(drupal_realpath($current_row->eps_psd_uri))) {
      return FALSE;
    }

    $result = db_query("SELECT ff.* FROM field_data_field_file ff INNER JOIN migrate_map_imageassetnode ian ON ff.entity_id = ian.destid1 WHERE sourceid1 = :sid", array(':sid' => $current_row->fcid));

    //If there is more then one file field entry attached to the node then skip.
    if ($result->rowCount() > 1) {
      return FALSE;
    }
  }
}

class MigrateDestinationNodeExtended extends MigrateDestinationNode {
  /**
   * Basic initialization
   *
   * @param string $bundle
   *  A.k.a. the content type (page, article, etc.) of the node.
   * @param array $options
   *  Options applied to nodes.
   */
  public function __construct($bundle, array $options = array()) {
    parent::__construct($bundle, $options);
  }

  /**
   * Import a single node.
   *
   * @param $node
   *  Node object to build. Prefilled with any fields mapped in the Migration.
   * @param $row
   *  Raw source data object - passed through to prepare/complete handlers.
   * @return array
   *  Array of key fields (nid only in this case) of the node that was saved if
   *  successful. FALSE on failure.
   */
  public function import(stdClass $node, stdClass $row) {
    // Updating previously-migrated content?
    $migration = Migration::currentMigration();

    if (isset($row->migrate_map_destid1)) {
      // Make sure is_new is off
      $node->is_new = FALSE;

      if (isset($node->nid)) {
        if ($node->nid != $row->migrate_map_destid1) {
          throw new MigrateException(t("Incoming nid !nid and map destination nid !destid1 don't match",
            array('!nid' => $node->nid, '!destid1' => $row->migrate_map_destid1)));
        }
      }
      else {
        $node->nid = $row->migrate_map_destid1;
      }

      // Get the existing vid, tnid so updates don't generate notices
      $values = db_select('node', 'n')
                   ->fields('n', array('vid', 'tnid'))
                   ->condition('nid', $node->nid)
                   ->execute()
                   ->fetchAssoc();

      $node->vid = $values['vid'];
      $node->tnid = $values['tnid'];
    }

    if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
      if (!isset($node->nid)) {
        throw new MigrateException(t('System-of-record is DESTINATION, but no destination nid provided'));
      }

      $old_node = node_load($node->nid);

      if (!isset($node->created) && isset($old_node->created)) {
        $node->created = $old_node->created;
      }

      if (!isset($node->vid) && isset($old_node->vid)) {
        $node->vid = $old_node->vid;
      }

      if (!isset($node->status) && isset($old_node->status)) {
        $node->status = $old_node->status;
      }

      if (!isset($node->uid) && isset($old_node->uid)) {
        $node->uid = $old_node->uid;
      }
    }

    // Set some required properties.
    // Set type before invoking prepare handlers - they may take type-dependent actions.
    $node->type = $this->bundle;

    if ($migration->getSystemOfRecord() == Migration::SOURCE) {
      if (!isset($node->language)) {
        $node->language = $this->language;
      }

      // Apply defaults, allow standard node prepare hooks to fire.
      // node_object_prepare() will blow these away, so save them here and
      // stuff them in later if need be.
      if (isset($node->created)) {
        $created = MigrationBase::timestamp($node->created);
      }
      else {
        // To keep node_object_prepare() from choking
        $node->created = REQUEST_TIME;
      }

      if (isset($node->changed)) {
        $changed = MigrationBase::timestamp($node->changed);
      }

      if (isset($node->uid)) {
        $uid = $node->uid;
      }

      node_object_prepare($node);

      if (isset($created)) {
        $node->created = $created;
      }

      // No point to resetting $node->changed here, node_save() will overwrite it
      if (isset($uid)) {
        $node->uid = $uid;
      }
    }

    // Invoke migration prepare handlers
    $this->prepare($node, $row);

    if (!isset($node->revision)) {
      $node->revision = 0; // Saves disk space and writes. Can be overridden.
    }

    // Trying to update an existing node
    if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
      // Incoming data overrides existing data, so only copy non-existent fields
      if ( !isset($old_node) || ( isset($old_node) && (empty($old_node) || !is_array($old_node)) )) {
        $return = FALSE;
      }
      else {
        foreach ($old_node as $field => $value) {
          // An explicit NULL in the source data means to wipe to old     value (i.e.,
          // don't copy it over from $old_node)
          if (property_exists($node, $field) && $node->$field === NULL) {
            // Ignore this field
          }
          elseif ($field == 'field_file') {
            $file_field = $node->$field;
            $lang_files = array();

            // We can import this, got to do it on a per language basis
            foreach ($value AS $lang => $files) {
              if (isset($file_field[$lang])) {
                $new_node_files = $file_field[$lang];
              }
              else {
                $new_node_files = array();
              }

              $lang_files[$lang] = array_merge($new_node_files, $files);
            }

            $node->$field = $lang_files;
          }
          elseif (!isset($node->$field)) {
            $node->$field = $old_node->$field;
          }
        }
      }

    }

    if (isset($node->nid) && !(isset($node->is_new) && $node->is_new)) {
      $updating = TRUE;
    }
    else {
      $updating = FALSE;
    }

    migrate_instrument_start('node_save');
    node_save($node);
    migrate_instrument_stop('node_save');

    if (isset($node->nid)) {
      if ($updating) {
        $this->numUpdated++;
      }
      else {
        $this->numCreated++;
      }

      // Unfortunately, http://drupal.org/node/722688 was not accepted, so fix
      // the changed timestamp
      if (isset($changed)) {
        db_update('node')
          ->fields(array('changed' => $changed))
          ->condition('nid', $node->nid)
          ->execute();

        $node->changed = $changed;
      }

      // Potentially fix uid and timestamp in node_revisions.
      $query = db_update('node_revision')
                 ->condition('vid', $node->vid);

      if (isset($changed)) {
        $fields['timestamp'] = $changed;
      }

      $revision_uid = isset($node->revision_uid) ? $node->revision_uid : $node->uid;

      if ($revision_uid != $GLOBALS['user']->uid) {
        $fields['uid'] = $revision_uid;
      }

      if (!empty($fields)) {
        // We actually have something to update.
        $query->fields($fields);
        $query->execute();

        if (isset($changed)) {
          $node->timestamp = $changed;
        }
      }

      $return = array($node->nid);
    }
    else {
      $return = FALSE;
    }

    $this->complete($node, $row);
    return $return;
  }
}
?>
</code>
Pastebin Link as well: http://pastebin.com/ykzgVvCF


Criando arquivo XML Com Buscar um determinado usuario na tabela usando forEach jpa java

Question: Bom dia !!
Pessoal minha duvida é a seguinte
tenho duas tabelas uma Pessoa e outra Funcionário.
estou fazendo um for nas duas tabelas para poder criar um arquivo Xml, porem como eu não estou retornado os resultados por Id e sim pela ordem do for,
meu xml esta sendo criado porem não está puxando os dados corretos.
o campo cargo está puxando o de outro funcionário conforme exemplo abaixo
Errado

    2
    Rafael
    Analista de Sistema

Certo

    2
    Rafael
    Editor

segue abaixo o código para criar o Xml
    // Gerando Arquivo Xml Para Exportação.
private File GerarXmlFuncionarios() {

    List<FuncionarioModel> funcionariosModel = funcionarioRepository.todos();

    List<PessoaModel> pessoasModel = pessoaRepository.todas();

    // Nome do Elemento Raiz do Xml
    Element elementDados = new Element("funcionarios");

    Document documentoFuncionarios = new Document(elementDados);

    funcionariosModel.forEach(funcionario -> {
        pessoasModel.forEach(pessoa -> {
            // Campos dos Xml com os Seus Valores
            Element elementFuncionario = new Element("funcionario");
            elementFuncionario.addContent(new Element("codigo").setText(pessoa.getCodigo().toString()));
            elementFuncionario.addContent(new Element("nome").setText(pessoa.getNome()));
            elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));

            elementDados.addContent(elementFuncionario);
        });
    });

    XMLOutputter xmlGerado = new XMLOutputter();
    xmlGerado.setFormat(Format.getPrettyFormat().setEncoding("ISO-8859-1"));

    try {

        // Gera o Nome do Arquivo
        String nomeArquivo = "funcionarios_".concat(java.util.UUID.randomUUID().toString()).concat(".xml");

        // Caminho que o Arquivo Sera Salvo
        File arquivo = new File("C:/Pasta/Sistema_Web/".concat(nomeArquivo));

        FileWriter fileWriter = new FileWriter(arquivo);

        xmlGerado.output(documentoFuncionarios, fileWriter);

        return arquivo;

    } catch (Exception ex) {

        ex.printStackTrace();
    }

    return null;
}

Classes PessoaRepository e FuncionarioRepository onde eu retorno minha lista de ambas classes
    public List<PessoaModel> todas() {
    TypedQuery<PessoaModel> query = manager.createQuery("from PessoaModel", PessoaModel.class);
    return query.getResultList();
}

    public List<FuncionarioModel> todos() {
    TypedQuery<FuncionarioModel> query = manager.createQuery("from FuncionarioModel", FuncionarioModel.class);
    return query.getResultList();
}

segue solução abaixo
    funcionariosModel.forEach(funcionario -> {
                    // Campos dos Xml com os Seus Valores
                    Element elementFuncionario = new Element("funcionario");
                    elementFuncionario.addContent(new Element("codigo").setText(funcionario.getPessoaModel().getCodigo().toString()));
                    elementFuncionario.addContent(new Element("nome").setText(funcionario.getPessoaModel().getNome()));
                    elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));
                    elementDados.addContent(elementFuncionario);
        });
Comment: Me parece que o problema é no seu `pessoasModel.forEach` **dentro** do `funcionariosModel.forEach`. Você está percorrendo toda a lista de pessoas para cada funcionário. Qual é a relação entre funcionários e pessoa? Se houver uma relação, não seria melhor retorná-los em uma única consulta, já que do modo que você está fazendo, não há nenhuma garantia de que o funcionário esteja relacionado aquela pessoa especificamente.
Comment: Oi Felipe, primeiramente obrigado por responder.  sei que o meu problema é mesmo esse que vc mencionou, um forEach dentro de outro não me da o resultado esperado.   e dentro da minha tabela funcionário tenho o Id_pessoa que seria minha chave estrangeira da tabela pessoa, sei que o certo é fazer o uso dessa chave. e fazer somente um for de funcionário e retorna a pessoa pelo id mais não sei como poderia fazer isso. caso possa me ajudar fico grato
Comment: Pela resposta que você deu abaixo, parece que você já resolveu o problema. Para você compreender um pouco melhor como o relacionamento entre as entidades funciona dê uma olhada nesses dois links sobre [Lazy e Eager Load](http://blog.caelum.com.br/entendendo-o-lazy-e-o-eager-load-da-jpa/) e [Fetch Strategy](https://vladmihalcea.com/2013/10/17/hibernate-facts-the-importance-of-fetch-strategy/).
Answer: Já que não tem um controle efetivo de cada elemento, sugiro realizar sua consulta no banco de dados de forma ordenada (ORDER BY) para ter maior garantia de que os dados corretos caminhem em paralelo.
Segunda coisa é fazer essa interação com o forEach do Java 8, mas eu não sei como isso deverá ser feito, porém com uma interação com o tradicional for ficaria algo assim:
int funcionarioAdd = 0;
int pessoaAdd = 0;

for(List<FuncionarioModel> funcionario: funcionariosModel) {
 for(List<PessoaModel> pessoa: pessoasModel) {
   if(funcionarioAdd == pessoaAdd++) {
    // Campos dos Xml com os Seus Valores
    Element elementFuncionario = new Element("funcionario");
    elementFuncionario.addContent(new Element("codigo").setText(pessoa.getCodigo()));
    elementFuncionario.addContent(new Element("nome").setText(pessoa.getNome()));
    elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));
    elementDados.addContent(elementFuncionario);
    pessoaAdd = 0;
    break;
   }
  }
 funcionarioAdd++;
}

Verifique a lógica corretamente e tome cuidado pois as chances de os dados perderem a ordenação é muito alta nesse tipo de procedimento (ordenar sem as chaves que garantem a consistência).
Answer: Felipe e n3uRoQuiLa, Muito Obrigado mais uma vez pela ajuda  de vocês.
consegui resolver conforme abaixo, afinal estou trabalhando orientado a objeto era mais simples do que pensei.
        funcionariosModel.forEach(funcionario -> {
                // Campos dos Xml com os Seus Valores
                Element elementFuncionario = new Element("funcionario");
                elementFuncionario.addContent(new Element("codigo").setText(funcionario.getPessoaModel().getCodigo().toString()));
                elementFuncionario.addContent(new Element("nome").setText(funcionario.getPessoaModel().getNome()));
                elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));
                elementDados.addContent(elementFuncionario);
    });

mais uma vez grato espero um dia poder retribuir


Problemas para fechar comunicação com o Banco de dados

Question: Estou com algumas aplicações consumindo dados do banco de dados, mas de um tempo pra cá as aplicações não estão conseguindo fechar a conexão, quando eu dou um conexao.close(); o Java fala que não pode fechar por que o ResultSet que esta logo a cima no bloco try já foi fechado.
Vejam abaixo meu código
    public ResultSet getHist(int ID) {
    ResultSet rs = null;
    PreparedStatement state = null;
    Connection conexao = null;
    try{
        conexao = FactoryConnection_MySQL.getConnection("base");
        state = conexao.prepareStatement("SELECT * FROM table where id = ?");
        state.setInt(1, ID);
        rs = state.executeQuery();
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if(!rs.isClosed()){//aqui eu verifico se o rs ta fechado ou não
                System.out.println("Rs não fechado...");
                conexao.close();
            }else{
            System.out.println("Rs ja fechado!");
        }
        } catch (Exception err) {
            err.getMessage();
        }
    }
    return rs;
}

Segue o erro :
Informações:   Rs não fechado...false
Advertência:   StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.sql.SQLException: Operation not allowed after ResultSet closed
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
    at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
    at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6289)
    at org.apache.jsp.historico_jsp._jspService(historico_jsp.java:985)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)

Comment: Possível duplicata de [MySQL deixando conexões abertas por muito tempo](https://pt.stackoverflow.com/q/346798/28595)
Answer: Sugiro que você mude o código para usar o bloco try-with-resources.
Declare os seus recursos (ResultSet, PreparedStatement e Connection) desta forma, pois todas elas implementam atualmente a interface java.lang.AutoCloseable.
Assim, você não precisará se preocupar em fechar os recursos manualmente.
Para entender o conceito e ver exemplos, veja em: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


how to stop the current included execution in PHP?

Question: I know it sounds a bit hacky but is there a way of stopping the execution of an included script in php ? Giving this example here

Is there a function or a tiny trick to use to have this effect here ?
note 1 : I know b.php in the example has a closed conditional structure but if there is code after that structure It will get executed.
note 2 : exit will stop the whole php running execution, that is not what I need.
Comment: Maybe using constants?? http://php.net/manual/es/function.defined.php... If defined constant skip whole block.
Comment: @Ikillnukes does constants has even something to do with what I ask ?
Comment: Yes, you can skip a block of code if you define it, if not you can execute it.
Comment: @Ikillnukes well, this is php, not c or c++ question. And I am not meaning `require_once` or something,
Answer: You can use a return statement in the included file to return to the file that includes it.
From the documentation of include:

It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it.
Comment: I found it odd when I first saw `$a= include 'file.php';` it's used in places where file.php builds a config and the `return` will pass the value back to `$a`
Comment: wow thanks I didn't know we could do that, that sounds nice, any known downsides to that method ?
Comment: No downsides I know of. I consider it poor style to use include files this way. The best way to use include files is for them to define classes and/or functions that you call, rather than expecting the include file to do stuff by itself. The exception is simple include files that just set some variables, often used to load configuration settings.