C# Class project - need help calculating perimeter

Question: Consider the following project:
Create a new Windows Forms Application project and change its Name to MyRectangle. Create a class named Rectangle. Add a private integer variable named _height, and another private integer variable named _width. Add accessors for both variables, calling them Height and Width. Have the accessors read and write the _height and _width variables. Add a public method named GetArea() that returns the area of the rectangle, and another named GetPerimeter() that returns the perimeter of the rectangle. Use the code shown below to define these methods.
public int GetArea()
  {
   return (_width * _height);
   }

   public int GetPerimeter()
  {
   return ((2 * _width) + (2 * _height));
   }

Modify the public MyRectangle() method to create an instance of your Rectangle class. Use the Height accessor to set the rectangle height to 6, and the Width accessor to set the rectangle width to 8. Call the GetArea() and GetPerimeter() methods, and output the results to the Console.
---End of project instructions----
I created the class.cs as follow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyRectangle
{
    internal class Rectangle
    {
        // ** Properties **
        private int _height = 0;
        private int _width = 0;

        // ** Accessors for Height**
    public int Height
        {
            set
            {
                _height = value;
            }
            get
            {
                return _height;
            }
        }

        // ** Accessors for Width **
    public int Width
        {
            set
            {
                _width = value;
            }
            get
            {
                return _width;
            }
        }
    public int GetArea()
    {
        return (_width * _height);
    }

    public int GetPerimeter()
    {
        return ((2 * _width) + (2 * _height));
    }
    }
}

I think I got the class file right, but beyond that I am completely stuck.
Comment: Hi, Second part of the code is the class.cs file i did which was the goal of the training... i got stuck calling the class from the form code... by the way this is not an official "credit school work" just a side training i am taking to learn about C#.. thanks for the comments
Answer: You develop the Rectangle class correctly, remaining reuse it
MyRectangle.Rectangle _Rectangle = new MyRectangle.Rectangle();
_Rectangle.Height = 6;
_Rectangle.Width = 8;
int _RectangleArea = _Rectangle.GetArea();
int _RectanglePerimeter = _Rectangle.GetPerimeter();

Comment: Many Thank you for your help ...

"the world is much better because of peps like you!"


How to use constructor objects in another state using flutter

