Accessing pyomo variables with two indices

Question: I have started using pyomo to solve optimization problems. I have a bit of an issue regarding accessing the variables, which use two indices. I can easily print the solution, but I want to store the index depending variable values within a pd.DataFrame to further analyze the result. I have written following code, but it needs forever to store the variables. Is there a faster way?
<code>df_results = pd.DataFrame()
df_variables = pd.DataFrame()

results.write()
instance.solutions.load_from(results)

for v in instance.component_objects(Var, active=True):
    print ("Variable",v)
    varobject = getattr(instance, str(v))

    frequency = np.empty([len(price_dict)])

    for index in varobject:
        exist = False
        two = False
        if index is not None:
            if type(index) is int:
                #For time index t (0:8760 hours of year)
                exists = True #does a index exist
                frequency[index] = float(varobject[index].value)
            else:
                #For components (names)
                if type(index) is str:
                    print(index)
                    print(varobject[index].value)
                else:
                    #for all index with two indices
                    two = True #is index of two indices
                    if index[1] in df_variables.columns:
                        df_variables[index[0], str(index[1]) + '_' + str(v)] = varobject[index].value
                    else:
                        df_variables[index[1]] = np.nan
                        df_variables[index[0], str(index[1]) + '_' + str(v)] = varobject[index].value

        else:
            # If no index exist, simple print the variable value
            print(varobject.value)

        if not(exists):
            if not(two):
                df_variable = pd.Series(frequency, name=str(v))
                df_results = pd.concat([df_results, df_variable], axis=1)
                df_variable.drop(df_variable.index, inplace=True)
            else:
                df_results = pd.concat([df_results, df_variable], axis=1)
                df_variable.drop(df_variable.index, inplace=True)
</code>
Comment: Try to avoid writing to the dataframe directly, it is very slow. Store all rows in a list or dict and only create the dataframe at the end
Answer: with some more work and less DataFrame, I have solved the issue with following code. Thanks to BlackBear for the comment
<code>    df_results = pd.DataFrame()
    df_variables = pd.DataFrame()

    results.write()
    instance.solutions.load_from(results)

    for v in instance.component_objects(Var, active=True):
        print ("Variable",v)
        varobject = getattr(instance, str(v))

        frequency = np.empty([20,len(price_dict)])

        exist = False
        two = False

        list_index = []
        dict_position = {}
        count = 0

        for index in varobject:
            if index is not None:
                if type(index) is int:
                    #For time index t (0:8760 hours of year)
                    exist = True #does a index exist
                    frequency[0,index] = float(varobject[index].value)
                else:
                    #For components (names)
                    if type(index) is str:
                        print(index)
                        print(varobject[index].value)
                    else:
                        #for all index with two indices
                        exist = True
                        two = True #is index of two indices
                        if index[1] in list_index:
                            position = dict_position[index[1]]
                            frequency[position,index[0]] = varobject[index].value
                        else:
                            dict_position[index[1]] = count
                            list_index.append(index[1])
                            print(list_index)
                            frequency[count,index[0]] = varobject[index].value
                            count += 1
            else:
                # If no index exist, simple print the variable value
                print(varobject.value)

        if exist:
            if not(two):
                frequency = np.transpose(frequency)
                df_variable = pd.Series(frequency[:,0], name=str(v))
                df_results = pd.concat([df_results, df_variable], axis=1)
                df_variable.drop(df_variable.index, inplace=True)
            else:
                for i in range(count):
                    df_variable = pd.Series(frequency[i,:], name=str(v)+ '_' + list_index[i])
                    df_results = pd.concat([df_results, df_variable], axis=1)
                    df_variable.drop(df_variable.index, inplace=True)
</code>


Name instance tag not applied when calling run-instance JSON in python awscli

Question: i'm experiencing a strange issue with using of AWS CLI tools (awscli python module awscli-1.11.136, awscli-1.11.177). When calling 'run-instances' action with --cli-input-json argument, instance is not Tagged with the Name tag i specify in a call. Example of the call: aws ec2 run-instances --cli-input-json file://test-1c.json.
The test-1c.json contains following TagSpecifications:
"TagSpecifications": [
        {
            "ResourceType": "instance",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "test-1c"
                }
            ],
            "ResourceType": "volume",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "test-1c"
                }
            ]
        }
    ]

Volume is properly tagged with the specified Name tag, but instance is not.
When calling the same using command line arguments, it works properly:
aws ec2 run-instances \
--image-id ami-123456 \
--instance-type t2.micro \
--placement AvailabilityZone=eu-central-1b \
--security-group-ids sg-123456 \
--subnet-id subnet-123456 \
--private-ip-address 172.31.0.1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=test-1c}]' 'ResourceType=volume,Tags=[{Key=name,Value=test-1c}]'{code}

Is there a bug in the JSON's run-instances awscli python module functionality or am i doing anything wrong?
Thanks in advance for any help!
Answer: There is a problem with your JSON structure.
Your TagSpecifications array only has a single tag object in it. That one object has 2 ResourceType and 2 Tags properties, the 2nd of which (for the volume) is overriding the 1st (for the instance). This is the cause for the failure.
Add missing },{ into your structure before "ResourceType": "volume",
Such as
"TagSpecifications": [
        {
            "ResourceType": "instance",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "test-1c"
                }
            ],
        },
        {
            "ResourceType": "volume",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "test-1c"
                }
            ]
        }
    ]


Dompdf generate with bootstrap and yii2

Question:

Hi, i'm using a framework yii2 with a component DomPDF to generate pdf's from a  GridView::widget to generate a table with bootstrap. but my pdf doesn't look like a bootstrap table and i don't know why, please somebody help me
i use this template:
<?php
/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

/*
 * Variáveis Globais
 */
