C++ Method Overriding from another Class in Composition

Question: How to override a method from another class?
The situation is the following:
class foot:
{
    void kick() { clumsyKick(); };
}

class person: /* Person has Foot */
{
    foot *personsFoot;
}

class soccerPlayer: /* SoccerPlayer has Foot too, but his foot is better */
{
    foot *soccerPlayerFoot;
}

Now I want to override the foot class Kick() method for the soccerPlayer class only with the following method (I understand syntax is not correct bellow):
soccerPlayer::foot::Kick() { expertKick(); }

Is it possible in C++? What is the best workaround for such a situation?
ps: I can't afford to create a derived class for each implementation of foot::Kick();
Comment: The problem with the question is that you are not really talking about a problem to solve, but about how to implement a solution that might not be appropriate. It is impossible to even offer pointers into the right direction when there is not enough information of the *real* problem. BTW, feet's don't kick, people with feet kick (in the same way that [cannons don't sink ships, pirates with cannons sink ships](http://826valencia.org/store/products/cannons-dont-sink-ships-pirates-with-cannons-sink-ships-poster/))
Comment: *I can't afford to create a derived class for each implementation of foot::Kick();* Do you want to expand on this? What is your concern? If they are *different* they should be... different. It is not clear what you really want to obtain, an option would be to parametrize `foot` or `foot::kick` to take a *quality* value, and have the `person` do the `kick`ing (by dispatching internally to it's foot)
Comment: @DavidRodríguez-dribeas Yes, I agree, the problem is that this approach would create dozens of derived classes for foot only (there are 3 other bases as well), which would increase complexity beyond acceptable. If I have to create derived class I'd ratter change the software architecture.
Comment: Your syntax is all wrong.
Comment: @David How many ships could a ship shinker _[sic]_ shink if a ship shinker could shink ships?#
Comment: @DavidRodríguez-dribeas Your perspective of what kicks has just been very enlightening, it solves the problem.
Comment: @David Feet's _[sic]_ don't kick people, rabbits do!
Comment: @LightnessRacesinOrbit: sue me :) One of these days we'll discuss in Spanish, then I'll get revenge!
Answer: The direct answer is that you cannot override a method of a composed class. Overriding is only possible with inheritance.
You could use other design patterns in this case, such as delegates. C++ doesn't offer delegates natively but you can simulate them or use a framework that provides an implementation. You could make the foot class take a delegate for the implementation of kick and supply an alternate one in the soccerPlayer class.
You can simulate a delegate using function pointers or using a single method abstract class. For instance you might create
class IKick{
    public:
    virtual void kick() = 0;
}

Then you can have specialized implementations of IKick provided by the classes that extend person.
Of course in order to make the kick method do anything useful you'll probably want to change the signature to have some parameters that pass state to and form the caller.
Comment: @fanl: Simple answer: redesign. But that of course cannot be hinted without a better description of the real problem
Comment: @DavidRodríguez-dribeas True, but yet debating on the available information of the topic may get us good results.
Comment: Definitely delegate pattern is the far better solution when method override is necessary on an object basis. Thanks miky.
Answer: I can see what you are trying to do, but Miky Dinescu is correct, you cannot do this in the manner that you have described.
You could do this with inheritance, that is, have a generic Person object with a Kick method, and have a sub-class (SoccerPlayer) override that method:
class person: /* Person has Foot */
{
    virtual void kick() { clumsyKick(); }
}

class soccerPlayer: /* SoccerPlayer has Foot too, but his foot is better */
{
    virtual void kick() { expertKick(); }
}

However, you appear to be attempting to do this via composition, rather than inheritance. How about this:
class foot
{
    virtual void Kick() { clumsyKick(); }
}

class soccerFoot: foot
{
    virtual void Kick() { expertKick(); }
}

class person: /* Person has Foot */
{
    private foot *personsFoot;
    person(foot* theFoot)
    {
        personsFoot = theFoot;
    }
}

void main()
{
    person soccerPlayer = new person(new soccerFoot());
    person.Kick(); //output of expertKick();
}

This is just a suggestion - but there are a lot of ways to override behavior, which is what you appear to be trying to do, but you cannot override the actual method of another class without inheritance.
Answer: I think David Rodríguez has pointed the correct way of dealing with this situation:
class foot:
{
    /* Foot internals */
}

class person: /* Person has Foot and uses it to kick */
{
    foot *personsFoot;
    void kick() { clumsyKick(foot); };
}

class soccerPlayer: /* SoccerPlayer has Foot too, but his KICK is better */
{
    foot *soccerPlayerFoot;
    void kick() { expertKick(foot); };
}


How can I run a cmd.exe cmd file as an apache for windows cgi

Question: It sounds simple enough, but I'm having a hell of a time getting it to work.
Apache expects the first line of my script to say #!<path_to_cmd_shell>
And I don't want to use perl or anything else, I want to use c:\windows\system32\cmd.exe
But no go.
When I run the rest of the cmd file from the cmd prompt, it works as expected.
I even have a test cgi that does this:
@echo off
echo Content-Type: text/html
echo.
echo ^^^^hi from stu the cgi ^^

and that works.
But when I change the script to run another exe (whose output would be the cgi response) I get all sorts of premature end of script headers.
I'm guessing that it has something to do with the output of the exe not piping back through the shell's output.
Any idea how to make this go?
Answer: I think your guess is correct. The exe file probably writes to the screen rather than stdout.
Answer: Forgive me for saying this if I'm wrong, but does Apache know how to execute a CMD file?  In essence, I would expect you would have to give the script to apache in a manner it can understand.  Perhaps you'd have more luck attempting to have a perl script execute the CMD and stream the output that way instead of attempting to directly execute the CMD script.
Comment: The first thing I tried was the @echo off in the first line, that seemed to tip apache off to something, because when I take that out, it just dumps the file contents to the browser.
The other thing I tried was to put #!c:\windows\system32\cmd.exe  as the first line so it would use that as the shell, and it did run that, but the stdout part doesn't work.


Problem using module_load_include

Question: I need to use node_add(), but when I called it in my module I get the "undefined function" message.
So I'm trying to include it using module_load_include('inc', 'node', 'node.pages'), but I'm getting the error message:

Fatal error: Unsupported operand types in /var/www/vhosts/**.es/httpdocs/includes/common.inc on line 2946

Do you have any idea?
Comment: Maybe errors are below in your code. Try to comment your lines of code one by one and you will find which function called incorrect.
Comment: nop because if i comment the line with module_load_include it works although I get the message "undefined function"
Comment: But you could call `node_add()` in wrong way and got error when it was found
Answer: Maybe you are using an old version of PHP. Have you tried also running "php -l your_file.php". That will run just the parser to see if you have any php syntax problem.
Answer: I suggest you 3 method to  add a node programatically

first method
// required for Drupal 6
module_load_include('inc', 'node', 'node.pages');
// which nodeform you want
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node
$node = array(
 'uid' => $user->uid,
 'name' => (isset($user->name) ? $user->name : ''),
 'type' => $node_type,
  );
  // Invoke hook_nodapi and hook_node
  node_object_prepare($node);
 // Or you can also use an exiting node, for example
 // $node = node_load(123);
 // and the display the form:
 $output = drupal_get_form($form_id, $node);

second method
 module_load_include('inc', 'node', 'node.pages');
 $node_type = 'YOURNODETYPE';
 $form_id = $node_type . '_node_form';
 global $user;
 $node = array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => $node_type,
);
node_object_prepare($node);
print drupal_get_form($form_id, $node);

third method
module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
$output = drupal_render($form);

Problem using module_load_include


Parameter estimation with GMM

Question: I have estimated the parameters of normal distribution with GMM
and got the follwing results :
mean = -0.01168 , p-value = 0.83519
i'm bit confused in interpreting the result. can i say that the mean is zero as it is not statistically significant.
thanks
Answer: No, you cannot say it is 0. All you can say is that there is not much evidence that it isn't 0. More precisely, a p-value of 0.84 means that, if, in the population from which this sample was drawn there was no effect at all, the probability of getting a test statistic at least as extreme as this one, in a sample the size of the one drawn, is 0.84.
Comment: For us to be able to say what these mean, in any practical sense, you need to tell us a lot more. What are you modeling? What is your DV and IVs? Your last comment makes no sense with your origianl post, which is about a normal distribution and says nothing about time.
Comment: thanks , and the $Sd = 1.77$ with $p value = 0.0000$ how can i interpret this parameter
Comment: I can't tell for sure what Sd is, from what you've written.
Comment: sd = standard deviation.
Comment: secondly can we say that mean is stable with respect to time ?

Parameter estimation with GMM


why this POW loop keeps the initial values?

Question: I'm just starting to learn C. I wrote this beautiful little program that was meant to print "11111". But the pow function doesn't actualize the variable, that changes every time, that is being used in it.
I created the loop using if, goto and adding 1's. That's the only way I know to create a loop yet.
Can I overcome this problem using the same tools I've used?
Here's my code:
#include <stdio.h>
#include <math.h>

main (void)
{
     int b = 0;
     int a = 0;
     int c = 0;

     up:
     b = pow (10,a);
     c = c + b;
     a = a + 1;

     if (a = 6)
     {
         goto stop;
     }
     else
     {
         goto up;
     }

     stop:
     printf("%d\n",c);
 }

Comment: Even after indenting into a code block, your code has random blank lines, _very_ bizarre indentation, and is missing at least one line at the end. Please fix.
Comment: Why all the goto to implement a loop?  Why not something simpler, like `while (a=0;a<7;a++) { c += pow (10,a); }`
Comment: Have a look at `while` loops and try to restructure your code. The answer from Lightness Races in Orbit has identified the main cause of the problem.
Answer: if (a = 6)

That sets a to 6.
You probably meant:
if (a == 6)

Comment: @Robert: May not have warnings on. May not be using an IDE. May not be looking at the compilation output (wouldn't surprise me). May be ignoring it (also wouldn't surprise me).


Is ObjectDB JPQL different from normal JPQL

Question: I was discussing with someone about comparisons in JPQL, I gave him this link, http://www.objectdb.com/java/jpa/query/jpql/comparison, I think that ObjectDB uses the normal JPQL and so it sufficed the question. But someone told me that it is ObjectDB's JPQL so it is not useful, to a degree. Is this true because it doesn't seem that way in the link.
Answer: It is exactly the same JPQL.
In this specific documentation page, the right column in the first table is about Java and JDO operators  (as explained explicitly in the page), but everything else is about pure JPA and JPQL.
Every JPA implementation, and ObjectDB as well, includes various extensions to the standard. But extensions of ObjectDB are explicitly specified as extensions in the documentation.


Describing the following region in the complex plane $|z-1|<\Im(z)$

Question: I was considering the region shown in the title
$$|z-1|<\Im(z)$$
I took the approach of considering $z\in \mathbb{C}$ and taking $z=x+iy$ then breaking down the inequality as follows
$$|z-1|=\sqrt{(x-1)^2+y^2}<y$$
squaring both sides
$$(x-1)^2+y^2<y^2$$
but this gives $(x-1)^2<0$ which is impossible therefore I said that the set of points satisfying the inequality would be empty, but my professor keeps telling me that the solution is wrong am I missing something
Comment: You are right and your professor is wrong. More simply $|\Im z| =|\Im (z-1)| \leq |z-1| <\Im z$ is impossible.
Answer: Suppose we consider $|z - 1| \le r$ in the complex plane. Then let $z = a + bi$ and so we have $\sqrt{(a - 1)^2 + b^2} \le r$ or $(a - 1)^2 + b^2 \le r^2$. This is the set of points that have a circle with center $(a + 1, b)$ and radius $r$ as the boundary. In other words, you may think of it as concentric circles with that center and radii from $0$ to $r$, inclusive. If we change the inequality to being strict, then it the set of concentric circles with radii $0$ to $r$ without including $r$.
Clearly, this is perfectly fine for $r > 0$, but if $r < 0$, then this does not make sense. So consider $\text{Im}(z) > 0$, since we may exclude the other case entirely. If $\text{Im}(z) > 0$, then we proceed with your steps and find that $(a - 1)^2 + b^2 < b^2$, which indeed also has no solutions.
There was mistake when you squared both sides of the inequality since you assumed that $y > 0$.
Since neither $\text{Im}(z) > 0$ or $< 0$ has solutions, we can conclude there are no solutions at all. (note $b = 0$ immediately gives $(a - 1)^2 < 0 $)
Comment: " There was mistake when you squared both sides of the inequality since you assumed that y>0": y MUST be positive (strictly, I may add) because it is STRICTLY greater than a positive (or nonnegative)quantity (a square root).
Comment: @insipidintegrator We are starting from an arbitrary complex number. That complex number is not guaranteed to have a nonnegative imaginary part. What you said is true in the sense that is how we arrive at a contradiction.
Comment: Ffim the question statement itself the one can conclude y>0.
Comment: To be honest I'm not quite sure what you are arguing here. I excluded $y < 0$ at the very start: "Clearly, this is perfectly fine for >0, but if <0, then this does not make sense."

We started with a statement, and we showed the statement is bogus by considering all possible $y$ in different intervals.
Comment: Meaning that it is a mistake of rigor (not showing why $\Im(z)$) cant be less than zero ?
@politeproofs
Comment: @Eulerroid I'm not sure. I can't say for certain, but in your solution, you did assume that $y > 0$. Now, of course this has to be the case, but I think for such a problem I think part of the solution is explicitly excluding a case like that.


swift - how to modify property of object from another class?

Question: i added a second viewcontroller to my main viewcontroller. When my second viewcontroller want to modify the object of main viewcontroller its getting error.
first viewcontroller
class ViewController: UIViewController {

    var uview:UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        uview = UIView(frame: CGRectMake(55, 175, 100, 100))
        uview.backgroundColor = UIColor.greenColor()
        self.view.addSubview(uview)

        var sec = second()
        self.addChildViewController(sec)
        self.view.addSubview(sec.view)
        sec.didMoveToParentViewController(self)
    }
}

second viewcontroller
class second: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var button:UIButton = UIButton(frame: CGRectMake(55, 55, 100, 100))
        button.backgroundColor = UIColor.redColor()
        button.addTarget(self, action: "press", forControlEvents:UIControlEvents.TouchUpInside)
        self.view.addSubview(button)
    }

    func press(){
        var first:ViewController = ViewController()
        first.uview!.backgroundColor = UIColor.purpleColor()
    }
}

Error message
fatal error: unexpectedly found nil while unwrapping an Optional value

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

Answer: With this line var first:ViewController = ViewController() you are creating another instance of ViewController and not referencing to the view controller you want.
As you have a parent/child relationship, you can do
if let parent = self.parentViewController as ViewController {
    /*do something with parent variable*/
}