Question: I am creating this shopping app , the home page displays pictures and some data from firestore firebase as a gridView. THIS IS THE SCREEN OF THIS PAGE
Once the user click on one of the images in this page the app will show him another page contains more details about the product with Hero animation.
THIS IS THE SECOND PAGE
The second page is a stateless widget and it takes some parameters
<code>@override
 Widget build(BuildContext context) {
  return GridView.builder(

  ........

  itemBuilder: (BuildContext context, int index){
    String image = documents[index].data['image'].toString();
    String ti = documents[index].data['title'].toString();
    String prix = documents[index].data['price'].toString();
    String desc = documents[index].data['description'].toString();
    String categ = documents[index].data['category'].toString();
    return new Material(
      elevation: 5.0,
      borderRadius:
      new BorderRadius.all(new Radius.circular(15.0)),
      child: new InkWell(
        onTap: () {
          Navigator.push(
           context,
           new MaterialPageRoute(
           builder: (context) =>
           new FullScreenImagePage(image,ti,prix,desc,categ)));
        },
        child: new Hero(
          tag: image,
          child: new Column(
            children: <Widget>[
              new Padding(padding: EdgeInsets.all(4.0)),
              new FadeInImage(
                image: new NetworkImage(image),
                fit: BoxFit.cover,
                placeholder: new AssetImage("assets/ic.png"),
              ),
              new Text(ti, style: TextStyle(fontSize: 13.0, height: 1.0),),
              new Text('prix: $prix MAD', style: TextStyle(fontSize: 9.0),),
            ],
         ),
       ),
     ),
   );
</code>
Then I receive the parameters in this class
<code>class FullScreenImagePage extends StatelessWidget {
  String imgPath ,title,price,desc,categ;
  FullScreenImagePage(this.imgPath,this.title,this.price,this.desc,this.categ);

......

 Padding(
   padding: EdgeInsets.all(10.0),
   child: Hero(
     tag: imgPath,
     child: Material(
       elevation: 20.0,
       shadowColor: Colors.black26,
       child: Image(
         image: NetworkImage(imgPath),
         fit: BoxFit.cover,
       ),
     ),
   ),
 ),
</code>
The problem that I have is that I wanna change the stateless widget of FullScreenImagePage to stateful with keeping the same variables
Answer: if you are using IntelliJ
you can change you stateless widget into a stateful one using alt+enter

go to the class name{{FullScreenImagePage}
press alt + Enter
Answer: Just convert the stateless widget to stateful widget either manually or by using the shortcut(quick fix). Then access your variable in the state subclass using widget.variable_name


Creating adjacency matrix

Question: I have a datastructure which looks like below
 id  year   club
"A" "2010" "C1"
"B" "2010" "C1"
"C" "2010" "C2"
"A" "2011" "C1"
"B" "2011" "C2"

etc. My problem is to create a matrix on a year by year basis where the each unique individual is fixed to a row and each unique club is fixed to a column. If in a given year the individual visits the club the corresponding intersecting cell takes the value of 1 else 0.
Any help on this is much appreciated.
Thanks
Anup
Comment: I'm a little confused by what you want here. Can you maybe provide a sample of how your output should look? I'm having trouble picturing how an "adjacency matrix" applies to this problem.
Comment: Hi David. I'm actually having trouble trying to format the data. Maybe the term adjacency matrix is incorrect here. What I'm trying to do is set unique ids as rows and unique clubs as columns. If an id visits a club then the intersecting cell takes the value 1 or 0 otherwise. But I have to do this on a year by year basis. I hope this is clearer
Comment: When you say "year by year," do you want a separate matrix for each year, or do you want to count the number of years (or times) an id visits each club?
Comment: No I need separate matrices for each year stacked one after the other. Therefore if we make two matrices for 2010 and 2011, then i guess I need to rbind(mat1, mat2).
Comment: Please give us an example of what you expect the solution to look like.  You lack the language, which is ok, but use an alternative method to convey what you're after.
Answer: In base R, I would use by and xtabs:
by(dat, dat$year, with, as.matrix(xtabs(~ id + club) * 1L))

It returns a list of matrices (one per year). Also, I would recommend not multiplying by 1L to return matrices of booleans.

Edit1: as suggested, you can also create a contingency table quite easily:
table(dat[c("id", "club", "year")])

Edit2: I see your comment to Ricardo's answer, maybe this is what you are looking for:
library(plyr)
ddply(dat, .(year, id), with, 1L * (table(club) > 0))
#   year id C1 C2
# 1 2010  A  1  0
# 2 2010  B  1  0
# 3 2010  C  0  1
# 4 2011  A  1  0
# 5 2011  B  0  1

You might also want to use .drop = FALSE to get all (6) possible year/id combinations:
ddply(dat, .(year, id), with, 1L * (table(club) > 0), .drop = FALSE)
#   year id C1 C2
# 1 2010  A  1  0
# 2 2010  B  1  0
# 3 2010  C  0  1
# 4 2011  A  1  0
# 5 2011  B  0  1
# 6 2011  C  0  0

Comment: Why not `table(dat[c(1, 3, 2)])` or `ftable(dat, row.vars=c(2, 1), col.vars=3)`? Just curious...
Comment: If the LHS of the formula is empty, you can also use `table` in place of `xtabs` which will produce a contingency table of counts: `table(id, club)`
Comment: Thank you very much folks. This is very helpful indeed.
Answer: This one-line solution outputs a single dataframe instead of separate matrices like the other solutions thus far posted. It requires the reshape2 package, which if you've never used it before is extremely useful for this sort of thing.
require(reshape2)

df = data.frame(id=c('a','b','c','a','b')
               ,year=c(2010,2010,2010,2011,2011)
               ,club=c('c1','c1','c2','c1','c2')
                )

result = dcast(df, year + id ~ club, fun.aggregate=length, drop=F)

> result

  year id c1 c2
1 2010  a  1  0
2 2010  b  1  0
3 2010  c  0  1
4 2011  a  1  0
5 2011  b  0  1
6 2011  c  0  0  # If you don't want this record, use: drop=T

Comment: Maybe add a `drop = FALSE` to your `dcast` in case unused levels are to be kept (as with year = 2011 and id = c).
Comment: @AnandaMahto Good call
Answer: based on the comments, suitable formats are either a three-dimensional array or a list of data.frames / data.tables.
    library(data.table)
DT <- data.table

### create a template matrix
# find all unique ID's and unique Club's
ids <- unique(DT$id)
clubs <- unique(DT$club)
# matrix template based on the number of ids & clubs
mat.template <- matrix(0L, nrow=length(ids), ncol=length(clubs), dimnames=list(ids, clubs))

# iterate over the unique values of year
DT <- data.table(dat, key="id,club")
res <- lapply(unique(DT$year), function(y) {
    # index the matrix by the DT where y == year. Set those values to 1
        mat <- copy(mat.template)
        mat[as.matrix(DT[y==year, list(id, club)])] <- 1
        mat
    })

setattr(res, "names", unique(DT$year))

Results:
res

$`2010`
  C1 C2
A  1  0
B  1  0
C  0  1

$`2011`
  C1 C2
A  1  0
B  0  1
C  0  0

Comment: Hi Ricardo. Thanks for the solution but it looks I did not specify my problem correctly. I have now edited the problem statement. The expand.grid option is not giving me the dummy variable output that I was looking for.
Comment: @Anup. First try not to change your mind regarding a question. But more important, if you do, make that updated request inside your question, not as a comment to someone's answer.
Comment: Note: There's a function `CJ` for `data.table` that performs the job of `expand.grid`.
Comment: thanks @Arun, I always forget about CJ
Comment: Hi Ricardo. Great it works just fine. One last question. Is it possible for me to get this into a four column matrix where Column 1 is the year, column 2 is the ID and columns 3 and 4 represent the dummy variables?
Comment: @ flodel: I agree. I apologize for the confusion in the question. Next time I will post a question with the expected output. I think that would have solved the problem. My bad.
Comment: @anup, the first answer I posted was more in line with what you were looking for.  While flodel is correct, I would add that taking the time to think out your question will actually help clarify the problem for yourself as well as for others.  This will save a lot of time for all involved :)    Please don't let this deter you from asking more questions

Creating adjacency matrix


Como identificar o elemento HTML em que um script js está contido?

Question: Assim: Eu coloco um script js dentro de uma div, por exemplo. Como eu posso fazer esse script identificar a DIV em que está contido sem seletores como ID ou Class?
É que vejo alguns scripts de incorporação que inserem coisas (imagens, videos e etc) dentro do elemento em que eles são colocados, sem precisar usar seletores. Como isso é feito?
OBS: Javascript puro. Estou aprendendo o js puro.
Obrigado e boa tarde à todos.
Comment: Mas  a div tem uma identificação ?
Comment: Podes dar um exemplo do código que referes para percebermos melhor a que te referes? _"vejo alguns scripts de incorporação que inserem coisas [...] dentro do elemento em que eles são colocados"_
Answer: Se você não quer recuperar pelo Id ou Class. Você pode recuperar pela TagName.
document.getElementsByTagName

No exemplo abaixo, criei uma
 de bebidas e também criei uma  para adicionar o valor recuperado via javascript.
<!DOCTYPE html>

Bebidas

Coca Cola

Pepsi

Fanta

<button onclick="minhaFuncao()">Clique Aqui</button>

Answer: Você consegue passar o elemento por parâmetro usando o comando this.
Exemplo:
function teste(elemento) { ... }

em seguida:


Fetch row from tableview on Button click in same row JavaFX

Question: I have created a TableView in JavaFX it contains two columns :

First Row (Roll): It contains roll no. of student
Second Row (Details): It contains a Button which when clicked prints "Roll" of corresponding row.

My Approach is:
    static ObservableList<Student> list= FXCollections.observableArrayList();
    static ObservableList<Student> getStudentList() throws SQLException {
        con = ConnectionUtil.getDataBaseConnection();

        String SQL = "Select * from student;";
            ResultSet rs = con.createStatement().executeQuery(SQL);
            while(rs.next()){
              //Student cm = new Student(rs.getInt("rno"), rs.getString("name"),false);
                Student cm = new Student();
                cm.setFullName(rs.getString("name"));
                cm.setRoll(rs.getString("rno"));
                cm.setSingle(false);
              list.add(cm);
            }
      return list;
    }

    static TableColumn<Student, String> rollCol = new TableColumn<Student, String>("Roll");

    static TableColumn<Student, Void> viewCol = new TableColumn<Student, Void>("Details");

      static TableColumn<Student, Void>  addButtonToTable() {
        //TableColumn<Student, Void> viewCol = new TableColumn("Button Column");

        Callback<TableColumn<Student, Void>, TableCell<Student, Void>> cellFactory = new Callback<TableColumn<Student, Void>, TableCell<Student, Void>>() {
            @Override
            public TableCell<Student, Void> call(final TableColumn<Student, Void> param) {
                final TableCell<Student, Void> cell = new TableCell<Student, Void>() {

                    private final Button btn = new Button("View");

                    {

                        btn.setOnAction((ActionEvent event) -> {

                            /////////////////WORK START FROM HERE
                            static Student stu=tables.getItems();

                            String res = (stu.getRollNo().toString());

                            System.out.println(res);
                        });
                    }

                    @Override
                    public void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(btn);
                        }
                    }
                };
                return cell;
            }
        };

        viewCol.setCellFactory(cellFactory);

        return viewCol;
    }
    public String getRollNo() {
        return rollNo;
    }
    public void setRoll(String rollNo) {
        this.rollNo = rollNo;
    }

Problem with me:

My Table shows both columns well
But it doesn't prints the "Roll" in the output.

Please tell me how can I do this...
Thanks in advance
Answer: static is not allowed for declarations of local variables and TableView.getItems returns a ObservableList, not Student. Access the Student instance via the TableRow. (If you display all the buttons in a row, not in a column, the required logic would be very different.)
private final Button btn = new Button("View");

{

    btn.setOnAction((ActionEvent event) -> {
        Student stu = getTableRow().getItem();
        String res = stu.getRollNo().toString();
        System.out.println(res);
    });
}

@Override
public void updateItem(Void item, boolean empty) {
    super.updateItem(item, empty);
    setGraphic(empty ? null : btn);
}


Undefined index php ajuda

Question: Boas pessoal estou a fazer um teste de php e deu me um erro que nao estou a conseguir resolver este é o teste:
e aqui esta o meu trabalho o erro e na linha 22
Comment: vc iniciou a sessão dentro da função mas não fez a chamada dela, logo `$_SESSION['x']` não existe.
Comment: Inclua o código ao invés das imagens
Comment: Utilize uma condição `if..else` ou *ternário* para verificar se o valor existe, antes de imprimi-lo. Ex.: `echo isset($_SESSION['x']) ? $_SESSION['x'] : 'No ecxiste';`
Answer: Acredito que esse problema esta acontecendo porque não há a Session com value 'x' definida. Pelo seu código a session é definida em uma função javascript que nunca é chamada :/. Ou seja se você tentar usar a Session 'x' e ela nao existe provavelmente dará erro de undefined index. E isso você pode tratar com um if antes de exibir, como por exemplo:
<code>isset($_SESSION['x']) ? $_SESSION['a'] : null;
</code>
Tenta chamar a função "numerox();" ou por um evento onclick/onchange ou coloque esse trecho após o término da função, só para ver se funciona, caso não funcione, poste o código pra poder ajuda-lo melhor.

Undefined index php ajuda


Prove there are no prime numbers in the sequence $a_n=10017,100117,1001117,10011117, \dots$

Question: Define a sequence as $a_n=10017,100117,1001117,10011117$. (The $nth$ term has $n$ ones after the two zeroes.)
I conjecture that there are no prime numbers in the sequence. I used wolfram to find the first few factorisations:
$10017=3^3 \cdot 7 \cdot 53$
$100117=53\cdot 1889$
$1001117=13 \cdot 53\cdot1453$ and so on.
I've noticed the early terms all have a factor of $53$, so the problem can be restated as showing that all numbers of this form have a factor of $53$. However, I wouldn't know how to prove a statement like this. Nor am I sure that all of the terms do have a factor of $53$.
I began by writing the $nth$ term of the sequence as
$a_n=10^{n+3}+10^n+10^{n-1}+10^{n-2}+10^{n-3}+\cdots+10^3+10^2+10^1+7$ but cannot continue the proof.
Answer: It is as simple as $$a_{n+1}=10a_n-53$$
Comment: $1001117+53=1001170$, so if $100117$ is a multiple of $53$, $1001117$ must be too.
Comment: Just to clarify: $a_{n+1}=10(a_n-7+1)+7=10a_n-53$.
Comment: Can you elaborate a little further?
Answer: Use induction in order to complete the (excellent) hint by @Michael.

First, show that this is true for $n=1$:
$a_1=53\cdot189$
Second, assume that this is true for $n$:
$a_n=53k$
Third, prove that this is true for $n+1$:
$a_{n+1}=$
$10\cdot\color\red{a_n}-53=$
$10\cdot\color\red{53k}-53=$
$530k-53=$
$53(10k-1)$

Please note that the assumption is used only in the part marked red.
Answer: The sequence is given by
$$
a_n = 10^{n+3}+10\cdot \frac{10^n-1}{9}+7
$$
Then
$$
9a_n = 9\cdot10^{n+3}+10\cdot (10^n-1)+63
= 9010\cdot 10^n+53
= 53\cdot(170 \cdot 10^n+1)
$$
Therefore, $53$ divides $9a_n$.
Since $53$ does not divide $9$, we have that $53$ divides $a_n$, by Euclid's lemma. (We don't even need to use that $53$ is prime, just that $9$ and $53$ are coprime.)
Comment: When you have a number whose base-10 representation has long strings of repeated digits, multiplying by 9 tends to make them turn into long strings of 0s (or sometimes 9s for the obvious reason). Here are two ways to see why. (1) 1111111=9999999/9 = (10000000-1)/9, etc. (2) 9 = 10-1, so multiplying by 9 means shifting one place left and subtracting the original number, which makes those long strings of digits cancel out.
Comment: Can you explain the last line?
Comment: Thank you! Your answer makes a lot of sense. Can you explain why you decided to multiply by $9$?
Comment: @zz20s, to clear the denominators.
Comment: Bottom line: $1001\cdots 17= 53 \cdot 18\cdots 89$.
Answer: Another way to find the inductive relationship already cited, from a character manipulation point of view:
Consider any number in the sequence, $a_n$.  To create the next number, you must:

Subtract $17$, leaving a number terminating in two zeroes;
Divide by $10$, dropping one of the terminal zeroes;
Add $1$, changing the remaining terminal zero to a $1$;
Multiply by $100$, sticking a terminal double zero back on;
Add $17$, converting the terminal double zero back to $17$

Expressing this procedure algebraically, and simplifying:
$$a_{n+1}=\left (\frac{a_n-17}{10}+1 \right ) \times 100+17=10a_n-53$$


How to create a protocol in objective-C

Question: I want to create a Utils file, to have some functions and use them in some classes, but I'm not sure of how to do it.
I have:
Utils.h
#import <Foundation/Foundation.h>

@protocol Utils

@optional

-(NSString*)colorToHex:(UIColor*)color;

@end

@interface Utils : NSObject

@end

Utils.m
#import "Utils.h"

@implementation Utils

-(NSString*)colorToHex:(UIColor*)color{
    return @"Working";
}

@end

mainClass.h (snippet)
@interface StyleTableViewController : UITableViewController <Utils>

mainClass.m (the call)
NSString *myString = [self colorToHex:color];
NSLog(@"%@",myString);

And it crashes when it calls the function. What should I do?
Thanks
Comment: I'm not sure what you're trying to do and what this has to do with protocols?
Answer: When you state that your class conforms to a protocol (by adding ) you tell the compiler that this class implements all the methods defined in the protocol.
A Protocol is not a class - it's just a list of methods. So in your code, you had a protocol call Utils, and a class called Utils. You conformed to the protocol, but did not implement the methods, which is why the program crashed when you tried to call colorToHex.
What you need to do in your case is create a Util object in your StyleTableViewController and use it to call the colorToHex method, or make the colorToHex method a class method and call it from the Util class when needed. Another option would be to make StyleTableViewController a subclass of Utils, but I doubt this will be a good design here.
Comment: I didn't understand at all the use of protocols, thanks for the explanation!
Answer: Another option would be to add a category Utils to UIColor. Not exactly what you asked for but it solves your problem more elegantly than using a protocol.

How to create a protocol in objective-C


Openssl "Self-signed certificate in certificate chain" when server sends whole certificate chain with the self-signed certificate to the client

Question: I am having the following certificate chain:
Self-signed Certificate --> Intermediate --> Client cert, Server cert. I have application for ssl communication and also verify peer setting. I try to test this chain with openssl s_client command and I get Verify return code: 19 (self signed certificate in certificate chain). The server sends the whole chain in the handshake.
I tried to test this with Bundle.pem which contains the self-signed and the intermediate certificates and also with the Self-signed.pem but the result is the same.
openssl s_client -msg -connect localhost:1500 -CAfile Self-signed.pem/Bundle.pem -cert Client.crt -key Client.key

Then I issued another intermediate certificate and from that one I issued new server certificate
openssl s_client -msg -connect localhost:1500 -CAfile Bundle2.pem -cert Client.crt -key Client.key

Bundle2.pem contains the second intermediate certificate and the self-signed certificate and this works fine. Also the server now does not send the whole chain of certificates, its how the application is designed.
Can someone explain why this is a issue, why I cannot make successful verification if server and client have the same intermediate certificate?
Answer: Solved this by adding basicConstraints=CA:TRUE in openssl.conf to the imtermediate certificate when issuing


How to test whether 2 prediction intervals are statistically different?

Question: I've been struggling with this for a while now, hopefully someone will know how to help me :)
Here it is :
1) I'm using a linear mixed effects model on longitudinal data (biological values of many patients over time). Basically, the model predicts a quatitative outcome from the treatment group (2 groups) and the time since treatment initiation.
2) Note that i force the model to deny any baseline difference between groups, by removing the treatment effect by itself => the treatment effect is thus only present as an interaction with time. Apparently this is legit in my case, because there is no reason for the treatment to impact baseline value since it has "just started".
3) Anyways, now i want to predict an "average" trajectory for each treatment group : i thus simulate the treatment by "fixing" the treatment group for every point in time, and i obtain a prediction for each group at every time mark. If i plot this, i obtain to curves (lines) with similar intercept but different slopes.
4) Now i've only performed the simulation once for each treatment at each point in time. If i repeat the process 1000 times, I obtain a distribution of predictions for each group at every timemark. I extract the 2.5 and 97.5 percentiles of my predictions, which gives me a 95% prediction interval, for each group at every point in time.
5) I have one particular time mark that I'm interested in : i thus have 2 prediction means with prediction intervals (one for each treatment group).
Here's the question : how do I compare those 2 prediction intervals ? Regular test use the standard error, which is linked to the number of observations, but in my case observations are just simulations. What i mean is I could easily Perform 1 million simulations and thus obtain a somewhat "artificial" statistical difference.
I'm pretty sure I got something wrong somewhere, just not sure where ...
Thanks in advance for your help !
Answer: From 1), the model can be written as:
$$Y=\beta_0 +\beta_1 T +\beta_2 TX + \text{ random effects } + \epsilon$$
where $T$ is time and $X=0$ for treatment 1, and = 1 for treatment 2. You used this model means you think you data meet the assumptions of this model.
For 2), if the time is the time from baseline date (it means for baseline the time =0), your method is correct. If not, (for example age is used) the treatment effect should be kept.
3) and 4): It is unnecessary to do simulation to get the statistical inference under the specified mixed linear model, because under the assumptions of this model, the distribution of the estimates are well established. If you want to predict the mean of $Y$ for treatment $x$ at time $t$ then $\hat{\mathrm{E}(Y|T=t,X=x)} = \hat\beta_0 +\hat\beta_1 t +\hat\beta_2 tx$. Its confidence interval can be constructed based on $t$ distribution with given estimated variance and degree of freedom.
5) For testing the difference between treatment at the specified time $t$, you still can construct the linear combination of the parameters. For treatment 1, $$\mathrm{ E}(Y) = \beta_0 +\beta_1 t$$ For treatment 2,
$$\mathrm{ E}(Y) = \beta_0 + \beta_1t + \beta_2t$$
Their difference is
$\beta_2t$. So by testing the null hypothesis $H_o: \beta_2t = 0$, you get the result. In fact, its p-value is equal to p-value given at the estimate of $\beta_2$ by most statistical software. It is easy to get the its confident interval.


