text:
Q: Mysql query to get the value I got the table structure as follows

--------------------------------
id   processId   newId     value
--------------------------------
1        1        1         a
2        1        2         b
3        1        4         c
4        2        5         d
--------------------------------

and

------------------------
id   processId  mapnewId
------------------------
1        1        1
2        1        2
------------------------

How should i get the value "c" (that means i should get the value which is not mapped to "1" in the second table) from the table in which the id mapped.

A: Here is the answer for single record
Select
    t1.processId,
    t1.newId,
    t1.value,
    t2.processId,
    t2.mapnewId
FROM  t1
LEFT JOIN t2
ON t1.processId = t2.processId and t1.newId =  t2.mapnewId
where t1.processId = 1 and t2.processId is null

A: As per the my understanding you are looking for some query which will return the rows which are not der in second table..
If that's fine, then "Except" operation will help you out with the same :
The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. This means EXCEPT returns only rows which are not available in second SELECT statement.
Please refer:  http://www.tutorialspoint.com/sql/sql-except-clause.htm


text:
Q: nested For loop pattern in c++ in c++, when I am making nested For loop and I am trying to calculate the factorial...I don't get the correct factorials...I don't know why. For example factorial of 5 is 120 but here it results in 34560. why?
and here is the code:
int fact=1;

for (int number=1; number<=10; number++) {
    for (int i=1; i<=number; i++)

           fact=fact*i;

           cout <<"factorial of "<<number<<"="<<fact<<"\n";
}

here is it pictured:

A: You need to re-initialize fact for each number.
int fact=1;