One more thing, your crash happens because your new instances had not load its view already (viewDidLoad) and your uview variable is not set.
Comment: if viewcontroller doesnt have parent/child relationship,i still want to change then property of object from another viewcontroller ,so what i want to do?
Comment: Create a custom variable of type ViewController in `second`. Then do `var sec = second();    sec.<#ViewController#> = self` in your first view controller.


Is this tab notation a "soft pulloff"?

Question: I've seen several tab notations like the following:

What does it mean? You hold the original note for a bar, then do a "soft pulloff" (take your finger off the fretboard) for the next bar?
Answer: That's how I understand it, yes. I often find this sort of notation in tapping parts.
Make sure that you time the first note's vibrato to the moment where you transition to the second note with a pulloff. ;)

Is this tab notation a "soft pulloff"?


Unable to send push notifications from Firebase console using react-native-firebase

Question: I am trying to send a push notification to my ios device from the Firebase console by token ID. I am using react-native-firebase to allow the app to perform actions based on the notification events. I followed the instructions to integrate the SDK and have set up the APNS certs etc:
http://invertase.io/react-native-firebase/#/installation-ios
My firebase.js config file looks like this:
import RNFirebase from 'react-native-firebase';

const configurationOptions = {
  debug: true
};

const firebase = RNFirebase.initializeApp(configurationOptions);

export default firebase;

My main React component looks like this:
import React, { Component } from 'react'
import {
  Text,
  View,
  Alert,
  Platform
} from 'react-native'
import firebase from './firebase'

export default class extends Component {

  constructor(props) {
     super(props)
     this.state = {
        token: ''
     }
  }

  componentDidMount() {
     firebase.messaging().getToken()
        .then((token) => {
           this.setState({ token })
           console.log('token: ', token)
        })

     firebase.messaging().getInitialNotification()
        .then((notification) => {
           console.log('Notification which opened the app: ', notification)
        })

     firebase.messaging().onMessage((message) => {
        console.log('messaging', message)
     })

     firebase.messaging().onTokenRefresh((token) => {
        console.log('Refreshed FCM token: ', token)
     })
  }