$tituloPrincipal = $this->params['tituloPrincipal'];
//$tituloSecundario = $this->params['tituloSecundario'];
//$utilizador = $this->params['utilizador'];
//$breadcrumb = $this->params['breadcrumb'];
/*
 * *** *** ***
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/styleImpressoes.css" rel="stylesheet" type="text/css" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
        <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

                            <?php echo $tituloPrincipal; ?>

                <?php
                echo $content;
                ?>

the view:

<?= Html::encode($this->title) ?>

    <?php // var_dump($dataProvider);die;  ?>
    <?=
    GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'assunto_r',
            'descricao_r',
        ],
        'showFooter' => true,
         'tableOptions' =>['class' => 'table table-striped table-bordered'],
    ]);
    ?>

the controller:
$pdfGen->render('impressao/impressaoAssuntoA4', [
    'dataProvider' => $dataProvider,
]);

Comment: Share what you tried
Comment: I add my code up in the comment. it seems the dompdf doesn't work with bootstrap
Comment: I replace:

For:

And now obtain this error:
Illegal string offset 'hex'
Answer: dompdf will not perfectly render a bootstrap-based layout, but it should be able to render a majority of the styling. Your issue is likely not related to using bootstrap but to the stylesheet not loading.
Please note that I do not know much about Yii, so my analysis is based on some quick google-fu and my knowledge of dompdf.
In your template you reference the stylesheet as follows:
<link href="<?php echo Yii::$app->request->baseUrl; ?>/css/styleImpressoes.css" rel="stylesheet" type="text/css" />

Yii::$app->request->baseUrl retuns a relative url for the application root (e.g. the path to the root of your web app). Because of how you are loading your document into dompdf the assumption is a URL without protocol and domain are relative to the running script on the file system.
Your URL reference (<?php echo Yii::$app->request->baseUrl; ?>/css/styleImpressoes.css) parses as "/css/styleImpressoes.css" which translates to the path on the filesystem. The easiest fix is to add a protocol and domain to your references using Yii::app()->getBaseUrl(true), e.g.
<link href="<?php echo Yii::app()->getBaseUrl(true); ?>/css/styleImpressoes.css" rel="stylesheet" type="text/css" />

You could also pass in a full filesystem path (maybe using something like YiiBase::getPathOfAlias('webroot')), but if you're sharing this template between web views and PDF rendering that would be problematic.
Comment: I replace:  For:  And now obtain this error: Illegal string offset 'hex
Comment: Now *that* is an error with dompdf's processing of the bootstrap styling. This issue has been addressed in the latest stable version of dompdf.

Dompdf generate with bootstrap and yii2


How to wrap email addresses to fit in fixed width box

Question: I have a problem, see the image below:

As you can see, the text is overflowing instead of breaking the text into a new line. My question is: How can I solve this issue?
The text is being inputted via CKEditor. I leave you with the code:
<fieldset>
    <legend><?php echo $myData09 ?></legend>

<?php echo $myData10 ?>

<?php echo $myData11 ?>

<?php echo $myData12 ?>

</fieldset>

Answer: The email addresses are too long and won't wrap as is. You could replace the displayed email address with 'Email' and link it to their address using mailto.
Or you could use word-wrap: break-word or one of the options in this article.
-ms-word-break: break-all; /* Be VERY careful with this, breaks normal words wh_erever */
word-break: break-all; /* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;

Comment: Glad you figured it out. It'll be nice when these typography helpers are more standard.
Comment: Now that is something I did not know about. Thank you very much for that knowledge! I did solve the situation by typing personname [@] email.com and so it will remain because of your warning -ms-word-break: break-all; but I will definitely be watching over the evolution of this CSS rule. Thanks!


What is the relationship between the Archimedean Property and Calculus?

Question: My textbook begin with a chapter dedicaded to the Real Numbers. It introduces firstly integers and rational numbers, then it introduces the irrational numbers, which appeared in the first place as a necessity of expressing the length of incommesurable line segments. To my understanding, all of this helps to introduce the notion of continuity of a variable, which is put into work when treating the continuity of a variable dependent of another variable (if we restrict ourselves to single-valued functions).
The Archimedean Property is stated as follows (or as it is written in my textbook):

Given any number $c > 0$, there exists  a natural number $n$, such that $n > c$.
Given any positive number $\epsilon$, there always exists a natural
  number $n$ such that the inequality  $1/n < \epsilon$ is fulfilled.

The last statement is the first one with $c = 1/\epsilon$. Although I understand what is meant by it (I think it can readily be proved by contradiction), what I'm not getting is how the Archimedean Property fits in the preparatory material preceding that dealing with supremum, infimum and then with continuity and limits.
Does it have something to do with the concept of limit, perhaps?
Answer: Yes, the proof of this argument uses the fact that a non-empty subset bounded above in $\mathbb R$ has a supremum.
As an example using this notion try to show that $$\lim_{n \to \infty} \frac{n}{n^2 + 1} = 0$$
And also that $$0 =\inf \Big\{\frac{1}{n} ; n \in \mathbb N\Big\}$$
The fact that $\mathbb R$ is a complete ordered field, makes possible the idea of finding a number such as the limit or the infimum from the examples above.
Comment: @AaronMaroja, The Archimedean property is not valid for any ordered field: see [this](https://en.wikipedia.org/wiki/Non-Archimedean_ordered_field) for example. True, that such fields are 'bigger' than $\Bbb R$, but they exist.
Comment: @Silent You're right, I edited. One may consider the subset of polynomials $f/g$ suh that $g$ is nonzero and the leading coefficients of $f$ and $g$ have the same sign. It is an ordered field but any rational function $f/1$ is a bound for the constant rational functions of the form $n/1$, with $n \in \mathbb Q$.
Comment: Feel free to ask any questions.
Comment: So if $\epsilon$ is very small, $1/\epsilon$ is very big, but we always can pick a $n \in \mathbb{N}$ such that the A.P holds, right? This enables to deal with the notion of the limit without violating the A.P itself (since $(-\infty, \infty) = \mathbb{R}$). Am I understanding this?
Comment: Yes, you're on the right track. The idea of supremum and infimum are very important to the theory of calculus, and A.P. is a tool that enables us to find certain limits.
Comment: Thanks (:. Another thing I've been reading (and that Ittay also pointed outer below) is that we can't deal with infinitesimals in classical calculus. Does it mean that we can apply the properties of the field axiom to some number $\frac{\Delta y}{\Delta x}$ but not $\frac{dy}{dx}$? Does it mean the A.P allows us to turn a quantity in a ordered field $K$ into one that is not? If so, that would be pretty neat (:.
Answer: (I have written this before)
Proving the Archimedean principle first for ${\mathbb R}$, using the  $\sup$, is in a way cheating. This principle is already present in ${\mathbb N}$ and should be proven from the Peano axioms.
Archimedean principle for ${\mathbb N}$: Given natural numbers $x\geq 1$ and $y\geq0$ there is an $n\geq1 $ such that $n\>x>y$.
Proof. This is true for $y=0$ and all $x\geq1$. Assume that it is true for some $y\geq0$ and all $x\geq1$. Consider now $y+1$ and an arbitrary $x\geq1$. By the induction assumption there is an $n\geq1$ with  $n\>x>y$, and putting $n':=n+1$ we have
$$n'\>x=n x+x>y+x\geq y+1\ .$$
It is not difficult to extend this from ${\mathbb N}$ to ${\mathbb Q}_{>0}$ and then to ${\mathbb R}$.
Answer: The Archimedean property states that the real numbers do not posses infinitely large number, nor does it have infinitesimals. It's a fundamental property of the reals setting it apart from what are known as nonstandard models of the reals. So the relationship between it and calculus is that classical calculus states no infinitesimals exist, and thus takes the reals of be an Archimedean field. In nonstandard analysis the reals do have infinitesimals, and thus are not an Archimedean field.
Comment: I've been looking for more information about it and found this: [Non-standard analysis](http://en.wikipedia.org/wiki/Non-standard_analysis). Does it mean I have to consider the A.P. as a kind of constraint that prohibit us to apply the properties used with numbers in an Archimedean Ordered Field (i.e. $\mathbb{R}$)? The axioms of ordered field applies to $\frac{\Delta y}{\Delta x}$ but not to $\frac{dy}{dx}$, for example?
Answer: The classical calculus as developed by the pioneers of mathematical analysis like Leibniz and Euler exploited numbers called infinitesimals (the term was possibly introduced by Leibniz himself). These are numbers that violate the Archimedean property when compared to $1$.  Thus, adding an infinitesimal to itself finitely many times produces a number that is again an infinitesimal.  Thus the number systems used by the pioneers of analysis were non-Archimedean.
At the end of the 19th century a different approach to analysis was developed by Cantor, Dedekind, Weierstrass, and others.  In this approach one only uses the Archimedean complete ordered field. Some of the arguments and procedures of the pioneers of the calculus have to be reformulated in this approach using long-winded paraphrases that make the subject harder to learn.
An approach to calculus using infinitesimals is developed in Keisler's textbook.


How to get the last $n$ digits of Ackermann function?

Question: The Ackerman function is defined as follows:
$$A(m,n)=
\begin{cases}
 n+1,& m= 1\\
 A(m-1,1), & m>0, n=0\\
      A(m-1, A(m,n-1)), &m,n>0
\end{cases}$$
Is it possible to get the last few digits of Ackermann function?

I refer to the method in this article: Is this the correct way to compute the last $n$ digits of Graham's number?
If the iterations are large enough, the last 10 digits will be fixed at 3432948733.
But in many cases the number of iterations of the function is not so large.
Is there a more suitable algorithm to deal with the case of Ackerman function?
Answer: The Ackermann function is known to have the form
$$A(m,n)=2\uparrow^{m-2}(n+3)-3$$
to which the problem boils down in largely the same manner to finding the eventual last digits of
$$2\uparrow^2k$$
for large $k$ in much the same manner as the provided link, though you will have to take care of the fact that $2$ and $10$ are not relatively prime. A direct computation shows that the last $n$ digits of this should remain constant for $k\ge n+2$.
When the arguments are sufficiently small, then a more direct computation can be used instead.


Showing the existence of subsequences

Question: Let $E$ be a complex Hilbert space. Let $(x_n)_{n}\subseteq E$ and $(y_n)_{n}\subseteq E$ such that $\|x_n\|=\|y_n\|=1$.
Assume that $\forall\, \theta<1$, there exists $n_{\theta}$ such that $|\langle x_{n_{\theta}}\; ,\;y_{n_{\theta}}\rangle|> \theta$.

How we can show the existence of  $(x_{n_k})_k$ and $(y_{n_k})_k$ two subsequences of $(x_n)_{n\geq1}$ and $(y_n)_{n\geq1}$ such that
    $$\displaystyle\lim_{k\longrightarrow\infty}|\langle x_{n_k}\; ,\;y_{n_k}\rangle|=1.$$
  How we construct $n_k$ such that $n_{k+1}>n_k$?

Thank you!!
Answer: For all $\theta_k=\frac{k}{k+1}<1$ there exists $m$ such that
$$
|\langle x_{m},y_{m}\rangle|>\frac{k}{k+1}
$$
Set
$$n_1=
\inf\left\{ m\in\mathbb{N}: |\langle x_{m},y_{m}\rangle|>\frac{1}{1+1}\right\}
$$
and
$$n_{k+1}=
\inf\left\{
m\in\mathbb{N}:
m>n_{k}
\mbox{ and }
|\langle x_{m},y_{m}\rangle|>\frac{(k+1)}{(k+1)+1}
\right\}
$$

Showing the existence of subsequences


How to broadcast RDD in PySpark?

Question: Is it possible to broadcast an RDD in Python?
I am following the book "Advanced Analytics with Spark: Patterns for Learning from Data at Scale" and on chapter 3 an RDD needs to be broadcasted. I'm trying to follow the examples using Python instead of Scala.
Anyway, even with this simple example I have an error:
my_list = ["a", "d", "c", "b"]
my_list_rdd = sc.parallelize(my_list)
sc.broadcast(my_list_rdd)

The error being:
"It appears that you are attempting to broadcast an RDD or reference an RDD from an "
Exception: It appears that you are attempting to broadcast an RDD or reference an RDD from an
action or transformation. RDD transformations and actions can only be invoked by the driver, n
ot inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) i
s invalid because the values transformation and count action cannot be performed inside of the
 rdd1.map transformation. For more information, see SPARK-5063.

I don't really understand what "action or transformation" the error is referring to.
I am using spark-2.1.1-hadoop2.7.
Important Edit: the book is correct. I just failed to read that it wasn't an RDD that was being broadcasted but a map version of it obtained with collectAsMap().
Thanks!
Answer:
Is it possible to broadcast an RDD in Python?

TL;DR No.
When you think what RDD really is you'll find it's simply not possible. There is nothing in an RDD you could broadcast. It's too fragile (so to speak).
RDD is a data structure that describes a distributed computation on some datasets. By the features of RDD you can describe what and how to compute. It's an abstract entity.
Quoting the scaladoc of RDD:

Represents an immutable, partitioned collection of elements that can be operated on in parallel
Internally, each RDD is characterized by five main properties:

A list of partitions

A function for computing each split

A list of dependencies on other RDDs

Optionally, a Partitioner for key-value RDDs (e.g. to say that the RDD is hash-partitioned)

Optionally, a list of preferred locations to compute each split on (e.g. block locations for an HDFS file)

There's not much you could broadcast as (quoting SparkContext.broadcast method's scaladoc):

broadcast[T](value: T)(implicit arg0: ClassTag[T]): Broadcast[T] Broadcast a read-only variable to the cluster, returning a org.apache.spark.broadcast.Broadcast object for reading it in distributed functions. The variable will be sent to each cluster only once.

You can only broadcast a real value, but an RDD is just a container of values that are only available when executors process its data.
From Broadcast Variables:

Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks. They can be used, for example, to give every node a copy of a large input dataset in an efficient manner.

And later in the same document:

This means that explicitly creating broadcast variables is only useful when tasks across multiple stages need the same data or when caching the data in deserialized form is important.

You could however collect the dataset an RDD holds and broadcast it as follows:
my_list = ["a", "d", "c", "b"]
my_list_rdd = sc.parallelize(my_list)
sc.broadcast(my_list_rdd.collect) // <-- collect the dataset

At "collect the dataset" step, the dataset leaves an RDD space and becomes a locally-available collection, a Python value, that can be then broadcast.
Comment: Nice answer but it's always essential to give the warning on using collect with large RDDs, specially for new users.
Comment: Isn't collecting this dataset the same as not making it an RDD in the first place?
Answer: you cannot broadcast an RDD. you broadcast values to all your executors nodes that is used multiple times while process your RDD. So in your code you should collect your RDD before broadcasting it. The collect converts a RDD into a local python object which can be broadcasted without issues.
sc.broadcast(my_list_rdd.collect())

When you broadcast a value, the value is serialized and sent over the network to all the executor nodes. your my_list_rdd is just a reference to an RDD that is distributed across multiple nodes. serializing this reference and broadcasting this reference to all worker nodes wouldn't mean anything in the worker node. so you should collect the values of your RDD and broadcast the value instead.
more information on Spark Broadcast can be found here
Note: If your RDD is too large, the application might run into a OutOfMemory error. The collect method pull all the data the driver's memory which usually isn't large enough.

How to broadcast RDD in PySpark?


Computable 2D random-ish function with scale-invariant features

Question: I'm looking for a function; probably vaguely related to fractals, the Weierstrass function, etc.  Here's the motivation.  Say I'm developing a game, similar in ways to Minecraft: there's an infinite world, randomly generated.  However, my overall impression in Minecraft is that once you zoom out a ways, the world becomes kindof uniform.  I could be wrong, but I don't think there are any hugely massive deserts or the like.  I wish to see if it can be done differently.  What I would like, what I suspect exists, but what I'm not sure how to generate, is a function $F:R^n\rightarrow R$ with ideally the following properties:

Features at any scale
Continuous
Random-ish
Computable

Suppose that I use such a function over $R^n$ to determine, say, the "corruption" of an area in the game.  You might be in a relatively fine area, with a few small patches of slight corruption scattered around nearby, and a few hundred feet away there'd be a larger area of deeper corruption, and a billion blocks away there's a massive sinkhole of horrible corruption a million blocks in diameter - and maybe this is all taking place in the foothills of a trillion-block-diameter mountain of holy land or something.  Since the function is computable, each block can determine its own level of corruption without having to look to one of its neighbors, which would make million-block-diameter features infeasible.  Is there a function that could work for this?  Can I contort the Weierstrass function into a usable form, perhaps, or is there something more inherently appropriate?
Answer: One way to do this is to hash grid coordinates for use as parameters for Perlin noise.  Combine a few "octaves" of noise at different frequencies to get fractal structure.  It's deterministic noise because the hashing from coordinates (used as pseudo-random number generator) is deterministic.  I found some example code with images, there is also the libnoise coherent noise library.


Equation of Normal?

Question: I got a question that I need help on:
Q1: The curve C has the equation $2x+3y^2+3x^2y=4x^2$.
The point P on the curve has coordinates $(-1,1).$
(a): Find the gradient of the curve at P.
So I did: $\frac{d}{dx}(2x+3y^2+3x^2y=4x^2$
$2+6y\frac{dy}{dx}+6xy+3x^2\frac{dy}{dx}=8x$
$\frac{dy}{dx}=\frac{8x-2}{6y+6xy}$
Using the coordinates (-1,1)
$\frac{dy}{dx}=\frac{1}{2}$
Q2: Hence find the equation of the normal to curve C at P, giving your answer in the form of $ax+by+c=0$.
I just don't understand what they want me to do, "normal to the curve C at P?"
Comment: Is your question "what does 'normal to the curve' mean?" or "how do I compute the normal to the curve?"
Answer: $2x+3y^2+3x^2y = 4x^2$
$2+6yy'+6xy+3x^2y'=8x$
$y' = \frac{8x-2-6xy}{6y+3x^2}$
$y'|_P = \frac{-8-2+6}{6+3} =\frac{-4}{9} $

Slope of the normal at $P$,  $\ \ $ $m = -\frac{1}{y'} = +\frac{9}{4}$

So the equation of the normal to the curve at $P\equiv(-1,1)$ is,
$y - 1 = m(x-(-1))$
$y - 1 = \frac{9}{4}(x+1)$
$4y-4 = 9x + 9$

$$9x-4y+13=0$$
Answer:
$2+6y\frac{dy}{dx}+6xy+3x^2\frac{dy}{dx}=8x$
$\frac{dy}{dx}=\frac{8x-2}{6y+6xy}$

That didn't go right, solving for $\frac{dy}{dx}$ gives:
$$\frac{dy}{dx}=\frac{8x-2-6xy}{6y+3x^2}$$
which evaluates to $-\tfrac{4}{9}$ at $(-1,1)$.

I just don't understand what they want me to do, "normal to the curve C at P?"

Now a normal (line) is perpendicular to the curve and thus to the tangent line, which means you want a slope corresponding to a line which is orthogonal to one with slope $-\tfrac{4}{9}$, that is $\tfrac{9}{4}$.
The problem is now reduced to setting up the equation of a line through the point $(-1,1)$ and with slope $\tfrac{9}{4}$:
$$y-1=\tfrac{9}{4}\left(x+1\right)$$

Equation of Normal?


Create bin intervals for a range in R for two different variables

Question: I would like to create two bin intervals, one for "Sales", and another for "PCT change", for the Product Category at the same time. The "PCT change" varies from -ve to +ve, and Sales range from $2000 to $19000.
Below is my dataset.
Product,Sales,PCT Change
A,4769,0.72
A,9841,0.14
A,2594,-0.37
A,15970,-0.76
A,18142,0.9
A,19935,0.63
A,19023,0.63
A,4097,-0.31
A,17318,-0.38
A,15533,1.14
A,7596,0.74
A,4099,0.06
B,7294,-0.45
B,5473,-0.81
B,5813,-0.31
B,4084,0.8
B,10446,0.08
B,3820,0.12
B,3208,0.02
B,10100,-0.82
B,19125,0.14
B,7332,0.9
C,1870,0.28
C,5949,-0.62
C,2739,0.98
C,14388,0
C,19307,1.08
C,12312,0.68
C,15120,0.08
C,16456,0.24
C,1063,0.64
C,3587,-0.07
C,15480,0.31
C,8934,0.79
C,10392,0.57
C,9705,0.87
C,18181,0.93
C,4700,-0.88
C,7392,-0.79
C,7504,-0.75
C,14943,1.06

Below is the code i am trying.
df %>%
group_by(Product) %>%
mutate(freq=cut(Sales, breaks=seq(0,8000,by=50), include.lowest=TRUE))

I am not sure how the breaks will help.. I don't want to create more than 10 size of different bin. Also, not sure how to append the "PCT change" as well in the same code, to bring in two different intervals.
Expected output:
Product,Sales,PCT Change
    A,4769,0.72, [4000-5000],[0.65-0.78]
    A,9841,0.14 ,[9000-10000],[0.04-0.17]
    B,2594,-0.37,[2000-3000],[-0.39- -0.31]

Also, i am looking options to customize the range, suppose i want to bring 4500-5000 instead of 4000-5000. I am running a simulation actually, hence want to explore feasible options.
Any leads would be highly appreciated.
Thanks,
J
Comment: It is unclear what you expect the out put to look like. It would help if you could post an example of the result you expect.
Comment: Hi,
I have provided the expected output.
Answer:  A potential solution with data.table
Not absolutely certain if you want to examine the data to find appropriate bins or if you simply would like to filter data. This solution addresses the former--if this is not what you are looking for, then edit your question and I'll update my solution.
library(data.table)

DT[, sales.bins := paste0(round(floor(Sales), -3)-1000, "-", round(ceiling(Sales),-3)+1000)]
DT[, PCT.change.bins := paste0(floor(`PCT Change`)-1, "-", ceiling(`PCT Change`))]

 This produces the following output:
> DT
    Product Sales PCT Change  sales.bins PCT.change.bins
 1:       A  4769       0.72   4000-6000            -1-1
 2:       A  9841       0.14  9000-11000            -1-1
 3:       A  2594      -0.37   2000-4000            -2-0
 4:       A 15970      -0.76 15000-17000            -2-0
 5:       A 18142       0.90 17000-19000            -1-1
 6:       A 19935       0.63 19000-21000            -1-1
 7:       A 19023       0.63 18000-20000            -1-1
 8:       A  4097      -0.31   3000-5000            -2-0
 9:       A 17318      -0.38 16000-18000            -2-0
10:       A 15533       1.14 15000-17000             0-2
11:       A  7596       0.74   7000-9000            -1-1
12:       A  4099       0.06   3000-5000            -1-1
13:       B  7294      -0.45   6000-8000            -2-0
14:       B  5473      -0.81   4000-6000            -2-0
15:       B  5813      -0.31   5000-7000            -2-0
16:       B  4084       0.80   3000-5000            -1-1
17:       B 10446       0.08  9000-11000            -1-1
18:       B  3820       0.12   3000-5000            -1-1
19:       B  3208       0.02   2000-4000            -1-1
20:       B 10100      -0.82  9000-11000            -2-0
21:       B 19125       0.14 18000-20000            -1-1
22:       B  7332       0.90   6000-8000            -1-1
23:       C  1870       0.28   1000-3000            -1-1
24:       C  5949      -0.62   5000-7000            -2-0
25:       C  2739       0.98   2000-4000            -1-1
26:       C 14388       0.00 13000-15000            -1-0
27:       C 19307       1.08 18000-20000             0-2
28:       C 12312       0.68 11000-13000            -1-1
29:       C 15120       0.08 14000-16000            -1-1
30:       C 16456       0.24 15000-17000            -1-1
31:       C  1063       0.64      0-2000            -1-1
32:       C  3587      -0.07   3000-5000            -2-0
33:       C 15480       0.31 14000-16000            -1-1
34:       C  8934       0.79  8000-10000            -1-1
35:       C 10392       0.57  9000-11000            -1-1
36:       C  9705       0.87  9000-11000            -1-1
37:       C 18181       0.93 17000-19000            -1-1
38:       C  4700      -0.88   4000-6000            -2-0
39:       C  7392      -0.79   6000-8000            -2-0
40:       C  7504      -0.75   7000-9000            -2-0
41:       C 14943       1.06 14000-16000             0-2
    Product Sales PCT Change  sales.bins PCT.change.bins

 Find unique bins with the following:
> unique(DT$sales.bins)
 [1] "4000-6000"   "9000-11000"  "2000-4000"   "15000-17000" "17000-19000" "19000-21000" "18000-20000" "3000-5000"   "16000-18000"
[10] "7000-9000"   "6000-8000"   "5000-7000"   "1000-3000"   "13000-15000" "11000-13000" "14000-16000" "0-2000"      "8000-10000"

> unique(DT$PCT.change.bins)
[1] "-1-1" "-2-0" "0-2"  "-1-0"

Answer: Expanding on the method you were using in the question:
sales_bin_size = 1000

df %>%
    group_by(Product) %>%
    mutate(Sales_bin=cut(Sales, breaks=seq(0,round(max(Sales), -3),by=sales_bin_size), include.lowest=TRUE),
           PCT_change_bin=cut(`PCT Change`,breaks = 10, include.lowest=TRUE))

You can play around with the sales_bin_size to get the bin size you want. You can do the same for the PCT_change_bin by adding a new variable in a similar method.


Pass checkbox data to next activity

Question: I am creating a list of items with a listview with checkbox. I want to pass the checked options to next activity.
For this I am using an string array for passing  the results to other activity. Everything is going fine but as I click on button to pass the data to next activity, Application halts with a logcat error of NullPointerException. It maybe a very simple concept but I am not known to it as I am a newbie to android.
Any help would be appreciated..
Java File..
package com.example.travelplanner;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{

    String[] builder;
    Button btn1;
    ListView mListView;
    String[] array = new String[] {"Ham", "Turkey", "Bread"};

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tailoredtwo);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);

        mListView = (ListView) findViewById(R.id.listViewcity);
        mListView.setAdapter(adapter);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
        button.setOnClickListener(this);
    }

    public void onClick(View view) {
        SparseBooleanArray positions = mListView.getCheckedItemPositions();
        for(int index = 0; index < array.length; index++) {
            if(positions.get(index)==true)
            {
                 builder[index] = array[index];
            }
        }
        Intent i1 = new Intent(this, TailoredthreeActivity.class);
        Bundle b = new Bundle();
        b.putStringArray("city", builder);
        i1.putExtras(b);
        startActivity(i1);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
}

This is logcat:
07-12 10:48:49.686: E/AndroidRuntime(13047): FATAL EXCEPTION: main
07-12 10:48:49.686: E/AndroidRuntime(13047): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.travelplanner/com.example.travelplanner.TailoredthreeActivity}: java.lang.NullPointerException
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.os.Looper.loop(Looper.java:137)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread.main(ActivityThread.java:4448)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at java.lang.reflect.Method.invokeNative(Native Method)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at java.lang.reflect.Method.invoke(Method.java:511)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at dalvik.system.NativeStart.main(Native Method)
07-12 10:48:49.686: E/AndroidRuntime(13047): Caused by: java.lang.NullPointerException
07-12 10:48:49.686: E/AndroidRuntime(13047):    at com.example.travelplanner.TailoredthreeActivity.onCreate(TailoredthreeActivity.java:59)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.Activity.performCreate(Activity.java:4465)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-12 10:48:49.686: E/AndroidRuntime(13047):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
07-12 10:48:49.686: E/AndroidRuntime(13047):    ... 11 more

Comment: please add onCreate method of TailoredthreeActivity, becouse there will be problem
Comment: i think you forget to initialize builder array
Comment: which line no - 59 indicate  of TailoredthreeActivity
Comment: what is written in TailoredthreeActivity.java: at line 59? paste the oncreate() method of TailoredthreeActivity.java.
Answer: I will suggest you to use a arraylist to add items selected and pass the arraylist to the second activity
   checked = new ArrayList<String>();
   public void onClick(View view) {
        SparseBooleanArray positions = mListView.getCheckedItemPositions();
        for(int index = 0; index < array.length; index++) {
            if(positions.get(index)==true)
            {
                 checked.add(array[index]);
            }
        }
        Intent i1 = new Intent(MainActivity.this, TailoredthreeActivity.class);
            i1.putStringArrayListExtra("list",checked);
        startActivity(i1);
    }

To receive
 ArrayList<String> getChecked;
 Bundle extras = getIntent().getExtras();
    if(extras!=null)
    {
      getChecked = extras.getStringArrayList("list");

   }

Answer: You need to initialize the array first because every array is an object in java
public void onClick(View view) {
        SparseBooleanArray positions = mListView.getCheckedItemPositions();
         builder= new String[array.length];
        for(int index = 0; index < array.length; index++) {
            if(positions.get(index)==true)
            {
                 builder[index] = array[index];
            }
        }

Pass checkbox data to next activity


Selecting records using Linq2sql into linq2sql classes?

Question: Been succcesfully adding records using Linq2Sql with the linq2sql genereated classes, works great..
But i need to now select the records, i can't seem to figure this out
This is how i am adding records - reservation is a generated linq2sql class
            TestDataContext db = new TestDataContext();

            db.Reservations.InsertOnSubmit(reservation);
            db.SubmitChanges();

So i wanted to pass in a reservation number (which is a field) a retrieve a populated Reservation class
Can anyone help?
Thanks
Answer: If you're using a strongly typed datacontext object you should be able to do something like this:
public Reservation GetReservation(int id) {

return db.Reservations.Where(r =>   r.ReservationId == id ).SingleOrDefault();

}

Comment: Thanks! yes that worked but my reservation class has linked object i.e. I have a class called "Calls" and a Class called "Dropped"  - both are actualy separate tables, I see properties of Count which is 1 on Calls and 3 on Dropped..  Do i need to explicitly create a calls object or something to view the details?  Thanks again
Comment: Actuall i saw there is a property called entities and under that is items but its "NOT" public..
Comment: No, as a matter of fact your Reservation object should have a propertie named Calls which is actually a list of all Calls linked to this Reservation. To get the Calls you could simply loop through each Call like this:
    foreach(Call call in Reservation.Calls) {
        //Do something with the call
    }
Answer: You can do something like:
Reservation reservation =
    db.Reservations.Where(r => r.id == reservationId).Single();

or
// Use this if you're not positive the single record exists
Reservation reservation =
    db.Reservations.Where(r => r.id == reservationId).SingleOrDefault();

You can now work with reservation and then db.SumbitChanges() will save any modifications to the object back to the database.


Read data frame from get_prediction function of statsmodels library

Question: I am creating forecast model using arima here i have use statsmodels
Get forecast steps ahead in future
pred_uc = results.get_prediction(start='2001-05-01',end='2002-05-01')
print(pred_uc)

When I print this i get its in objects can it be converted into readable format in array or data frame
<statsmodels.tsa.statespace.mlemodel.PredictionResultsWrapper object at 0x00000000156E71D0>

Here it looks like data is stored in memory location and since i am noob in python i need a bit of help here...
code from
Source code of statsmodels library
Answer: Based on this Google search result (Japanese), try
pred_uc.predicted_mean

You can also get a DataFrame of 95% confidence intervals with
pred_uc_ci = pred_uc.conf_int(alpha=0.05)

Answer: You may try this:
pred_uc = fitted_model.get_prediction(start='2001-05-01', end='2002-05-01')
pred_uc = pred_uc.predicted_mean
pred_uc.columns = ['predicted1','predicted2', 'predicted_n']
pred_uc.head()

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


using template engine to generate code (text)

Question: I have bunch of YAML files in a config folder and bunch of templates in a template folder. The use case I have is to generate text file based on the yaml config and templates. I want to see if python tempting engines can be used to solve this problem.
I see that template  engines are used in a web development context. The use case I have is very similar (but not same). I want to generate some text. It need not be displayed on a web page. Instead it should generate just a text file.
Example
    Inputs:
    config folder: config/yaml1, config/yaml2, config/yaml3..
    template: template/template1, template/template2, template3.
Output
scripts/script1, script2, script3

The number of scripts = number of templates
There are 2 types of templates
One that is straightforward/direct substitution Example
YAML1:
    Titles:4
    SubTitles:10
Template1:
Number of Titles {Titles} where as Number of Subtitles is {SubTitles}

Other Template is a nested one. Basically the template needs to be looped based on YAML Example:
    YAML2:
        Book: "The Choice of using Choice"
            Author: "Unknown1"
        Book: "Chasing Choices"
            Author:"Known2"

Template2
Here are all the Books with Author Info
The author of the {Book} is {Author}

Expected output is a single text file that has
Number of Titles 4 where as Number of Subtitles is 10
The author of the The Choice of using Choice is Unknown1
The author of the Chasing Choices is known2
Can someone post me in the right direction?
Answer: You can do this with regular expressions and search/replace.  You can pass a function instead of a string to the re.sub function.  Of course, it relies on having valid YAML:

YAML1:
    Titles: 4
    #      ^ need space here
    SubTitles: 10
Template1:
    Number of Titles {Titles} where as Number of Subtitles is {SubTitles}
    # Need indentation here

The python code would look like this:
import re
import yaml

# Match either {var}, {{, or }}
TEMPLATE_CODE = re.compile(r'\{(\w+)\}|\{\{|\}\}')

def expand(tmpl, namespace):
    print(namespace)
    def repl(m):
        name = m.group(1)
        if name:
            # Matched {var}
            return str(namespace[name])
        # matched {{ or }}
        return m.group(0)[0]
    return TEMPLATE_CODE.sub(repl, tmpl)

def expand_file(path):
    with open(path) as fp:
        data = yaml.safe_load(fp)
    print(expand(data['Template1'], data['YAML1']))

And here's the output:

Number of Titles 4 where as Number of Subtitles is 10

There are, of course, a lot of ways to make this more complicated, like using a proper templating engine.
Comment: I'm specifically looking for a simpler solution like using tempting engine like cheetah. I was wondering if someone can point me in the right direction
Comment: @pmv: Why is this the wrong direction?  If you already know what templating engine you want to use (Cheetah), then why not just go ahead and use it?
Comment: I'm thinking about using the template engine as means to solve the problem. I'm specifically looking for a pseudo code
Comment: The above code is similar to how a template engine works.  You can just drop in a templating system to replace `expand` if you want.


Problema sintaxe MySql gerando pelo PhpMyAdmin

Question: Estou com um problema na hora que o MyAdmin gera um script de criação da tabela.
O Script:
CREATE TABLE `crud_ABC`.`cliente_ABC` ( `id` INT(10) NOT NULL AUTO_INCREMENT , `nome` VARCHAR(300) NOT NULL , `valor` DOUBLE(20) NOT NULL , `descricao` TINYTEXT NOT NULL , PRIMARY KEY (`id`(10))) ENGINE = MyISAM;

Porém ele me reporta o erro de:

1064 - Você tem um erro de sintaxe no seu SQL próximo a ') NOT NULL , `descricao` TINYTEXT NOT NULL , PRIMARY KEY (`id`(10))) ENGINE = My' na linha 1

O que será que pode ser? Já tentei troca as aspas.
Answer: Há alguns problemas no seu código:

Você está passando apenas um valor para double. Nesse tipo você precisa informar o tamanho e o número de casas decimais. DOUBLE(20,10) NOT NULL
Você está passando o tamanho da chave primaria, isso não é necessário, na verdade é errado, basta apenas informar o campo. PRIMARY KEY (id)

Segue exemplo:
CREATE `crud_ABC`.`cliente_ABC` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `nome` VARCHAR(300) NOT NULL,
    `valor` DOUBLE(20,10) NOT NULL,
    `descricao` TINYTEXT NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

Referência: https://dev.mysql.com/doc/refman/5.7/en/create-table.html
Comment: Obg, me ajudou!! Eu tinha corrigido, mas o MyAdmin estava gerando o código assim. \o/


Configure Apache to Remove BOM Automatically

Question: Is it possible to configure Apache or PHP to remove BOM automatically so users do not need to remove BOM manually before uploading scripts.
Comment: This question may be better suited for [SO], but you need to meet the minimum effort requirement first. Please take a look at the references provided below and ask on [SO] if you are still having troubles. Thank you!
Answer: Assuming by "BOM" you're referring to a Unicode byte-order mark, you could handle it with PHP's output-buffering functions. Have a look at this question on Stack Overflow and adapt-to-taste.
Comment: I need PHP do remove BOM from all scripts arround the server by default at the time of displaying output I want to make it as a global configuration so none of users worry about BOM issue.
Answer: This will be fixed in PHP6. The best way to approach it for each vhost in php5 would be to write your own patch for php.
The following guide goes through writing extentions for php;
Write extensions
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Shaking Object With Swinging/Tilting Effect in AS3

Question: I have an image of a bottle on the stage. I want to have it so that the user can click and drag the bottle around. I want the bottle to sway as it's dragged so tilt and rotate as if it's being pulled back and forth. I've Googled this and found nothing. How can I achieve this effect through code?
So far I've created a timer that tracks a start and end point during drag, calculates distance travelled to get a rough idea of speed and direction and then rotates the bottle within a range of 120 degrees using the Tween class (and then bounce back to 0 after). It's close but not quite as fluid looking as I'd like.. I feel like I need some kind of custom easing function but I'm not great with this type of math.
function distanceTimerBeat(e:TimerEvent):void
{//speed detection beat timer
distCounter++;
if(!distSwitch)
{
    startX = product.x;
    startY = product.y;
    distSwitch = true;
}
else
{
    endX = product.x;
    endY = product.y;
    distSwitch = false;
    var newDistance = calculateDistance();
    setRotation();
    //trace('>> ('+distCounter+') distance travelled = '+newDistance);
    //produceNewFirework()
    }
}

function calculateDistance():Number
{//returns distance travelled over beat timer intervals

var rawDistance = (( startX - endX ) * (startX - endX )) + ((startY - endY ) * (startY - endY ));
var distance = Math.sqrt( rawDistance);
var xDistance = startX - endX;
if(xDistance < 0)
{
    speedDirection = 'right';
    directionModifier = -1;
}
else if(xDistance > 0)
{
    speedDirection = 'left';
    directionModifier = 1;
}

//trace('>> going '+speedDirection+' at '+xDistance);
return distance;
}

function setRotation():void
{ //once start & end values are detected, check speed and set the rotation.

var curSpeed = calculateDistance();

if(curSpeed > 4)
{
    tweenLock = false;

    var speedPercent = curSpeed/maxSpeed * 100;

    var rotationDegree = (speedPercent*120)/300;
    var newRotation = directionModifier*rotationDegree;

    var reversePercent = 100 - speedPercent;
    var tweenSpeedModifier = (speedPercent/100);
    //trace(tweenSpeedModifier*1);

    //if(!tweenLock)
        //rotationTween = null;

        if(rotationTween) rotationTween.stop();
        rotationTween = new Tween(product, "rotation", Strong.easeInOut, product.rotation, newRotation, 0.25, true);
        //rotationTween.resume();
        rotationTween.addEventListener(TweenEvent.MOTION_FINISH, resetProductTween);
        //trace('speed percet = '+speedPercent);

}
else
{
    //tweenLock = true;
}
}

function resetProductTween(e:TweenEvent)
{//after the product rotates, snap it back to it's original position.
tweenLock = false;
if(!tweenLock)
{
    rotationTween = new Tween(product, "rotation", Strong.easeOut, product.rotation, 0, 0.75, true);
    rotationTween.addEventListener(TweenEvent.MOTION_FINISH, tweenUnlock);
}
}

Answer: http://code.tutsplus.com/tutorials/quick-tip-trigonometry-for-flash-game-developers--active-4458
stage.addEventListener(MouseEvent.CLICK, calculateAngle);

var myAtan2:Number;

function calculateAngle(e:MouseEvent):void
{
    myAtan2 = Math.atan2(e.stageY - mCircle.y, e.stageX - mCircle.x);
    trace(myAtan2);
}


Non trivial projector on $C^{0}( \mathbb{R}, \mathbb {R} )$?

Question: I am looking for a projection operator $P: C^{0}( \mathbb{R}, \mathbb {R} ) \rightarrow C^{0}(\mathbb{R}, \mathbb {R})$, i.e. a linear operator s.t. $T^2 = T$, continuous or not.
Edit :
I found a lot projectors :
For examples :
The composition with map $g_{a,b}$ such $g|_{ [a,b]}=Id$ and $g(x)=a \ \forall x \leq a$ and $g(x)=b \ \forall x \geq b$
The "constant" operator $T_y:f \rightarrow (x \rightarrow f(y))$
The "even" operator : $f \rightarrow (x \rightarrow \frac{f(x)+f(-x)}{2}$
The "odd" operator : $f \rightarrow (x \rightarrow \frac{f(x)-f(-x)}{2}$
If we have a projector $T'$ on $[a,b]$ and $T''$ on $[c,d]$ and $b < c$, we can build $T''$ on $\mathbb{R}$ :
$T(f)=T'(f)$ on $[a,b]$
$T(f)=T''(f)$ on $[c,d]$
$T(f)(x)=T'(f)(a) on $(- \infty,a]$
$T(f)(x)=T''(f)(a) on $[d, \infty $
$T(f)(x)=(x-b) \frac{T(f)(c)-T(f)(b)}{c-b} + f(b)$ on $[b,c]$
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: As written, the question seems to be impossible to understand. Where from and where to are you projecting? What is a "trivial projector"? What is your exact question?
Comment: I have edited your question. Is this what you are asking? If so, what norm/topology do you consider on $C^{0}(\mathbb{R}, \mathbb {R})$?
Answer: Example: let $P: C^{0}( \mathbb{R}, \mathbb {R} ) \rightarrow C^{0}(\mathbb{R}, \mathbb {R})$ be definde by $P(f):=f-f(0).$
$P$ is linear and $P^2=P.$


ajuda para View passar várias linha para um Controller

Question: Galera, tenho um modelo simples para estudos. São 3 tabelas, Pessoa, Alergia e PessoaAlergia. Sendo que uma pessoa pode ter várias alergias.
Meu modelo de pessoa é:
 public partial class Pessoa
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Pessoa()
        {
            this.AlergiasPessoas = new HashSet<AlergiasPessoas>();
        }

        public int ID { get; set; }
        public string nome { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AlergiasPessoas> AlergiasPessoas { get; set; }
    }
}

Em minha View Create recebo os dados da tabela alergia em uma listbox onde o usuário pode selecionar vários.
@Html.ListBox("Alergia", (MultiSelectList)ViewBag.Alergia, new { @id = "Fonte", @class = "form-control", @onclick = "teste(this)", @style = "height:150px" })

Ao enviar os dados para o Concroller por submit, espero gravar tanto a pessoa quanto as alergias selecionadas na tabela PessoaAlergia
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,nome")] Pessoa pessoa, ALGO_QUE_TRAGA_OS_ITENS_SELECIONADOS)
    {
        if (ModelState.IsValid)
        {
            db.Pessoa.Add(pessoa);
            db.SaveChanges();

            foreach (var item in ALGO_QUE_TRAGA_OS_ITENS_SELECIONADOS)
            {
                AlergiasPessoas alergiasPessoas = new AlergiasPessoas();
                alergiasPessoas.ID_Pessoa = pessoa.ID;
                alergiasPessoas.ID_Alergia = item.ID;
                db.AlergiasPessoas.Add(alergiasPessoas);
            }
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(pessoa);
    }

Não estou sabendo como receber os itens selecionados na action create. Alguma sugestão?
Answer: @AlamBique, o @Html.ListBox vai passar um array com os Ids selecionados na View.
Você pode pegar do jeito que estava fazendo mesmo usando um foreach.
Mude seu metodo POST para...
public ActionResult Create([Bind(Include = "ID,nome")] Pessoa pessoa, int[] Alergia)
Comment: Obrigado Daniel!
Comment: Então o que vale é o nome do item HTML para poder receber no controller? Tipo nesse exemplo a tag  gerada @Html.ListBox("Alergia". Para receber eu uso Alergia.
Answer: Olá, uma das formas de fazer isso é utilizando uma ViewModel, que irá trafegar as informações para da controller para a view e retornar da View para a controller. Veja no link a seguir uma referencia sobre como esses componentes funcionam no detalhe e um exemplo: Microsoft Docs: Views And ViewModels
Sobre o seu caso, pode fazer o seguinte:
 1- criar uma ViewModel contendo uma propriedade com a classe Pessoa.
2- Referenciar a ViewModel na view @model ViewModelPessoa
3- Utilizar a ViewModel para carregar os dados na view e submeter os dados por um formulário:
@using (Html.BeginForm())
{
        @Html.ListBoxFor(m => m.Pessoa.AlergiasPessoasSelecionada, m.AlergiasPossiveis, new { id = ListAlergiaPessoas })

        <input type="submit" value="Submit" />
}

Comment: Isto AlamBique! E a solução apontada pelo @Alexandre é a mais elegante, se já estiver usando o conceito de View Model no seu projeto, pode usar a solução que ele apontou.  Eu pessoalmente gosto muito deste conceito.


Error SQL7008 while updating a DB2 for iSeries table

Question: I have a Java Web application using Hibernate and DB2 for iSeries and during update of a table I get he following error:-

Error SQL7008 while updating a DB2 for
  iSeries table
Answer: From doing some googling on this error message I noticed that it happens when you are running an insert/update in a non-transactional mode. The explanation is given here.

This occurs because the table you are
  trying to update is not being
  journalled, and your update is being
  run within a transaction.

Generally, you should always commit (and rollback if an exception occurs) your transactions. Usually I never set auto commit to true but in this case I would like to understand if it's truly needed as mentioned in the link above. Can you set the auto commit to true in your connection to see if this goes away?
<property name="hibernate.connection.autocommit" value="true"/>
Also this link has some tutorials on transaction management with hibernate.
Answer: I found the answer to my question,
This occurs As CoolBeans mentioned because the table I was trying to update is not being journalled.
Add this table to Journal, here are the steps
this took care of my problem.
Comment: This is way better than having external connections update a database.  Because the journal will give you a log of the database transactions including their origin


Unable to autofill tabs of website through excel vba

Question:
I have managed to create the below code, but I'm unable to autofill the fields marked with red arrows shown in the image, as there is no ID available for them in the HTML code.
All the tabs shown in image does not have IDs.
What should be the coding for filling these ?
Sub TDS_Autofill()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://onlineservices.tin.egov-nsdl.com/etaxnew/tdsnontds.jsp"
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop

Set doc = IE.document
doc.parentWindow.execScript "sendRequest(281)", "JavaScript"

Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop

If ThisWorkbook.Sheets("Challan AutoFill").Range("m2").Value = "Company"
Then
doc.getElementById("0020").Click
ElseIf ThisWorkbook.Sheets("Challan AutoFill").Range("m2").Value = "Non
Company" Then
doc.getElementById("0021").Click
End If

If ThisWorkbook.Sheets("Challan AutoFill").Range("o2").Value = "(200)
TDS/TCS Payable by Taxpayer" Then
doc.getElementById("200").Click
ElseIf ThisWorkbook.Sheets("Challan AutoFill").Range("o2").Value = "(400)
TDS/TCS Regular Assessment" Then
doc.getElementById("400").Click
End If

IE.document.querySelector("select.form-control").selectedIndex =
ThisWorkbook.Sheets("Challan AutoFill").Range("r2").Value

doc.getElementById("NetBanking").Click

doc.getElementById("NetBank_Name_c").Value = ThisWorkbook.Sheets("Challan
AutoFill").Range("t2").Value

End Sub```

Comment: It is a jsp, so it is Java. You won´t find any variable there.
Answer: You could get the inputs using their names by doc.getElementsByName. It returns a collection of all elements in the document with the specified name. Then you should find out the index number of the element you want.

For example, you can set the value of "Tax Deduction Account No" using the following code:
doc.getElementsByName("TAN")(1).Value = "abc"

For the other inputs, you could use the same methods. I make a test with setting some of the values and you can see the result:
Answer: You can use getElementsByTag("input") that returns a collection of components that you can access with an index, and then set their value to what you need.
doc.getElementsByTagName("input")(0).value = "My value"


Deprecated Dependency Warning not removing

Question: In my Drupal 8.9.6 (Installed with Lightning distribution) Status Admin Page, there are three warnings showing after updating several modules and core to the latest versions:

DEPRECATED DEPENDENCY: ENTITY EMBED Lightning Media 5.0 will not include the Entity Embed module. Please add it to your project directly: composer require drupal/entity_embed:^1.0
DEPRECATED DEPENDENCY: VIDEO EMBED MEDIA Lightning Media 5.0 will not include the Video Embed Media module. Please add it to your project directly: composer require drupal/video_embed_field:^2.0.
DEPRECATED DEPENDENCY: VIEWS INFINITE SCROLL Lightning Media 5.0 will not include the Views Infinite Scroll module. Please add it to your project directly: composer require drupal/views_infinite_scroll:^1.6.

I have installed the latest versions of these contributed modules through composer. But the warning not going away from the admin status page. How to remove these warning?
Comment: did you try clearing cache and run cron.
Comment: Yeap, several times.
Answer: The Lighting Media modules have hard-wired checks to report this information if it finds Video Embed Media or Entity Embed & Views Infinite Scroll installed. It doesn't check the Composer requirements to see if the warning message is still applicable.
Either ignore the warning until the 5.x release is out or patch away checks in hook_requirements() if it bothers you that much.


A linear function from polynomial space to matrices

Question: Let $B$ be the standard basis for $Mat_{2,2}$ and $B'$ be the standard basis for $Pol_2$. Find the change of basis matrix for $$p(x) \rightarrow
\begin{pmatrix}
p'(1) & 2p(0)\\
0 & p''(3)\\
\end{pmatrix}
$$
In the solution it just directly gives $f(1)=E_{11}, f(x)=1E_{11}, f(x^2)=2E_{11}+2E_{22}$
My question is how were they calculated?
Comment: How indeed! I get that the polynomial $1$ maps under the linear map $f$ to the matrix $\begin{pmatrix} 0 & 2\\0 &0\end{pmatrix}$ so that $f(1)=2E_{12}$. I did get that $x$  and $x^2$ map to the matrices that they claim, though. [You just have to work out for $p=1, p=x, p=x^2$ the values of $p'(1), 2p(0), p''(3)$ and express the three matrices in terms of the four $E_{ij}$.]
Answer: If $p(x) = a_0 +a_1x+a_2x^2$, then the map sends
$$
\begin{split}
a_0+a_1.x + a_2.x^2 &\to
\left(\begin{array}{cc}a_1+2a_2 & 2a_0 \\
0 & 2a_2\end{array}\right)\\
&=a_0(2E_{12}) + a_1.E_{11}+ a_{2}.(2E_{11}+2E_{22}).
\end{split}
$$
thus the map obviously corresponds to the map of bases which sends $1$ to $2E_{12}$, $x\to E_11$ and $x^2$ to $2E_{12}$,


How to change values in an array when comparing two arrays

Question: var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];

I want output to be like this:
[{"name":"SAM","surname":"SAMEERA","location":"mumbai","age":"22"}];

using javascript and underscorejs
My attempt is as below:
var workingValues = _.filter(array1, function(item){ return item});
console.log(workingValues);
var validItems = [];

for(var i =0 ; i < array2.length; i++){
  var item = array2[i];
  console.log(item);

  var findItems = _.filter(array1,function(ite) {
    return ite.name.toUpperCase() == item.name.toUpperCase() && ite.surname.toUpperCase() == item.surname.toUpperCase()});
  validItems.push(item);
  console.log(findItems);
}

Comment: `i want` Have you tried writing any code yourself yet in an attempt to accomplish what you want? Please post it if you want debugging help
Comment: Please include the code of whatever you have tried. This site can only help with specific problems and won't be doing your whole homework or job.
Comment: var arr =_.filter(array1, function(item){ return item});
Comment: var workingValues = _.filter(array1, function(item){ return item});
        console.log(workingValues);

        var validItems = [];

        for(var i =0 ; i < array2.length; i++){
            var item = array2[i];
            console.log(item);

       var findItems = _.filter(array1,function(ite) {return  ite.name.toUpperCase() == item.name.toUpperCase() && ite.surname.toUpperCase() == item.surname.toUpperCase()});
         validItems.push(item);

        console.log(findItems);
}
Answer:

var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];

var result = [{...array1[0],...array2[0]}];
console.log(result);
Comment: please use underscorejs or other normal javascript methods and dont use ...array[0]
i have multiple array objects
Answer: Based on the limited data you've provided.

var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"sameera"}];
console.log( _.extend(array2, array1))

Comment: i want output like this  [
  {
    "name": "SAM",
    "surname": "sameera",
    "location": "mumbai",
    "age": "22"
  }
]
but here does not change the value sam as SAM
Answer: You can try this

var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"},{"name":"sam123","surname":"sameera123","location":"mumbai","age":"22"} ];
var array2 =[ {"name":"SAM","surname":"SAMEERA"},{"name":"SAM123","surname":"SAMEERA123"}];

var ret = [];

for(var i = 0; i < array1.length; i += 1) {
  var newArray = array2.filter(function (el) {
      return el.name.toUpperCase() == array1[i].name.toUpperCase() &&                                                  el.surname.toUpperCase() ==array1[i].surname.toUpperCase();
  });
  if(newArray.length ==0)
  {
     ret.push(array1[i]);
  }
  else
  {
     array1[i].name = newArray[0].name; //change valuse
     array1[i].surname = newArray[0].surname; //change valuse
     ret.push(array1[i]);
  }
};

console.log(ret);
Comment: var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"},{"name":"sam123","surname":"sameera123","location":"mumbai","age":"22"}....etc
];
var array2 =[ {"name":"SAM","surname":"SAMEERA"},{"name":"SAM123","surname":"SAMEERA123"}....etc];
how can i do this bro
Comment: @pradeep I have updated my code. please check and if any issues please let me know.
Comment: var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"},{"name":"sam123","surname":"sameera123","location":"mumbai","age":"22"} ];
var array2 =[ {"name":"SAM","surname":"SAMEERA"},{"name":"SAM123","surname":"SAMEERA123"}];
please  check this
Comment: @pradeep Sorry I do not know undesorejs.
Comment: @pradeep ok checking
Comment: @pradeep I have updated my code. please check and I do not found any issues.
Comment: how can i follow u in stackoverflow
Comment: @pradeep Can you mark this answer correct if it is useful? for follow

https://meta.stackexchange.com/questions/18978/is-there-a-way-to-follow-peoples-activity

It's my pleasure someone wants to follow me.
Comment: @pradeep Can you mark this answer correct if it is useful?
Answer: var array1 = [{
    "name":"sam",
    "surname":"sameera",
    "location":"mumbai",
    "age":"22"
}];
var array2 =[{
    "name":"SAM",
    "surname":"sameera"
}];
var mergearray= array1 .concat(array2);


crontab emails bounce, others don't but are not delivered

Question: Does anyone know what might be causing the following situation?
Crontab emails are bouncing with the message "Message rejected as spam by Content Filtering." (I've contacted the mail server admin about this.)
But emails sent with the command "mail email@example.com" etc. are "stat=Sent ... Queued mail for delivery" (according to the log), but never arrive and never bounce. I've tried sending as root and as other users.
Any help would be greatly appreciated! Thanks.
Answer: Well, you haven't really given us any good information to go on, but if I were to guess, the server sending the mails most likely doesn't have a proper DNS PTR (reverse) record. Have you tried instead of having that server deliver mail directly, having it send through a known-good smarthost instead?
Comment: Yes, it looks like this was the problem.  The (Windows) sysadmin didn't fix the reverse DNS problem, but did add my host's name to a whitelist, and now emails are being sent fine. Doesn't explain why root crontab emails were sending OK — but now things are working I haven't time to investigate!  Thanks for your help.


A question in compactifications in topology

Question: I have been taking a course on topology this semester and I need help in this particular exercise.

Prove that the function $f: (0,1)\to \mathbb{R}$ defined by $f(x)= \sin(1/x)$ cannot be extended to a continuous function with domain $[0,1]$.

We have studied 1 point compactifications but here 2 points are being added. I am unable to think of which result to use and would very much appreciate hints.
I am doing masters level course but first course.
Comment: Suppose you have such an extension. Then $f(0)=\lim_{x\to 0+} f(x)$, but that limit does not exist.
Comment: This has nothing to do with compactications of $(0,1)$.
Comment: Notice that the point $x=1$ does not have any discontinuity, so you can define an easy continuous extension with only problems at $x=0$.
Answer: $1$ is irrelevant, there also is no extension to $[0,1)$, e.g.
Consider the sequences $a_n = \frac{1}{\pi n}$ and $b_n = \frac{1}{2\pi n + \frac{\pi}{2}}$ in $(0,1)$.


Workflow : Best way to carry my projects over to multiple computers?

Question: I wonder if this question really fall in the topic of this site and feel free to tell me if it doesn't. But anyway, here's the situation : I'm currently in college and when I'm at school, I program on my lap top, and when I'm at home, I'd like to programm on my desktop. I was wondering, what is the best way to carry my projects over from one PC to another? I currently use Visual Studio 2015.
I tought of one solution, set my VS Workspace in my Google Drive so everytime I save a project, it's carried over.
But do you guys have a better solution? Thanks for your responses! :)
Answer: I also don't know whether this question belongs to SO. Anyway, I will try to answer your question.
In situation where you program in groups, a source code management system (version control) is absolutely necessary to synchronize code and avoid conflicts. A very popular one is Git which is used in many various projects in different programming languages. For other version control systems, look at the bottom of the wiki article.
It would be too much to explain Git (or version control in general) in this answer, but the general work flow is always the same: There is a server somewhere, an when you start coding you 'check out' your project, which means you copy the most recent updates to your local machine. When you are done, you commit the changes to the server. If you want to work on another computer, you just check your project out again. When finished, commit again.


I'd like to plot the two graph together

Question: Here are the 2 graphs.

I'd like to plot them together(share the same x-axis) but the problem is: the X-axis of the right one has the format: Year-Month(e.g. as shown), while the left is in Year-month-day(e.g. 2020-03-23).
How can I reformat the axis? i.e. from Year-month-day --> Year and month.
Here is the date for the 2nd graph: from DataFrame function
               0
0     2014-11-10
1     2014-11-11
2     2014-11-12
3     2014-11-13
4     2014-11-14
...          ...

Here is the code for 2 graph: 1st graph
data = pd.read_json(r"C:\Users\taibo\Desktop\Solar_Cycle\observed-solar-cycle-indices.json", orient='records')
data2 = pd.DataFrame(data)
ndata = data2[ (data2['time-tag'] > '2014-01') & (data2['time-tag'] < '2020-12')]
x = ndata['time-tag']
y = ndata['ssn']

2nd graph:
Dose_data = pd.read_csv(r"C:\Users\taibo\Desktop\MSL_Script\Code\Btmp.txt",sep='\s+',header=None,)
Dose_data = pd.DataFrame(Dose_data)
sol_list = Dose_data[0]
def soltodate():
    list = []
    for sols in sol_list:
        landing_date = "12/08/06" #landing date of curiosity
        landing_date_strip = datetime.strptime(landing_date, "%y/%m/%d").date()
        #print(landing_date_strip)
        x = sols*1.0275
        #x = sols to earth day
        sol_to_date = landing_date_strip + timedelta(days=x-1) # plus landing date with number of earth day
        date_list = np.array(sol_to_date)
        list.append(str(date_list))
    return(list)
Dose_date = soltodate()
Dose_date = pd.DataFrame(Dose_date)

Dose_x = new_Dosedate[0]
Dose_y = Dose_data[1]

Here is raw data for 1st graph:https://services.swpc.noaa.gov/json/solar-cycle/observed-solar-cycle-indices.json
2nd: https://drive.google.com/file/d/1GRcjhVVg_S9PU8LJxybR-fnY7Z2kdWUw/view?usp=sharing
Answer: That's not that difficult. Just convert the dates of the other chart to year-month.
Let's say your dates were inside a variable called dates. Then:
new_values = [str(a.year)+'-'+str(a.month) for a in dates]

Example:
from datetime import date, timedelta

sdate = date(2019,3,22)   # start date
edate = date(2019,4,9)   # end date

dates = pd.date_range(sdate,edate-timedelta(days=1),freq='d')

new_values = [str(a.year)+'-'+str(a.month) for a in dates]

print(new_values)

['2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-3', '2019-4', '2019-4', '2019-4', '2019-4', '2019-4', '2019-4', '2019-4', '2019-4']

I hope this resolves your problem.
Once you set the date values to this new one.
Just do:
plt.figure()
plt.plot(data1)
plt.plot(data2)
plt.show()

And that should do the trick I hope.
Comment: I'm getting AttributeError: 'int' object has no attribute 'year'
Comment: The date is from a datafram: Dose_date = pd.DataFrame(Dose_date)

new_Dosedate = [str(a.year)+'-'+str(a.month) for a in (Dose_date)]
Comment: Don't make it a dataframe, just pass it as it is.
Comment: Can you print your Dose_date variable before converting it to a DataFrame and share the output here?
Comment: How do I shere it in the comment section?
Comment: ```2014-11-10, 2014-11-11```
Comment: I added the date value on the Question
Comment: I am actually trying to figure out if your dates are in string format or datetime objects. Let's do one thing. Can you by chance share these two dataframes in google drive? Just change the data but keep the dates as it is. I'll post a solution for you.
Comment: I have edited the question and added code for where both of the data from 2 graphs comes from. I am not sure what the final formats are because both data I have manipulated it from the raw data.

I'd like to plot the two graph together


Centering bottom positioned button within flex DIV

Question: I'm trying to show a flex grid, all working, with some options to users. The boxes match each other's height so I don't want to set one in order to have buttons all in the same position at the bottom. The snippet below is where I'm up to.

.site-membership-breakdown {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  padding-top: 15px;
}

.site-membership-breakdown-module {
  width: 20%;
  /*I don't want to set a height because the buttons need to fit within the DIV and be centered 15px up from the bottom*/
  display: flex;
  margin-top: 0px;
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #FFFFFF;
  border-radius: 0;
  border: 10px solid #000000;
  padding: 10px;
}