Continuity of the Euler characteristic with respect to the Hausdorff metric

Question: Hadwiger's theorem of integral geometry states that all continuous valuations which are invariant under rigid motions are expressible in terms of the intrinsic volumes. The continuity property means with respect to the Hausdorff distance:
$$d_H(X, Y) = \max{(
\sup_{x \in X} \inf_{y \in Y} d(x,y),
\sup_{y \in Y} \inf_{x \in X} d(x,y) )}$$
where $X,Y \subseteq \mathbb{R}^n$ and $d(\cdot,\cdot)$ is the Euclidean distance metric.
Now, the zero dimensional intrinsic volume is the Euler characteristic $\chi$. I am confused by how $\chi$ is continuous with respect to the Hausdorff distance. Consider the following example: two identical balls $A,B$ having diameter $\sigma$ are separated by a distance $r$. The Euler characteristic of their union is a valuation, i.e.
$$\chi(A \cup B) = \chi(A) + \chi(B) - \chi(A \cap B)$$
And according to standard texts on integral geometry (e.g. Klain & Rota Introduction to Geometric Probability (2006)) this is continuous with respect to the distance metric above. However, explicitly the Euler characteristic is discontinuous:
$$\chi(A \cup B) = \begin{cases}1 & \forall \; r < 2\sigma \\ 2 & \forall \; r > 2\sigma\end{cases}$$
whereas the Hausdorff distance between them is simply their separation $d_H(A,B)\equiv r$.
How is the Euler characteristic in my counter example continuous with respect to $d_H(A,B)$?
Edit: It is quite rightly pointed out in the comments that Hadwiger's theorem applies to strictly convex sets. I am in fact assuming a second extension theorem due to Groemer which generalises the result to so-called polyconvex sets, i.e. sets formed by countable union of convex sets.
Comment: I do not know this area, but the linked statement says that Hadwiger's theorem is true for convex bodies, not unions thereof.
Comment: Certainly. In Klain & Rota (see post above for full reference) the relevant theorems are: Groemer's extensions theorem 5.1.1 on page 44, the volume characterisation theorem 8.1.5 on page 105 and Hadwiger's theorem 9.1.1 on page 118.
Comment: The theorem is generalisable to polyconvex sets, meaning any body formed by countable union of convex sets. My example is the union of two convex sets, where the discontinuity occurs as they become disjoint.
Comment: Which is why I am skeptical of your first sentence. ;) You are of course completely correct that there is a jump in the Euler characteristic of this continuously varying family. There must be something about the hypotheses that goes wrong here.
Comment: Agreed, I have misunderstood something; the question is what. I will dig up the generalisation of the theorem and update my question.
Comment: Could you give a textbook reference (page/theorem number) for the precise statement of this generalization (or possibly the original paper)? I will gladly take a look.
Answer: Klain and Rota only claim (and only prove) that Euler characteristic is convex-continuous, meaning it's only continuous with respect to sequences of convex compact subsets. This is slightly buried in the discussion in Chapter 4 because they use "continuous" to name this condition in this chapter, which I personally think is very confusing (it took me the last half hour or so to notice this).
But the theorem establishing the existence of the Euler characteristic (Theorem 5.2.1) is careful to specify "convex-continuous," as is the statement of Hadwiger's theorem (Theorem 9.1.1). And Groemer's extension theorem (Theorem 5.1.1) only claims that a convex-continuous valuation extends to a valuation on polyconvex sets, not that the resulting valuation is continuous on polyconvex sets.
If you don't want to restrict to convex sets, I think the correct the sense in which the Euler characteristic is continuous is that it's continuous on the space of step functions spanned by indicator functions of polyconvex sets (it's a measure against which such step functions can be integrated). What happens when two balls (or more general sets) collide is that the corresponding sum of indicator functions is equal to $2$ on their intersection. So the integral against the Euler characteristic has an extra term corresponding to the Euler characteristic of the intersection, and for balls it remains $2$ as expected.


Error creating Coded UI Test in Visual Studio 2010 Ultimate

Question: I am attempting to create a Coded UI Test in a Visual Studio 2010 test project.
I right click on the project,
     Select Add
        Select Coded UI Test
I then get the error warning:

The following package failed to load:
  C:\Users[File Path Goes
  Here]\Microsoft.VisualStudio.TestTools.UITest.Extension.IE.dll.
  Coded UI Test is now in an
  inconsistent state.  Remove this
  package and restart Visual Studio to
  work with Coded UI Test.

Once I click OK, I can create the Coded UI Test (CUIT) but when the test is over, the test file is empty.
Does anyone know how to fix this problem?  I've already deleted my settings, AND reinstalled VS 2010, all to no avail.
Thanks everyone.
Comment: It sounds to me like perhaps your UI Test module got corrupted? You might consider uninstalling it, closing VS, deleting all the cache (from your AppSettings as well), the re-installing.
Comment: I have reinstalled, as well as done a repair install.  I have not deleted the cache though.
Answer: No idea about the source of the problem, but if you go to C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\ and copy the Microsoft.VisualStudio.TestTools.UITest.Extension.IE.dll file into the bin/debug directory everything works fine.
I don't know why VS assumes that the .dll is there when it's not, but that is the fix.
Comment: I now find that the above solution only works once.  Does anyone else have any ideas?
Comment: Is that dll referenced from the project?
Comment: If yes, try removing the reference. Also, do you have any other Visual Studio installs to tests that?
Comment: And, well, is that problem reproduced when you create a project from scratch?
Comment: I have removed the reference, and I still get the same error - I have also created several projects from scratch and I still get the same error.
Comment: Weird, huh. Seems to be an environmental problem. Do you have Visual Studio Feature Pack 2?
Comment: If you post a non-working test solution somewhere, I can open it with my Visual Studio and look if it works. I'm really curious now what's wrong with it.
Comment: Here is a test solution where I get the same error.  I've even gone so far as to download the microsoft test manager, and apply every hotfixknown to man, all to no avail.  I would be hugely appreciative if you could help me with this.
Comment: It would help if I included the link  http://www.digitaltoolfactory.net/cuittest.zip
Comment: got that. In VS Premium at workplace worked fine. In 7-8 hours I'll check that under VS Ultimate at home.
Comment: Thank you.  I've been pulling my hair out over this, it would be the perfect solution for one client and I can't get it to work.
Comment: Steve, I'm really sorry to say that, but with none of my Visual Studios installed I can reproduce your issue. You seem to have some problem with OS, or CLR, or I don't even know. Were I you, I'd set up a virtual machine, put Visual Studio there and then worked. I believe that VS will work fine there. VMs are really fast to create, so it shouldn't be a big deal to create one.
Comment: That is an odd thing.  I just tried in on my home machien as well actually and I get the same error.  I woner if there is a software conflict of some kind.
Comment: Really odd. Which Windows version do you use?
Comment: I'm on Windows 7 Ultimate, all patched and updated in both cases.
Comment: I'm on Enterprise and Ultimate, both x32. No more ideas what can be wrong with it. Clean install seems to be the only option to work that out.
Comment: I've done that, all to no avail, which makes me wonder what sort of conclicts I might have.  There was something about it conflicting with mvc 3 scaffolding, but I have no idea why that would be the case.
Comment: So, I'm prepared to declare this a massive bug on Microsoft's part, and closing it out.
Answer: So, I'm prepared to declare this a massive bug on Microsoft's part, and closing it out.
Comment: And if you don't have MVC 3 scaffolding installed, everything goes smoothly?
Comment: If yes, you could add this workaround to the question to clarify what to do with it.
Comment: Uninstalling the mvc scaffolding NuGet package really does fix the problem, that's all it takes.  It makes absolutely no sense, but that's all it takes.
Answer: I was able to get past this issue by changing the 'Copy Local' property of the referenced DLL to 'true'.  After this change the DLL is automatically copied into the Bin\Debug directory.


Como saber se devo atualizar ou não um componente?

Question: Estou usando o React, React Native e Redux para fazer um aplicativo.
Tentei estudar um pouco sobre os ciclos de vida de um componente mas acabei ficando confuso em relação às diversas opções presentes na hora de iniciá-lo. O problema é o seguinte:
Quando um usuário estiver na screen Feed da minha aplicação, ele poderá encontrar um usuário e, eventualmente, tocar neste e isso abrirá a screen Profile. Nesta tela, no evento componentDidMount() eu faço uma busca usando o Redux para obter o objeto user. Acontece que, eu gostaria de mostrar uma tela de carregamento antes desse objeto chegar no props e estar "pronto". Eu consegui fazer isso. Se eu voltar para tela Feed e tocar para ver outro user, mesmo comportamento. O problema é que, se eu entrei na tela Profile para ver o usuário X, voltar para o Feed e tocar novamente no usuário X, a tela de carregamento será novamente mostrada, o que eu não quero por que, naturalmente, os dados já estão carregados.
Gostaria que a resposta contivesse a solução do problema e também uma análise se a forma e os eventos que estou usando estão corretos para esta ocasião.
class LocalInside extends Component {

componentDidUpdate(prevProps){
    if(this.props.user != null){
        if(prevProps.user == null){
            this.setState({showUser: true})
        }
        if(prevProps.user != null && prevProps.user != this.props.user){
            this.setState({showUser: true})
        }
    }
}

componentDidMount(){
    const { dispatch } = this.props
    if(this.props.userId != null){
        dispatch(getSingleUser(this.props.userId))
    }
}

state = {
    showUser: false
}

render(){
    if(this.state.showUser){
        //Aqui mostra o user
    }else{
        //Aqui mostra o carregando.
    }
}

Comment: Qual middleware você usa (Redux Saga, Redux Thunk)? O Redux é um objeto, então dentro dele vai estar "salvo" o último dado carregado. Você pode checar se o id do usuário é o mesmo que está lá no objeto do Redux. Ai vc usa o middleware pra pegar isso e testar antes de chamar sua API.
Comment: Atualmente estou usando o Redux Thunk. Como poderia fazer essa verificação que tu mencionou?
Answer: Você precisa salvar na store que os dados de perfil do usuário em questão já foram carregados. Isto é, no componentDidMount, você checa na store se o hasUserDataLoaded (Vinculado ao userId por exemplo) é false ou não. Se não tiver carregado, você renderiza a parte de carregamento e já dá um dispatch de uma action pra atualizar a store dizendo que hasUserDataLoaded agora é true (Esse dispatch é realizado dentro do componendDidMount mesmo). Desta forma, na próxima vez que o usuário acessar o perfil, ele não renderizará a parte de carregamento de novo. O ponto é, além de salvar os dados na store, precisa salvar o estado de carregamento (Ou checar de outra forma, checar se os dados estão vazios por exemplo).


Q-Learning Without Complete Training Data

Question: I am implementing Q-Learning to find the "Next Best Action" a sales rep should take on a particular account to collect more money.
I am feeding the algorithm past actions taken on the accounts and the resulting states from those actions in order to learn the Q matrix.  My problem is not every account had all available actions taken on it.
So in the first iteration of the Q-Learning algorithm we randomly select an initial state s (In my application this would be a unique account z AND state s combination). We then randomly chose an action a to execute. Unfortunately we may not have a ever taken action a on that particular account z, and as a result cannot observe any resulting state s'. Note: State transitions are constrained to one account. For example: I can't invoke an action a on account z1 and observe the resulting state on a different account z2.
If this scenario occurs should I just end the episode?  However I never reached the goal state. Do I violate any assumptions for ending the episode early for reasons other than reaching the goal state?
Is there a better way to implement Q-Learning using past data that does not include records for all state and action combinations?
Should I even be using Reinforcement Learning, or should I use Markov Decision Processes since I can compute the transition matrix using my past records of the system?
Answer: I would approach the problem in the following way.

Cluster the accounts so that the state is (account cluster, state of
the account)
Construct the transition matrices with de data you
have available.
Use Dynamic programming to find the optimal policy.
Force the sales representatives to follow the actions of Q-learning. So that it implements the optimal policy found by
dynamic programming most of the time and takes a random action from
time to time (greedy exploration)
Q-Learning will be start gathering more data and modifing the best
policy.

Step 1. Would help reduce the dimensionality of the problem. It will be useful with new accounts, since you would be able to use the best policy found in other accounts.
Steps 2. and 3. would use the data you have to construct the best static policy so far. This will make the Q-learning have a better start.
Steps 4. and 5. would help you balance the tradeoff between gathering data to construct the optimal policy and actually helping the sales representatives gathering more money.
Comment: Rather than clustering the accounts, you could use features of the account as part of the state to create a state feature vector and use function approximation (caveat - this can make the algorithm trickier to train). Either way, it depends whether there is enough useful information about each account to have predictive features, or to be able to choose meaningful clusters of similar accounts where it is reasonable to expect them to behave in the same way given same state and action.
Answer: I found an important statement from Francisco S. Melo of the Institute for Systems and Robotics, Instituto Superior Técnico, Lisboa, PORTUGAL, which might help you:
"Theorem 1.[...] the Q-learning algorithm, given by the update rule [math formula] converges w.p.1 to the optimal Q-function as long as [...]  all state-action pairs be visited infinitely often."[1]
So, if you aim to have the optimal Q-function and thus to obtain the optimal policy, then the answer should be: yes, you need for each state all possible actions according to the above quote.
However, I am not sure, if RL is the right tool here, because recall that in RL actions should bring you from one state to another state. I am not sure, if an action is taken on one account (I understood that your state is formed by a tuple (acc_id, some account attributes list) correct?), how would you go from that state to another?
E.g. lets assume initial state is (id:0, {age:20, income:1000}) -> (do some action) -> Transition to state (id:2, {age:35, income:2000}).
What about reading on recommendation systems, since your problem seems to be closely related to it, at least this is my impression? See [2]. It seems that you want to recommend an action based on some attributes of an account.
Hope that helps a bit :).
[1] http://users.isr.ist.utl.pt/~mtjspaan/readingGroup/ProofQlearning.pdf
[2]Toward the next generation of recommender systems: a survey of the state-of-the-art and possible extensions
Comment: Thank you Tukk. So state transitions would be constrained to one account. You would not expect to take a random action on one account and then observe the resulting state that belongs to another account. I would prevent that scenario from happening.


How can I translate the checkout system?

Question: I have been translating my Commerce Kickstart site with no ease although with success until now. Have translated content, taxonomy, product fields etc, following some tutorials and Drupal own documentation. Have installed a variety of modules for localization.
But now as regarding checkout system. I'm calling checkout system all screens starting by clicking on "checkout" in shopping cart block that appear in above and right corner of Kickstart demo store.
To translate checkout system, I went in https://localize.drupal.org/translate/downloads?project=commerce and downloaded my translation (Portuguese, Brazil). Then I imported that with /admin/config/regional/translate/import. In Overview tab all the 1222 expressions (100%) are translated. In Translate tab I searched for some strings that appear in that checkout system screens, like "Payment", "Checkout complete", and indeed there are already translations in Portuguese Brazil.
In /admin/config/regional/language/configure, on Detection and selection tab I enabled URL and Session as Detection methods.
So, are there more configurations that I need to do to have checkout system translated?
Answer: In importing translation page /admin/config/regional/translate/import I have chosen "Drupal commerce"in Text group section. The process went fine, but the words to translate were indeed in Bult-in interface. So I imported the same file again but now choosing "Bult-in interface" in Text group section. Now I have checkout system translated at some degree.
I think perhaps because I installed Commerce Kickstart 2 and Drupal Commerce comes all in Built-in interface.


Conjectured analogue of Fermat's Little Theorem for Bernouli numbers

Question: Is the following analogue of Fermat's Little Theorem for Bernouli numbers true?

Let $D_{2n}$ be the denominator of $\frac{B_{2n}}{4n}$ where $B_n$ is
the $n$-th Bernoulli number. If $\gcd(a, D_{2n}) = 1$ then
$$ a^{2n} \equiv 1 \;(\bmod\; D_{2n}) $$

Update 18-Jan-2022: Posted in MO
Comment: To prove this it is sufficient to prove $$\lambda(D_{2n})\mid 2n$$ for every positive integer $n$ , where $\lambda(k)$ is the Carmichaelfunction. This gives a far more efficient search since we need not check any particular coprime number $a$. Upto $n=10^4$, this is true and therefore the conjecture. Range upto $n=10^5$ is still running.
Comment: Aborted at $n=2\cdot 10^4$ , no counterexample found.
Comment: @lhf Its true for all $a \le 10000, n \le 1000$
Comment: the tag "Bernoulli numbers" would be appropriate
Comment: A proof is essentially given in Section 5.1 of [Notes on primitive lambda-roots](http://www.maths.qmul.ac.uk/~pjc/csgnotes/lambda.pdf) by P. J. Cameron and D. A. Preece.
Comment: What numerical evidence do you have?
Answer: If you work out the powers of a prime dividing $D_{2n}$ you get the following which is a well-known stronger version of the Clausen-von Staudt result.
If $p=2$, $\nu_2(D_{2n})=\nu_2(n)+3$.
If $p$ is odd and $(p-1)\mid 2n$ then $\nu_p(D_{2n})=\nu_p(n)+1$, otherwise $\nu_p(D_{2n})=0$.
Now for the congruence to hold you just need to check it modulo these powers of each prime and this is easy because of the structure of the group of units module a prime power.
Answer: I found a partial proof that $a^{2n} - 1$ is divisible by the denominator of $D_{2n}$. Haven't been able to account for the additional factor $4n$.
The Von Staudt–Clausen theorem is that $D_{2n}$ is given by the product of all primes $p$ for which $p − 1|2n$. In particular, $D_{2n}$ is square free. Thus if $p_1, p_2, \ldots, p_k$ are the distinct prime factors of $D_{2n}$ then
$$p_1p_2 \ldots p_k = D_{2n}$$
$$(p_1-1)(p_2-1)\ldots (p_k-1) = 2n$$
If $\gcd(a,D_{2n}) = 1$ then by Fermat's Little theorem,
$$ a^{(p_1-1)(p_2-1)\ldots (p_k-1)} \equiv 1 \;(\bmod\; p_1) $$
$$ a^{(p_1-1)(p_2-1)\ldots (p_k-1)} \equiv 1 \;(\bmod\; p_2) $$
$$\cdots$$
$$ a^{(p_1-1)(p_2-1)\ldots (p_k-1)} \equiv 1 \;(\bmod\; p_k) $$
Since the moduli are all distinct primes, they have no common factor. Thus
$$ a^{(p_1-1)(p_2-1)\ldots (p_k-1)} \equiv 1 \;(\bmod\; p_1 p_2 \ldots p_k) $$
i.e. $a^{2n}-1$ is divisible by the denominator of $D_{2n}$.
Comment: I don't think we know that $(p_1 - 1) \cdots (p_k - 1) = 2n$, do we?  In any case this isn't necessary, since your proof only uses the fact that each $(p_i-1) | 2n$, which comes straight from the von Staudt-Clausen theorem.
Comment: What about the additional factor $4n$ in the denominator ? Do the primes not satisfying the condition cancel out with the numerator of the Bernoulli number ? This is what I wondered when trying a proof myself.
Comment: If this proof is correct, it is a great help to prove your other conjecture (and it can probably be even strengthened)
Comment: @Peter You are right, this is only a proof of the weaker claim that $a^{2n}-1$ is divisible by the denominator of $B_{2n}$. Haven't been able to account for the additional factor $4n$ so far.
Comment: I think you have confused $D_{2n}$ with the denominator of  $B_{2n}$.


what is psp script file?

Question: What kind of script file has ext psp ?
Moreover this script looks like it has perl content but it is wrapped in <% %>
Can someone tell me what this is? I cannot disclose the script due to privacy issue but I want to understand what this is.
Thanks in advance.
Comment: Pretty S****y Privacy?
Comment: Typo? Maybe php was meant. Got any actuall code from within the file? That would help.
Comment: It's definitely perl code but I am wondering why wrapping these things under <% %>     Also this is used by webserver like CGI...
Answer: It's most likely a template for the Template::PSP templating engine.
Comment: I looked at the code again and it has perl code wrapped in <% %> and other section contains normal looking html
Comment: It's actually apache::asp  but this answer gave me clue to look there.. thank you!
Comment: Either way it's something ancient and horrendous. Get rid of it as soon as you can!

what is psp script file?


Wordpress gallery shortcode and get_page

Question: I render some pages to a content slider like this:
function tonal_get_slide($postID) {
    $page_data = get_page( $postID );
    $title = $page_data->post_title;
    $content = "
" . $title . "
";
    $content .= apply_filters('the_content', $page_data->post_content);
    return $content;
}

All my self-created shortcodes work like a charm, but the gallery-shortcode gets ignored (it does return nothing, not the shortcode, no empty
, nothing...)
Any help on would be appreciated,
Thanks
Answer: got it...
only works with the $post variable:
$post    = get_page( $postID );
$content = apply_filters('the_content', $post->post_content);


D8 Webforms Predefined Options

Question: How would you use/access D8 Webforms Predefined Options (such as days,months,gender, marital status,country etc,etc) in code, say in MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id). Where is the predefined options data stored ?
For example, for country codes options ["AF"=>"Afghanistan","AL"=>"Albania",....,"US"=>"United States",..] how would you get country name from country code.
Your aasistance will be greatly appreciated.
Answer: You can alter the options in this hook:
/**
 * Alter form options by id.
 *
 * @param array $options
 *   An associative array of options.
 * @param array $element
 *   The form element that the options is for.
 * @param string $options_id
 *   The form options id. Set to NULL if the options are custom.
 */
function hook_webform_options_alter(array &$options, array &$element, $options_id = NULL) {

See http://cgit.drupalcode.org/webform/tree/webform.api.php
The options are stored in the config entity webform_options, see http://cgit.drupalcode.org/webform/tree/src/Entity/WebformOptions.php
Comment: can have **hook_webform_options_alter** in my custom module ?Check I have edited my question for clarity
Comment: The example you've added is not a good example, because Webform doesn't store country names (only if you edit them), instead it gets the country names from the service CountryManager. You can do the same, see https://drupal.stackexchange.com/questions/222834/how-to-get-country-list-array-with-their-corresponding-country-codes
Comment: No check any recent version of webform has country_codes as one of predifined options just like gender,education,marital status etc etc mention it.
Comment: See webform_webform_options_country_names_alter() in http://cgit.drupalcode.org/webform/tree/includes/webform.options.inc
Comment: In fact country codes was just an example. Any webforms predefined option has key value pair. So in general sense how would I get the value if I known its key, that is, from code.
Comment: Use the entity mentioned in the answer and an example where the values are stored in Webform like Months: \Drupal\webform\Entity\WebformOptions::load('months')->getOptions()
Comment: I was about to accept this as the right answer but to my surprise it does not work for other predefined options such as country_codes,country_names. They output an empty array. Any idea why this is so. I am using machine name as id for the entity.
Comment: I'm telling you this from the beginning when you brought up this example. Webform doesn't store this data. Look at the webform code linked in a  previous comment.
Answer: use use Drupal\webform\Entity\WebformOptions;
// **ID of option = country_code or gender**
 $webform_test_options = WebformOptions::load('ID of option');
 $options = $webform_test_options->getOptions();
 /* Update predefind options --- */
$webform_test_options->set('options', Yaml::encode($data));
/* $data will be array ["AF"=>"Afghanistan","AL"=>"Albania",....,"US"=>"United States",..]*/ $webform_test_options->save();
Hope this help.

D8 Webforms Predefined Options


How to debug postfix connection timeout

Question: I used this and this blog posts to configure postfix to relay mails to a specific server using authentication. The following settings have been made in main.cf:
# sender-dependent sasl authentication
smtp_sender_dependent_authentication = yes
sender_dependent_relayhost_maps = hash:/etc/postfix/sender_relay

# default relayhost setting
relayhost = [fully.qualified.target.server]:587

# smtp authentication settings
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = lmdb:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
smtp_tls_CAfile = /var/lib/ca-certificates/ca-bundle.pem
smtp_use_tls = yes
smtp_tls_security_level = encrypt

I created /etc/postfix/sender_relay with the following content:
email@example.com    [fully.qualified.target.server]:587
firstname.lastname@example.com    [fully.qualified.target.server]:587
email@example.com   [fully.qualified.target.server]:587
firstname.lastname@example.com     [fully.qualified.target.server]:587

and encoded it as lmdb by postmap sender_relay so that the sender_relay.lmdb was created in /etc/postfix/
I created /etc/postfix/sasl_passwd with the following content:
email@example.com   email@example.com:password1
email@example.com   email@example.com:password2
email@example.com   firstname.lastname@example.com:password3
email@example.com   email@example.com:password4

[fully.qualified.target.server]:587   email@example.com:passwordDefault

and encoded it as well using postmap sasl_passwd.
Now when I try to send an email using that relay I get:

Jan 16 11:57:08 mail postfix/qmgr[12939]: 199FA1206D3: email@example.com, size=454, nrcpt=1 (queue active)
Jan 16 11:57:38 mail postfix/smtp[12952]: connect to fully.qualified.target.server[ip.of.target.server]:587: Connection timed out
Jan 16 11:57:38 mail postfix/smtp[12952]: 199FA1206D3: firstname.lastname@example.com, relay=none, delay=1062, delays=1032/0.03/30/0, dsn=4.4.1, status=deferred (connect to fully.qualified.target.server[ip.of.target.server]:587: Connection timed out)

Although I edited master.cf to get debugging output, i do not get more information:
smtp      inet  n       -       n       -       -       smtpd -v

I checked certificates / connectivity using openssl:
openssl s_client -connect fully.qualified.target.server:587 -starttls smtp -crlf

and no problems where found.
What else can I do to debug this situation?
Platform ist openSuse Leap 15.3
Comment: The hard-and-dirty way is to capture traffic and see when packets go missing. If you can do this on both sides, you likely have enough power to fix the entire problem; if you don't, your best guess will be something like "it doesn't answer to my packets, all what I can suppose it's a firewall". Also check *all* logs; maybe SElinux permits your interactive telnet session, but doesn't permit Postfix smtp client to originate session, and it should write that into logs.
Comment: A timeout usually points toward a firewall issue. Many hosters block outgoing port 25 to prevent spam.
Comment: I can telnet to the server on the port and I can also connect using openssl... so most probably not a firewall issue....
Comment: Can you confirm your openssl test tried exactly the IP address (version) that postfix logs mention? Can you confirm that `iptables-save`/`ip6tables-save` dumps the stock empty/ACCEPT firewall policies?
Comment: I can confirm, that openssl used the exact IP address that postfix uses. And I successfully connected using telnet on that IP address as well... your command do not work unfortunately
Comment: his issue may be caused by a number of factors, such as a network issue preventing the connection, a firewall blocking the connection at the destination, or an issue with the target server.
Comment: That's my question: How do I debug this...
Answer: Just for somebody stumbling over this: It really was a firewall issue on another system. It blocked the mail communication.
As suggested by Nikita in the comments I used tcpdump to check the connection and found out, that telnet / openssl used the interface eth0 whereas postfix used the interface tun0 (there is a VPN tunnel on that machine).
And the "endpoint" of the VPN tunnel blocked all SMTP ports.
I made the traffic go through the right interface and now postfix does what it should and debugging works as well.
I was just confused as postfix does not show any debug output when the underlying tcpip connection is blocked. Because of that I thought that my debugging parameters were not used by postfix.

How to debug postfix connection timeout


how to make an arc rotating around a center in ExtendScript After Effects?

Question: I want to make a loading animation in After Effects using scripts
I get no arc only white screen with shape layer there
and this is what gets rendered in the app

This is my code that doesn't work

app.project.close(CloseOptions.DO_NOT_SAVE_CHANGES);
app.newProject();
app.beginUndoGroup("Create Comp");

// Create a new composition with a solid layer
var comp = app.project.items.addComp("My Composition", 1920, 1080, 1, 10, 24);

comp.openInViewer();

var solid = comp.layers.addSolid([1, 1, 1], "My Solid", 1920, 1080, 1, 10);

// Create a new shape layer
var shapeLayer = comp.layers.addShape();
// shapeLayer.moveToStart();
shapeLayer.enabled= true;

// Set position of the shape layer
var shapePosition = shapeLayer.property("ADBE Transform Group").property("ADBE Position");
shapePosition.setValue([960,540]);

var path = shapeLayer.property("ADBE Root Vectors Group").addProperty("ADBE Vector Shape - Group");
// make a arc
path.property("ADBE Vector Shape").setValue(new Shape());
path.property("ADBE Vector Shape").value.vertices = [[0, 0], [100, 100], [200, 0]];
path.property("ADBE Vector Shape").value.inTangents = [[-50, -50], [0, 0]];
path.property("ADBE Vector Shape").value.outTangents = [[0, 0], [50, 50]];
path.property("ADBE Vector Shape").value.closed = true;
path.enabled = true;

var stroke = shapeLayer.property("ADBE Root Vectors Group").addProperty("ADBE Vector Graphic - Stroke");
stroke.property("ADBE Vector Stroke Width").setValue(5);
stroke.property("ADBE Vector Stroke Color").setValue([1, 0, 0]);
stroke.enabled = true;

var fill = shapeLayer.property("ADBE Root Vectors Group").addProperty("ADBE Vector Graphic - Fill");
fill.property("ADBE Vector Fill Color").setValue([1, 0, 0]);
fill.enabled = true;

// Create an animation for the rotation property
var rotation = shapeLayer.property("ADBE Transform Group").property("ADBE Rotate Z");
rotation.setValueAtTime(0, 0);
rotation.setValueAtTime(5, 180);

// Set the composition duration to 10 seconds
comp.duration = 10;

app.endUndoGroup();

Answer: Properties in AE can't be set by assigning values to them. You need to use the setValue() method. Additionally in this instance you want to set the values of the shape object before assigning it to the path property.
var theShape = new Shape();
theShape.vertices = [[0, 0], [100, 100], [200, 0]];
theShape.inTangents = [[-50, -50], [0, 0]];
theShape.outTangents = [[0, 0], [50, 50]];
theShape.closed = true;
path.property("ADBE Vector Shape").setValue(theShape);

Also, as an AE developer:


The request sent by the client was syntactically incorrect using @DateTimeFormat

Question: I have a JSON formatted String which I send with a HTTP-PUT to a server with Spring MVC and Hibernate.
Controller:
@RequestMapping(value = "/", method = RequestMethod.PUT)
public ResponseEntity<Map<String, Object>> myTest(
        @RequestHeader("a") String a,
        @RequestBody MyTestClass b) { … }

JSON:
{
 "number":"123",
 "test":"11/14"
}

test is a java.util.Date (MySQL -> date) and I annotated the POJO like this:
@Column(name = "TEST")
@DateTimeFormat(pattern = "MM/yy")
private Date test;

So test should be formatted as month/year. But I tried it with Firefox RESTClient and I always get
The request sent by the client was syntactically incorrect. Removing test, everything is okay and works as expected.
So it seems, that with @DateTimeFormat(pattern = "MM/yy") is something wrong?
Answer: Because you are using RequestBody with an application/json content type, Spring will use its MappingJackson2HttpMessageConverter to convert your JSON to an object of your type. However the date string you provide, 11/14 does not match any of the pre-configured date patterns and therefore it can't parse it correctly. The MappingJackson2HttpMessageConverter, or more specifically the ObjectMapper that does the job, doesn't know anything about @DateTimeFormat, a Spring annotation.
You will need to tell Jackson which date pattern you want to use. You can do so with a custom date deserializer
public class CustomDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("MM/yy");
        String date = jp.getText();

        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new JsonParseException(e);
        }
    }
}