  render() {
     return (
        <View style={{ marginTop: 22 }}>
           <Text>{this.state.token}</Text>
        </View>
     )
  }

}
I successfully get the token when the component mounts and then use that in the Firebase console to send a notification, but the notification is not received. I am using a real device, not and iPhone. I am using a development provisioning profile with Push notifications enabled and the remove notifications back ground entitlement enabled successfully, along with the appropriate development APNs certificate, which has been uploaded to the firebase console.
Why am I not receiving the notification on the device?
Answer: Okay, it looks like it was just ignoring the remote notifications because I had not requested permissions from the user. Just needed to do that via the SDK:
componentDidMount() {
    firebase.messaging().requestPermissions()
    firebase.messageing().getToken().then...


Edit tabs missing on Views block

Question: I'm new to Drupal and despite making progress over the last few days I've hit a problem.
I've got two custom content types linked with an entity reference. I'm using the Views module to create a relationship between them and output the results as a block. The block also uses a contextual filter.
All of this is working ok, I add the block to a page and the content is shown exactly as expected, except I don't get the edit/view tabs that I usually see above nodes.
If I navigate to the node by itself via the 'find content' page the edit tabs are there, but once inside the block they're missing.
I found one post mentioning that edit tabs don't appear as standard when contextual filters are used, but the post was three years old, had no solution or discussion, and and nothing to confirm whether it was actually true.
I know I can add an edit link from the Fields menu in Views but it makes the UI look inconsistent.
I'd appreciate if someone could let me know:

What exactly stops them from appearing.
What to read up on to get them working again.

Thanks.
Answer: You found the answer already. The contextual links you're looking for are just not provided by the views module when using fields (except when you add them explicitly). If you use the node row style in views they're provided through the node system of drupal. For convenience and many more options there's a module for it: Custom Contextual Links
Answer: Thanks for confirming. The editing behaviour seemed so obviously inconsistent (always visible tabs for some things and hover menus for others) that I wasn't sure if I'd made an error somewhere. I guess my question should be 'how do I make the admin UI more consistent'. It looks like the module you recommended might help me with that. If I can get rid of tabs completely and have hovers for everything it should be a bit more intuitive to use.
Incidentally, it looks like this has been addressed in Drupal 8. Some discussion here for anyone interested: https://www.drupal.org/node/1874664

Edit tabs missing on Views block


Pandas: keep group in data when a value in the group falls within a range

Question: I have values in a group and if the value falls within the range 5 to 25, then I want to keep this group in the data.
Based on Pandas: remove group from the data when a value in the group meets a required condition, I wrote this:
dfnew = df.groupby('groupname').filter(lambda x: (x['column2']>=5) & (x['column2']<=25))
When I use this, there's this error:
filter function returned a Series, but expected a scalar bool
Then I also tried:
dfnew = df.groupby('groupname').filter(lambda x: 5<= x['column2']<=25)
But it gave error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
And then I tried:
dfnew = df.groupby('groupname').filter(lambda x: (x['column2'].any()>=5) & (x['column2'].any()<=25))
Which just returns an empty dataframe with the column names
I am very new to python and datascience (literally coded for a few days). Please explain what's going on and help! Thank you so much!!
Comment: Show a small `df`
Answer: I think you were almost there. You need to use max and min to test the values in the group. Here is an example with a toy dataset.
First the data:
import pandas as pd

data = pd.DataFrame(
    {
        'id': [1, 2, 3] * 3,
        'value': [3, 20, 21, 6, 24, 7, 21, 8, 50]
    }
)

data

Which gives us:
    id  value
0   1   3
1   2   20
2   3   21
3   1   6
4   2   24
5   3   7
6   1   21
7   2   8
8   3   50

Then use a group/filter pattern to retain only the groups where the min value in the group is greater than or equal to 5, and the max value in the group is less than or equal to 25. In this case, we expect only group 2 to be returned.
data.groupby('id').filter(lambda x: (x['value'].max() <= 25) & (x['value'].min() >= 5))

And that is what we get:
id  value
1   2   20
4   2   24
7   2   8


Qual a melhor forma de verificar a existência de um registro no banco de dados via aplicação?

Question: Hoje eu utilizo um método que envia um COUNT com o Id do registro como parâmetro para o banco de dados. Há uma forma melhor, talvez mais performática de fazer isso?
Answer: Olá, Seria bom que colocasse o código utilizado na aplicação.
Com acesso a banco de dados eu utilizo da seguinte maneira.
Select 1 from tabela where coluna=valor

Simples e Funcional.
Dados Adicionais:

Utilizando em Dados Reais
Tabela com 1.541.770 registros.
SGBD: PostgreSQL

Sendo pesquisado através de um campo que compõe a chave primaria
SELECT count(*) FROM parcela_prev WHERE  cor_cod = 'x'

Total query runtime: 916 ms.
  1 row retrieved.

SELECT 1 FROM parcela_prev WHERE  cor_cod = 'x'

Total query runtime: 949 ms.
  26299 rows retrieved.

No ambiente real deu pouca diferença, seguindo pela lógica em ambos os casos quando retorna 1 ou mais registros a primeira opção se tornou mais performática.
Comment: O que acontece se tivemos 50.000 registros que satisfazem esta condição?
Comment: Iria retornar 50 mil linhas, porém pelo que eu entendi da pergunta ele quer saber apenas se existe através de uma chave "id" então sempre retornaria 1, não sei se tem muito ganho ou diferença entre o Select 1, para Select Count(), visto que para 50 mil linhas o BD iria também fazer uma operação Contar.
Comment: @TobyMosque Editei minha resposta e efetuei a Operação com cada uma das maneiras, realmente a 1ª opção aparenta ser melhor com pouca diferença.
Answer: Até onde eu sei esta forma está boa e não há nada que traga melhora significativa. Basta isto mesmo:
SELECT COUNT(id) FROM tabela WHERE coluna = valor

Coloquei no GitHub para referência futura.
Mas isso só funciona se só quer verificar a existência mesmo. Se depois vai dar um INSERT, UPDATE ou fazer alguma outra coisa que depende da existência ou não do registro, então está fazendo algo errado porque pode incorrer em condição de corrida.
Answer: Conforme o @Andrew mencionou, prefiro usar também:
select 1 from tabela where coluna=valor

Por curiosidade, no SQL Server você pode precisar de algo assim se precisar criar um script SQL que precisa tomar alguma decisão em cima da existência de um registro:
if exists (select 1 from tabela where coluna=valor)
begin
    //SQL
end


How can I compare two 2D NumPy arrays of size 40k × 40k?

Question: I must compare 2 NumPy arrays of floats. Unfortunately of the order of  10^-3 or smaller, of size 40k × 40k. They must be identical. Can I directly print/mask the elements that differ?
I tried allclose and isclose:
>>> import numpy as np
>>> F_sp = np.load('./Matrix/Fmatrix.npy')
>>> F_org = np.load('./../Org/FMatrix.npy')
>>> print(" all close? {} ".format(np.allclose(F_sp,F_org,equal_nan=True)))
all close? False

>>> print(" is close? {} ".format(np.isclose(F_sp,F_org,equal_nan=True)))
is close? [[ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 ...
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]]

>>> print(" is close? {} ".format(np.isclose(F_sp,F_org,equal_nan=False)))
is close? [[ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 ...
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]]

>>> np.set_printoptions(threshold=sys.maxsize)
>>> print(" is close? {} ".format(np.isclose(F_sp,F_org,equal_nan=True)))
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
  print(" is close? {} ".format(np.isclose(F_sp,F_org,equal_nan=True)))
OverflowError: cannot serialize a string larger than 4GiB

Answer: If they must be identical, it is not necessary to check if the values are close, but simply if they are identical.
Using:
identical = F_sp == F_org

should give an array with true and false.
To print the elements that differ, use np.where(condition).
This will give an array with the elements that fill the condition.
Comment: Make sure to mark an answer as the correct answer when your question is answered; this way others know this too.


Showing that the Crank-Nicolson method is second order

Question: For the diffusion equation $\dfrac{\partial \rho}{\partial t} = D\,\Delta \rho$, I'm trying to show that Crank-Nicolson is second order. I've isolated the truncation error $\tau_i^{n+1}$ to be $ D\left(\frac{\rho(x_{i+1}, t_{n+1}) + \rho(x_{i-1}, t_{n+1}) - 2\rho(x_i, t_{n+1})}{2(\Delta x)^2} + \frac{\rho(x_{i+1}, t_n) + \rho(x_{i-1}, t_n) - 2\rho(x_i, t_n)}{2(\Delta x)^2}\right)$, but I'm having trouble actually showing that it's $O((\Delta t)^2 + O((\Delta x)^2)$.
How should I proceed? A simple hint (ie how to to the Taylor Series) would be just fine!
Thank you!
Comment: is $D$ the derivative or just a scalar?
Comment: Hint: try to develop each of the first long fraction near the point $(x_i,t_{n+1})$ and the second near $(x_i,t_n)$ up to fourth degree.
Answer: Taylor's in two variables:
$f(x,y)=f(a,b)+\sum_{1\le r+s\le n}\frac{\partial^{r+s}f(a,b)}{\partial x^r\partial y^s}\frac{(x-a)^r}{r!}\frac{(y-b)^s}{s!}+E_n(x,y)$
Where the error term $E_n(x,y)=\sum_{r+s=n+1}\frac{\partial^{r+s}f(\xi,\eta)}{\partial x^r\partial y^s}\frac{(x-a)^r}{r!}\frac{(y-b)^s}{s!}$
Where $(\xi,\eta)$ is some value on the line between the points $(a,b)$ and $(x,y)$.
And as the commenter pointed out you will probably need a fourth order approximation to cancel with the $(\Delta x)^2$ on the bottom of the fraction.


Using tensorflow.js to predict movie desirability based on genre

Question: using the default basic example of tensorflow.js website I'm trying to change it so by giving it an array that specifies movie genres it can predict if I will like the movie or not:
  // Define a model for linear regression.
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  // Prepare the model for training: Specify the loss and the optimizer.
  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  // Generate some synthetic data for training.

  //[action, adventure, romance]
  const xs = tf.tensor1d([1,1,0]);
  //target data should be rating from 1 to 5
  const ys = tf.tensor1d([3]);

  // Train the model using the data.
  model.fit(xs, ys).then(() => {
    // Use the model to do inference on a data point the model hasn't seen before:
    // Open the browser devtools to see the output
    model.predict(tf.tensor2d([1,0,0])).print();
  });

however, regarding the const ys = tf.tensor1d([3]); it throws an error telling me that Input Tensors should have the same number of samples as target Tensors. Found 3 input sample(s) and 1 target sample(s), but I want a prediction from an array[3] to a number from 1 to 5 and I don't know how to achieve this using this sample
Answer: The number of samples should match the number of targets, otherwise model can not learn. I updated your example, added another sample, and another target, and corrected the shapes.
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputDim: 3 }));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
// Generate some synthetic data for training.

//[action, adventure, romance]
const xs = tf.tensor2d([[1, 1, 0], [1, 0, 1]]);
//target data should be rating from 1 to 5
const ys = tf.tensor2d([[3], [2]]);

// Train the model using the data.
model.fit(xs, ys).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  // Open the browser devtools to see the output
  model.predict(tf.tensor2d([[1, 0, 0]])).print();
});

this compiles and produces the following result:
Tensor
     [[1.6977279],]

Comment: The way I see it you only changed `inputDim` parameter of the dense layer, is that correct?
Comment: @mohas also changed the shape of input `[[1,0,1,]]` and output `[[3]]`, and made them `tensor2d`


How to access items in other page's global Declarative Environment Record -- if possible?

Question: I'm trying to find out if a script running in a wrapper page can access and use certain JavaScript object types  defined on another page which is loaded in an iframe.  And no, I'm not trying to set up a phishing site :)
All global var declared variables as well as functions are added as properties on the other page's window object.  These I can access perfectly fine, assuming I've set up the security correctly (like cross site scripting etc.).  This way I can also use these from within the wrapping page by using e.g.
// other page's javascript:
function MyFunction() {return 42}

// wrapper page's javascript:
let iframe = document.getElementsById('frameID') // or such
window.MyFunction = iframe.contentWindow['MyFunction']
console.log(MyFunction()) // should say 42

But let and const declared variables, as well as class objects do not partake in this behavior.  They are only stored in the other page's global declarative environment record, and not in its global object environment record.
Is there a way that I can get access to the object types that are only stored in the other page's declarative environment record?  It wouldn't surprise me if it's browser dependent, or if its not possible at all due to security concerns or 'who needs that' or such...
For a little background: I'm the creator of Jazillionth, and I got some feedback from a user that tried to test a class object, which my script failed to access.  He could store the class in a regular var like var MyClass = class {} as a workaround, but that sort of defeats my purpose of Jazillionth (of not being obtrusive wrt your pages under test)...
Answer: You'll need to resort to eval (or similar) to access those variables that are not properties of the global object:
const iframeMyFunction = iframe.contentWindow.eval('MyFunction')

Comment: Very nice!  I tested it out, and it works perfectly.
Comment: Now I can relay it back to that user and put a smile on his face too :)


Scrapy spider cralws only one link per page

Question: I would like to scrape all the events data from http://www.nyhistory.org/programs/upcoming-public-programs. The events are paginated, 5 events per page. I created two rules: one to follow the next page and another one to follow events' details pages. So, I expect the spider first to enter each of the events' urls, to collect all the data I need from there and then to proceed to the next page, enter each of the events' urls and so on. However, for some reason my Spider accesses only one event from each of the pages, and that is the first event only. Please, see my code below
import scrapy
from nyhistory.items import EventItem
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from datetime import datetime
from w3lib.html import remove_tags
from scrapy.selector import Selector
import re