@media only screen and (max-width: 500px) {
  .site-membership-breakdown-module {
    width: 100%;
    height: 250px display: flex;
    margin-top: 0px;
    margin-bottom: 10px;
    margin-left: 10px;
    margin-right: 10px;
    background-color: #FFFFFF;
    border-radius: 0;
    border: 10px solid #000000;
    padding: 10px;
  }
}

.site-membership-breakdown-module-inner {
  display: block;
  width: 100%;
  position: relative;
}

Plan 1

• Thing 1.
• Thing 2.
• Thing 3.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 1

            </button>

Plan 2

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 2

            </button>

Plan 3

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.
• Thing 5.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 3

            </button>

Plan 4

Some info about the biggest of the plans, this one has the most information as a paragraph to show what is available within the plan.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Free Trial

            </button>

This next snippet is what I've tried which sort of works for positioning but needs a height set on the black outlined box. Ideally the buttons would sit at the bottom of each box being the same height. On smaller viewport widths the height can be the same for all or just enough to fit the content.

.site-membership-breakdown {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  padding-top: 15px;
}

.site-membership-breakdown-module {
  width: 20%;
  /*I don't want to set a height because the buttons need to fit within the DIV and be centered 15px up from the bottom*/
  display: flex;
  margin-top: 0px;
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #FFFFFF;
  border-radius: 0;
  border: 10px solid #000000;
  padding: 10px;
}