Then simply annotate your field so that Jackson knows how to deserialize it.
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date test;

You could use @DateTimeFormat if you were using url-encoded form parameters with @ModelAttribute. Spring registers some converters that can convert a String value from a request parameters into a Date object. This is described in the deocumentation.


Windows 10, develop Android project in Qt Creator

Question: I would like to build my Android project in Qt Creator (Ver. 4.3.1). I've set JDK, Android SDK and NDK location in Tools -> Options -> Devices -> Android. Then Qt Creator show info: Found 8 toolchains for this NDK and a warning: Qt versions for 2 architectures are missing. To add the Qt versions, select Options > Build & Run > Qt Versions.
So I set Qt versions, and I got 2 auto-detected Qt versions. Qt 5.9.0 for Android armv7 and for Android x86. Both with warning signs. The warning is No compiler can produce code for this Qt version. Please define one or more compilers for: arm-linux-android-elf-32bit. I am using Windows 10, why the ABI is arm-linux-android-elf-32bit? And what compiler can I use? I've set MinGW and Microsoft Visual C++ compiler 14.0. Both has same problem.
Answer: I had the same problem and solved it

downloaded android-ndk-r10e-windows-x86_64.zip from https://developer.android.com/ndk/index.html, Downloads -> Older versions (NDK Archives)
extracted the contained folder to C: (-> Folder C:\android-ndk-r10e)
in the Qt Creator in Tools -> Options -> Devices -> Android set the NDK location to C:\android-ndk-r10e and pressed OK