class NyhistorySpider(CrawlSpider):

    name = "events"

    start_urls = ['http://www.nyhistory.org/programs/upcoming-public-programs',]

    rules = [Rule(LinkExtractor(allow='.*?page=.*',restrict_xpaths='//li[@class="pager-next"]'), follow=True),
            Rule(LinkExtractor(restrict_xpaths='//div[@class="view-content"]/div[contains(@class,"views-row")]'), callback='parse_event_details',follow=True),
            ]

    def parse_event_details(self, response):

        base_url = 'http://www.nyhistory.org'

        item = EventItem()
        item['title'] = response.xpath('//div[@class="views-field-title"]//text()')[2].extract()
        item['eventWebsite'] = response.url

        details_area = response.xpath('//div[@class="body-programs"]')
        details_area_str = " ".join(details_area.extract())
        details_area_str_split = re.split('EVENT DETAILS|LOCATION|PURCHASING TICKETS', details_area_str)
        speakers_names_area = details_area_str_split[1]
        speakersNames = Selector(text=speakers_names_area).xpath('strong').extract()
        try:
            item['speaker1FirstName'] = speakersNames[0].split()[0]
            item['speaker1LastName'] = speakersNames[0].split()[1]
        except:
            item['speaker1FirstName'] = ''
            item['speaker1LastName'] = ''

        description = remove_tags(details_area_str_split[1]).strip()
        item['description'] = description

        try:
            address_line = remove_tags(details_area_str_split[2]).strip()
            item['location'] = address_line.split(',')[0]
            item['city'] = address_line.split(',')[-2].strip()
            item['state'] = address_line.split(',')[-1].split()[0]
            item['zip'] = address_line.split(',')[-1].split()[1]
            item['street'] = address_line.split(',')[1].strip()
        except:
            item['location'] = ''
            item['city'] = ''
            item['state'] = ''
            item['zip'] = ''
            item['street'] = ''

        try:
            item['dateFrom'] = self.date_converter(response.xpath('//span[@class="date-display-single"]/text()').extract_first(default='').rstrip(' - '))
        except:
            try:
                item['dateFrom'] = response.xpath('//span[@class="date-display-single"]/text()').extract()[1].split('|')[0]
            except:
                item['dateFrom'] = ''
        try:
            item['startTime'] = self.time_converter(response.xpath('//span[@class="date-display-start"]/text()')[1].extract())
            # item['endTime'] = self.time_converter(response.xpath('//span[@class="date-display-end"]/text()')[1].extract())
        except:
            try:
                item['startTime'] = self.time_converter(response.xpath('//span[@class="date-display-single"]/text()').extract()[1].split(' | ')[1])
            except:
                item['startTime'] = ''
        item['In_group_id'] = ''
        try:
            item['ticketUrl'] = base_url + response.xpath('//a[contains(@class,"btn-buy-tickets")]/@href').extract_first()
        except:
            item['ticketUrl'] = ''
        item['eventImage'] = response.xpath('//div[@class="views-field-field-speaker-photo-1"]/div/div/img/@src').extract_first(default='')
        item['organization'] = "New York Historical Society"

        yield item

    @staticmethod
    def date_converter(raw_date):
        try:
            raw_date_datetime_object = datetime.strptime(raw_date.replace(',',''), '%a %m/%d/%Y')
            final_date = raw_date_datetime_object.strftime('%d/%m/%Y')
            return final_date
        except:
            raw_date_datetime_object = datetime.strptime(raw_date.replace(',','').replace('th','').strip(), '%a %B %d %Y')
            final_date = raw_date_datetime_object.strftime('%d/%m/%Y')
            return final_date
    @staticmethod
    def time_converter(raw_time):
        raw_time_datetime_object = datetime.strptime(raw_time, '%I:%M %p')
        final_time = raw_time_datetime_object.strftime('%I:%M %p')
        return final_time

Answer: when using CrawlSpider the rules are as you mentioned for following the respective links "until" you find the ones that you actually want to get for an item.
But, how does the spider (or the rule) know when to stop? That is for the use of the callback and follow attributes. If you are using the callback then you don't need the follow (because callback specifies that that link needs to be handled as a response), and if you use the follow then you don't need the callback, because it tells the spider to continue on the quest for new links.
You'll have to define better rules and specify which ones to follow and which ones to return to a callback.
Comment: Thank you! In accordance with your suggestion, I modified my code like below and it works now!

    rules = [Rule(LinkExtractor(allow='.*?page=.*',restrict_xpaths='//li[@class="pager-next"]'), follow=True), Rule(LinkExtractor(restrict_xpaths='//div[@class="view-content"]/div[contains(@class,"views-row")]'), callback='parse_event_details'),]
Comment: So you have to use Rules, not possible without?
Comment: @JohnAndrews what do you mean? What are you trying to do? Rules are used with CrawlSpider
Comment: You have to use Rules in order to recursively scrape all the pages on a website? I used a simple example and noticed that also in my case it skips when it finds one use case. Thus I am looking for a concrete simple example how to expand this, that it doesn't stop when it finds one, but stops when found all urls


Drupal 7.x - Webforms and nodes

Question: I am using the webforms module and created a new webform.
Now my problem is... after I have created a specific content type, I would like to diplay this webform...
Imagine: Create a new event with title, start, end und location.
After this, Visitors should see the webform below:
webform contains attend=yes/no, name, email and a submit button that sends an email.
How can I achieve that?
Thanks!
Answer: Are you going to use the same webform for all your node events?
Then maybe you should consider creating a url pointing to your webform with parameters. In your webform you can catch the parameters with %get[parameter].
Although I should warn you that when I tried something similar I had this problem: Ampersand does not get urlencoded and breaks my GET parameters
Comment: Yes, one webform for all node events.

can I handover e.g. the event title to the webform?
Comment: Yes you can. In my scenario I had a View that displayed a table with available events along with a link to register to the event. The link was created dynamically using views. If your webform is name "registration" then you should link to it like this [site_link]/registration?t=[title]&d=[date]. You can add as I told you hidden components to your webform to grab the parameters from the url.

Drupal 7.x - Webforms and nodes


How to load image in image control and templatebinding using control template?

Question: I have a simple form where i have added a image control .Now i want to load image from local directory. I want to use templatebinding .How can i use image control through templatebinding ? Please give me suggesstion.
Answer: this may work for you
<code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Control Tag="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg">
        <Control.Template>
            <ControlTemplate>
                <StackPanel>
                    <Image Source="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}"/>
                </StackPanel>
            </ControlTemplate>
        </Control.Template>
    </Control>
</Page>
</code>
Comment: Its working fine but i want load image using relative path (../Images/Flower2.jpg).I am writing below code but its not loading the image .Image folder location is Myproject bin folder

  please help how it can be possible ?


Should you change the current directory in a shell script?

Question: I've always mentally regarded the current directory as something for users, not scripts, since it is dependent on the user's location and can be different each time the script is executed.
So when I came across the Java jar utility's -C option I was a little puzzled.

For those who don't know the -C option is used before specifying a file/folder to include in a jar. Since the path to the file/folder is replicated in the jar, the -C option changes directories before including the file:
in other words:
jar -C flower lily.class

will make a jar containing the lily.class file, whereas:
jar flower/lily.class

will make a flower folder in the jar which contains lily.class

For a jar-ing script I'm making I want to use Bourne wild-cards folder/* but that would make using -C impossible since it only applies to the next immediate argument.
So the only way to use wild-cards is run from the current directory; but I still feel uneasy towards changing and using the current directory in a script.
Is there any downside to using the current directory in scripts? Is it frowned upon for some reason perhaps?
Comment: I don't see why the animosity, since the `cd` is local to the subprocess. Try this: `pwd; (cd ..; pwd); pwd` and see that as you exit the subshell (denoted by the parentheses), the current directory is back to where it started. Whatever the script does (unless you `source` it as opposed to executing it), it won't matter to the user.
Comment: It's okay, just put it back to where it was when you've finished.
Comment: There are other programs that support changing directories, `tar -C dirname` and `find -execdir` are two examples.
Comment: A `goto` was an abomination because it was unrestricted, way back when. You could jump from one subroutine to another, which made a mess of the environment and induced serious brain damage to anyone who had to read the code later. They are perfectly fine when used situationally. Interestingly, the situations where they are acceptable almost perfectly coincide with places you can use exceptions (which preserve hierarchical structure of the program). You can notice the same kind of thing going on here - a `cd` can't affect a superprocess, and subprocesses are your own responsibility.
Comment: @Amadan I realize that, but Gotos work too, yet they are frowned upon. I was wondering if there is something similar here with changing directories in scripts.
Comment: @Amadan actually I've found `goto`s amusing recently, since in assembly you essentially *only* have `goto` flow control since there are no loops.
Comment: Of course you will use `goto` if you don't have other flow control. In current languages, we do have `if`, `while`, `throw`, function execution (`gosub`, if you will) - and given that, I have everything I need. Same with global variables - if that's all you have, fine. If you have local variables, closures, object members, then global variables suddenly look like the ugly cousin with bad B.O.
Answer: I don't think there's anything inherently wrong with changing the current directory from a shell script.  Certainly it won't cause anything bad to happen, if taken by itself.
In fact, I have a standard script that I use for starting up a Java-based server, and the very first line is:
cd `dirname $0`