@media only screen and (max-width: 500px) {
  .site-membership-breakdown-module {
    width: 100%;
    height: 250px display: flex;
    margin-top: 0px;
    margin-bottom: 10px;
    margin-left: 10px;
    margin-right: 10px;
    background-color: #FFFFFF;
    border-radius: 0;
    border: 10px solid #000000;
    padding: 10px;
  }
}

.site-membership-breakdown-module-inner {
  display: block;
  width: 100%;
  position: relative;
}

.site-join-button {
    height: 60px;
    width: 120px;
    padding: 0;
    margin-left: 0;
    margin-right: 0;
    margin-top: 20px;
    margin-bottom: 15px;
    color: #FFFFFF;
    background-color: #000000;
    border: 5px solid #000000;
    border-radius: 0;
    position: absolute;
    bottom: 0;
}

@media only screen and (max-width: 500px) {
.site-join-button {
    height: 60px;
    width: 120px;
    padding: 0;
    margin-left: 0;
    margin-right: 0;
    margin-top: 15px;
    margin-bottom: 15px;
    color: #FFFFFF;
    background-color: #000000;
    border: 5px solid #000000;
    border-radius: 0;
    position: absolute;
    bottom: 0;
}
}

.site-join-button:hover {
    color: #000000;
    background-color: #FFFFFF;
}