for (int number=1; number<=10; number++) {
    fact = 1;
    for (int i=1; i<=number; i++)

           fact=fact*i;

           cout <<"factorial of "<<number<<"="<<fact<<"\n";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: optimize $x^2+y$ on the constraint that $x^2-y^3=0$ Problem: Find maximum and minimum value for the function $f(x,y)=x^2+y$ on the constraint $x^2-y^3=0$.
My Solution:
I have started solving this by using the Lagrange method to find points where the gradients are perpendicular and where the points are also satisfied by the constraint.
I get (by solving for when the determinant that holds the two gradients is zero) the equation $-2x(3y^2+1)=0$.
So this gives me first with $-2x=0$ and the constraint $x^2-y^3=0$ the system of equations:
$$x=0$$
$$x^2-y^3=0$$
Which gives me the point $(0,0)$ with value $f(0,0)=0$
With $3y^2+1=0$ and the constraint I get:
$$y^2=-1/3$$
$$x^2-y^3=0$$
Questions:

*

*My question for the second system of equation is: with $y^2=-1/3$ does this mean that there is no solution? Or did I do something wrong?

*The constraint is not a compact set of value, it is not bounded? My textbook gives the answer to this problem as minimum value is 0 and maximum does not exist. How can I prove this and how do I know that 0 is the minimum and not the maximum value?

A: WLOG $x=t^3,y=t^2$
$x^2+y=t^6+t^2=t^2(t^4+1)\ge0$


text:
Q: A non-empty closed proper set in a metric space
Let $A$ be a non-empty closed proper set in a metric space $\langle M,\rho\rangle$.
Let $x_0 \in M-A$, and let $\beta = \inf \{ \ \rho (x_0,a) \mid a \in A\}$.
Show that $\beta > 0$.

I know the requirements for a metric space but I don't know where $\beta$ comes into this problem. Any help on what I'm not seeing here would be greatly appreciated.

A: HINT: $\beta$ is basically the "distance" from $x_0$ to the set $A$. Unfortunately, sometimes we have $\beta=0$ even though $x_0$ isn't actually in $A$ - for example, take $A=(0, 1)$ and $\beta=0$. Then $x_0\not\in A$, but there are elements of $A$ "arbitrarily close" to $x_0$, so $\beta$ - the infimum (over $a\in A$) of the distances from $x_0$ to $a$ - is zero.
Of course, in that example, $A$ is not closed. The question is asking you to show that, if $A$ is closed, this silly behavior can't happen - if $x_0\not\in A$ then $\beta>0$.
So, towards solving the problem: in the example above ($x_0=0, A=(0, 1)$), what exactly made $\beta=0$? And how would $A$ being closed prevent that from happening?

A: Suppose $inf\{\rho(x_0,a), a\in A\}=0$. This implies that for every integer $n>0$, there exists $a_n\in A$ such that $\rho(x_0,a_n)<1/n$. This implies that the sequence $a_n$ converges to $x_0$ thus $x_0\in A$ since $A$ is closed. Contradiction. done.


text:
Q: How to use css for chart bar color in Javafx I have created a chart bar, and I wish to change the bar color according to the name of values. It has two series one shows number of green values which should be green and the other one yellow. I have also created a css file, but first problem is a get unknown property error for -fx-bar-fill in css. Beside I do not know how to call the appropriate color after creating the series? I face this warning at the time:
Mar 23, 2015 8:50:02 AM com.sun.javafx.css.parser.CSSParser parse
WARNING: CSS Error parsing file:/home/iman/workspace/AddNodeDynamicly  /bin/application/chart.css: Expected LBRACE at [1,9]

Here I create the chart
public class MostComputerizedController {
    @FXML
    private BarChart<String, Number> barChart;
    @FXML
    private CategoryAxis orgNameAxis;
    @FXML
    private NumberAxis yAxis;

    private ObservableList<String> orgNames = FXCollections
            .observableArrayList();

    private DataConstructor dc = new DataConstructor();

    @FXML
    private void initialize() {

        orgNames.addAll(dc.getSortedAssignedOrg().values());
        orgNameAxis.setCategories(orgNames);
        orgNameAxis.setLabel("Name of Organizations");
        orgNameAxis.tickLabelFontProperty().set(Font.font(10));
        yAxis.setLabel("Saturation");
        orgNameAxis.getStylesheets().add(
                getClass().getResource("/application/application.css").toExternalForm());

    }

    /*
     * *
     * Sets the organization to show the statistics for.
     *
     * @param
     */
    public void setPersonData() {

        XYChart.Series<String, Number> series = new XYChart.Series<>();
        XYChart.Series<String, Number> seriesy = new XYChart.Series<>();
        series.setName("Green");
        seriesy.setName("Yellow");

        for (String entryOrg : dc.getSortedAssignedOrg().values()) {
            for (List<String> entryfuncType : dc.getFuncTypeOrg().values()) {
                if (entryOrg.equals(entryfuncType.get(5))
                        && entryfuncType.contains("hasType")) {

                    int yellow = Collections.frequency(entryfuncType, "yellow");
                    int green = Collections.frequency(entryfuncType, "Green");
                    int typeNumber = Collections.frequency(entryfuncType,
                            "hasType");

                    series.getData().add(
                            new XYChart.Data<String, Number>(entryOrg, green));
                    seriesy.getData().add(
                            new XYChart.Data<String, Number>(entryOrg, yellow));

                }
            }

        }

        barChart.getData().addAll(series,seriesy);
    }
}

In main I add it to stage:
public class Main extends Application {
    private Stage primaryStage;
    private BorderPane rootLayout;
    private Model model = new Model();

    @Override
    public void start(Stage primaryStage) {

        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("IT-Saturation");
        initRootLayout();
        showOverView();

    }

    private void showOverView() {
        try {
            FXMLLoader loader = new FXMLLoader();

            loader.setLocation(Main.class.getResource("/view/OverView.fxml"));
            loader.setController(new OverViewController(model));

            AnchorPane overView = (AnchorPane) loader.load();
            rootLayout.setCenter(overView);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initRootLayout() {
        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("/view/RootLayout.fxml"));
            loader.setController(new RootLayoutController(model));

            rootLayout = (BorderPane) loader.load();
            // show scene containing the root layout
            Scene scene = new Scene(rootLayout);
            scene.getStylesheets().add(
                    getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            RootLayoutController controller = loader.getController();
            controller.setMainApp(this);
            primaryStage.show();

        } catch (IOException e) {

            e.printStackTrace();
        }

    public void showMostComputerizedStatistics() {
        try {
            // Load the fxml file and create a new stage for the popup.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class
                    .getResource("/view/MostComputerized.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();

            dialogStage.setTitle("Saturation in Organizations");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.initOwner(primaryStage);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);
            dialogStage.getScene().getStylesheets().add(
                    getClass().getResource("chart.css").toExternalForm());
            MostComputerizedController controller = loader.getController();
            controller.setPersonData();
            dialogStage.show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

and this is the css file:
@CHARSET "UTF-8";

.default-color0.chart-bar {
-fx-bar-fill: green;
}

.default-color1.chart-bar {
-fx-bar-fill: yellow;
}

A: If could get rid of the css warning by using -fx-background-color instead
.default-color0.chart-bar { -fx-background-color: rgb(146,208,80); }


text:
Q: AWK Assignment to variable I am looking for assignment of value of variable to another variable in awk.
Below is the example
if (substr($0,1,1) == "4")
{
    COUNT_DETAIL_SEG++
    SUM_OF_DETAIL_RCDS=$(COUNT_DETAIL_SEG)
    print "Sum of detail records is" SUM_OF_DETAIL_RCDS
}

Suppose if 1st character of line comes out to be "4" then i want to increment value of COUNT_DETAIL_SEG and assign this value to SUM_OF_DETAIL_RCDS and thereby print it.
But i am unable to retain this value.
Can anyone have any idea about this?

A: I think instead of
SUM_OF_DETAIL_RCDS=$(COUNT_DETAIL_SEG)

you want :
SUM_OF_DETAIL_RCDS=COUNT_DETAIL_SEG

because in awk, when you put $(INT), you refer no the N'th column of the current input line.

A: Maybe you want to do this at the start of the awk statement.  @sputnick is on the right track.
awk -v var="$bash_var" '{ awk code here}'

This will use the awk internal variable var instead of the shell variable bash_var.


text:
Q: Dynamic SQL with parameters is faster than stored procedure? I have found that if I have the same query created in code with a parameterized command, then its faster than if I run the same query in a stored procedure with parameters.
Why is this happening?
For example, when I run a query without stored proc , it takes 2 seconds, while if I run it in a stored procedure with parameters then it takes 4 to 5 seconds.


text:
Q: Iterate through items in list within dict in python Please help me with basics of dict.
I have a dict which has value as a list  below:
test = {2:['a',2,4,6], 3:[1,2,4,8]}

i need to get value with index[0] in k==2
output must be 'a'

A: Really simple:
test[2][0]

If you are a beginner you should check out the python docs for information on dict access.


text:
Q: Difference between git add ., git add -A and git add -u What is the difference between the following commands?

*

*git add .

*git add -A

*git add -u

I tried to execute them, and they create the same results.

A: git help add
   -A, --all, --no-ignore-removal
       Update the index not only where the working tree has a file matching <pathspec> but also where the index already has an
       entry. This adds, modifies, and removes index entries to match the working tree.

       If no <pathspec> is given, the current version of Git defaults to "."; in other words, update all files in the current
       directory and its subdirectories. This default will change in a future version of Git, hence the form without <pathspec>
       should not be used.

   -u, --update
       Update the index just where it already has an entry matching <pathspec>. This removes as well as modifies index entries to
       match the working tree, but adds no new files.

       If no <pathspec> is given, the current version of Git defaults to "."; in other words, update all tracked files in the
       current directory and its subdirectories. This default will change in a future version of Git, hence the form without
       <pathspec> should not be used.

*

*. is implied by both -A and -u if no <pathspec> is given (which is the case in your question).

*-A will stage changes, removed files, and added files.

*-u will stage changes and removed files, but not added files.


text:
Q: Divergence of the harmonic series and the Cauchy criterion imply $\lim_{n\to\infty} \sqrt[n]n=1$ Why the divergence of the harmonic series and the Cauchy criterion immediately imply $\displaystyle\lim_{n\to{+}\infty}{\sqrt[n]{n}}=1$?
Thanks for your help

A: The Cauchy root test says that $\limsup_{n\to\infty} \sqrt[n] {|a_n|}<1$ implies (absolute) convergence of $\sum_{n=1}^\infty a_n$.
Since we know that $\sum_{n=1}^\infty \frac1n$ is divergent, we conclude  $\limsup_{n\to\infty} \sqrt[n] {\frac1n}\ge1$, i.e. $\liminf_{n\to\infty} \sqrt[n] n\le1$. In fact, $\sqrt[n]n\ge1$ for all $n$ implies $\liminf_{n\to\infty} \sqrt[n] n=1$.
Therefore, if you knew that $\sqrt[n]n$ converges to some limit, then this limit must equal the $\limsup$, i.e. 1.

A: As Hagen already said it suffices to show, that $\sqrt[n] n$ converges. (Then by $\liminf_{n\to\infty} \sqrt[n] n=1$ the assertion follows.)
I think for the Cauchy criterion it was meant to show, that $\sqrt[n] n$ is a Cauchy sequence and hence converges.
But here you can easily check that the sequence is monotonously decreasing (for $n\geq 2$). Since (the sequence is bounded from below by $1$ or) $\liminf_{n\to\infty} \sqrt[n] n=1$ this would imply convergence.
For all $n\geq 2$ we have
$$ (n+1)^n = \sum\limits_{k=0}^{n}{\binom{n}{k}n^k}<n^n\sum\limits_{k=0}^{n}{\binom{n}{k}}=2^n\cdot n^n\leq n^n\cdot n^n=n^{n+1} $$
and hence
$$ \sqrt[n+1]{n+1}< \sqrt[n] n.$$

A: I'm not sure what you can do with the divergence of the harmonic series, but a much simpler approach is to notice the following: $n^{\frac{1}{n}} = e^{\ln(n^{\frac{1}{n}})} = e^\frac{\ln(n)}{n}$. Now, $$\lim_{n\to\infty}{e^{ \frac{\ln(n)}{n}}} = e^{\lim_{n\to\infty}\frac{\ln(n)}{n}} = e^0 = 1.$$ The last step follows by L'Hopital's rule on $\frac{\ln(n)}{n}$. I'm sorry if this solution isn't  what you were looking for and there is some other way you had in mind to solve this problem.


text:
Q: What are important pure mathematics courses for a prospective statistics PhD student? I know that linear algebra and analysis (especially measure theory) are important. Is it helpful to take graduate level courses in real and complex analysis? Should I take courses in abstract algebra beyond the introductory courses, e.g., commutative algebra and algebraic geometry?

A: In my opinion, some options to investigate at the graduate level could be: functional analysis (a natural framework for statistical formulations), stochastic processes, stochastic control (sequential analysis is optimal stopping), various flavors of PDE (many probabilistic problems are formulated as parabolic and nonlinear PDE's).  Pretty much all of these require real analysis at an undergrad level.  If you're interested in theoretical stuff, then taking measure theory is also pretty important as a prerequisite for the full treatment of these topics.  Complex analysis will have some use, but less than the above; there are connections to probability (i.e. harmonic functions), but it could very well be not worth it
Commutative algebra and algebraic geometry will be not be very useful (one connection I can think of is algebraic statistics, which isn't widely taught).  These topics will also be very challenging without a solid background in mathematics.

A: If you want to understand measure theory you have no choice but to take real analysis and advanced analysis (i.e. point set topology). Abstract algebra is definitely more grade-friendly than analysis, however I think it is far less useful.

A: Get real analysis, but not in the way I see people do it. When we interview math undergrads they don't seem to master the tools of real analysis, simple things like taking integrals are out of reach for most of them. I still don't understand why. So, my advice: pay attention to applications first and foremost.
Also get ODE and PDE course, and functional analysis and differential geometry. Linear algebra and tensors, of course, too. All with focus on applications.

A: With regards to commutative algebra and algebraic geometry, the subjects which are least addressed in the other answers, my impression is that as long as you avoid algebraic statistics, you can get by entirely without them. Avoiding algebraic statistics may be more and more difficult in the future though, since it has a lot of applications and intersections with machine/statistical learning, which is very prominent in present-day research, as well as applications in other areas. Commutative algebra and algebraic geometry are the subjects you want to learn the most specifically for algebraic statistics, see for example the answers to this question: Algebraic Geometry for Statistics
In contrast, all subfields of statistics use analysis. (Not so much complex analysis though, although that may be useful for understanding characteristic functions, a point which seems not to have been raised yet.) I think undergraduate level measure theory would probably be sufficient, since I have met professional statisticians (e.g. professors at top departments) who look down on measure theory, but if you really want to understand measure theory, a graduate level course in real analysis is a great help. Undergraduate measure theory tends to focus exclusively on Lebesgue measure on the real line, which has a lot of nice properties which general measures may not necessarily have, and moreover is an infinite measure. In contrast, a graduate level real analysis course will tend to have more emphasis on abstract measures, which make probability measures in general easier to understand, and also make the relationship clearer between continuous and discrete probability measures -- in other words, you will be able to see both subjects come together within one framework in your mind for the first time. Likewise, one might prove the Kolmogorov extension theorem in such a course. And an understanding of abstract measures is really indispensable for a rigorous understanding of stochastic processes in continuous time. It is even useful for understanding stochastic processes in discrete time, although less important than in the continuous case.


text:
Q: Formik + Yup form string validation not working with either Material UI TextField +useFormik or Formik component I have created a few different versions of a Formik form using different methods to try to get error handling to work properly (specifically, to reject inputs in certain fields if those inputs are not strings).  Struggling to see why a non-string isn't getting picked up and throwing an error...
Here's my first attempt, which uses Material UI TextField + useFormik
import { useFormik } from 'formik';
import * as yup from 'yup';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import { IAssetDTO } from '../types/types';

const validationSchema = yup.object({
    id: yup
        .string()
        .min(1, "Please enter id more than 1 character")
        .required("This field is required"),
    name: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    tags: yup
        .array()
        .nullable(),
    type: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    s3URL: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),
    thumbnailImageURL: yup
        .string()
        .min(1, "Please enter name more than 1 character")
        .required("This field is required"),

});

//create your own upload component
export const EditAssetForm = (props:IAssetDTO) => {

    const formik = useFormik({
        initialValues: {
            id: props.id,
            name: props.name,
            tags: props.tags,
            type: props.type,
            s3URL: props.s3URL,
            thumbnailImageURL: props.thumbnailImageURL,
            createdAt:props.createdAt,
            updatedAt:props.createdAt

        },
        validationSchema: validationSchema,
        onSubmit: (values) => {

            console.log("logging values" +JSON.stringify(values))

            alert(JSON.stringify(values, null, 2));
        },
    });

    return (

            <form onSubmit={formik.handleSubmit}>
                <TextField
                    fullWidth
                    id="id"
                    name="id"
                    label="ID"
                    value={formik.values.id}
                    onChange={formik.handleChange}
                    error={formik.touched.id && Boolean(formik.errors.id)}
                    helperText={formik.touched.id && formik.errors.id}
                />...

Everything renders fine, and the proper error gets thrown for character minimum, and being required.  But if I enter a string, no error gets thrown.
Here's my second attempt, in which I changed the component to use Formik, Form, and Field with schema validation
import { Formik, Form, Field } from 'formik';
 import * as Yup from 'yup';
 import { IAssetDTO } from '../types/types';

 const ValidationSchema = Yup.object().shape({
    id: Yup
    .string()
    .min(25, "Please enter id more than 25 character")
    .required("This field is required"),
name: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
tags: Yup
    .array()
    .nullable(),
type: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
s3URL: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
thumbnailImageURL: Yup
    .string()
    .min(1, "Please enter name more than 1 character")
    .required("This field is required"),
 });

 export const NewEditAssetForm = (props:IAssetDTO) => (

Signup

     <Formik
       initialValues={{
        id: props.id,
        name: props.name,
        tags: props.tags,
        type: props.type,
        s3URL: props.s3URL,
        thumbnailImageURL: props.thumbnailImageURL,
        createdAt:props.createdAt,
        updatedAt:props.createdAt

    }}
       validationSchema={ValidationSchema}
       onSubmit={values => {
       console.log("logging values" +JSON.stringify(values))

        alert(JSON.stringify(values, null, 2));
       }}
     >
       {({ errors, touched }) => (
         <Form>
           <Field name="id" />
           {errors.id && touched.id ? (

{errors.id}

           ) : null}...

Still no errors get thrown when input value is not a string (when I input a number, for example).
I though maybe it is because I am passing props to the form?  So I took the props out.
My last attempt used the exact copy and paste of the validation schema example and is not throwing errors when the input is a number.
What simple thing am I missing?
Thanks

A: For any string validations from Yup, they accept alphanumeric values. You would want to explore regex if you wanted letters only (for example a name).


text:
Q: Multer File Upload error I am using multer to upload file when i try to upload a file it show me error following are my code
var multer = require('multer');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../public/uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

var upload = multer({ storage: storage });

my form in ejs view is
<form action="class/<%= record.Class_Name %>/detial" method="post" enctype="multipart/form-data">
     <input type="text" name="UploaderName">
     input type="text" name="Title" >
     <input type="file" name="ThesisFile">
      <button type="submit">Choose File</button>
 </form>

my route code is
router.post('/Class/:name/detial' , isLoggedIn , upload.single('ThesisFile') , function(req ,  res , next) {
  var Name = req.body.UploaderName;
  var Title = req.body.Title;
  var file = req.body.ThesisFile;
  var thesis = {
    Submitted_By: Name,
    Title : Title,
    File: file
  };
  ClassModel.findOne({ Class_Name : req.params.name } , function(err , record) {
    record.ClassFiles.push(thesis);
        record.save().then(function(record) {
          req.flash('sucess_msg' , 'Thesis Added Sucessfully');
          res.render('class' , {
            "record" : record
          });
        });
  });
});

when i submit form it show me following error

A: <form id="myForm" name="myForm" action="class/<%= record.Class_Name %>/detial" method="POST" enctype="multipart/form-data">
  <input type="text" name="uploaderName">
  <input type="text" name="title" >
  <input type="file" id="thesisFile" name="thesisFile">
  <button type="submit">Upload</button>
</form>

You can handle the request in JavaScript instead of doing it in the html.
const $ = (selector) => {
  return document.querySelector(selector);
};

const submit = (event) => {
  event.preventDefault();
  const form = $("#myForm");
  const thesisFile = $("#thesisFile").files[0];

  const oData = new FormData(form);

  const request = new XMLHttpRequest();

  // replace "/Class/:name/detial" appropriately
  request.open("POST", "/Class/:name/detial", true);

  request.onload = (event) => {
    if (request.status === 200) {
      // do something
    } else {
      console.log("Error occurred");
    }
  };

  request.send(oData);
};

const form = document.forms.namedItem("myForm");
form.onsubmit = submit;


text:
Q: In Wikipedia's motivating example of wedge product, what happened to $e_1 \wedge e_1$ Wikipedia (https://en.wikipedia.org/wiki/Exterior_algebra) has a motivating example for wedge product.
In particular, it was written that:
$
\begin{align}
{\mathbf v}\wedge {\mathbf w} & = (a{\mathbf e}_1 + b{\mathbf e}_2) \wedge (c{\mathbf e}_1 + d{\mathbf e}_2) \\
& = ac{\mathbf e}_1 \wedge {\mathbf e}_1+ ad{\mathbf e}_1 \wedge {\mathbf e}_2+bc{\mathbf e}_2 \wedge {\mathbf e}_1+bd{\mathbf e}_2 \wedge {\mathbf e}_2 \\
& =(ad-bc){\mathbf e}_1 \wedge {\mathbf e}_2
\end{align}
$
It is explained that:

where the first step uses the distributive law for the exterior
  product, and the last uses the fact that the exterior product is
  alternating, and in particular $e_2 ∧ e_1 = −e_1 ∧ e_2$.

In this example, whatever happened to the term associated with $e_1 \wedge e_1$? and $e_2 \wedge e_2$?
Wikipedia doesn't say.

A: Since the product is alternating,
$$\color{red}{e_1}\wedge\color{blue}{e_1} = -\color{blue}{e_1}\wedge\color{red}{e_1}$$
and therefore
$$e_1\wedge e_1 = 0$$

A: We have
$$e_1\wedge e_1=-e_1\wedge e_1,$$
so $e_1\wedge e_1=0$.

A: The wedge product is defined to be the asymmetric tensors
$$ v_1 \wedge v_2 = v_1 \otimes v_2 - v_2 \otimes v_1 $$
Therefore $e_1 \wedge e_1 = 0$ vanishes.


text:
Q: One-sided limits for Greatest Integer Function evaluating to 0 / 0 I'm currently taking introduction to Calculus and I've been presented with this limit involving the greatest integer function (GIF):
$$\lim_{x \to 2^-} \frac{\lfloor x \rfloor - 1}{\lfloor x \rfloor - x}$$
Now since $x \to 2^-$ I figured I could immediately evaluate the limits of the first terms of the numerator and denominator and replace it with 1. This makes the numerator 0 and the denominator will be $1 - x$. After evaluating the limit of the denominator I arrive at $\frac{0}{-1}$ which is basically 0. However looking at the problem's answer keys it said that the limit should have been $-\infty$. I wasn't sure where I got it wrong so I thought that the key must be wrong for that item until I tried solving for this next limit:
$$\lim_{x \to 1^+} \frac{\lfloor x^2 \rfloor - \lfloor x \rfloor^2}{x^2 - 1}$$
Since $x \to 1^+$, I thought that $\lfloor x^2 \rfloor$ and $\lfloor x \rfloor$ would both resolve to 1 right? And that's what I did but the limit of the entire function then becomes an indeterminate form of type $\frac{0}{0}$. Now I know that I should rewrite the function in order to get rid of the terms that would cause it to become $\frac{0}{0}$ and factoring the denominator gives me $(x + 1)(x - 1)$ which will become $(2)(0^+)$ but given that the numerator is 0, isn't that the same indeterminate form? The answer key says that the limit is 0.
Am I missing something here? Is there a way to manipulate or rewrite these GIF that simply hasn't been taught to us?
EDIT
If you guys think that the question or the answer key must be wrong then please feel free to tell me :) I'm preparing for the exam tomorrow and I don't want to be bogged down thinking about these limits if they're wrong. I got most of the problems correctly and it's only these two that's been weird for me, I've tried what I can but I'm just stumped. I'm currently googling ways to rewrite the GIF function.

A: For the first one, you're right and the answer key would be for $x \to 2^+$. To see why, observe that we can work in the interval $(1, 2)$. Here, $\lfloor x \rfloor - 1 = 0$, and so the limit is $0$ if the denominator is not $0$. Indeed, that's exactly what happens, since $x - \lfloor x \rfloor$ is the fractional part function, that's $0$ only at the integers. Since there are no integers in $(1, 2)$, the limit is $0$.
For the second limit, we can apply the same reasoning with the interval $(1, \sqrt 2)$. Here, the numerator is identically zero, while the denominator is never zero. Hence, the limit evaluates to $0$ once again.


text:
Q: Issues with the labels in image in matplotlib I have to show a confusion matrix with corresponding labels in an image. I am using matplotlib for the same. But when the image is created it shows only alternative labels and all the labels are not shown. Also the data in the matrix get overlapped with the other grid data. Is shall be thankful for the help.
labels_x = ['D','F','A','G','DG','R','I','BS','COA','W','T','UserAcc%'] #create labels  for each classes
labels_y = ['D','F','A','G','DG','R','I','BS','COA','W','T','ProdAcc%']
# Guassian Confusion Matrix plo
fig = plt.figure(figsize=(18, 18))
ax = fig.add_subplot(111)
cax = ax.matshow(cm1 )

pl.title('CONFUSION MATRIX(Guassian)')
for i,j in ((x,y) for x in xrange(len(cm1))
        for y in xrange(len(cm1[0]))):
    ax.annotate(str(cm1[j][i]),xy=(i,j))
fig.colorbar(cax)
ax.set_xticklabels(['']+labels_x)
ax.set_yticklabels(['']+labels_y)
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.set_cmap('Pastel1')
plt.savefig(finaldata_path_plot+"GuassianConfusionMatrix.pdf", format ='pdf')
plt.show()
plt.close()

A: By default, matplotlib automatically chooses tick locations at "even" intervals.  Tick labels only occur at tick locations, so if you'd like to label every column and row, you'll need to set the tick positions as well as the tick labels.
Basically, you want something like:
i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

As a complete example:
import numpy as np
import matplotlib.pyplot as plt

labels = ['D', 'F', 'A', 'G', 'DG', 'R', 'I', 'BS', 'COA', 'W', 'T']
data = np.random.random((len(labels), len(labels)))

fig, ax = plt.subplots()
im = ax.matshow(data, cmap='Pastel1')
fig.colorbar(im)

i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

ax.set(ylabel='True label', xlabel='Predicted label', title='Confusion Matrix')
plt.show()


text:
Q: Rearranging terms in a summation and product Let $\mathcal{F}$ be the countable set of finitely-supported multi-indices, i.e. $$\mathcal{F} = \{\nu\in\mathbb{N}_0^{\mathbb{N}}:\nu_1+\nu_2+\ldots<\infty\}.$$
Let $(\rho_j)_{j\geq 1}$ be a sequence of positive real numbers. Then, we have
$$
\sum_{\nu\in\mathcal{F}}\prod_{j\geq 1}\left(\sum_{\ell=0}^{r}{\nu_j\choose \ell}\rho^\ell_j\right)^q = \prod_{j\geq 1}\sum_{n\geq 0}\left(\sum_{\ell=0}^{r}{n\choose \ell}\rho^\ell_j\right)^q,$$
with the convention that
$${n\choose m}=0\quad\text{if}\quad m>n.$$
It looks like it is doing some factorisation, but I can't see it cearly even if I write the sum explicitly. May I know what exactly it is doing with this series?

A: Let
$$f(n,j):=\left(\sum_{\ell=0}^{r}{n\choose \ell}\rho^\ell_j\right)^q>0.$$
Generally,
$$
\sum_{\nu\in\mathcal{F}}\prod_{j\geq 1}f(\nu_j,j)<\prod_{j\geq 1}\sum_{n\geq 0}f(n,j)$$
because when you develop the RHS, you get the sum of finite products of the LHS but also the sum of infinite products, which may be $>0.$


text:
Q: Can I order objects in Flexbox columns horizontally? I'm using Flexbox to display variable sized objects into multiple columns. I've noticed that they tend to get ordered in the following way:
+---+  +---+
| 1 |  | 3 |
+---+  |   |
+---+  |   |
| 2 |  +---+
|   |
+---+

If I'm sorting things by relevancy or age, this causes users to need to go back to the top of the page to view the next column, which isn't desirable. Is there a CSS property I can set so that each object gets placed in the shortest column? For example:
+---+  +---+
| 1 |  | 2 |
+---+  |   |
+---+  |   |
| 3 |  +---+
|   |
+---+


text:
Q: Getting Mutual Facebook Friends iOS SDK is there any way I can get friends of friends with a FBRequest or something like it? Right now I can only retrieve a users friends, but I want to retrieve my user's mutual friends. I realize that this won't work for all users, since of privacy permissions, but there should be at least a few users who have their profiles set to everyone. Could anyone move me in the right direction? Thanks so much.

A: Yes you can use Social Context API to get mutual friends: https://developers.facebook.com/docs/graph-api/reference/v2.0/user.context/mutual_friends
It will only returns mutual friends that are using the app and a total count


text:
Q: FutureBuilder doesn't update after failure recieved via try/catch I have FutureBuilder which takes future coming from HTTP GET request. Future object is initialized on tap of submit button, that too is based on isInEditMode bool.

*

*First time I tap on Submit, it's connectionState goes from none to waiting to done as expected.

*Lets say future catches error from Get request and I can thow it inside catch block gracefully, I get connectionState.done which is good.

*Now the problem comes on second tap of submit button, which doesnt update future's connectionState to waiting and in turn, builder doesnt show accordingly on screen.

*I have checked, everytime I tap on Submit button, brand new future object is retrieved from Get request, but it doesn't reflect in FutureBuilder. How to let FutureBuilder know that Future object is renewed/changed, adapt to the new one??

class AddEditProductSoScreen extends StatefulWidget {
  static const routeName = '/add-edit-product';

  @override
  _AddEditProductSoScreenState createState() => _AddEditProductSoScreenState();
}

class _AddEditProductSoScreenState extends State<AddEditProductSoScreen> {
  var isEditMode = false;
  final _formKey = GlobalKey<FormState>();
  ProductFormModel _formProduct;
  Future<Response> futureOfSubmit;
  bool isLoadingVisible = false;

  @override
  Widget build(BuildContext context) {
    final productsProvider =
        Provider.of<ProductsProvider>(context, listen: false);
    Product product = ModalRoute.of(context).settings.arguments;
    if (product != null) {
      isEditMode = true;
      _formProduct = ProductFormModel.copyFromProduct(product);
    } else {
      _formProduct = ProductFormModel.init();
    }

    return Scaffold(
      bottomNavigationBar: Container(
        height: 50,
        child: Material(
          color: Theme.of(context).accentColor,
          child: InkWell(
            onTap: isLoadingVisible
                ? null
                : () {
                    if (isEditMode) {
                      futureOfSubmit =
                          productsProvider.editProduct(_formProduct);
                    } else {
                      futureOfSubmit =
                          productsProvider.addProduct(_formProduct);
                    }
                    isLoadingVisible = true;
                    futureOfSubmit.then((value) {
                      //Navigator.of(context).pop();
                    }).catchError((error) {
                      showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                                title: Text('An error occurred!'),
                                content: Text('Something went wrong.'),
                                actions: [
                                  FlatButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                      child: Text('Okay'))
                                ],
                              ));
                    }).whenComplete(() {
                      setState(() {
                        isLoadingVisible = false;
                      });
                    });
                  },
            child: FutureBuilder(
              future: futureOfSubmit,
              builder: (context, AsyncSnapshot<Response> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Align(
                    alignment: Alignment.center,
                    child: Container(
                        height: 30,
                        width: 30,
                        child: CircularProgressIndicator(
                          backgroundColor: Colors.white,
                        )),
                  );
                } else {
                  return Container(
                    padding: EdgeInsets.all(10),
                    width: double.infinity,
                    child: Text(
                      'SUBMIT',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                      textAlign: TextAlign.center,
                    ),
                  );
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}

Any help would be appreciated, thanks!
Edit: here is addProduct method of productProvider class which gives back future object and do throw the exception as well..
Future<Response> addProduct(ProductFormModel product) async {
    const url = '................';

    try {
      Response response = await http.post(url,
          body: json.encode({
            'title': product.title,
            'description': product.description,
            'imageUrl': product.imageUrl,
            'price': product.price,
            'isFavorite': product.isFav
          }));

      Map respMap = json.decode(response.body);
      product.id = respMap['name'];
      _items.add(product.toProduct());
      notifyListeners();
      return response;
    } on Exception catch (error) {
      print("error is :: " + error.toString());
      throw Exception('Something went wrong!!');
    }
  }

A: To notify the framework, that the state of your widget has changed, you can use the setState method of StatefulWidget.
So this:
futureOfSubmit = productsProvider.editProduct(_formProduct);

should be:
setState(() { futureOfSubmit = productsProvider.editProduct(_formProduct); });

And the others accordingly.

A: use

setState((){});

to notify the framework ,that the state has changed.
use setState in your If else block
setState(() {
futureOfSubmit = productsProvider.editProduct(_formProduct);
 });


text:
Q: How to get all the selected options in a drop down list with JavaScript? I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc

                    <select name="SearchIn[]" multiple="multiple"  onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">

                    <option value="" disabled selected>Select</option>
                    <?php
//Loop over the options

 for($i=0;$i<sizeof($SearchCriteria);$i++){
  ?>

        <option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
        <?php echo $SearchCriteria[$i]['display'];?>
        </option>
   <?php
     }//!End of looping over search criteria
      ?>
                    </select>

                    <input type="hidden" name="Heading" valtue="" />

in another php file, I have included  firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
  $Heading = $dat->if_default('Heading', '');

but it only gives me the first option that the user has selected, but I need  all of them. How can I get them?

A: First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3

You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];

$selectedArr = array();
foreach($SearchCriteria as $item) {
    if (in_array($item["value"], $SearchIn)) {
        $selectedArr[] = $item["display"];
    }
}

$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3

2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">

        <select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
            <option value="" disabled selected>Select</option>
            <?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
            <option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
                <?php echo $SearchCriteria[$i]['display'];?>
            </option>
            <?php } ?>
        </select>

        <input id="heading" type="hidden" name="Heading" value="" />

    <input type="submit">
</form>

3) For a pure JavaScript solution (use the same HTML as above):


text:
Q: How to tell if any element in an array is a substring of a given string? I'm wondering if there's a more efficient way to do this in Python. I found a good solution in Ruby but it seems fairly specific.
Basically, I'm fetching weather condition data from an API and want to standardize their many nuanced conditions down to seven I can easily deal with them.
def standardize_weather_conditions(s):
    clear_chars = ['clear', 'sunny']
    clouds_chars = ['cloudy', 'overcast', 'fog']
    storm_chars = ['thunder']
    freezing_chars = ['ice', 'sleet', 'freezing rain', 'freezing drizzle']
    snow_chars = ['snow', 'blizzard']
    rain_chars = ['rain', 'drizzle', 'mist']

    if any_in_string(s, clear_chars):
        conditions = 'clear'
    elif any_in_string(s, clouds_chars):
        conditions = 'clouds'
    elif any_in_string(s, storm_chars):
        conditions = 'storm'
    elif any_in_string(s, freezing_chars):
        conditions = 'freezing'
    elif any_in_string(s, snow_chars):
        conditions = 'snow'
    elif any_in_string(s, wet_chars):
        conditions = 'wet'
    else:
        conditions = 'other'
    return conditions

def any_in_string(s, array):
    for e in array:
        if e in s:
            return True
    return False

A: You can define like this:
def any_in_string(s, lst):
    return any(word in s for word in lst)

A: any_in_string can be made a one-liner by doing return any([x in s for x in array])
Then you could make a dictionary mapping your description to your lists of search words:
all_chars = {'clear':clear_chars, \
             'clouds':clouds_chars, \
             'storm':storm_chars, \
             'freezing':freezing_chars, \
             'snow':snow_chars, \
             'wet':rain_chars }

for key in all_chars.keys():
     if any_in_string(s, all_chars[keys]):
         return key

return 'other'

That would help avoid the 'spaghetti-code' if-else block you have.
If you wanted to get a little more fancy, you could change the for loop above to:
conditions = [x for x in all_chars.keys() if any_in_string(s, all_chars[x])]
conditions = ' and '.join(conditions)
return conditions

This way you could get something like cloudy and wet.


text:
Q: Firebase fetches whole parents data, even when there is no valid path, How to avoid this? I am fetching data from firebase using ref(). The issue , i am facing is when there is no valid child path means, its fetching whole parent. For example, when i need to fetch something from ('User/'+phone), it works correctly when the phone is provided, But when there is no data in phone, then it goes to parent to fetch all.
I am using this, using redux and thunk. So the firebase values are fetched by the actions
Here is my Firebase Code in actions !:
 export const fetchOrderHistory = (phone, callback) => {
 return (dispatch) => {
    dispatch({ type: START_SPINNER_ACTION_FOR_ORDER_HISTORY })
    firebase.database().ref('orders/'+phone)
    .on('value', snapshot => {
        const snapShotValue = snapshot.val();
        callback(snapShotValue);
        dispatch ({ type: ORDER_HISTORY_FETCHED , payload: snapshot.val()});
        dispatch({ type: STOP_SPINNER_ACTION_FRO_ORDER_HISTORY })
    });

};

};
Kindly help !

A: You misunderstood the logic
firebase.database().ref('orders/'+ phone)

First of all, the word phone here is a variable, you could put x, and its value will be passed to firebase, like this
firebase.database().ref('orders/'+ x)

If x = 'phone' then this mean you are asking firebase to get you
  firebase.database().ref('orders/phone')

If x = 'users', this means you are asking firebase to get you this
  firebase.database().ref('orders/users')

If x = '', this means you are asking firebase to get you this
  firebase.database().ref('orders/')


text:
Q: d3 convert x axis from array indices to dates I have a data that is an array of values, like this:
[244, 13, 24, 0, 18, 24, 3, 4, ... ]

While array indices are simply integers, in this data they represent a range of dates such that the 0th index represents, say, 06/04/2013 and the last index represents 09/30/2013 although they're actually in seconds since 1970, so 1370378409 and 1380575923 would be more precise.
I would like my x-axis to show the dates that the array indices represent.  So that the ticks would look like dates: Mon 08, Tue 09 and so on.  As the data will change, I cannot know what the ticks should be ahead of time.. I'm hoping they can be calculated from the endpoints which I do know.
Theoretically, I'm thinking that I can convert from the domain of the x-axis (the chart's width) to the date range represented in the array.  Something like this (but this didn't work in this formulation):
var xAsTime = d3.time.scale()
                 .domain([0, width])
                 .range([startDate, endDate])

which should nicely translate from integers to dates.

A: d3 has a built in time scale specifically for this purpose:
https://github.com/mbostock/d3/wiki/Time-Scales

A: The x function usually scales from your data domain to the range needed which is often the width of your chart.  This is how you'll find things in many examples.
Usually to create axes, you pass to d3.svg.axis() your x function.  However, the main job of the x function is often to create, in my case, the bars of a bar chart.
My own x function that I'm using in this bar chart:
var x = d3.scale.linear()
            .domain([0, data.length])
            .rangeRound([0, width]);

Here's one from MBostock:
var x = d3.scale.ordinal()
            .rangeRoundBands([0, width], .1);

And another with a JSFiddle:
var x = d3.time.scale()
            .domain([new Date(data[0].date),
                    d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
            .rangeRound([0, width - margin.left - margin.right]);

Using the power and simplicity of d3 scales, I was able to solve this problem by converting from array indices to dates with a separate x function, xAsTime, like so:
var xAsTime = d3.time.scale()
                  .domain([this.start * 1000, this.end * 1000])
                  .range([0, width])

var xAxis = d3.svg.axis()
                .scale(xAsTime)
                .tickSize(-height)
                .tickPadding(3);

As per my question, the only change was to switch the domain and ranges.  While I unsure of the details, it seems like the domain of the scale is what is displayed as ticks.


text:
Q: Using subquery in SSIS results in NULL values I am trying to execute some SQL within a OLE DB Source Connector within SSIS that will get some statistics regarding databasesizes.
This query ran fine when used in SSIS for one server. Now however I am looping through a number of servers and two columns that should be (and had been) producing ints now produce NULLS with datatype four-byte signed integer [DT_I4].
These are DataFileSizeMB and LogFileSizeMB.
I am at a total loss here... (as always when turning here, it kinda feels like defeat simply having to ask ;)
This is the query, why won't it run in SSIS and does it run in SSMS?
   SELECT       @@SERVERNAME as Server
                ,getdate() as Meetmoment
                ,name as Databasenaam
                ,(  SELECT CAST(ROUND(SUM(size), 0) AS float) AS Expr1
                    FROM  ( SELECT database_id, type, size * 8.0 / 1024 AS size
                            FROM sys.master_files) AS fs_2
                    WHERE        (type = 0) AND (database_id = db.database_id)
                ) AS DataFileSizeMB
                ,(  SELECT CAST(ROUND(SUM(size), 0) AS float) AS Expr1
                    FROM (  SELECT database_id, type, size * 8.0 / 1024 AS size
                            FROM sys.master_files) AS fs_1
                     WHERE        (type = 1) AND (database_id = db.database_id)
                ) AS LogFileSizeMB
 FROM            sys.databases AS db
 ORDER BY DataFileSizeMB DESC

I changed the query to
select @@SERVERNAME as Server,
            getdate() as Meetmoment,
            mdf.name as Databasename,
            mdf.Size_MBs as  DataFileSizeMB,
            ldf.Size_MBs as LogFileSizeMB
FROM

(SELECT d.name,
ROUND(SUM(mf.size) * 8 / 1024, 0) Size_MBs
FROM sys.master_files mf
INNER JOIN sys.databases d ON d.database_id = mf.database_id
where type = 0
GROUP BY d.name) as mdf

LEFT JOIN

(SELECT d.name,
ROUND(SUM(mf.size) * 8 / 1024, 0) Size_MBs
FROM sys.master_files mf
INNER JOIN sys.databases d ON d.database_id = mf.database_id
where type = 1
GROUP BY d.name) as ldf on mdf.name = ldf.name

but alas...... It must be something else............ Where to look?
As far as I can see these columns are ints all the way, except during calculation. I tried changing all relevant columns, in- and outputs to float but no difference.
Already in Query Builder the outcome fopr these columns is NULL where in SSMS the query runs just fine

A: My assumption is that you are running into a permissions issue on the connection with the NULL. –  @billinkc 18 hours ago
Well, bugger..... That is actually it.... Turns out the account I used DOES have access to SYS.DATABASES but NOT to SYS.master_files.....
I have something to look into ;)
See the following threads

*

*How to give a user access to sys.master_files in SQL Server?

*SQL Server: sys.master_files vs. sys.database_files
I ended up creating a script that creates a job that creates a table that inserts the relevant columns from sys.master_files in a table on which the reporting user has db_datareader. It is that table I use in the query used in SYS

A: I rewrote the query and avoided all subqueries: this one did the trick:
select     @@SERVERNAME as Server,
            getdate() as Meetmoment,
            sysdb.name as Databasename,
            sum(datafile.Size* 8 / 1024) as  DataFileSizeMB,
            sum(logfile.Size* 8 / 1024) as LogFileSizeMB
FROM SYS.DATABASES (NOLOCK) sysdb
        left join SYS.master_files datafile on sysdb.database_id = datafile.database_id and datafile.type = 0
        left join SYS.master_files logfile on sysdb.database_id = logfile.database_id and logfile.type = 1
group by sysdb.name


text:
Q: How to use GROUP BY in Firebird? The structure of T_TABLE2 is
ID INT
TBL1_ID INT
TESTER VARCHAR
LOT_ID VARCHAR
GRP VARCHAR
SITE_NUM INT
TEST_NUM VARCHAR
TEST_DESC VARCHAR
MEASUREMENT DOUBLE PRECISION
UNIT VARCHAR
LL DOUBLE PRECISION
UL DOUBLE PRECISION
STATUS VARCHAR

and I use SQL editor in Firebird to test my query. The query is
SELECT TEST_DESC, MEASUREMENT, LL, UL
FROM T_TABLE2
GROUP BY TEST_DESC

but I got this error in GROUP BY.
Invalid token.
Dynamic SQL Error.
SQL error code = -104.
Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause).

A: You have to apply some aggregate function (COUNT(),MIN(), MAX(), SUM(),...) to each of the columns in SELECT clause that are not part of GROUP BY.
For example your query might look like
SELECT TEST_DESC, MAX(MEASUREMENT) MAX_MEASUREMENT, MAX(LL) MAX_LL, MAX(UL) MAX_UL
  FROM T_TABLE2
 GROUP BY TEST_DESC

Another syntactically valid usage is to get a list of distinct values
SELECT TEST_DESC, MEASUREMENT, LL, UL
  FROM T_TABLE2
 GROUP BY TEST_DESC, MEASUREMENT, LL, UL

which is equivalent of
SELECT DISTINCT TEST_DESC, MEASUREMENT, LL, UL
  FROM T_TABLE2

If you would been more specific in your question about what exactly you're trying to achieve with this query then the answer could've addressed you particular needs.

A: While some databases, such as MySQL, are more lenient, in standard SQL when you use GROUP BY, the SELECT list must only contain the columns being grouped by and aggregate functions (e.g. SUM(), MAX()). If you were allowed to specify other columns, it's unpredictable which of the rows of the grouped column these columns will come from -- you may even get a mix of columns from different rows.
So you need to do something like:
SELECT TEST_DESC, MAX(MEASUREMENT) MEASUREMENT, MAX(LL) LL, MAX(UL) UL
FROM T_TABLE2
GROUP BY TEST_DESC

A: You must be coming from MySQL. MySQL - IMHO misleadingly, incorrectly, and in a black-magicky, unpredictible sort of way - allows you to specify partial GROUP BY queries and the database engine tries to figure out from the rest of the query which value of the non-grouped-by columns you want. Standard SQL (Firebird and most other RDBMSes), on the other hand, does not; it requires any non-aggregate columns to be contained in the group by, and any non-group-by columns to explicitly specify which row you want.
In your case, the offending columns are MEASUREMENT, LL, and UL. You need to specify which MEASUREMENT, LL, and UL you want (yes, even if they are all the same; the database engine has no way of knowing or guaranteeing this), or if you want to group by one or more of the columns or possibly you forgot to aggregate (Did you want the SUM?)

Examples of valid queries:

*

*Group by all columns (equivalent to a SELECT DISTINCT):
SELECT TEST_DESC, MEASUREMENT, LL, UL
FROM T_TABLE2
GROUP BY TEST_DESC, MEASUREMENT, LL, UL

*Group by MEASUREMENT as well and return the MIN LL and MAX UL:
SELECT TEST_DESC, MEASUREMENT, MIN(LL), MAX(UL)
FROM T_TABLE2
GROUP BY TEST_DESC, MEASUREMENT

*SUM non-grouped columns:
SELECT TEST_DESC, SUM(MEASUREMENT), SUM(LL), SUM(UL)
FROM T_TABLE2
GROUP BY TEST_DESC

*A combination of aggregates:
SELECT TEST_DESC, COUNT(DISTINCT MEASUREMENT), SUM(LL), MAX(UL)
FROM T_TABLE2
GROUP BY TEST_DESC


text:
Q: Set rectangle style in OpenCV I wish to know how many styles does OpenCV have for drawing detections. I wish know how to draw the rectangle like in this image:

A: OpenCV doesn't provide styles. You can only draw a rectangle with a given color, with 4/8 connected or with anti-aliasing points, with a given thickness.
You can, however, simply draw 8 lines recovering the coordinates from the rectangle:

The code is pretty straightforward:
#include <opencv2/opencv.hpp>
using namespace cv;

void drawDetection(Mat3b& img, const Rect& r, Scalar color = Scalar(0,255,0), int thickness = 3)
{
    int hor = r.width / 7;
    int ver = r.height / 7;

    // Top left corner
    line(img, r.tl(), Point(r.x, r.y + ver), color, thickness);
    line(img, r.tl(), Point(r.x + hor, r.y), color, thickness);

    // Top right corner
    line(img, Point(r.br().x - hor, r.y), Point(r.br().x, r.y), color, thickness);
    line(img, Point(r.br().x, r.y + ver), Point(r.br().x, r.y), color, thickness);

    // Bottom right corner
    line(img, Point(r.br().x, r.br().y - ver), r.br(), color, thickness);
    line(img, Point(r.br().x - hor, r.br().y), r.br(), color, thickness);

    // Bottom left corner
    line(img, Point(r.x, r.br().y - ver), Point(r.x, r.br().y), color, thickness);
    line(img, Point(r.x + hor, r.br().y), Point(r.x, r.br().y), color, thickness);
}

int main()
{
    // Load image
    Mat3b img = imread("path_to_image");

    // Your detection
    Rect detection(180, 160, 220, 240);

    // Custom draw
    drawDetection(img, detection);

    imshow("Detection", img);
    waitKey();

    return 0;
}


text:
Q: creating timeago with result from mysql fetch array I have a script for converting a datetime value into a timeago. I have a php script that fetches the admin's message rows and time they were sent. However, i wish to convert this time to something like 20mins ago, hence i want to convert the time on each message to a certain time ago. So each time i add the timeago script into the mysql query, the page refuses to comeup. I guess the two script isnt working hand in hand.
This is my timeago script:
$ptime = "2017-06-08 03:16:20";
function get_timeago( $ptime )
{
    $estimate_time = time() - $ptime;

    if( $estimate_time < 1 )
    {
        return 'less than 1 second ago';
    }

    $condition = array(
                12 * 30 * 24 * 60 * 60  =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
    );

    foreach( $condition as $secs => $str )
    {
        $d = $estimate_time / $secs;

        if( $d >= 1 )
        {
            $r = round( $d );
            return ' This Happened About ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';

            echo "$r";
        }
    }
}

$timeago=get_timeago(strtotime($ptime));
echo $timeago;

This is my mysql query:
 <?php
            $sql2="SELECT * FROM ".$cn."msg ";
            $result2= mysql_query($sql2) or die(mysql_error());
                    while($rwsm=  mysql_fetch_array($result2)){
                  echo"
";
                    echo "";

                    echo "
";

                      echo "".$rwsm[3]."";

                      echo "
 ".$rwsm[2]."
";

                      $msg= $rwsm[1];
                      echo "
".$msg."
";

                    echo "
";
                  echo "
";
                      }
                  ?>

This is where i tried to combine the both script to convert the .$rwsm[3]. time variable to some time ago:
<?php
                   $sql2="SELECT * FROM ".$cn."msg ";
                $result2= mysql_query($sql2) or die(mysql_error());
                        while($rwsm=  mysql_fetch_array($result2)){
                  echo"
";
                    echo "";

                    echo "
";

//THE TIMEAGO SCRIPT STARTS HERE
$ptime = $rwsm[3];
function get_timeago( $ptime )
{
    $estimate_time = time() - $ptime;

    if( $estimate_time < 1 )
    {
        return 'less than 1 second ago';
    }

    $condition = array(
                12 * 30 * 24 * 60 * 60  =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
    );

    foreach( $condition as $secs => $str )
    {
        $d = $estimate_time / $secs;

        if( $d >= 1 )
        {
            $r = round( $d );
            return 'Last Updated:   ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';

            echo "$r";
        }
    }
}
$timeago=get_timeago(strtotime($ptime));
echo "".$timeago."ago";
//THE TIMEAGO SCRIPT ENDS HERE

    echo "
 ".$rwsm[2]."
";

                      $msg= $rwsm[1];
                      echo "
".$msg."
";

                    echo "
";
                  echo "
";
                      }
                  ?>


text:
Q: unity3d ios xcode error ,google VR sdk
I am using xphone in the Iphone package error, I built a new project only googleVR a plug
Iphone 6sp,IOS11
unity 5.6.2
GoogleVRForUnity_1.70.0.unitypackage

A: you must open the workspace containing the project (not the project itself) in XCode and build and run the project there.
Run from "Unity-iPhone.xcworkspace" instead of "Unity-iPhone.xcodeproj"


text:
Q: Change admin password alfresco share I can't login with my user administrator "admin" and I can't reset the password
I try to reset the password in Postgresql data base with this comande
UPDATE alf_node_properties SET string_value='f59601091e5cbb1dcf28bbb15a30c50b' WHERE node_id=4 and qname_id=12;
but don't resolve the problème !!!

A: Are you using the correct Alfresco's reset password method ?
Things have changed since Alfresco 5.1, you might be doing it the wrong way.
You globally have three ways to do it :

*

*Set a user with a known password as admin :
in alfresco-global.properties set the alfresco_user_store.adminusername=username property

*Configure the authentication component to accept all logins using org.alfresco.repo.security.authentication.SimpleAcceptOrRejectAllAuthenticationComponentImpl

*Change the admin password in the DB (By following the correct alfresco's version instructions)


text:
Q: using user input to setstate and then using the value of the state as part of the url for an axios request
*

*everything was working before trying to have the first axios request use the state that was set by the user input.

*i think my problem might have something to due with the async nature of setState and axios

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      summonerLevel: "",
      accountId: "",
      matchHistory: []
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({ name: event.target.value });
  }
  handleSubmit(event) {
    console.log(this.state);
    event.preventDefault();
  }

- the first axios request using this.state.name in the url
  componentDidMount() {
    var api_key = "...";
    axios
      .get(
        `https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/${
          this.state.name
        }?api_key=${api_key}`
      )
      .then(response => {
        var { summonerLevel, accountId } = response.data;

        this.setState({ summonerLevel, accountId });
        console.log(this.state);

A: Your this.state.name is null at the beginning. so your request will be sent is
https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/?api_key=...
try using
async componentDidMount() {
     var api_key = "...";
     await axios
      .get(
         `https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/${
         this.state.name
         }?api_key=${api_key}`
      )
      .then(response => {
         const { summonerLevel, accountId } = response.data;
         this.setState({ summonerLevel, accountId });
         console.log(this.state);
         }
}


text:
Q: Error message from previous request is popping up whenever the user types in input field -[ redux with useselector] Below is a snippet which I'm using to implement login functionality with redux and saga, I'm using the functional component. The problem is if I enter the wrong password and email saga triggers an error and the redux action is set to log in error and in the component using selectors I'm able to catch it and show it as an error(I'm using a general toast android component for showing errors) But after this step, if the user start's typing new email or password in the input field, the error message from previous requests again starts popping up without even pressing the login button. What is the better way to clear an error message from the state, once it is shown?
Login.js
function Login({ navigation }, props) {
  const dispatch = useDispatch();

  // Application states
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [emailColor, setEmailColor] = React.useState('black');
  const [passwordColor, setpasswordColor] = React.useState('black');

  //selectors
  const loginSelector = useSelector(state => state.login);
  console.log('selector resp ==>', loginSelector);
  if (loginSelector.error && !loginSelector.loading) {
    console.log(loginSelector.error_message);
    danger(loginSelector.error_message);
  }
  //selector end

  //func start
  const checkLogin = () => {
    setEmailColor('#000');
    setpasswordColor('#000');
    if (!validation.isEmail(email)) {
      warning('Invalid Email');
      setEmailColor('red');
      return;
    } else if (validation.isEmpty(password)) {
      warning('Invalid Password');
      setpasswordColor('red');
      return;
    } else {
      dispatch(userLogin(email, password));
    }
  };
  //func end

  return (
    <ScrollView showsVerticalScrollIndicator={false} >
      <View style={styles.container}>
        <View style={styles.topArea}>
        </View>
        <View style={styles.middleArea}>
          <View style={[styles.loginColumn, styles.centralize]}>
            <Text style={styles.loginImage}>trōc</Text>

            <MaterialIconTextbox
              handler={setEmail}
              type="email"
              icon="email-outline"
              label="Email"
              statusColor={emailColor}
              style={styles.loginFields}
            />
            <MaterialIconTextbox
              handler={setPassword}
              type="password"
              icon="pencil-box-outline"
              label="Password"
              statusColor={passwordColor}
              style={styles.loginFields}
              secure={true}
            />
            <Text />
          </View>
        </View>
        <View style={styles.bottomArea}>
          <View style={styles.centralize}>
            <TouchableOpacity
              style={styles.loginButton}
              onPress={checkLogin}>
              <Text style={styles.loginButtonText}>Login</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.loginButtonGoogle}
              onPress={() => onGoogleButtonPress()}>
              <Text style={styles.loginButtonText}>Sign in with google</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.topMargin}
              onPress={() => navigation.navigate('Signup')}>
              <Text style={styles.signupText}>New? Signup</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.topMargin}
              onPress={() => this.props.navigation.navigate('Forgot')}>
              <Text style={styles.forgotText}>Forgot password.</Text>
            </TouchableOpacity>
            {/* <Text>{users.error_message}</Text> */}
          </View>
        </View>

      </View>
    </ScrollView>
  );
}
export default Login;

loginReducer.js
import {LOGIN_SUCCESS, LOGIN_ERROR} from '../../utils/Constants';
import {danger} from '../../utils/Notification';
import initialState from './initialState';
export default function loginReducer(state = initialState.login, action) {
  switch (action.type) {
    case LOGIN_SUCCESS:
      return {
        ...state,
        error: false,
        loading: false,
        ...action,
      };
    case LOGIN_ERROR:
      return {
        ...state,
        error: true,
        loading: false,
        ...action,
      };
    default:
      return state;
  }
}

Any help will be highly appreciated :)
Update
I came up with two solutions, but which one is better, I'm not able to figure out
first is
 if (loginSelector.error && !loginSelector.loading) {
    console.log(loginSelector.error_message);
    danger(loginSelector.error_message);
    dispatch(clearLoginError());
  }

second is
React.useEffect(() => {
    if (loginSelector.error && !loginSelector.loading) {
      danger(loginSelector.error_message);
      dispatch(clearLoginError());
    }
  }, [loginSelector.error, loginSelector.loading]);

Can you folks help me out

A: So I believe both the methods are ok to change a state in redux, the one without using useEffect and the one with useEffect
if (loginSelector.error && !loginSelector.loading) {
    console.log(loginSelector.error_message);
    danger(loginSelector.error_message);
    dispatch(clearLoginError());
  }

and

React.useEffect(() => {
    if (loginSelector.error && !loginSelector.loading) {
      danger(loginSelector.error_message);
      dispatch(clearLoginError());
    }
  }, [loginSelector.error, loginSelector.loading]);


text:
Q: How to make a transaction flow from Navision to a C# component registered for COM interop? In my context I have Navision involved, but perhaps this is related to every COM interop scenario, I don't know.
Anyway, the situation:
- I've a simple C# component registered for COM Interop
- I call it from Navision, just before inserting a new record (for who knows Navision, inside an 'OnInsert' trigger, thus in the context of a transaction)
I was expecting to have an ambient transaction, but System.Transactions.Transaction.Current is null.
Am I missing something?
Are there particular techniques I should adopt to make the transaction flow into my interop component?

A: Are you trying to begin a transaction in NAV and then access that transaction using your COM object?
It sounds like the System.Transactions.Transaction.Current value is null because you haven't initialised a transaction in your COM object - can you post a code sample of it?
Although from your post it sounds like you're expecting the Transaction.Current value to refer to the transaction you have initiated in NAV and I don't think this is what will happen, or is even possible!
What is your COM object trying to do with the transaction? Perhaps there is a different approach we could take?

A: Talking with Navision: Exposing .NET Components to Navision
How to: Use the BYOT (Bring Your Own Transaction) Feature of COM+
How to use COM+ transactions in a Visual C# component (MS KB 816141)


text:
Q: Shell Script: Speed of transfer of a hop using command Ping Create a shell script that relates the speed of transfer of a HOP between the machine and the IP chosen. Use the PING command and express the result in kB/sec.
!/bin/bash

I create a temporary file
touch info.txt;

I take the second line of command PING stopped after two seconds
I post the results in the file.
ping -t 2 $1 | head -2 | tail -1 > info.txt;

I take bytes
cut -c -2 info.txt;

I take ms
cut -c 53-59 info.txt;

Now, how to make transformations in KB and in Sec?
Show result
echo "Result: .....";

I delete the file.
rm file.txt;

A: You can do:
bytes=$(cut -c -2 info.txt)
ms=$(cut -c 53-59 info.txt)
echo "KiB: "$(($bytes/1024))
echo "Sec: "$(($ms/1000))
speed=$((1000*$bytes*1000/1024/$ms))
speed=$(echo $speed|sed -r 's/^(.*)(.{3})$/\1.\2/')
echo "Speed: $speed KiB/s"

This is of course considering 1 KiB = 1024 bytes, where KiB is usually used for KB.

A: RESULT=$(ping  -t 2 -c 2 $1 | grep 'time=' | head -1 | sed 's/([0-9][0-9]).(time=)(.)(ms)/\1:\3/g')
echo "BYTES = ${RESULT%:}"
echo "SPEED = ${RESULT#:}"

For the conversion part you might need to use python or perl. In bash it is not possible to calculate fractional numbers.

A: Thank you all! WORK!

touch info.txt;
ping -t 2 $1 | head -2 | tail -1 > info.txt;
bytes=$(cut -c -2 info.txt);
ms=$(cut -c 53-59 info.txt);
KB=$(echo "scale=5; $bytes /1024" | bc);
Sec=$(echo "scale=5; $ms /1000" | bc);
Speed=$(echo "scale=5; $KB/$Sec" | bc);
echo "Speed of HOP: $Speed KB/sec.";
rm info.txt;


text:
Q: How to suppress bullet points in HTML list

(a) mines, quarries, and other works for the extraction of minerals from the earth;

(b) industries in which articles are manufactured, altered, cleaned, repaired, ornamented, finished, adapted for sale, broken up or demolished, or in which materials are transformed; including shipbuilding and the generation, transformation and transmission of electricity or motive power of any kind;

(c) construction, reconstruction, maintenance, repair, alteration, or demolition of any building, railway, tramway, harbour, dock, pier, canal, inland waterway, road, tunnel, bridge, viaduct, sewer, drain, well, telegraphic or telephonic installation, electrical undertaking, gas work, water work, or other work of construction, as well as the preparation for or laying the foundations of any such work or structure;

(d) transport of passengers or goods by road, rail, or inland waterway, including the handling of goods at docks, quays, wharves or warehouses, but excluding transport by hand.

I have the above HTML.  What CSS coding can I add above this HTML that will suppress the bullet points generated by the
 tags?

A: Try following in your HTML, which will hide bullets of
:


text:
Q: Python Regex String not getting split correctly I am trying to split a line of text that looks something like this
host=randomhostid123 moreinfo id=otherstuffhere version="morestuff" type=TYPEA::TYPEB

i am tying to use split to parse it into
host=randomhostid123 moreinfo
id=otherstuffhere
version="morestuff"
type=TYPEA::TYPEB

to do this I was using
str.split('?[a-zA-Z]*=')

but all this is producing is the original string all over again
I think the regex looks ok, but I am new to python regex

A: You are using str.split(). What you want is re.split:
re.split(r'\s+(?=[a-zA-Z]+=)', str)

This will split on spaces which are followed by words which in turn are immediately followed by =. Note, that you have to put everything but the spaces in a lookahead, so that it is not swallowed by the split operation.

A: The ? in your regex is being parsed literally, and since there's no ? in  your string it doesn't split. I think you may have been going for a regex lookahead match, but string.split doesn't support regexes.

Ah—too long looking at the documentation! m.buettner summarized things very nicely.


text:
Q: Template specialization of constructor within class definition I can't get the syntax right for in-class constructor template specialization, despite trying to copy exactly as it is done elsewhere.
Consider the following class:
template<int A, int B>
struct Point {
    const int x;
    const int y;

    Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
    void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};

Implementing specialized template-based constructors outside of the class definition, namely
template<int A, int B>
struct Point {
    const int x;
    const int y;

    Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
    void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};

template<> Point<0, 0>::Point() : x(0), y(0) { std::cout << "Constructing origin" << std::endl; }

works just fine. However, when I try to do so within the class definition itself by adding the line
template<int A, int B>
struct Point {
    const int x;
    const int y;

    Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
    template<> Point<0, 0>::Point() : x(0), y(0) { std::cout << "Constructing origin" << std::endl; }
    void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};

I receive the following errors:
9:14: error: explicit specialization in non-namespace scope 'struct Point<A, B>'
9:35: error: invalid use of incomplete type 'struct Point<0, 0>'
4:8: error: declaration of 'struct Point<0, 0>'

Another SO template specialisation question I tried to copy:
explicit-template-specialization-for-constructor

A: You can't. Specialization required a complete, well-defined type. So when the compiler encounters your Point<0,0>::Point() definition, the templated type Point is still incomplete. What you're trying to do is explaining the exception before you present the rule.
In the example you provided, the constructor is not a specialization, rather a template on a additional type (C).


text:
Q: Configure Nginx, Kibana, Elasticsearch My setup
Nginx + Kibana - same box different domain, sub-domain (nginx - example.com, kibana - kibana.example.com)
Elasticsearch - 192.168.100.31
I have used the config defined below. Replaced 127.0.0.1 with Elasticsearch ip 192.168.100.31
https://github.com/elasticsearch/kibana/blob/master/sample/nginx.conf
This setup works within local network. But fails when connecting externally with error message on browser "Error Could not contact Elasticsearch at http://192.168.100.31:9200. Please ensure that Elasticsearch is reachable from your system.".
Kibana config.js points to ip and port 9200 -
  elasticsearch: "http://192.168.100.31:9200",

Note: Changing this port to match port defined in nginx config 8433 makes it stop functioning.
nginx config
server {
    listen          8443 ssl;
    server_name     kibana.example.com;

    access_log  /var/logs/nginx/kibana.access.log main;
    error_log   /var/logs/nginx/kibana.error.log;

    auth_basic "Authorized users";
    auth_basic_user_file /file/location/kibana.htpasswd;

    location / {
        root  /usr/local/kibana-3.1.0;
        index  index.html  index.htm;
    }

    location ~ ^/_aliases$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
    }
    location ~ ^/.*/_aliases$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
    }
    location ~ ^/_nodes$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
    }
    location ~ ^/.*/_search$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
    }
    location ~ ^/.*/_mapping {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
    }

    # Password protected end points
    location ~ ^/kibana-int/dashboard/.*$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
        limit_except GET {
          proxy_pass http://192.168.100.31:9200;
          # auth_basic "Restricted";
          # auth_basic_user_file /file/location/kibana.htpasswd;
        }
    }
    location ~ ^/kibana-int/temp.*$ {
        proxy_pass http://192.168.100.31:9200;
        proxy_read_timeout 90;
        limit_except GET {
            proxy_pass http://192.168.100.31:9200;
            # auth_basic "Restricted";
            # auth_basic_user_file /file/location/kibana.htpasswd;
        }
    }
}

Feels there has to be some proxy setting between nginx and elasticsearch to prevent local ip displayed on browser. Can someone show how to get this configured.

A: Found solution, had to set PROXY in nginx and of course set FQDN matching in Kibana's configs.js


text:
Q: Asyncio errors: CLI - python daemon example but has errors/undesired behavior on exit I've developed a pattern to use for a commanding a python daemon through cmd module shell using an eventloop. However, its not ready yet because I can't figure out how to gracefully exit the two applications (I'm still learning asyncio and can't figure out the following problem). When the cmd module is commanded to exit I get:
(Cmd) exit
Shutting down client...
Traceback (most recent call last):
  File "client_loop.py", line 10, in <module>
    loop.run_until_complete(test.cmdloop())
  File "...\asyncio\base_events.py", line 467, in run_until_complete
    future = tasks.ensure_future(future, loop=self)
  File "...\lib\asyncio\tasks.py", line 526, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required

I'm not good with asyncio yet, what am I doing wrong? Sorry for the long question but the files/errors make it long and hopefully makes it easier to debug.
Here are the supporting files:
shell.py
# implementation of the (Cmd) prompt with history functionality
# standard imports
import cmd as cmd

class Shell(cmd.Cmd):
    def __init__(self, **kwargs):
        cmd.Cmd.__init__(self, **kwargs)
        self.eventloop = None
        self.shutdown_client = None
        self.tcp_echo_client = None

    def set_eventloop(self, loop):
        self.eventloop = loop

    def set_funcs(self, tcp_echo_client, shutdown_client):
        self.tcp_echo_client = tcp_echo_client
        self.shutdown_client = shutdown_client

    def do_exit(self,*args):
        """
        Exits the shell gracefully
        :param args:
        :return:
        """
        print('Shutting down client...')
        self.shutdown_client(self.eventloop)
        return True

    def default(self, line):
        try:
            self.eventloop.run_until_complete(self.tcp_echo_client(line, self.eventloop))
        except SystemExit:
            pass

server.py
# server logic to parse arguments coming over the TCP socket and echo it back

# standard imports
import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print("Received %r from %r" % (message, addr))

    print("Send: %r" % message)
    writer.write(data)
    await writer.drain()

    print("Close the client socket")
    writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    # Close the server
    for task in asyncio.Task.all_tasks():
        loop.run_until_complete(task)

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.stop()
    loop.close()
    exit(0)

client.py
# client functions to send message over TCP and process response
# standard imports
import asyncio

# user imports
import shell

async def tcp_echo_client(message, loop):
    reader, writer = await asyncio.open_connection('127.0.0.1', 8888,
                                                   loop=loop)

    print('Send: %r' % message)
    writer.write(message.encode())

    data = await reader.read(100)
    print('Received: %r' % data.decode())

    print('Close the socket')
    writer.close()

def shutdown_client(loop):
    loop.stop()

    # Find all running tasks:
    pending = asyncio.Task.all_tasks()

    # Run loop until tasks done:
    loop.run_until_complete(asyncio.gather(*pending))

loop = asyncio.get_event_loop()
test = shell.Shell()
test.set_eventloop(loop)
test.set_funcs(tcp_echo_client, shutdown_client)
loop.run_until_complete(test.cmdloop())
loop.close()

A: The problem lies in the fact that cmd doesn't require asyncio to process input from the user and send a message to through the TCP/IP socket. Simply removing asyncio from the client side solved the problem. It still offers the shell implementation and the client-server pattern. Here is the new code:
server.py
# server logic to parse arguments coming over the TCP socket and echo it back

# standard imports
import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print("Received %r from %r" % (message, addr))

    print("Send: %r" % message)
    writer.write(data)
    await writer.drain()

    print("Close the client socket")
    writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    # Close the server
    for task in asyncio.Task.all_tasks():
        loop.run_until_complete(task)

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.stop()
    loop.close()
    exit(0)

client_shell.py
# implementation of a shell prompt (using Cmd module) to send message over TCP and process response
# standard imports
import socket
import cmd as cmd

class Shell(cmd.Cmd):
    def __init__(self, **kwargs):
        cmd.Cmd.__init__(self, **kwargs)

    def do_exit(self,*args):
        """
        Exits the shell gracefully
        :param args:
        :return:
        """
        print('Shutting down client...')
        return True

    def default(self, line):
        try:
            self._tcp_echo_client(line.encode())
        except SystemExit:
            pass

    def _tcp_echo_client(self, message):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            print('Send: %r' % message)
            s.connect(('127.0.0.1', 8888))
            s.sendall(message)
            data = s.recv(1000)
            print('Received: %r' % data.decode())
            print('Close the socket')

if __name__ == '__main__':
    Shell().cmdloop()


text:
Q: Jenkins pipeline sh step not returning different status code I have the following code inside the pipeline
def deploy(branch='master', repo='xxx'){
    if (env.BRANCH_NAME.trim() == branch) {
        def script = libraryResource 'build/package_indexes/python/build_push.sh'
        env.PYPI_REPO = repo
        sh script
    }else {
        echo "Not pushing to repo because branch is: "+env.BRANCH_NAME.trim()+" and not "+branch
    }
}

And the script looks like this:
if [ -f "setup.cfg" ]; then
  # only build a wheel if setup.cfg exists, so we can disable wheel build if need be
  echo "Build package ${PACKAGE_NAME} tar.gz and wheel, and push to jfrog repo: $PYPI_REPO"
  python setup.py sdist upload -r jfrog
  echo "status code: $?"
fi

When I execute the script directly in shell:
sh push.sh
It returns the status code 1 when failed to push to the repo, see output:
Submitting dist/xxx-xxxx-0.0.7.tar.gz to https://xxx.jfrog.io/xxx/xxx-pypi/
Upload failed (405): Method Not Allowed
error: Upload failed (405): Method Not Allowed
status code: 1

But when I execute the pipeline in Jenkins, the status code is 0 when failed to push to the repo:
Submitting dist/xxx-xxxx-0.0.7.tar.gz to https://xxx.jfrog.io/xxx/xxx-pypi/
Upload failed (403): Forbidden
+ echo status code: 0
status code: 0

How do I make it to return status code 1 when it fails in Jenkins job?
UPDATE
Looks like the problem is not inside Jenkins, I can replicate the same problem on the shell of the Jenkins server.

A: This is not a Jenkins pipeline issue but a bash issue. You can read this article to learn how bash scripts exit codes work.

In Linux any script run from the command line has an exit code. With
  Bash scripts, if the exit code is not specified in the script itself
  the exit code used will be the exit code of the last command run.

Basically, your inner Python script returns a non-zero code but the echo command, which is the last command executed, is successful, making your script return a 0/success code.
You can either remove the echo or add an exit 1 when needed.

A: To return the status code, you need to invoke sh like this: sh returnStatus: true, script: 'echo "test"'

Regarding to your output, it looks like you have different results here, are you sure that you should get the same exit code? The echo is only invoked in the second case.


text:
Q: CSS line up DIV TABLE to stack when longer than width Hey all I am trying to find the correct code in order for the input thats within the DIV TABLE to go to the next line if it's too long to display on one line:
The JSFIDDLE is here
The HTML code:

Accident Information:

                Date of Accident:

                {AI_DATEOF}

                Type of Accident:

                {AI_ACCIDENT}

                Accident Location:

                {AI_LOCATION}

                Accident Details:

                {AI_DETAILS}

                List Of Other Family Members

 That Were Involved:

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

                      Name:

                      {AID_NAME}

                      ID#

                      {AID_ID}

                      Relation:

                      {AID_RELATION}

A: Instead of making your own CSS, if you're using Bootstrap, why don't you change the class of cell to col-sm-2 or so on?


text:
Q: Perl - How to find out whether a request was made via proxy? My question is, if its possible to find out whether a request was made via proxy or not?
Is there an environment variable i can use?
I looked through some lists of environment variables and didn't find something useful.
Or do i have to directly read the http header for this purpose?
E.g. As long as the 'via' field is empty no proxy was used?
Would be thankful if someone got an easy solution for this in perl.
May you have other advices to verify a user and block/filter requests that are fake visitors.

A: First, use of a proxy does not mean the user is fake. It is very common inside companies to use a proxy server for security purposes. Second, not all proxy servers add a Via header so a request from a proxy might be no different than a request from the browser itself.


text:
Q: How To Suppress Output of a Cell in Jupyter Notebook with Julia I've been trying to figure out how to suppress the output of the last line in Jupyter Notebook with Julia. In particular, when the last line is an assignment. In Jupyter Notebook with a Python kernel, when I do
k=5

in a cell, no output is produced. However, in Julia, a simple assignment also returns a value, which makes the notebook visually redundant, and sometimes impossible to read with long return values. For example, when I have
using Random
Random.seed!(0)

in a cell, the cell produces a very long output that contains pretty much unnecessary details.
MersenneTwister(UInt32[0x00000000], Random.DSFMT.DSFMT_state(Int32[748398797, 1073523691, -1738140313, 1073664641, -1492392947, 1073490074, -1625281839, 1073254801, 1875112882, 1073717145  …  943540191, 1073626624, 1091647724, 1073372234, -1273625233, -823628301, 835224507, 991807863, 382, 0]), [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0  …  0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], UInt128[0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000  …  0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000, 0x00000000000000000000000000000000], 1002, 0)

A related question suggested using the %%capture magic. However, this is not applicable to a Julia kernel.
Is there any simple way of suppressing such unnecessary output?

A: Ok I figured it out. The output can be disabled by simply appending a semicolon at the end of the last statement. A cell with
Random.seed!(0);

with produce no output.


text:
Q: SSL error on xbox.client.authenticate I am following this documentation http://xbox.readthedocs.org/en/latest/authentication.html
    try:
        xbox.client.authenticate('joe@example.org', 'hunter2')
        gt = xbox.GamerProfile.from_gamertag('JoeAlcorn')
        print gt.gamerscore
    except Exception as exception:
        print exception

My code create exception
[Errno 185090050] _ssl.c:344: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

what am i doing wrong?

A: I was receiving the same error while I was trying to debug the xbox client.
While I was researching the error, I found out the "certifi" module needs to be installed.
pip install certifi

Installing this module will fix the SSL error.
On a side note, after I installed this module, I ran into another error while testing with a real gamer tag:
TypeError: sequence item 0: expected string, int found

In order to fix this issue, you will need to physically update one of the module's files.
xbox.resource

is the file and
_def fetch(cls, base_url)

is the method to update.
Within this method, you will find this line of code:
headers = {'x-xbl-contract-version': 2}

You will need to change the int value of 2 to a string:
headers = {'x-xbl-contract-version': '2'}

I hope this works for you!


text:
Q: image is not rendered though its shown in the storyboard So I'm working on Xamarin studio 6.1.1 and am building a native Xamarin.iOS app, on the LaunchScreen.storyboard file I have two UIImageViews, assigned image for each one from image assets.
the problem is when I run my app one of the two images is shown and another one is not though both are shown in the storyboard file.
I have placed all my images directly in the Resource folder and made sure that there is nothing missing, The scenario is soo simple and I'm not sure what the reason behind this.