This ensures that the rest of the commands in the script are executed in the directory that contains the script file itself (useful when a single machine is hosting multiple server instances), regardless of where the shell script was actually invoked from.  Without changing the current directory in the script, it would only work correctly if the user remember to manually cd into the corresponding directory before running the script.
In this case, performing the cd operation from within the script removes a manual step from the server startup/shutdown process, and makes things slightly less error-prone as a result.
So as with most things, there are legitimate uses for this sort of thing.  And I'm sure there are also some questionable ones, as well.  It really depends upon what's most appropriate for your specific use-case.  Which is something I can't really comment on...I always just let maven build my JAR's for me.
Comment: @Hawken: Please see [BashFAQ/028](http://mywiki.wooledge.org/BashFAQ/028) regarding the location of a script.
Comment: @Hawken - The question of _should_ is really up to you.  There's nothing to prevent you from doing so, though there are some _very_ obscure caveats that may come up as per Dennis's link above.  You just have to decide if you're happy to live with those caveats or not.  Personally they don't bother me, as I'd _much_ rather have a self-contained server deployment than a bulletproof solution that won't break if someone `mv`'s the script out from under me as I'm running it.  If another sysadmin is `mv`'ing my stuff around, then I've got more serious problems to worry about anyways.
Comment: yep, `\`dirname $0\`` was what I used as well, I was wondering whether or not I **should**.


Why are professional athletes allowed to compete in the Olympic games?

Question: When the International Olympic Committee was formed in 1894 by Pierre de Coubertin, he intended the athletes competing in the Olympics to only be amateur athletes.
The definition of an amateur athlete is someone who doesn't receive compensation:

Amateur sports are sports in which participants engage largely or
  entirely without remuneration. The distinction is made between amateur
  sporting participants and professional sporting participants, who are
  financially remunerated for the time they spend playing or training.

Why are professional athletes now allowed to compete in the Olympic games?
Answer: The IOC officially began allowing professional athletes to compete in the Olypmic Games in 1988, basically leaving it up to the individual sporting federations to decide if they would permit it. The only sports which continue to claim they are "amateur only" are boxing and wrestling, but even that's a bit of a misnomer: certain national boxing or wrestling Olympics committees pay out cash rewards, but since the fighters are not paid to fight, they are not considered professional.
This topic is actually the subject of an article by Simon Eassem, published for the Second International Symposium for Olympic Research. The entire publication is called Critical reflections on Olympic ideology though it seems to be pretty hard to find. But the basic factors behind the IOC's decision were:

In many sports, all of the truly dominant athletes are professionals; amateur athletes, especially in team sports, are "going pro" much younger, sometimes right out of high school. This means that the idea of the best athletes in the world competing in the Olympics was simply not true, since the best in the world were excluded.
A number of high profile "scandals" occurred due to the strict application of the definition of a professional. One notable example was Jim Thorpe, who won multiple medals in 1912. He had previously played semi-pro baseball, so even though his medals were not in baseball (he was a track & field athlete), his medals were stripped. In addition, many athletes were excluded from competing because they earned money as trainers or tutors, and not as competitors.
The whole idea of pure-amateur competition was rooted heavily in the aristocratic English public school. The original intent was that amateur athletes not only didn't play professionally, they didn't train professionally -- any sort of training was considered cheating. Clearly, by the 1970s, that idea was long since abandoned, and was considered an artifact of the English "class system".
Most importantly, IMO, was the fact that so many countries just flat out cheated. Eastern-bloc countries were notorious for skirting the edge of the rules by having state-sponsored "full time amateurs". Their Olympic athletes were given everything they needed to live and train, but were not technically paid to do it, and all the money came from the government. This put the Soviet countries at a distinct advantage over the privately-funded Western athletes for a long, long time.

Ultimately, the IOC just decided that excluding pro athletes made the games less interesting, less competitive, and less fair. It also helped that the Olympics were big business by that point, with television rights fees, sponsorship money and similar sources of income. Having huge, marquee-level celebrity athletes brought in lots more money.
Comment: In fairness to Mr. Thorpe, the IOC eventually decided they had overreacted and gave his medals back; unfortunately he had died 30 years earlier.
Comment: That explains the 1992 dream team then, doesn't it.
Comment: Your last point, BTW, was being copied by Western teams too; part of the USOC's job as of the late 70s if not earlier was to appropriate Federal monies to training and housing the US Olympic teams as they prepared for the Games. Otherwise it would have been even harder to attract the best amateur athletes to compete, for team sports especially where they all have to be in the same place at the same time.
Comment: Also worth considering that this controversy already existed in sport before Coubertin. For example WG Grace technically was an amateur cricket player but in fact was paid. Also that football (soccer) has tried a series of real messes of rules which try to increase the amateur-ness of the players without actually coming out and saying that (because then they'd get fourth-rate squads). For example in 1984 European and South American (i.e, strong) countries were limited in what professional players they could use, and others weren't.
Comment: Interesting - people often enquire on Stack Exchange about whether I'm named after or any relation to Jim Thorpe (no, and nope - I'd never even heard of him before said comments) - now I find out he's scandalous!
Comment: You strongly eluded to this but I feel it's worth saying explicitly "who wants to watch a bunch of amateurs compete when audiences are already used to watching professionals in sports everyday?"  It'd certainly make things like [this](https://www.youtube.com/watch?v=IEEENsZnu48) much more common place.
Answer: Several reasons:

The more compensation amateurs were allowed to receive, the more the definition between "amateurs" and "professionals" became indistinguishable (if it wasn't already).
Increased viewership.
$$$

Pierre de Coubertin, the founder of the International Olympic Committee (IOC) in 1894, had intended that Olympic competition should be among amateurs rather than professionals.
In the dictionary, "amateur" means:

a person who engages in a study, sport, or other activity for pleasure rather than for financial benefit or professional reasons.

However, in 1971, the IOC approved compensation for amateur athletes(1).
Eastern nations were sponsored to train and compete on a full-time basis by their governments. As a result, US athletes found it difficult to compete with athletes from eastern nations, resulting in the Ted Stevens Olympic and Amateur Sports Act in 1978 allowing US athletes to receive compensation.
Moreover, professionals had better brand-recognition than amateurs, as the following quote notes(2):

"The pros are there for a reason," the esteemed sports journalist Ron Rapoport, who has covered six Olympics ... "People will tune in to watch athletes they know. The pro athletes are pre-sold to the public, which means increased viewership."

After these developments, professionals became eligible for the Olympics(3):

After the 1988 Games, the IOC voted to declare all professionals eligible for the Olympics, subject to the approval of the international federations in charge of each sport.


Using D3 Charts in Apache Zeppelin

Question: I'm mostly using Scala for all my data engineering needs and I'm already feeling that there is not many support when it comes to using some good libraries that are available in Pyhton. One example is the plotting libraries. Seems like there is none in Scala. The ones that I find in GitHub like the matplotlib4j seems to be outdated or no one is working on it anymore.
I realized that we can use Javascript libraries and I came across D3 and I would like to try it out. I have this example below:
%angular

    <svg class="chart"></svg>

It renders what it should, but my question is how could I get the data from my Spark Scala into this Javascript? For example., I have the following scala tuple printed out from one of my DataFrame computations:
Threshold = 0.0, Features = 48
Threshold = 0.05, Features = 36
Threshold = 0.1, Features = 35
Threshold = 0.15, Features = 34
Threshold = 0.2, Features = 34
Threshold = 0.25, Features = 34
Threshold = 0.3, Features = 34
Threshold = 0.35, Features = 34
Threshold = 0.4, Features = 34
Threshold = 0.45, Features = 32
Threshold = 0.5, Features = 30

I would like to plot this with Threshold on the x-axis and Features on the y-axis. How could I do this?
Answer: d3's quite a low-level library that can let you build up very complex interactive visualisations using data to visual variable (usually svg element attributes) mappings.
However, I would suggest if you want to just use 'standard' charts like scatterplots, bar charts etc in javascript use a d3-based charting library like britecharts, billboard etc that have these available in a much more convenient and shorter syntax, rather than 're-inventing the wheel' by building them in d3 yourself where you'll have to plot the data, calculate the ranges/scales and set-up the axes (a surprising amount of work).
https://britecharts.github.io/britecharts/tutorial-scatter-plot.html
https://naver.github.io/billboard.js/
Others are available but these are actively maintained

Using D3 Charts in Apache Zeppelin


Ajax POST utilizando uma variavel e um objeto

Question: Olá, estou com problemas para enviar um POST, utilizando Ajax, só que o conteúdo tem que ser nesse formato:
name: 'Nome Candidato',
contents = {
'email': 'firstname.lastname@example.com,
'formacao': 'superior completo'
}

Ao fazer o POST pelo Postman, ele envia normalmente:

Porém ao fazer pelo HTML, retorna sempre erro 422 na URL.
var vNome = $("#nome").val();
var vEmail = $("#email").val();

var vData = {
    name : vNome
    <<<<<< Não sei o que colocar aqui >>>>>>
};

$.ajax({
    method: "POST",
    url: vUrl,
    data: JSON.stringify(vData)
})
.done(function(msg){
    $("#resultado").html(msg);
})
.fail(function(jqXHR, textStatus, msg){
    alert(jqXHR);
});

Answer:
O primeiro erro está aqui:

name: 'Nome Candidato',
contents = {
'email': 'firstname.lastname@example.com,
'formacao': 'superior completo'
}

Porque, aparentemente, você está tentando enviar um objeto, entretanto,
  a sintaxe de um objeto, em javascript, não é dessa forma aí (não digo por causa das aspas simples, por mais que dê certo, digo por causa da igualdade após a palavra contentes), mas sim desta, aqui, que é a correta sintaxe:

name: 'Nome Candidato',
contents: {
  email: 'email@example.com',
  formacao: 'superior completo'
}

Outra coisa: Ao enviar desta forma data: JSON.stringify(vData), seus
  dados serão enviados como string, mas não objetos, pois a função
  stringify converte um objeto para uma string.

Então, para corrigir, estou lhe enviando um código completo e testado, espero que lhe ajude.
index.php:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <input type="text" id="nome" autofocus>
    <input type="text" id="email">
    <input type="text" id="formacao">
    <button id="enviar">Enviar</button>

teste.php:
<?php
print_r($_POST);

print_r("\nChaves:\n\n");

print_r(array_keys($_POST));

print_r('
Saida:
');

var_dump('name =>'.$_POST['name']);

var_dump('contents[emai] => '.$_POST['contents']['email']);

var_dump('contents[formacao] => '.$_POST['contents']['formacao']);

/*Saída:

Array
(
    [name] => Taffarel
    [contents] => Array
        (
            [email] => Xavier
            [formacao] => sadfads
        )

)

Chaves:

Array
(
    [0] => name
    [1] => contents
)

string(15) "name =>Taffarel"
string(24) "contents[emai] => Xavier"
string(29) "contents[formacao] => sadfads"
*/

Ia esquecendo: a variável vUrl tinha algum valor no seu código?
Print:

REFERÊNCIA:
Ajax Form Data
Comment: Obrigado pela ajuda Taffarel. Realmente era o JSON.stringify. Obrigado!
Answer: var vData = {
    name : vNome,
    contents : {
        e-mail : vEmail,
        formacao : 'Superior completo'
   }
};

Comment: @DaniloKörber sua resposta é bem vaga, poderia explicar como ela supostamente responde a pergunta?
Comment: Eu continuo recebendo a mesma informação Danilo. Eu já fiz esse teste, acredito que seja uma variavel (name) e um objeto (contents)
Comment: Tenta tirar o JSON.stringify ou alterá-lo para JSON.parse


How to reset Services.msc console

Question: After updating to Internet Explorer 9 on a Server 2008 R2 SP1 box, I noticed that my services.msc console looked a little off.  If you check out the screenshot (http://www.flickr.com/photos/nosenseworrying/8614996608/in/photostream), you'll notice a huge gap at the top of the window before the list of services starts.
Is there any way to reset this window's display?  Functionally, everything seems to work OK, but I'm a little leery of this, because I'm not sure what other issues may be present on the system now.
I confirmed that IE9 was in fact the issue, because the issue goes away if I uninstall the update.
Any help is greatly appreciated.  Thanks!
Update: This is the closest I've gotten to finding anything similar to my case:
http://forum.kaspersky.com/index.php?showtopic=218082
Unfortunately, they just say it's due to an "improper" install of IE9 and don't go into any detail.  Basically, I'm still at a loss.
Comment: Does it do it when you select the "standard" tab at the bottom as well?
Comment: Hi Mike -- no it does not. The standard tab looks completely normal. I've been using that instead in the meantime, but it still really bothers me that the default tab is messed up.
Answer: Interesting..
Now, is it ONLY the services dialog that does this?   Do you see the same behavior if you were to open up the Computer Management MMC ( compmgmt.msc )?
While I do not know how to reset the view of the MMC, what you could do is create a new custom MMC (that is, as long as the services dialog is the only one with this issue) by doing the following

Start > Run > type mmc > press enter
File > Add/Remove Snap In
Select Services from the available snap ins
Click Add
Select Local Computer and click Finish
Click OK
Go to File > Save As
Save the file as Services.mmc (to wherever)
Add the Services.mmc to C:\Windows\System32 and just remember to
type services.mmc instead of msc
Comment: Thanks for the quick reply.  As far as I can tell, so far it is with services.msc only.  I've tried a couple other ones (including gpedit, and now compmgmt) and I don't see the same issue.

I actually thought of your proposal too -- great minds think alike.  Unfortunately, even in the MMC, it shows the same problem.  So odd!  Even stranger still, if I run this services.msc (or even mmc) from another server via UNC, the problem doesn't show up.  So, it's almost like there's nothing wrong with the mmc, but something else underlying.
Answer: You can reset the MMC by navigatng to <code>%APPDATA%\Microsoft\</code> and renaming "MMC" i.e. mmc.old. After a reboot it will be recreated with default settings.
Comment: Thanks for the suggestion.  Unfortunately, this did not resolve the issue.  No matter who I log into the server as, I see the problem, so it appears to be deeper than a user profile issue.  I'm not sure what files the IE9 install modified, but it sure did something odd here.
Answer: I found an old Windows XP website that tells you how to fix this.  I had the same issue.  You have to run "regsvr32.exe  jscript.dll" as administrator to correct this.
http://www.winhelponline.com/blog/fix-services-mmc-extended-view-blank-xp/
Comment: Thanks!  I was looking for a blog post like this and always came up empty.  Clearly your Googling skills are superior to mine ;)
Comment: My trick to finding it was that you have 2 views at the bottom in  services.msc, Extended (default) and Standard.  I search for these words without quotes "mmc extended view top of window"  Because this only appeared to be happening on Extended view I was able to narrow it down with that keyword.

How to reset Services.msc console


Is there a trick to compute this multinomial-looking sum?

Question: The series I want to sum has this form
$\displaystyle \sum_{} 1^{l_1}(1+c)^{l_2} (1+2c)^{l_3} \cdot \ldots \cdot  (1+(N-1)c)^{l_{N}}$
for some constant $c$ and positive integers $N$ and $L$. Here the sum is taken over all ordered (finite) sequences $(l_1,l_2, \ldots , l_N)$ that satisfy $l_1+l_2+ \ldots l_N = L$. There are exactly $ {L+N-1} \choose {N-1}$ such sequences and the same number of terms to sum.
The reason this looks like the multinomial formula is because it came out of something similar. In particular it came out of the similar formula for the order-$L$ derivative of a product of $N$ many functions. The only difference is those formulas have coefficients that depend on $(l_1,l_2, \ldots , l_N)$.
So this guy is screaming out that he wants to be recovered as a coefficient of something. For example if I were to add up all the terms $1,1+c,1+2c,\ldots, 1+(N-1)c$ I'd get $\frac{n(n-1)}{2}c$. Then I could take the $L$-th power to get
$\displaystyle \left (\frac{n(n-1)}{2}c \right )^L = \Big( 1 + (1+c) + \ldots + (1 + (N-1)c)\Big )^L = \sum {L \choose{l_1 , \ldots , l_N}} 1^{l_1}(1+c)^{l_2} (1+2c)^{l_3} \cdot \ldots \cdot  (1+(N-1)c)^{l_{N}}$
where the last line uses the multinomial formula. Then I can compute the right-hand-side by computing the much easier left-hand-side. Except the right-hand-side is the wrong series!
Is there any trick to get rid of these pesky coefficients? One idea I had was to replace each $(1+mc)$ with some function which, when differentiated $l_m$ times adds an exponent of $l_m$ and a constant factor that cancels out the multinomial coefficients in the product rule. That would work if the left-hand-side looked like some easy to differentiate function. Unfortunately I already know what that function looks like, and it is the function that I derived the series from.
Edit: If we write $[L,N]$ for the sum above he satisfies the recurrence $[L,N] = (1+(N-1))[L-1,N]$ + [L,N-1] if anyone has ideas for that. Generating functions maybe?
Comment: Your sum is the coefficient of $t^L$ in the power series $\prod\limits_{k=0}^{N-1} \dfrac{1}{1-\left(1+kc\right)t}$. While I doubt this has a nice explicit form, it looks closely related to some standard generating functions for Stirling numbers.
Comment: Stirling numbers give the answer for $c=1$. The general case can only be harder.
Comment: This looks like a problem you have collected from / inspired by some source. According to recent discussions in Meta, we are looking forward to including sources for all applicable questions. Can you provide the source by editing the question?Refer-https://math.meta.stackexchange.com/questions/29290/is-it-a-good-idea-to-include-source-from-where-a-question-is-taken
Comment: This question comes out of trying to compute a certain probability associated with linear combinations of exponential random variables. Of course it LOOKS like some classic Olympiad-type problem which is why I thought is was worth posting in case someone had seen it before.
Answer: For $c=1$ we have
$\displaystyle \sum_{} 1^{l_1}2^{l_2} 3^{l_3} \cdot \ldots \cdot  N^{l_{N}} = {{N+L} \brace N}$
are the Stirling numbers of the second kind.
Write $(L,N)$ for the sum above. For each $(l_1, l_2 \ldots , l_N)$ we have either $l_N \ge 1$ or $l_N = 0$. The sequences with the first property correspond to the sequences $(l_1,l_2, \ldots , l_{N-1}, l_N-1)$ with sum $L-1$. It follows the sum over all such sequences is $N(L-1,N)$. The sequences with the second property correspond to the sequences $(l_1,l_2,\ldots, l_{N-1})$ with sum $L$. It follows the sum over all such sequences is $(L,N-1)$. Thus we have the recurrence $(L,N) = $ $N(L-1,N) + (L,N-1)$.
By iterating the recurrence we can express any given $(L,N)$ in terms of some collection of values $(1, \widetilde N)$ and $(\widetilde L,1)$. It follows any doubly-indexed sequence $C^L_N$ that satisfies the same recurrence and has all $C^L_1 = (L,1)$ and $C^1_N = (1,N)$ must have all $C^L_N = (L,N)$.
For a similar reason we see $C^L_N =  {{N+L} \brace {N}}$ satisfies the recurrence. It remains to show each $(L,1) = {{L+1} \brace 1} $ and $(1,N) = {{N+1} \brace N }$.
Clearly each $(L,1) = 1$. Since there is exactly one way to partition a set of $L+1$ elements into exactly one subset we have ${L+1 \brace 1}=1$ as well.
By definition each $(1,N) = 1 + 2 + \ldots + N = N(N+1)/2$ by the well-known formula. To compute ${{N+1} \brace N }$ observe each partition of $N+1$ into $N$ subsets consists of $N-1$ singletons and $1$ doubleton. Thus ${{N+1} \brace N }$ is just the number of doubletons of $N+1$ which is just ${N+1 \choose 2} = N(N+1)/2$. This completes the proof.


Mensagem de sucesso depois de enviar mensagem por formulário

Question: Quero que depois que preenchido o formulário e clicado no botão "enviar" apareça uma mensagem informando que o conteúdo foi enviado com sucesso, na mesma página!
Vou colocar o meu código, agradeço a ajuda.

                                <form method="post" action="email.php" class="contact_form">

                                            <input id="nome" name="nome" type="text" class="contact_input" placeholder="Nome" required>

                                            <input id="email" name="email" type="email" class="contact_input" placeholder="e-mail" required>

                                            <input id="assunto" name="assunto" type="text" class="contact_input" placeholder="Assunto" required>

                                            <textarea id="msg" class="contact_input contact_textarea" name="mensagem" placeholder="Mensagem" required></textarea>

                                    <button id="enviar" type="submit" value="ENVIAR" onClick="Enviar();" class="contact_button">ENVIAR</button>
                                </form>

e o php, que está sendo direcionado para outra página
<?php

$para="email@example.com";
$subject="Contato pelo site";

$nome= $_REQUEST['nome'];
$email= $_REQUEST['email'];
$assunto= $_REQUEST['assunto'];
$msg= $_REQUEST['mensagem'];

$enviar="Mensagem de contato

";
$enviar.="
Nome:  $nome";
$enviar.="
email:  $email";
$enviar.="
Assunto:  $assunto";
$enviar.="
Mensagem:  $msg";

$header="Content-Type: text/html; charset- utf-8\n";
$header.="From: $email Replay-to: $email\n";

$mail = mail($nome,$email,$assunto,$msg);
if($mail){
    echo("Enviado com sucesso!");
}else{
    echo("Erro!");
}

?>

Comment: Você pode fazer isso com `AJAX`.
Comment: use **AJAX** para isso, e para fica melhor legível troque **$_REQUEST** por **$_POST**
Answer: Olá @JulianyGarcia, seja bem-vinda ao StackOverflowPT, há "n" formas de fazer isso, usando ajax, e fazendo post diretamente na página.
Eu recomendaria você a estudar Javascript, que é uma linguagem client-side. Acredito que usar ajax, é uma maneira melhor de enviar os dados, pois evita o recarregamento da página desnecessariamente.
É importante também considerar a validação do formulário, para que ele não chegue incompleto, e validar o e-mail para que a função email() não retorne um erro.
Eu recomendaria ao invés de utilizar a função mail, usar uma biblioteca tipo PHPMailer, assim você não corre risco de que seu formulário pare de funcionar, caso seu servidor desative a função por questões de segurança.
Vou apresentar duas soluções, e você veja qual prefere, para a primeira forma vou colocar uma condicional na página, e todo o conteúdo na mesma página:
1) SOLUÇÃO (Método POST básico):
Salve sua página como contato.php e coloque uma condição de POST:
<?php

if ($_POST) {
   $err= false;
   if($_POST['nome'] == ""){
    $err = true;
     echo " - O nome precisa ser preenchido.
";
   }
   if(($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) || !$_POST['email']){
    $err = true;
     echo " - preencha um email válido.
";
   }
 if ($_POST['assunto'] == ""){
    $err = true;
     echo " - preencha o assunto.
";
 }
  if ($_POST['mensagem'] == ""){
     $err = true;
     echo " - preencha sua mensagem.
";
  }
  if (!$err) {
     $para="email@example.com";
     $subject="Contato pelo site";

     $nome= $_POST['nome'];
     $email= $_POST['email'];
     $assunto= $_POST['assunto'];
     $msg= $_POST['mensagem'];

     $enviar="Mensagem de contato

";
     $enviar.="
Nome:  $nome";
     $enviar.="
email:  $email";
     $enviar.="
Assunto:  $assunto";
     $enviar.="
Mensagem:  $msg";

     $header="Content-Type: text/html; charset- utf-8\n";
     $header.="From: $email Replay-to: $email\n";

     $mail = mail($nome,$email,$assunto,$msg);
     if ($mail) {
        echo "
Enviado com sucesso!
";
     } else {
        $err = true;
        echo "
Ocorreu um erro no servidor
";
     }
  }
} else {
   echo "
Por favor, preencha o formulário abaixo:
";
}

?>

    <form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>" class="contact_form">

                <input id="nome" name="nome" type="text" class="contact_input" placeholder="Nome" required>

                <input id="email" name="email" type="email" class="contact_input" placeholder="e-mail" required>

                <input id="assunto" name="assunto" type="text" class="contact_input" placeholder="Assunto" required>

                <textarea id="msg" class="contact_input contact_textarea" name="mensagem" placeholder="Mensagem" required></textarea>

        <button id="enviar" type="submit" value="ENVIAR" class="contact_button">ENVIAR</button>
    </form>

2) SOLUÇÃO (método ajax):
Iremos criar um método de envio (há pessoas que gostam de utilizar uma biblioteca chamada jquery, mas eu prefiro utilizar javascript puro, ES5 ou ES6).
Ao submeter o formulário, você continuará na página e enviará sincronamente os dados por ajax no formato json, assim que o php tratar isso no lado servidor (server-side), você receberá no escopo do seu método o retorno no formato que você solicitou no seu xhr.responseType, no caso um json:

Coloque a cima do form:

Por favor, preencha o formulário:

E remova o método Enviar() do seu botão de submissão. Mude o type para button.
Ou se preferir manter submit, no método de click (actionSend), acrescente event.preventDefault() para que a página não seja recarregada e acrescente o parâmetro event no método actionSend, ficaria assim: function actionSend(event) { ... }
Na outra página: outra-pagina.php, você recebe os dados e responde em json:
 <?php

 $arr = array();

  if ($_POST) {
       $status = true;
       if ($_POST['nome'] == "") {
          $status = false;
          $arr[] = " - O nome precisa ser preenchido.";
       }
       if (($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) || !$_POST['email']){
          $status = false;
          $arr[] = " - preencha um email válido.";
       }
     if ($_POST['assunto'] == ""){
         $status = false;
         $arr[] = " - preencha o assunto.";
     }
      if ($_POST['mensagem'] == ""){
         $status = false;
         $arr[] = " - preencha sua mensagem.";
      }
      if ($status) {
         $para="email@example.com";
         $subject="Contato pelo site";

         $nome= $_POST['nome'];
         $email= $_POST['email'];
         $assunto= $_POST['assunto'];
         $msg= $_POST['mensagem'];

         $enviar="Mensagem de contato

";
         $enviar.="
Nome:  $nome";
         $enviar.="
email:  $email";
         $enviar.="
Assunto:  $assunto";
         $enviar.="
Mensagem:  $msg";

         $header="Content-Type: text/html; charset- utf-8\n";
         $header.="From: $email Replay-to: $email\n";

         $mail = mail($nome,$email,$assunto,$msg);
         if ($mail) {
            $status = true;
            $message = "Enviado com sucesso!";
         } else {
            $status = false;
            $message = "Ocorreu um erro no servidor";
         }
      }
    } else {
        $message = "Por favor, preencha o formulário abaixo:";
    }

    $result = array(
     'message' => $message,
     'status' => $status
    );
    if(!$status && is_array($arr) && count($arr) > 0) {
       $msg = implode('
', $arr);
       $result['message'] = $msg;
    }
    echo json_encode($result);

    ?>

Answer: A forma de resposta do Ivan Ferrer é a correta, realmente através de AJAX é a solução mais fácil, um padrão de mensagens que eu utilizo:
Sweet Alert 2
Importe esse JS na sua aplicação:

E no seu AJAX faça da seguinte forma:
swal({
    title: "Sucesso!",
    text: "Cadastro concluído com êxito",
    icon: "success",
    button: "OK"
    });


Android SharedPreferences remove first entry regardless the key

Question: I need to remove first entry of SharedPreferences in my Android app
I know I can use remove("key") but in this case I don't know the key, need it to be dynamic
The reason is that I'm storing array with 10-value capacity. When SharedPreferences contains 10 instances, it removes the first and adds new.
Answer: I would store your preference as a single entry as a json list or a simple comma separated list. Thereby it is much easier to work with.
For JSON you can use the gson library (part of android 3.0+) or download it from: http://code.google.com/p/google-gson/


Adding multiple nodes using a single form

Question: I want a user to be able to create n nodes of type "Photo Gallery Photo" using a single form.
The node would have the following fields:

name (For the entire upload; only shown once)
phone number (For the entire upload; only shown once)
town (For the entire upload; only shown once)
email (For the entire upload; only shown once)
title (per photo)
description (per photo)
photo (Image, per photo)
galleries (node reference checkboxes, per photo)

Is this possible?
Answer: Your question is so specific to your implementation; what you want to do is create a node with some single value fields and multiple images, each image with a title, description and nodereference.
It is the last part of the above that is actually the question: How do you add fields to an image?

The file entity module allows you to add fields to a file, but those fields are not available on the node edit form, you have to go to admin/content/file to add these values.
The Field Collection Module allows you to define a set of fields, so on your node you would define a field collection field which has an image, a caption, nodereferences or whatever. (not too clear...try it out)
Answer: You should write a module that saves a node for each set of values. That's doable.
Anyway that's a strange approach. I think i could be of more help knowing more details about your final purpose
Comment: This is not the answer. Please use comments.
Answer: I think it will work for you
Multi Node Add

This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly

In your Navigation menu (the menu with your username as title) you should see a link called Create multiple nodes, -- links to the URL http://<yoursite>/multi_node_add
Answer: Use the file entity module!
You can create a new content type called Album. Add the fields you want (name, phone number, town, email, images). Then using the file entity module, create a new file type or edit the already created one (Image) and add the fields (title, description). Every time you add a new photo to the Album, the image fields will show under the uploaded photo.


Autocorrelative parameter in GAM in R

Question: I'm looking at a dataset of the number of users who used a specific software over a period of a year. I also have a binary predictor in the model. There is substantial autocorrelation in the data, and so I'm trying to include a parameter to account for this. Currently, my model is as such:
gam_y <- gamm(Users ~ s(Date, k = 365) + binary_pred, data = player_numbers, method = "REML", correlation = corAR1())
However, this model still comes up with substantial autocorrelation. Am I specifying the AR1 term incorrectly, or is there likely to be a different problem? (I'm quite new to GAMs).
Thanks in advance!
Answer: This is possibly correct; you are not setting this up to be robust to data issues however. Ideally you would use corAR1(form = ~ time) where time is some variable ordering the observations regularly in time. If your data are in time order and regularly spaced when the model sees the data then how you have it will work, but if you have NAs in the data for example or data get out of order, relying on the ordering is a bad thing.
I'm not sure how you determined that there was strong residual autocorrelation as you didn't mention this, but most often people come to this conclusion because they look at the ACF of the residuals and it remains autocorrelated. Unfortunately this is often a mistaken assumption because the autocorrelation structure is only taken into account if you extract the normalized residuals and these are not the default in the resid() method for "lme" classed models. Use resid(gam_y$lme, type = "normalized") to access the residuals for checking residual autocorrelation.
If you did that already, then consider if the dependence structure in the residuals really is AR(1) or whether higher order or whether moving average terms are needed in the correlation structure. You can specify these with the corARMA() correlation structure but model fitting will be a lot slower as there aren't the same computational tricks available that are used by corAR1().

Autocorrelative parameter in GAM in R


Does a Bessel sequence not being a frame mean that $\sum_n|\langle f,f_n\rangle|^2>B\|f\|^2$ for some $f\in H$?

Question: I'm posting this question again because I'm still confused about the answer!
A sequence $\{f_{n}\}_{n\in I}$ is called a Bessel sequence in a Hilbert space $H$, if there exists $B>0$ such that
$$\sum_{n\in I}|\langle f,f_{n}\rangle|^{2}\leq B\|f\|^{2}$$
for all $f\in H$.
Now my questin is: if a given sequence is not Bessel sequence, does it mean that
given $B>0$, there exists (a non-zero) $f\in H$ such that
$$ \sum_{n\in I}|\langle f,f_{n}\rangle|^{2}> B\|f\|^{2}$$
Thanks!
(old post: If a sequence is not a frame)
Comment: So just to be sure: if we pick another $B$ we would find another $f\in H$ satisfying the second relation, and so forth, right!
Comment: This is the negation that $\{f_{n}\}_n$ is a Bessel sequence and  the negation do not make sense if $f=0$ because both sides are zero.
Answer: The sequence $\{f_n\}$ is not a Bessel sequence if for all integer $N$, we can find $g_N\in  H$ such that for all integer $N$, $$\sum_{n\in I}|\langle g_N,f_n\rangle|^2> N \lVert g_N\rVert^2,$$
exactly what you mean.


ShellShock - Unable to update CentOS 5.7

Question: [user@server1 ~]$ wget http://mirror.centos.org/centos-5/5/updates/x86_64/RPMS/bash-3.2-33.el5.1.x86_64.rpm

[user@server1 ~]$ sudo rpm -Uvh bash-3.2-33.el5.1.x86_64.rpm
warning: bash-3.2-33.el5.1.x86_64.rpm: Header V3 DSA signature: NOKEY, key ID e8562897
Preparing...                ########################################### [100%]
        package bash-3.2-33.el5.1.x86_64 is installed

[user@server1 ~]$ exit

[user@server1 ~]$ rpm -q bash
bash-3.2-32.el5
bash-3.2-33.el5.1
[user@server1 ~]$ bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
[user@server1 ~]$ foo='() { echo not patched; }' bash -c foo
not patched
[user@server1 ~]$

Please help....
Comment: Why are you not using yum to install packages?
Comment: Good point on my answer @EEAA.  Deleted.  The RPM you're trying to install was the half-patch that doesn't address the issue fully.

You want to install `http://mirror.centos.org/centos-5/5/updates/x86_64/RPMS/bash-3.2-33.el5_11.4.x86_64.rpm`.
Comment: I did exit already and logged back in. Still the same. I can't reboot it right now. Yum update bash is not fetching any updates. Anyway I want to fix this manually.. Any other suggestions?
Answer: Use yum to update your system.
yum update bash

If it tells you 'No packages marked for update' try rebuilding the yum cache then updating:
yum clean all
yum makecache fast
yum update bash

If that still doesn't work then it might be a problem with the mirror you're using.  Try pointing your yum configuration directly to "mirror.centos.org" in the '/etc/yum.repos.d/CentOS-Base.repo' file:
sudo sed -i -e 's/^mirrorlist=/#mirrorlist=/' -e 's/^#baseurl=/baseurl=/' /etc/yum.repos.d/CentOS-Base.repo

Note: I'm providing this sed command assuming your 'CentOS-Base.repo' file has "baseurl" commented out and that it points to "mirror.centos.org".
Then run yum clean all, yum makecache fast, and yum update bash again.


Unable to compare calculated number with idential number?

Question: I'm working on a vector class. While testing the vector class, I ran into a failed test case when comparing the magnitude of a unit vector with 1.
When comparing them, they both appear to be 1, so what would cause this test to fail?
I have cut out as much as possible to get down to the root cause of the problem. I could just cast the numbers to strings and compare those, but that would only fix the test case, allowing the problem to show up again later down the line.
I'm using Lua 5.1 interpreter (to identify the root cause), bundled with LuaRocks.
local v = 0.70710678118655^2 + 0.70710678118655^2
print(v, v == 1)

v == 1 should be true, not false.
Comment: I did not think it was a floating point error since it still displayed both numbers as `1`. Would it just not display the remaining digits if they are small enough?
Comment: Related: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
Answer: When converting a float to a string, Lua rounds off to only 15 significant digits. Try making it 17 digits to get an exact representation.
local v = 0.70710678118655^2 + 0.70710678118655^2
print(("%.17g"):format(v), v == 1)

Output:
1.0000000000000071  false

Answer: Of course this is an examble of Is floating point math broken.
For more explanation: execute this code
local half = 0.50
local doubleHalf = half + half
if doubleHalf == 1 then
    print('doubleHalf is one')
else
    print('doubleHalf differs '.. doubleHalf - 1 ..'from one')
end
--> doubleHalf is one

local rootHalf = math.sqrt(half)
print('rootHalf is a '.. type(rootHalf) ..' with value', rootHalf)
--> rootHalf is a number with value    0.70710678118654

local square = rootHalf^2
print('square is a '.. type(square) ..' with value', square)
--> square is a number with value    0.5

if square == half then
    print('square is half')
else
    print('square differs '.. square - half ..' from half')
end
--> square differs 1.110223E-16 from half

vector_length = square + square
if vector_length == 1 then
    print('vector length is one')
else
    print('vector length differs '.. vector_length - 1 ..' from one')
end
--> vector length differs 2.220446E-16 from one

Any computer working with values will calculate with a limited precission.


Accessing a Entity Refererenced field of the current node

Question: I have to render a field of a node that is inside a content type in Drupal 8.
I have a content type called summary that has a field, called field_content that is an Entity reference field for unlimited items of a specific content type (article)
I'm able to get the current node and handle the field_content, but I cant access each of referenced items  inside  of this type.
Also I have tried to debug the field_content with  kint but the browser crashes (I suppose that it happens becasue the data dump is very big) and I can't access the inner properties (I have to get a field called field_desc_text inside each article).
I need the node or the nid to load it  of each of this inner items.
This is what i've tried:
       $currentNode = \Drupal::routeMatch()->getParameter('node');
    foreach ($currentNode->get('field_content') as $nodeRef)
    {
      kint($nodeRef); //*This debugs the entire referenced node, but there is no sight of my desired fields
      die;
     // kint($nodeRef[0]); *Cannot use object of type Drupal\\Core\\Field\\Plugin\\Field\\FieldType\\EntityReferenceItem as array
     // kint($nodeRef->get('title')); *Uncaught PHP Exception InvalidArgumentException: "Property title is unknown."

     die;

    }

And this is the output of the kint($currentNode):
https://mega.nz/#!Fogx0LpC!CYvc6YSRs1ZcgOAc4RCfDo5iVqjBLYckvuFEUgqRGx8
Thanks in advance!
Comment: `kint but the browser crashes`, you need to lower your max level [follow this answer](http://drupal.stackexchange.com/questions/224928/how-to-make-use-of-devel-debugging-functions-on-large-or-complex-objects#224931)
Answer: You can access the entities referenced by an entity reference field using the following code.
$currentNode = \Drupal::routeMatch()->getParameter('node');
$entities = $currentNode->get('field_content')->referencedEntities();

The value returned from referencedEntities() is an array of objects that implement EntityInterface.
See the documentation and the code used by EntityReferenceFieldItemList::referencedEntities() for more details.


Count Number of comment per user in my custom php website

Question: My website is a place to write things, i mean share posts. it is a custom php development.
i Want to count the number of Comments each user in my website.
 i have a table named comments
with this  structure:
id
name
date
storyid
title
content
userid
accepted
Someone can help me to find a way to count a comments for each user? in php..
Thank you guys..
Comment: which field is comment in table
Comment: using SQL COUNT and grouping by userid would seem the obvious thing to do
Answer: Try this query:
select count(comment) as comment from TABLE where user="USERNAME or ID"

Answer: There's a lack of specifics in your question so I'm going to make a couple of assumptions. I'm assuming that userID is the user who wrote the comment and accepted is a boolean that we want to be true.
Your database query would look like this:
SELECT COUNT(DISTINCT `id`) AS 'comments', `userid` FROM `comments` WHERE `accepted` = 1 GROUP BY `userid`

This will return a result table of two columns, the userid and the number of comments that have been accepted.
Answer: Looks like a SQL question... try the select above.
SELECT userid, COUNT(*) as commentsQuantity FROM comments GROUP BY userid

Maybe filter the "accepted" too.
@Strawberry pointed right. I altered the SQL replacing the * with userid


How to theme maintenance page for omega subtheme?

Question: Drupal's "Theming the Drupal maintenance page" gives a good overview for theming the maintenance page for 'normal' themes:

Copy modules/system/maintenance-page.tpl.php to your theme's templates directory
In the settings.php file, enable the $conf['maintenance_theme'] variable
Copy you page.tpl.php contents into maintenance-page.tpl.php and edit as necessary

But my site uses an Omega subtheme, so I don't have a page.tpl.php (well, it's not quite the same as these instructions are anticipating).  I'm a little lost among all the omega templates & regions.
How do I theme my omega subtheme's maintence page to look like the rest of my site?
Comment: It'd be good to know what version of Omega you're using, things are very different between v3 and v4
Comment: Good point.  I'm working with Omega 3.x
Answer: There's always a parent template, even if you don't see it in your base_theme.
The inheritance will go:

omega_subtheme template of NAME
then omega template of NAME
then drupal core template of name

So you'll need to copy the drupal core templates. They can be found in
DRUPALROOT/modules/system

You can find page.tpl, maintenance-page.tpl.php and all the base templates.


svn command not found for specific user

Question: I am implementing a system for exporting the source code from my svn server to the client's server (where the web is going to be hosted).
I asked my client to install subversion in his machine to be able to use the "svn export" command from his server command line via ssh.
I don't know how he has his server configured... I tested this in other local machines/servers, and I am able to retrieve the code from my server remotely, but in his server I get the error:
svn command not found
I told him to test with his user the "svn" command to check if it works, and he says that is ok for him "prompting type svn help... blabla". So I assume that is a permission issue.
What I have to tell him to do in his server to be able to access the svn command there? I tried to test it locally and in my server, but every new user I add (even with useradd and no specific permissions/groups) is able to access to the svn command, so I have no clues.
His machine is an Ubuntu 10.04.2 LTS
Any help appreciated.
EDIT------------------------------------
Is ok to add ~/bin to $PATH and ln -s /usr/bin/svn to ~bin/svn?
Is ok to give an user in visudo NOPASSWD rights to a specific command (usr/bin/svn in this case), to be able to use "sudo svn"? This should do the trick.

P.S. Excuse my English, it isn't my native language.
Comment: He needs to have his $PATH set to include the path to svn.
Comment: Read my edit if you can, please. Is ok to do that? Thank you!
Comment: You should NOT have him use sudo to run svn. If he does that, all his svn commands would be run as root, not as the user. This is probably not what you want!
Comment: does `/usr/bin/svn` work?
Answer: This is not the answer to your problem, but further investigation steps. I didn't have much space and formatting in the comment.
I would investigate that user's startup scripts, like .profile or .bashrc to see if the path is altered. You can try to ask your customer to log in with SSH. The following commands show on my server that svn command is available for invocation
:~> echo $PATH
/home/djechelon/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/usr/games
:~> whereis svn
svn: /usr/bin/svn /usr/share/man/man1/svn.1.gz

Explanation: the first command shows the active PATH in Linux, and the second tells me where svn executable is located. Forget the svn.1.gz which is for man command.
Usually svn binary is in /usr/bin, which is usually under PATH. If your customer set up the machine and/or SVN differently then you might find something different.
Please bear in mind that you or your customer must log in to the server with the same account having trouble.
Comment: bash-4.1$ echo $PATH --> /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games  <--- Apparently /usr/bin where the svn command is, is in my $PATH, but if I try access it I cannot. An ls over /usr/ only lists the "lib" folder, so I have a very restricted user I suppose. Another solution I have thinked is via sudo/visudo, giving NOPASSWD rights to my user over the /usr/bin/svn command. I don't know if is that ok in terms of security? Thank you!
Comment: You may be in some kind of jailed shell , in that case sudo won't work either. I suggest you export the code on your own machine, then ftp/scp/etc to the server. It will be much easier.

svn command not found for specific user


Change domain name for a multi site

Question: I currently have a Drupal 7 Multi-Site. In my sites folder, the domains are like this:
winatlife.guide
journal.winatlife.guide
store.winatlife.guide

I need to change the domains to this:
blog.blessingsjournal.com
journal.blessingsjournal.com
store.blessingsjournal.com

In addition, my root drupal folder is changing from win-at-life to blessingsjournal.
I have made all these changes. When I visit any of domains, I get the following error message:
Forbidden

You don't have permission to access / on this server.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

What could be chasing this? I haven't changed any of the permissions on the Drupal install.

Steps I have tried
1) Database Update
This StackOverflower answer says that the domain is hardcoded in the database and it provides a query to fix it. I have run the query, but it does't seem to have done anything.
It was written in 2010, so maybe it's for Drupal 6?
2) Make a sites.php file
According to this Drupal Groups thread, in Drupal 7 multisites, you need to put a file called sites.php in the root sites directory. (In that directory there is an example.sites.php which can be used as a template).
I made a sites.php file and used the new domains but it had no effect. (Nb I did not need to use such a file before the domain change)
3) Checking .htaccess
My .htaccess is set as follows:
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

Comment: What did you put in sites.php?
Answer: I was having problems because I was making a copy of the original site and then updating the code in the copy. For some reason the code was not copying properly. The databases were also not exporting properly from PHPmyadmin.
This is how I fixed it:

My site was in hosting that had Cpanel. So using Cpanel I made an archive of the site. I then downloaded the archive, renamed it and then uploaded to create a new copy of the site. This copy was a perfect replica of the original, so it had no problems.
For the databases, I used this command to export them via mysql in the command line:
mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME > dump.sql

In this command, you mustn't have a space after -p. So your command might look like this:
mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

I then created new databases.
Finally, I imported the code into the new databases using this command
mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME < dump.sql

Change domain name for a multi site


HTML being removed when rewriting field in Views

Question: I have completely stripped all my views/blocks down so they only produce exactly what I put into them..but I created a view and rewrote the fields and this part of my code will not print exactly as it is here:

Instead, when the block is rendered I get:

So it strips away come of my code. Does anyone know how I can get round this problem?
Comment: Have you tried PHP code?
Answer: Adding a class and then the style to your stylesheet is the normal practise.  Quick fix
.slides-full-screen-image {
Background-image:  url....
}
If you have more calls to that class where you don't want the image then you should add an additional class name.
Comment: Thanks but that means I cannot use the backend of Drupal to upload images, as the file names needs to be in the CSS. In this case it's a parallax website.
Comment: Does that mean you set up an empty class for .slides-full-screen-image and edit in firebug ; you can't get the image to display even if you use the full image url ? Inc Http://wwww.you website etc