Plan 1

• Thing 1.
• Thing 2.
• Thing 3.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 1

            </button>

Plan 2

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 2

            </button>

Plan 3

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.
• Thing 5.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 3

            </button>

Plan 4

Some info about the biggest of the plans, this one has the most information as a paragraph to show what is available within the plan.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Free Trial

            </button>

The closest I've got has the buttons all at the same height but because the container doesn't have a set height (300px has been used in testing) the buttons all float over the content. I'm aiming for them all to be aligned with each other at the bottom of the list by positioning at the bottom and using 15px margin to float it slightly.
Thanks in advance for any help.
EDIT
Here's my current view on top and the desired outcome on the bottom.
Comment: But the button will hide the texts
Comment: That's the point, it's not supposed to, it's to sit below @Viira
Comment: do you have to set height for the text container?
Comment: No, it should take the height of the content. I don't mind setting the height to 300px if the buttons can all be positioned the same. I've updated my question with desired outcome. Just changes to existing classes please as it is complex @Viira thank you.
Comment: I've updated my answer kindly do consider it.
Answer: flex implementation.
Add display: flex; flex-direction: column; to .site-membership-breakdown-module-inner
and
flex: 1; to .site-membership-breakdown-paragraph-text
This will make the cener content to grow and fit the blank space.