Now when I open Tools -> Options -> Build & Run -> Qt Versions the auto detected compilers are valid.


How to copy an image from one folder to other in php

Question: I have a image named xyz.  Besides this file named xyz has unknown extension viz jpg,jpeg, png, gif etc. I want to copy this file from one folder named advertisers/images to other folder publishers/images in my website cpanl. How to do this with php. Thanks in advance.
Comment: Possible duplicate of [Copy Files to another folder PHP](https://stackoverflow.com/questions/21526046/copy-files-to-another-folder-php)
Answer: You can use copy function:
$srcfile = 'source_path/xyz.jpg';
$dstfile = 'destination_path/xyz.jpg';
copy($srcfile, $dstfile);

Answer: Use    copy() function
copy('advertisers/images/xyz.png','publishers/
 images/xyz.png');

Change the file extension, whatever it is.
If you don't know the extension, go with the wildcard. It will give you the array of all the files matching with the wildcard.
$files = glob('advertisers/images/xyz.*');
    foreach ($files as $file) {
    copy($file,'publishers/images/'.$file);
}

Comment: sir file may vary, I want to copy a image file xyz along with its extension whatever be its extension among jpg, jpeg, JPG, JPEG, png, PNG, GIF, gif etc
Comment: @John use .* In place of extension. It will copy all the files having name xyz
Comment: i used $imagePath = "/home/public_html/advertisers/images/1adfd189e18d6d101a29cfd09b0426a4.*"; but image was not copied
Comment: Use glob('xyz.*') Function to get all the files with xyz name. It will provide array containing files. And use copy function inside loop.
http://biostall.com/using-php-to-find-files-with-name-containing-a-wildcard/
Comment: @John i have updated my answer as per your requirement.
Answer: You should write your code same as below:
<?php
$imagePath = "../Images/somepic.jpg";
$newPath = "../Uploads/";
$ext = '.jpg';
$newName  = $newPath."a".$ext;

$copied = copy($imagePath , $newName);

if ((!$copied))
{
    echo "Error : Not Copied";
}
else
{
    echo "Copied Successful";
}
?>


K-means clustering scaling

Question: I have a data set of 70 stores with a sales column (ranging from 50M to 70M) and 39 other features, like age group, income categories etc. I need to find the clusters based off of these metrics.
A sample dataset will have fields like this:
<code>Store#:   0101
Sales:    50M
Customers Between 20 and 40: Low
Customers Between 40 and 60: Low
Customers Between 60 and 80: High
Income<40: Low
40<Income<60: High
60<Income<90: Low
</code>
So you would read the dataset as follows:
Store #0101 has 50M worth of sales, Low number of customers between 20 and 40, low number of customers between 40 and 60 etc.
Here are my questions:

Does it make sense to convert Low, Medium, High to 0,0.5 and 1
respectively?
Does sales need to get normalized between 0 and 1 ?
Is there any other models than K-Means to address the clustering?
Answer: K-means is not appropriate for such data.
It is designed for continuous variables where the L2 error needs to be minimized. That does not seem to make sense for your data.

K-means clustering scaling


Howto run a php file from a other php file?

Question: Is it possible to launch a php file from a other php file?
I know that i can include a file but i don't mean this.
Small example:
i have a script which displays something from the database
and a other script which get the latest data from a other site and update the database.
When i include the update file, the first script will request the data from the server but i want to make it parallel so that only the update script request from server
Answer: Yes, and you can use include provided fopen wrappers are turned on.
include("http://otherserv.com/path/to/script.php");
If you don't care about the reponse from the other server, you can do
get_headers("http://otherserv.com/path/to/script.php");
This will complete much faster if the remote script takes time to process.
Answer: Yes, you need CURL (or any other HTTP library) to "run" a php file from another as you described in your scenario.
So, in your case:

CLIENT will run a REQUEST to SERVER1 (a.php)
SERVER1's a.php, will use CLIENT REQUEST to perform a remote PHP file in SERVER2 (b.php)
SERVER2's b.php will process SERVER1's REQUEST and place an appropriate response
SERVER1's a.php will receive SERVER2's b.php RESPONSE, parse it, and send appropriate response to CLIENT.

Hope it clarifies something to you.
Answer: you should look at exec http://au.php.net/manual/en/book.exec.php
Comment: exec is highly discouraged for various security reasons.  Byron has the most appropriate answer.


Como ler cada char de uma string, para saber se uma está contida na outra, em C?

Question: Bom dia, boa tarde, boa noite.
Estou tentando fazer um enunciado do meu curso de programação em C que pede para fazer um código que verifica se uma string2 está contida em uma string1, utilizando aritmética de ponteiros, tentei de diversas formas realizar este exercício, mas a única forma que encontrei de realiza-lo é a partir do método que irei mandar aqui, só que ao executar o código eu consigo verificar que está contida somente as primeiras letras da string1, por exemplo: se digito "brasil" para a primeira string e digito "bra" pra a segunda, ele detecta que está contida, mas se digito "brasil" para a primeira e "sil" para a segunda, ele não detecta que está contido, gostaria de saber como resolver este problema. Desde já agradeço, aguardo resposta. Obs.: O enunciado está como comentário no código, bem embaixo das bibliotecas.
<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>

/*
18) Elabora uma função que receba duas strings como parâmetros e
verifique se a segunda string está dentro da primeira. Para isso, utilize
apenas aritmética de ponteiros.
*/

void verifica(const char* ptr1,const char* ptr2) {
  int l=0;
  for (size_t i = 0; i < strlen(ptr1); i++) {
   if (ptr1[i]==ptr2[i]) {
     l++;
    }//if
  }//for

  if (l == strlen(ptr2)) {
    printf("Está contida!! \n");
  }else{
    printf("Não está contida!! \n");
  }//ifelse
}//verifica

int main (){
  setlocale(LC_ALL, "Portuguese");
  char str1[21], str2[21];
  char *ptr[2] = {str1, str2};

  for (size_t i = 0; i < 2; i++) {
    printf("Digite a %dº palavra de até 20 caracteres: ", i + 1);
    fgets(ptr[i], 21, stdin);
    ptr[i][strcspn(ptr[i],"\n")]='\0';
    setbuf(stdin,NULL);
  }//for

  verifica(ptr[0],ptr[1]);

return 0;
}//main

</code>
Answer: Olá. Entendendo a questão, pude perceber que o problema está na verificação de contido. Vamos lá:
Pense comigo, i vai de 0 a strlen(ptr1) -1. Correto?
Vamos usar os mesmos inputs do erro:
(brasil, sil)
i na posição 0:
string1 == b  e string2 == s -> logo o l não incrementa
i na posição 1:
string1 == r  e string2 == i -> logo o l não incrementa
i na posição 2:
string1 == a  e string2 == l -> logo o l não incrementa
O primeiro problema é que nesse caso nunca vai verificar. O segundo problema é que
após isso, o i vai continuar incrementando, mesmo que não exista mais letras na string2, e vai começar a comparar o resto das letras da string1 (sil) com lixo da string2.
Como verificar se uma string está contida em outra em C?
esse topico pode te ajudar bastante nessa questão. É basicamente a mesma dúvida.
Comment: vlw, muito obrigado mesmo!!!


Compiler error when destructor declared in class body with unique_ptr as member of the same class

Question: Below is the minimalist problem of the code:
struct B {
  B () = default;
  //~B () {};  // error: use of deleted function 'B& B::operator=(const B&)'
  std::unique_ptr<int> m_pB = nullptr;
};

int main ()
{
  std::vector vB;
  vB.erase(vB.begin());
}

Above code compiles fine, unless the destructor is uncommented. For my requirement, I need to have a body of ~B() explicitly defined.
How can I define the body of destructor with the unique_ptr co-existing in the same class?
Note: Tried defining = default versions of copy & move constructor to no avail. In my real code, unique_ptr<int> is unique_ptr<forward_declared_class>. Couldn't locate this problem in SO, though I am sure it must be present. Feel free to mark as dupe.
Comment: Being forward declared is relevant to the problem - can't call `delete` reliably (i.e. can't instantiate `std::default_deleter`) without a visible destructor.
Comment: See this question http://stackoverflow.com/questions/6012157/is-stdunique-ptrt-required-to-know-the-full-definition-of-t
Comment: There is no reason to assign nullptr to m_pB.
Answer: Seems like your code requires B to be copy constructible and copy assignable for std::vector (at least for visual c++, which I tested).
Copy constructor and copy assignement operators can only be = delete because of std::unique_ptr (implementations declared = default should cause the function to be deleted as well), and, by implementing destructor, you disable default implementations of move constructor and move assignment operator.
So you need to explicitly declare the move assignment operator. Try:
#include <memory>
#include <vector>

struct B {
  B () = default;
  ~B () {}
  B& operator=(B&&) = default;
  std::unique_ptr<int> m_pB = nullptr;
};

int main ()
{
  std::vector vB;
  vB.erase(vB.begin());
}

Answer: You might declare and implement a move-assignment operator, which the compiler asks for. Of course, it complains about copy assignment, but a sensible copy seems to be impossible for your structure.
Probably, the error message is a bit misleading because std::vector::erase implementation contains something like _data[i-1] = _data[i] in the code which pokes vector elements to places of deleted items. So the compiler needs any assignment operator, and we provide it with a moving one.
For example, this works fine (gcc 4.8.3):
struct B {
  B () = default;
  B& operator=(B&& op) {
    m_pB = std::move(op.m_pB);
    return *this;
  }
  ~B () {};  // no more errors.
  std::unique_ptr<int> m_pB = nullptr;
};

int main ()
{
  std::vector vB;
  vB.erase(vB.begin());
}

Answer: The vector code is a red herring.
When a class U has a member of type unique_ptr, and T is forward declared, the definition of the destructor has to be in the cpp file, when U is no longer an incomplete type.
You should have ~U(); in the header, and in the cpp file have U::~U(){} or U::~U() = default;