.site-membership-breakdown {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  padding-top: 15px;
}

.site-membership-breakdown-module {
  width: 20%;
  /*I don't want to set a height because the buttons need to fit within the DIV and be centered 15px up from the bottom*/
  display: flex;
  margin-top: 0px;
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #ffffff;
  border-radius: 0;
  border: 10px solid #000000;
  padding: 10px;
}

@media only screen and (max-width: 500px) {
  .site-membership-breakdown-module {
    width: 100%;
    height: 250px;
    display: flex;
    margin-top: 0px;
    margin-bottom: 10px;
    margin-left: 10px;
    margin-right: 10px;
    background-color: #ffffff;
    border-radius: 0;
    border: 10px solid #000000;
    padding: 10px;
  }
}

.site-membership-breakdown-module-inner {
  display: flex;
  width: 100%;
  /* position: relative; */
  flex-direction: column;
}

.site-membership-breakdown-paragraph-text {
  flex: 1;
}

        Plan 1

        • Thing 1.
• Thing 2.
• Thing 3.

      <button
        class="site-join-button"
        onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'"
      >

Join 1

      </button>

        Plan 2

        • Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.

      <button
        class="site-join-button"
        onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'"
      >

Join 2

      </button>

        Plan 3

        • Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.
•
        Thing 5.

      <button
        class="site-join-button"
        onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'"
      >

Join 3

      </button>

        Plan 4

        Some info about the biggest of the plans, this one has the most
        information as a paragraph to show what is available within the
        plan.

      <button
        class="site-join-button"
        onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'"
      >

Free Trial

      </button>

Comment: I had to add a margin auto to the left and right of the button to center after this, really appreciate your answer, have a great day.
Answer: You have to add transform: translateX(-50%) and left:50%; for the button since you're using position:absolute and add padding-bottom:65px 60px the button's height and 5px for space below the container.

.site-membership-breakdown {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  padding-top: 15px;
}

.site-membership-breakdown-module {
  width: 20%;
  /*I don't want to set a height because the buttons need to fit within the DIV and be centered 15px up from the bottom*/
  display: flex;
  margin-top: 0px;
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
  background-color: #FFFFFF;
  border-radius: 0;
  border: 10px solid #000000;
  padding: 10px;
}

@media only screen and (max-width: 500px) {
  .site-membership-breakdown-module {
    width: 100%;
    height: 250px display: flex;
    margin-top: 0px;
    margin-bottom: 10px;
    margin-left: 10px;
    margin-right: 10px;
    background-color: #FFFFFF;
    border-radius: 0;
    border: 10px solid #000000;
    padding: 10px;
  }
}

.site-membership-breakdown-module-inner {
  display: block;
  width: 100%;
  position: relative;
  padding-bottom: 65px;
}

.site-join-button {
    height: 60px;
    width: 120px;
    padding: 0;
    margin-left: 0;
    margin-right: 0;
    margin-top: 20px;
    margin-bottom: 15px;
    color: #FFFFFF;
    background-color: #000000;
    border: 5px solid #000000;
    border-radius: 0;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
}

@media only screen and (max-width: 500px) {
.site-join-button {
    height: 60px;
    width: 120px;
    padding: 0;
    margin-left: 0;
    margin-right: 0;
    margin-top: 15px;
    margin-bottom: 15px;
    color: #FFFFFF;
    background-color: #000000;
    border: 5px solid #000000;
    border-radius: 0;
    position: absolute;
    bottom: 0;
}
}

.site-join-button:hover {
    color: #000000;
    background-color: #FFFFFF;
}

Plan 1

• Thing 1.
• Thing 2.
• Thing 3.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 1

            </button>

Plan 2

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 2

            </button>

Plan 3

• Thing 1.
• Thing 2.
• Thing 3.
• Thing 4.
• Thing 5.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Join 3

            </button>

Plan 4

Some info about the biggest of the plans, this one has the most information as a paragraph to show what is available within the plan.

      <button class="site-join-button" onclick="if (!window.__cfRLUnblockHandlers) return false; location.href='/join'">

Free Trial

            </button>


Does anyone have a working Jenkins agent configuration for git clone on z/OS R2.4

Question: I am trying to use the GitSCM Jenkins plugin on z/OS R2.4 with Rocket's git implementation. The agent configuration that worked on R2.3 no longer works on R2.4 because the utf8 encoding no longer works - so the IBM documentation also is fairly out of date on this. We had to move to -Dfile.encoding=ISO8859-1 just to run commands on the system successfully - otherwise nothing.
However, when trying to use git checkout via SSH, I get public key authentication errors getting to the remote upstream. This also happens when we use the SSH Agent plugin. When attempting this outside Jenkins everything seems fine whether using an agent or directly with git. We have a valid ~/.ssh/config file on the agent that works for our Jenkins user from a command line as does ssh-agent. The git-jenkins.sh script to use instead of git directly, which IBM suggests using, simply does not work even after fixing the obvious scripting errors. I am suspicious that the SSH key/passphrase is not being encoded correctly for SSH communication but cannot prove that is causing the problem.
Does anyone have a working configuration on z/OS R2.4? We did not have encoding issues on R2.3 but cannot rollback and did not work with the GitSCM plugin back then anyway.
Answer: First, for testing, try with an SSH key without passphrase, in order to confirm is the issue is related to said passphrase or not.
Second, check the  R2.4 ServerPack for SSH and the OpenSSH_x version r(compared to R2.3): that can give some clues as to what has changed between the two versions, and why SSH (which was working before) no longer work.
Comment: Using SSH-AGENT and then git commands from shell within the SSH-Agent pipeline context in Jenkins works fine. It is only when the GitSCM plugin is involved that this fails. Looks like the private key is not being encoded correctly when sent to the upstream when GitSCM supplies credentials. We're working on figuring out where the gap in and suspect it is in IBM's git-jenkins.sh script. More to come when we figure this out.


New JQuery Mobile Version Affecting Page Transition?

Question: I have the following code:

Page1

Page2

Page1

Page2

The above codes will work if I use the following scripts. That is, Page 1 will have the Slide effect and Page 2 the Pop effect.
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />

However, when I used the following, the slide effect and pop effect are gone.
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />

Seems like the new JQM version has affected the page transition or am I missing something? Can anybody confirm?
Thanks.
Comment: Which device are you using for testing?
Comment: I am using my Android Sensation phone.
Answer: Read the transitions section in the announcement of 1.1.0:

Unfortunately, after a ton of work, we've determined that it's not possible to dumb down
  page transitions enough to get acceptable performance in Android 2.x, even on a newer device
  like a Nexus S running 2.3. After a lot of deliberation, we've decided to use a feature test
  for 3D transforms to target transitions: if a browser passes, it will see the full range of
  transitions. By default, if a browser fails this 3D test, they will fall back to a fade
  transition, regardless of the transition specified. All Android 1.x-2.x devices fail this
  test but Android 3.x and 4.x pass. The fallback behavior for each transition is completely
  configurable if you want to change this behavior.

If your testing browser doesn't support 3D transforms you will get a fade transition.