Convex set which is not connected

Question: I know that in $\mathbb{R}^n$ a convex set is connected, but is this true for other spaces (or metrics)? Is there an example of a convex set which is not connected?
Thanks in advance!
Comment: In any topological vector space any convex set is connected.
Answer: Take two points $x$ and $y$ in your convex set $E$. By convexity, the segment line joining $x$ to $y$ is included in $E$, therefore there is a path joining $x$ to $y$.
So $E$ is path connected, so it is connected.
Answer: In any normed (even topological) vector space (finite dimensional or not) $V$ over $\mathbb{R}$ a convex set is defined as any subset $A\subseteq V$ such that for any $v,w\in A$ and any $t\in[0,1]$ the intermediate point $tv+(1-t)w$ belongs to $A$.
This gives us a formula for a path $\lambda:[0,1]\to V$ connecting $v,w\in A$, namely $\lambda(t)=tv+(1-t)w$. The only remaining thing is whether $\lambda$ is continuous? It is, since vector addition and multiplication by scalar are.
Thus any convex subset is not only connected, but even path connected.

Outside of topological vector spaces convexity can be defined in multiple, non-equivalent ways. There is even a purely abstract "convexity space" term, see wiki. However most of them will remain connected, e.g. geodesic convexity. But not all, e.g. convexity inside $\mathbb{Q}$ with respect to the natural order.
Comment: Thank you for your answer! While reading your answer (and the other ones) I realized that I may have expressed myself wrong. So now I wonder if it is possible to talk about convexity in a not normed space. And moreover if it is possible to find a convex set which is **not** connected? I'm asking this because I read that in general "convex" and "connected" are independend concepts. Am I wrong?
Comment: It's all more clear now, thanks! And it's far more complex than I thought (I'm a first year student and we rarely work with non Euclidean spaces).
Answer: If $C$ is a  convex set in a topological vector space then $f(t)=(1-t)x+ty$ defines  a continuous map from $[0,1]$ to $C$ with $f(0)=x$ and $f(1)=y$. Hence $C$ is path connected. Any path connected space is connected.

Convex set which is not connected


How to fix my loop code in JAVA?

Question: I'm trying to make it such that if the person typed anything else besides "BMW" or "AUDI" that they would get sent back to the point where they get to retype, I'm a beginner coder so please explain if possible :3 thanks a lot! Sorry if my code is messy still new to this and working on it!
edit: Thanks alot guys/girls for helping :3
import java.util.Scanner;

class MyClass {

public static void main(String[ ] args) {
  Vehicle V1 = new Vehicle();
  Vehicle V2 = new Vehicle();

  //Vehicle 1 (BMW)
  V1.setColour("Blue");
  V1.setFuel(56);
  V1.setWheels(3);
  V1.setMaxSpeed(150);
  //Vehicle 2 (AUDI)
  V2.setColour("Red");
  V2.setFuel(59);
  //Wheels and Max speed are on default...

      System.out.println("Choose from Audi or BMW");
      Scanner input = new Scanner(System.in);
      String q = input.next();
      while(q.equalsIgnoreCase("BMW") || q.equalsIgnoreCase("AUDI")){

      if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
          System.out.println("Here is the latest BMW Car specifications:");
          System.out.println("Colour: " + V1.getColour());
          System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
          System.out.println("Wheel count: " + V1.getWheels());
          System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");
          break;
      }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
          System.out.println("Here is the latest AUDI Car specifications:");
          System.out.println("Colour: " + V2.getColour());
          System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
          System.out.println("Wheel count: " + V2.getWheels());
          System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
          break;
      }else{
          System.out.println("Sorry that is not a car manufacturer listed      (AUDI/BMW)");
      }
  }
}
}

Comment: You're not getting any input from within the loop. How will the variables ever change within the loop? How will it end?
Comment: You never assign a new string to `q` so how do you expect your loop to work? also `break` just exits the loop anyway
Comment: Woah guys go easy on me xD, thanks tho, can you give me some pointers on how to fix/make the code better, like edit it? cuz i getcha but i dont getcha P.S didn't mention that theres another class file.
Answer: You need to ask the user until he enters one of the correct words. So you have to do it like this:
 String q = input.next();
 while(!q.equalsIgnoreCase("BMW") && !q.equalsIgnoreCase("AUDI")){
    q = input.next();
 }

After that you can print out the information about the AUDI or BMW depending on what the user input was.
Comment: You need `q isn't BMW AND q isn't AUDI`, not `OR`. As it is, no input can get past that loop. For example, if the input is `"BMW"`, it doesn't equal `"AUDI"`, so the second part of the loop condition is `true`, and the whole loop condition is `true`, so the loop continues.
Comment: @ChaiT.Rex a String value cannot contain two values e.g. BMW and AUDI at the same time what do you mean by &&? you mean it must contain BMW and AUDI?
Comment: No, I mean it should be neither for the `while` loop to continue. When it's neither, you have `!BMW && !AUDI`. See the example at https://ideone.com/SNI83R, where using `||` leads to an infinite loop (the second loop never completes).
Comment: @ChaiT.Rex here I had edited my answer see my proper answer I added the logic
Answer: you need to exclude your if and else if statement out of the loop then reprompt
the user if it is not BMW or AUDI then outside the loop test the String
int car=0;
    while(car==0)
    {
        if(q.equalsIgnoreCase("BMW")||q.equalsIgnoreCase("AUDI"))
            car++;
        else
        {
            System.out.println("Sorry that is not a car manufacturer listed           (AUDI/BMW)");
            System.out.println("Choose from Audi or BMW");
            q = input.next();
        }

    }
if (q.equalsIgnoreCase("BMW")){ // Prints BMW Car Specifications
      System.out.println("Here is the latest BMW Car specifications:");
      System.out.println("Colour: " + V1.getColour());
      System.out.println("Fuel Capacity: " + V1.getFuel() + " Liters");
      System.out.println("Wheel count: " + V1.getWheels());
      System.out.println("Maximum Speed: " + V1.getMaxSpeed() + " KM/H");

  }else if(q.equalsIgnoreCase("AUDI")){ //Prints AUDI Car Specifications
      System.out.println("Here is the latest AUDI Car specifications:");
      System.out.println("Colour: " + V2.getColour());
      System.out.println("Fuel Capacity: " + V2.getFuel() + " Liters");
      System.out.println("Wheel count: " + V2.getWheels());
      System.out.println("Maximum Speed: " + V2.getMaxSpeed() + " KM/H");
    }

How to fix my loop code in JAVA?


Problemas com referências e MVC

Question: Tenho um projeto onde funciona. Precisei criar outro projeto em outro lugar e fui aproveitando o que eu já possuo. Acontece que está dando um erro em base.Initialize(...) dizendo que não reconhece esse cara. Coloquei os mesmos using do outro projeto, ou seja, ctrl+c e ctrl+v e nada mais. Abaixo meus métodos
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {

            requestContext.HttpContext.Response.Buffer = true;
            requestContext.HttpContext.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            requestContext.HttpContext.Response.Expires = 0;
            requestContext.HttpContext.Response.CacheControl = "no-cache";
            requestContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            string strPaginaAtual = requestContext.HttpContext.Request.CurrentExecutionFilePath;
            strPaginaAtual = strPaginaAtual.Remove(0, strPaginaAtual.LastIndexOf("/") + 1);

            base.Initialize(requestContext);

        }

        protected override void OnException(ExceptionContext filterContext)
        {

            base.OnException(filterContext);
        }

e meus usings:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

Fui compilar e deu esse erro:
Error   1   'V99Util.WebPageBase.Initialize(System.Web.Routing.RequestContext)': no suitable method found to override

Comment: Qual a classe base da classe `WebPageBase`?
Comment: @pnet, o lugar para publicar a solução do problema é numa Resposta e não dentro da Pergunta. Aparentemente, é a mesma solução que o Cigano postou, quiçá marcar a resposta dele como correta?
Answer: A mensagem no suitable method found to override indica que na classe ancestral não existe um método Initialize que seja virtual com os argumentos usados no método da classe filho.
Neste caso, sua classe precisa ser implementada com a seguinte declaração:
public abstract class WebPageBase : System.Web.Mvc.Controller

Comment: Perito em pnet. ;)
Comment: Daqui a pouco vão criar a Tag.
Comment: E a aceitação automática para a tag.

Problemas com referências e MVC


In how many ways a student can get $2m $ Marks

Question: An examination contains four Question papers each paper carrying maximum marks as $m$. Find number of ways a student appearing for all the four papers gets a total of $2m$ Marks.
I used generating Polynomial method that is to find coefficient of $x^{2m}$ in
$$(1+x+x^2+\cdots+x^m)^4$$ which is
$$(1-x^{m+1})^4(1-x)^{-4}$$ which gives the coefficient of $x^{2m}$ as
$$\binom{2m+3}{3}-4 \times \binom{m+2}{m-1}$$
But the answer is just $\binom{2m+3}{3}$. What went wrong?
Comment: I don't think the given answer is correct.  By stars and bars, ${2m+3\choose3}$ is the number of ways of distributing the $2m$ marks among $4$ papers.  Clearly, some of these ways include more than $m$ marks for a single paper.
Comment: One can confirm the answer with stars and bars.  ${2m+3\choose3}$ is the number of ways to distribute $2m$ marks among $4$ papers.  To get the number of ways in which one paper has more than $m$ marks, give $m+1$ marks to one of the $4$ papers, and distribute the remaining $m-1$ marks among all $4$ papers.  This is $4{m+2\choose3}=4{m+2\choose m-1}$
Comment: It seems you got it right. The answer seems problematic. This answer is just the counting on the number of solutions for the nonnegative integer equation $x+y+z+w=2m$, which is wrong 'cuz none of the variables should exceed $m$.
Comment: As a simple check, if $m=1$ then there are clearly ${4 \choose 2}=6$ ways of getting a total of $2m=2$ marks from the four papers. This is ${2\times 1 +3\choose 3}-4 \times {1+2 \choose 1-1} ={5 \choose 3}-4 \times {3 \choose 0} =10-4=6$
Answer: Let us consider the marks in all the $4$ papers as $a,b,c,d$; $0\le a,b,c,d\le m$
$$a+b+c+d=2m$$
Now we need to find the integer solution of the above equation in the given condition.
Number of solutions $=\dbinom{2m+4-1}{4-1}=\dbinom{2m+3}{3}$, but note that this also contains those solutions in which any variable is grater than $m$.
Hence we need to subtract those solutions for $a\ge m+1$ and let $t=a-(m=1),t\ge0$
$a+b+c+d=2m\implies t+b+c+d=m-1$.$$\dbinom{m-1+4-1}{4-1}=\dbinom{m+2}{3}$$and for $b\ge m+1,c\ge m+1, d\ge m+1$. Finally, $\dbinom{2m+3}{3}-4\times \dbinom{m+2}{3}$
Answer: Nothing went wrong. Your answer is correct.

Somewhat more detailed we obtain by using the coefficient of operator $[x^n]$ to denote the coefficient of $x^n$ in a series:
  \begin{align*}
\color{blue}{[x^{2m}]}&\color{blue}{(1+x+\cdots+x^m)^4}\\
&=[x^{2m}]\left(\frac{1-x^{m+1}}{1-x}\right)^4\\
&=[x^{2m}]\left(1-4x^{m+1}\right)\sum_{j=0}^\infty\binom{-4}{j}(-x)^j\tag{1}\\
&=\left([x^{2m}]-4[x^{m-1}]\right)\sum_{j=0}^\infty\binom{j+3}{3}x^j\tag{2}\\
&\,\,\color{blue}{=\binom{2m+3}{3}-4\binom{m+2}{3}[[m\geq 1]]}\tag{3}
\end{align*}
Comment:

In (1) we expand the numerator up to powers of $x^{m+1}$ since higher powers do not contribute to $x^{2m}$ and we use the binomial series expansion.
In (2) we use the linearity of the coefficient of operator and apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$. We also use the binomial identity $\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q$.
In (3) we select the coefficients accordingly. We also use the Iverson brackets to respect that the exponent in $[x^{m-1}]$ is non-negative.


How to install Zend Framework on Windows

Question: "installing Zend Framework is so easy!!!!" yeah right...
Ok I'm working with a beginner's book and the ONE thing that is not excessively detailed is the most important part: Installing the darn thing. After browsing the quickstart guide for hours, all it said was:
"download Zend [...] add the include directory (bla bla) and YOU'RE DONE!"
right, i'm done using Zend.
Ok, not really, not yet anyway. I beg of you people, I wanna go to bed, please tell me how (in simple 6th grade detail) to install the framework. I've got the unzipped folder in my htdocs directory, and I placed zf.bat+zf.php in the htdocs root.
What's next?
thank you so much.
Comment: I would just like to add that once you setup your environmental variable to include php.exe, zf.bat, and the ZF library, you will need to restart the command prompt for the paths to take effect. It seems that once you click on "OK," the changes in the paths are broadcasted throughout Windows, but you will need to restart your application for it to take effect on that application.
Comment: Glad you found a solution that works for you.  Have fun with PHP!
Answer: It seems like you're having trouble with the PATH in the Windows command shell.  This is independent of Zend Framework.  Understanding the PATH concept in a shell environment is a hurdle many programmers have to overcome, but once you get it, you can use it to increase your productivity.
You can always run a program from the command shell using that program's absolute path.  For example:
C:\> c:\wamp\bin\php\php.exe

You can also run a command using a relative path.  That is, you enter the path from your current working directory to the location of the program you want to run.
C:\> cd c:\wamp
C:\> bin\php\php.exe

But if you run a command in the command shell without naming the full path to the executable, the shell tries to find the program executable in one of the directories listed in your PATH environment variable.  That is, the path is a string with directory names separated by semicolons.  To run an executable, the shell tries each directory in that list, in order, as if you had
C:\> type %PATH%
C:\WINDOWS\;C:\WINDOWS\SYSTEM32
C:\> php.exe
...error that it cannot find php.exe...

Special case: running php.exe also works if your current working directory happens to be the location of that program executable.  But that's just an example of using a relative path, using a path with zero directory levels.
Second problem is that you're running zf.bat which is a script that in turn invokes php.exe without specifying a path.  It assumes you have added the location of php.exe to your PATH environment variable.
C:\> SET PATH=%PATH%;C:\wamp\bin\php
C:\> php.exe -v
PHP 5.3.1 (cli) (built: Nov 29 2009 13:59:20)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

The zf.bat script itself also needs to be found.  You can do this by adding the directory where it resides to your PATH.  Assuming you installed Zend Framework under C:\zf, for example:
C:\> type %PATH%
C:\WINDOWS\;C:\WINDOWS\SYSTEM32;C:\wamp\bin\php
C:\> zf.bat
...error that it cannot find zf.bat...
C:\> SET PATH=%PATH%;C:\zf\bin
C:\> zf.bat show version
Zend Framework Version: 1.10.0dev

I would also recommend that you install Zend Framework outside your htdocs directory.  There's only one PHP file you need under your htdocs: that is the single bootstrap file that Zend Framework uses to instantiate the Front Controller and dispatch the request.
When you use zf.bat to generate an skeleton application for you, it creates a directory public with a PHP script index.php inside that directory.  This index.php file is the one you need to be in your htdocs directory.  You also need assets like CSS, Javascript, and images to be under your htdocs.  The rest of your application code, and the entire Zend Framework itself, should be outside your htdocs.  Especially any config files where you store sensitive data such as your database password, etc.
You can edit the index.php file.  It may define a PHP constant APPLICATION_PATH, which is the location of the rest of your application code.
<?php

defined("APPLICATION_PATH")
    || define("APPLICATION_PATH", realpath(dirname(__FILE__) . "/../application"
));

That default definition for APPLICATION_PATH assumes that your htdocs is a sister directory to the rest of your application code generated by the zf.bat tool.  You can certainly put your app code anywhere else, but you have to change the above code so that the index.php script finds it.
Also the index.php script may add the location of library code to PHP's INCLUDE_PATH.  This is useful if you need to make the Zend Framework library findable, or if you use other third-party PHP code in your application.  Assuming you installed Zend Framework under C:\zf, you should add its library subdirectory to your PHP INCLUDE_PATH.
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    "C:/zf/library",
    realpath(APPLICATION_PATH . "/../library"),
    get_include_path()
)));

The code templates generated by the zf.bat script try to make sensible default guesses about where your code is located, but your environment is your own, and it's easy to edit these scripts to specify the true location where you installed your code and libraries.
Answer: The framework doesn't have to be in the htdocs folder, it can be anywhere. Once you decompressed it somewhere you're 50% done.
Next step is to locate your php.ini file (for instance create a file <?php phpinfo();?> in your htdocs folder execute it and look for "Configuration (php.ini) filepath" (or similar) in the first block. In that file add the path to the ZendFramework to the include_dir directive. This has to include the library folder. Your setting might look like this:
include_dir = .;c:\php\ZendFramework\library

Often it also includes the path to PEAR.
Then restart your server.
You are done.
Comment: ok, when i write c:\htdocs\zf.bat create project quickstart
in cmd, it notifies me that "php.exe" doesn't exist. What gives??
Comment: php.ini files are not executed, they are just viewed because they are a simple text file.
Comment: @Gal since you seem to be on Windows, add PHP to your enviroment variables to make use of the PHP CLI: http://www.rasyid.net/2008/05/11/setting-path-for-php-cli/
Answer:
Zend != Zend Framework
Zend Framework doesn't need to be installed. It is merely a library, it just needs to be placed somewhere.
As johannes says you need to tell php where to look for the library so you add the folder where the Zend Framework library is located to your php include path.

That's it, there is nothing more!
Now it seems that your real problem has nothing to do with Zend Framework as such. You're trying to use Zend_Tool but the command line tool zf.bat is not on your system path so you are not able to use the command 'zf'. Zend Framework works fine without the tool, if you want to use it anyways, invoke the command, when you're in the folder where zf.bat resides or add the path to zf.bat to your system path.
This means in a non-vague way:
if (path-to-zf.bat isOn SYSTEM_PATH)
{
    you can call 'zf' from anywhere;
}
else
{
    you must be in the folder where zf.bat also is, if you want to call 'zf';
}

Comment: if you're a complete newbie theny I'd advise not to bother with the tool.
Comment: thanks but you programmers always give such vague answers...

I mean, "invoke the command, when you're in the folder where zf.bat resides or add the path to zf.bat to your system path."

- please, can't you tell I'm a complete newbie?
Comment: i'm very good with PHP, I just tried using Zend and all tutorials are like "super simple to install! just download and bam!"

Reminds me a little bit of weight loss commercials on tv.
Comment: besides, it still tells me "php.exe" file does not exist, and when i look at zf.bat i see it contains "assume php.exe is executable"
Comment: which means that php.exe is also not on your system path.
Comment: It is super simple. Your problem doesn't have anything to do with installing Zend Framework. Mind it, Zend Framework... not Zend.
Comment: one last question, if I DO want to execute zf.bat on cmd, and my zf.bat file is inside the same folder with php.exe and on cmd I write:
"c:\php\zf.bat" it still tells me "php.exe" is not recognized as an internal/external command. What do I do?

And I understand, zend FRAMEWORK!! thanks.
Comment: You need to include php.exe on your Winows SYSTEM_PATH. And when you're at it, do it for both of them.
Answer: Derived from http://normankosmal.com/wordpress/?p=47:
****> ****Process  of install zend framework in window
> 1) Download zend framework
> 2)After installing xampp extract the
> Zend Framework files into a folder of
> your choice. Next step is to edit the
> php.ini. Usually this file can be
> found in the php folder in your xampp
> installation. Find the line that says
> include_path and edit the line like
> this:
>     Windows: "\path1;\path2″
>     include_path = ".;D:\Informatik\SERVER\xampp\php\pear\;D:\Informatik\SERVER\xampp\php\ZendFramework\library"
>     3)
>      did you add your php interpreter to %PATH%?
>     In which file i have to add the PHP interpreter?
>     You mean i need to edit zf.bat file
>     SET ZF_SCRIPT=%PHP_DIR%\zf.php
>     Here in place of %PHP_DIR% i need to add the path of my PHP directory?
>     Can you plzz help me out.
>     4) D:\Informatik\SERVER\xampp\htdocs>D:\Informatik\SERVER\xampp\php\ZendFramework\b
>     in\zf.bat create project testproject********

Answer: Gal - I had the same problem. We must be working on the same book this weekend.
I solved the project-creation problem when I figured out that in the terminal window, you need to first navigate to the PHP home directory you created.
So in other words if you are in the PHP5 folder, type "zf create project c:/Apache/htdocs/projectname"
I had the same issue re: missing php.exe file until I figured this out.
--
That's the good news. The bad news is you're going to have similar problems when you try setting up Controllers and Actions, and my fix won't work for this. I still haven't figured this out, so I'll post again with more info and perhaps the others can help.
Comment: thank you, i'll look into that.

gosh sometimes I just feel like beating these "it's so easy!" guys in the head with an inflatable rubber hammer!
Comment: I installed PHP into c:\php and it was there.
Comment: right, it was php-dist.ini, try copy/pasting it and changing the name from php-dist.ini to php.ini that worked for me
Comment: Thanks, will give it a try. Any luck with creating the new project using the workaround I suggested?
Comment: now when I write in cmd "c:\php\zf.bat" it shows a big ZF ERROR message saying I don't have Zend tool in my include_path...

I mean, for real, are these guys kidding me?? I would call ZF easy as crossing the chinese wall barefoot.
Comment: here's a step-by-step:
- open terminal window
- type cd c:\
- type cd php
- type zf create project c:/APACHE/htdocs/PROJECTNAME
That should work. Notice that you had to navigate to the PHP home directory because this is where the php.exe file is, and this is where the zf.bat and zf.php files are.
Answer: Gal, I don't understand what do you want to do.
There is no installation or configuration for the framework.
You just have to

Unpack the framework anywhere
Create a project running zf create "myproject"
Create a shourtcut/link in /library => root folder of the framework. You can also just unpack the whole framework in this folder (/library) but if you have many projects, you will end with many copies of the framework using diskspace.
change you apache configuration for opening /myproject/public/index.php when redirecting the web browser to your site.

I mean, this have nothing to do with zf, if you create a site in your computer, you have to tell Apache where is it.
You always can run zf.bat writing the whole path. If zf.bat returns un error, then very probably you have problems with you php installation.
Just in case it's helpful, this is my apache configuration (httpd.conf) for a project named zf_cms
<VirtualHost *:80>
ServerAdmin email@example.com
DocumentRoot "C:\Users\alex\Documents\My Web Sites\zf_cms/public"
ServerName zf_cms.conexion

<Directory "C:\Users\alex\Documents\My Web Sites\zf_cms/public">
    #DirectoryIndex index.php
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Then you have to add this line to %windir%\system32\drivers\etc\hosts
127.0.0.1     zf_cms.conexion

Comment: And an explanation for us, mortals?
Answer: Easier to read if I type it here.
Here's a step-by-step:

open terminal window
type cd c:\
type cd php
type zf create project c:/APACHE/htdocs/PROJECTNAME

Substitute your directory and project names where I used all caps.
That should work. Notice that you had to navigate to the PHP home directory because this is where the php.exe file is, and this is where the zf.bat and zf.php files are. Apparently both are required when using Zend_Tool.
Answer: You don't say what web stack you're using, but the simplest way that I've found to work with Zend on Windows is to install Zend Core. This installs a complete stack pre-configured with the Zend Framework.


Was Cristiano Ronaldo's 100th Champions League goal offside or not?

Question: On April 19, 2017, during the second period of the extra time of the second leg of the Champions League quarter-final match between Real Madrid and Bayern Munchen, Cristiano Ronaldo scored his hundredth UEFA Champions League goal (which was also his third goal of the night).
Was Ronaldo offside at the moment the final pass to him was made? Here is a picture of him receiving the ball from Marcelo before scoring:
Comment: The "watermark" on this image show this written: "Real Madrid ruling clubs since 1902". So I believe this is not a good source to show in an objective question
Comment: The offside line used in that image is horribly misleading as to whether the decision is correct. The official also seems to be trailing approximately level to the defender in red, so how it wasn't flagged, I don't know...
Comment: @ratchet freak, that there are, though unless the camera lens is circular (unlikely), I don't believe they should converge reliably. And minor errors in line diagnosis may lead to significant shifts in vanishing point?
Comment: @JeopardyTempest there are parallel lines in the grass (the different shades of green) so you can recreate the vanishing point for the lines parallel to the goal line which in turn lets you draw other parallel lines. But the shaded area is off parallel in the wrong way.
Comment: @ratchet freak: I'm certainly no industry expert on such topics, just subjects I've had to work with at times in the past.  I may sound like I'm trying to debate it, but really have no position on the game (and didn't see it).  Just giving my view when shown the image, and reasoning.  Since the SE request is that comments not be answers, and I felt I had a bit too much of one, I moved my comments into an answer, and am deleting my comments, so feel free to provide any pertinent details there :-)
Comment: The goal was allowed, so it was not offside. Clearly you are arguing that it perhaps should have been called. But, note that both players, one with the ball, have already beaten the defender. This is not offsides at this point. Bad defending, yes, but not offside.
Comment: The position of the second-last defender is only one consideration for offside. The position of the ball and the halfway line are also the others: a player must be level with or behind at least one of them to be onside. Ronaldo was apparently none; comparing these situations with rules and officiating knowledge to learn from the mistakes of those far better, is the crux of umpire and referee and judge development.
Answer: Laws of The Game; Law 11 - Offside; 1. Offside Position state that:

A player is in an offside position if:
...
any part of the head, body
or feet is nearer to the opponents' goal line than both the ball and
the second-last opponent.

It's obvious that Ronaldo was nearer to the goal line than the the second-last opponent (the guy in the red shirt: Mats Hummels).
Now the dubious part is whether Ronaldo was nearer to the goal line than the ball. The answer is yes, he was, hence, he was in the offside position.
Why? Because the offside-line in the picture you use is not quite parallel to the goal line, but look at another picture from goal.com, Ronaldo's head was closer to the goal line than the ball:
Comment: @gdrt Many Madrid supporters say that Ramos own goal was offside as Lewi was in offside position and he interrupted in play though he did not touch the ball. Questions is,was that offside or legal?
Comment: @Ganesh, It was illegal, because this goal was also scored when Lewandowski was in active offside position, as confirmed by [Sky Germany](http://www.sky.de/programm-entdecken/mediathek/videos-fc-bayern-muenchen/5402428838001). Look at 1:28 in the video, as you can see Lewandowski was closer to the goal line than the ball.
Answer: Looks like gdrt gave the rule well (and answered something I've wondered about for a long time too!)
But some of the complexities to the details make it appear close enough that I'm not sure all impartial arbitrators would agree that is a clear-cut offside call, in particular using this picture.
It may not be noticeable to the eye, but the lines drawn aren't parallel.  I verified this in GIMP by copying the line for the penalty box and translating it left:

If you look closely, you'll note the increasing green between the previously drawn line and the shifted penalty box line I overlaid as you go up the image.  Of course the resolution of that image isn't great, making it all that much more challenging to perfectly diagnose the line.
Then again, the big problem is that lines SHOULDN'T be exactly parallel, as there is always some perspective (angle change of truly parallel lines).  See how much the lines change angle in this image:

(Source: Okiespavement.com)
Perspective depends upon the distance, height, and lens shape on the camera. That picture of the American football field seems setup to exaggerate it.  But the result is that, unless the camera is situated on the line of interest (or a continuation of that line), or is directly above/below that line, any camera view can be surprisingly dubious (I've seen so many times where two views from similar locations appear to show different things due to very slight changes in perspective).  The fact that the top and side of the penalty box do not make near a 90 degree angle makes me more suspect there is quite a bit of perspective in this picture, though the camera location would need to be known to have more clarity on this. Also note, the perspective can actually converge in either direction due to the shape of the camera lens (and angle of the camera?), so the American football field image doesn't necessarily help determine the proper perspective changes either.
Now, there is the possibility that perhaps the line shown in the image was actually provided by the broadcasters themselves, and that they calculate it based upon the actual geometry of the camera similar to the NFL's 1st and 10 line.  That would make it a lot more reliable.  I've still seen such systems be imperfect, but it would allow a little more assurance that it is fairly correct, if we knew that they did that.  With the trend towards replay officials in soccer, it would seem very important to be able to overlay a properly calculated line reliably onto cameras, taking into account all camera details.  Here's to hoping they do that and make clear they are doing that.
That challenge of camera perspective, plus the added difficulty in determining the exact moment the ball left his foot, leads me to suggest it may be too close to say for sure.
In American football we face so many situations in our replay system where things are unclear or debatable that we require so-called "indisputable visual evidence" to make a call. Now what exactly that is... becomes a question in itself! But from my impartial perspective regarding the game (which I didn't see) (and for what it's worth, with that slight background in geometry and a bit of collegiate intramural refereeing experience) I would only suggest that Bayern fans would perhaps be best off not feeling particularly hard done by such a call, as it is quite close... and there continue to be many worse calls made and allowed to stand.
Comment: Your picture is worse than the one given in the OP! The offside line and the edge of area line should converge away from the camera, not diverge.
Comment: @AndyT I know it looks like my lines diverge, but if you read my details, you'd see it's just the actual line translated graphically, so that is deceptive.  I made no attempt at convergence/divergence, just a direct copy, showing the questionable nature of the other picture.  But as I stated, lens shape is everything, and without knowing it, you cannot say where they should converge...
Comment: Ok. So you're saying "The lines shouldn't be parallel. I've proved that the line drawn in the OP isn't parallel to the edge of the area. Therefore the line in the OP has made some attempt at perspective, but I make no comment as to whether it's a good attempt or not." ? I guess that's not too bad an answer. To my eyes the line drawn in the OP is incorrect (and favouring Ronaldo). How far it is incorrect is unclear, but given that the line drawn is right on the limit for both his head and knee, he is almost certainly offside, but it's close enough that you couldn't expect the linesman to know.


C# Parameter of IList>

Question: I can't seem to figure out why the following doesn't work.
From reading around it seems it must be somehow related to something like this.
public class Test<T>
{
    public void SomeFunction(IList<IList<T>> ListOfLists)
    {
    }
}

....

List<List<SimpleClass>> lists = new List<List<SimpleClass>>();
new Test<SimpleClass>().SomeFunction( (IList<IList<SimpleClass>>)lists );

How can I require a list to actually be a list of lists? I can't seem to grasp what I am doing wrong.
Thanks,
Answer: A List<List<SimpleClass>> isn't an IList<IList<SimpleClass>>.
For example, for the latter type, you could call lists.Add(new SimpleClass[5]) as SimpleClass[] implements IList<SimpleClass>. But you can't do that with a List<List<SimpleClass>>, because each element has to be a List<SimpleClass>.
This would be okay though:
List<IList<SimpleClass>> lists = new List<IList<SimpleClass>>();

Comment: I see clearly now. Hah. Thanks very much. I read into your other answer as well and between this post and the other. It makes sense.

C# Parameter of IList>


property in route undefined in controller

Question: In the IndexRoute of my Ember hello world app, I start a setInterval function that I wish to allow the end user to turn off (with clearInterval) by clicking a dom element in the template, which triggers an action in the IndexController. So, the setIntervalId is set in the IndexRoute, and I need to pass it to clearInterval in the IndexController, but the way I have it below, the setIntervalId is undefined.  I also tried to use App.IndexRoute.setIntervalId to no avail.
How would I accomplish this?
(function() {
  window.App = Ember.Application.create({

   LOG_TRANSITIONS: true,
   LOG_ACTIVE_GENERATION: true
    });

  App.IndexRoute = Ember.Route.extend({

      setIntervalId: 0,

      model: function() {
         this.setIntervalId = setInterval(this.someInterval, 5000)
      },
      someInterval: function(){
        var datasource = 'http://hackernews/blahblah';
        return new Ember.$.ajax({url: datasource, dataType: "json", type: 'GET'}).then(function(data){
             return data;
        })
      },

});

 App.IndexController = Ember.ObjectController.extend({
     actions: {
          clearTimeout: function(){
            console.log('clearing interval', this.setIntervalId); //undefined
            clearInterval(this.setIntervalId);

         }
         }
    })
})();

template

Answer: To set the model, you need to return the value in the route's model function:
model: function() {
  return this.setIntervalId = setInterval(this.someInterval, 5000)
}

To access the model in the controller, you need to use this.get('model').
actions: {
  clearTimeout: function(){
     console.log('clearing interval', this.get('model');
     clearInterval(this.get('model'));
  }
}

Comment: Thanks, so whatever's returned from the model function `is` the model?
Comment: Yes, that's the [purpose of the `model` function](http://emberjs.com/guides/routing/specifying-a-routes-model/).


TPROXY redirect and routing decision

Question: I would like to ask what happens internally when redirecting using Tproxy.
iptables -t mangle -A PREROUTING -p tcp --dport 443 -j TPROXY --tproxy-mark 1 --on-port 40001

It located in PREROUTING in the mangle table of iptables.
As far as I know, the routing decision is made after the PREROUTING chain.
When redirecting using Tproxy as above.
Packet through ip rule & routing table? Or does it go directly to the local 40001 port?
Answer: I have the same problem.
I want to know what happened because I find if I use TPROXY, the routing table looks like not work.
Chain PREROUTING (policy ACCEPT 887 packets, 200K bytes)
 pkts bytes target     prot opt in     out     source               destination
  20M 4462M TPROXY_SRV_eth3.1  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain TPROXY_SRV_eth3.1 (1 references)
 pkts bytes target     prot opt in     out     source               destination
  225 14048 TPROXY     tcp  --  eth3.1 *       0.0.0.0/0            126.96.36.199/24       tcp dpt:8000 TPROXY redirect 18.104.22.168:8000 mark 0x1/0x1

The route table with fwmark 1 like
local default dev lo scope host

The IP rule is
0:  from all lookup local
1:  from all fwmark 0x1 lookup 1
10: from all fwmark 0x29 lookup 41
10: from all fwmark 0xc lookup test
32766:  from all lookup main
32767:  from all lookup default

I found the packet does not go through table 1 because I can't capture it by tcpdump.
anyone can help me

TPROXY redirect and routing decision


SQL Query in Geoserver

Question: Anybody know why the geoserver does not implement a direct sql query when setup a layer?
Comment: Maybe it has something to do with the format of the Geoloc db field type?  If the database were a  upgrade from an older sql server that didn't have geocode data types, then by having a newer sql server implement a view, then the old data need no change??
Answer: The developers just hadn't gotten around to it yet.  (There is not a huge need for this feature since GeoServer can serve a database view as easily as a table.)  However, now GeoServer is able to dynamically alter the SQL used to fetch feature data from databases.  This functionality is discussed in the GeoServer users manual at http://docs.geoserver.org/stable/en/user/data/database/sqlview.html
Comment: since I wrote this response the feature has been documented in the geoserver manual.  I'll update the link to point at that, thanks for letting me know it was broken @djangofan .

SQL Query in Geoserver


Enforce the length of the arrays are the same in Rust function arguments

Question: We have a function with two vectors. We would like to ensure that the length of the two vectors is the same. Is there a way to enforce that from the type level in Rust?
For example, here we guarantee that the two input vectors num1 and num2 are of length 4.
fn foo(nums1: [i32; 4], nums2: Vec<[i32; 4]>) {
    println!("{:?}", nums1);
    println!("{:?}", nums2);
}

What we really want is this:
fn bar(nums1: Vec<i32>, nums2: Vec<Vec<i32>>) {
    for row in &nums2 {
        assert!(nums1.len() == row.len());
    }

    println!("{:?}", nums1);
    println!("{:?}", nums2);
}

We want them to be of the same length but they can be of any length. The above works fine of cause, however, it is a runtime check instead of a compile time check.
Is there a way to achieve this in compile time with some Rust generic, macro, or whatever dark magic?
# N to be any integer larger than 1
fn baz(nums1: [i32; N], nums2: Vec<[i32; N]>) {
    println!("{:?}", nums1);
    println!("{:?}", nums2);
}

Answer: You can use const generics.
fn foo<const N: usize>(nums1: [i32; N], nums2: Vec<[i32; N]>) {
    println!("{:?}", nums1);
    println!("{:?}", nums2);
}

fn main() {
    foo([1, 2], vec![[1, 2], [1, 2]]);
    foo([1, 2, 3], vec![[1, 2], [1, 2]]);
    //                   ^^^^ expected an array with a fixed size of 3 elements, found one with 2 elements
}

Comment: Was not expecting this to be possible. Thank you!
Comment: I didn't know you could do this, good info!


VueJs Vuetify Click on table row event not reading item

Question: i am new to VueJs and Vuetify and i have a script that read data from a Json and display it into a Table.is a glossary type app. I have the option to select from different languages to be shown into the table. The problem is that when i click on a row i would like to display into a popup (alert) the item information. What i did is not working at all, is just showing the Alert popup but without information.
The format of the Json is:
{"glossary":[
{"id":2,"English":{"term":"contact","definition":"the state of physical touching"},"Vietnamese":{"term":"tiếp xúc"},"Simplified_Chinese":{"term":"接触"},"Arabic":{"term":"ملامسة"},"Swahili":{"term":"mgusano"}}]}

    <v-data-table dense light :headers="selectedHeaders" :item-key="id" @click:row="showAlert(item)" :items="glossary.glossary" class="elevation-1" :single-expand="true" :disable-sort=true :search="search">
     <template #item.ar.term="{item}">

       {{item.ar.term}}

     </template>
</v-data-table>

Comment: ShowAlert is passing `a` which is the item as a variable but it's not used. `this` just returns the vue object
Comment: Then what do you recommand to use to show the value inside the item? i tried with a.English.term and is get error.
Comment: Try `console.log(a)` and see if the result you want is in there
Comment: sorry for my limited knowledge but how can i check the console.log if i am remote on a Ubuntu Azure VM with only SSH access?
Comment: I've added an answer and an example that should help. I'm not sure what your setup is like but I would assume if you are running this from the terminal then you should be able to see the console.log
Answer: You are not using a which is the item passed. this just returns the vue object. What you might want is this
 showAlert(a){
      if (a.target.classList.contains('btn__content')) return;
      alert('Extra Information:! \n'+a.English.term );
      console.log(a);
    }

Here is a codepen that I found that should help you understand it better https://codepen.io/nsiggel/pen/KRdGgE. Note: I did not write this codepen.


Display Default page until server starts

Question: I want to display a default custom page until my server starts completely.
Problem Statement : I am doing few setup things when the server starts, so it takes a very long time for the server to start. So in the meantime server stats if some user hits the home page url, so he should see some default page showing server is starting..blah blah...
Now the issue is if server is not started completely, neither my application context is loaded fully, and the response for the hit is "aborted", which is not a HTTP response, so how can i catch this response and show some error page.
Server can be jetty, tomcat any
Comment: If the server hasn't been fully initialized it cannot serve requests.
Comment: There sure is.  Artifactory does it for example.  However, you are going to have to move your long setup code out of the servlet initialization and into some other background worker thread.  The servlet initialization should just kick off your worker thread.  You then should have a servlet which checks to see if your application is initialized and responds appropriately.
Comment: yes correct..but is there a way i can do something to show some default page until server is started...
Answer: A quick and dirty example:
<code>public class DeferringServlet extends HttpServlet {

  private static final Logger logger = Logger.getLogger(DeferringServlet.class);

  private MyApp myApp;
  private Thread appInitializerThread;

  public void init() {
    myApp = new MyApp();
    appInitializerThread = new Thread(new Runnable() {
      public void run() {
        myApp.init();
      }
    });
    appInitializerThread.start();
  }

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    if(myApp.isInitialized()) {
      myApp.doGet(req, resp);
    } else {
      myApp.setStatus(503); //Service unavailable
      myApp.getWriter.println("Please wait.  App is loading");
    }
  }

  public void destroy() {
    if(appInitializerThread.isAlive()) {
      appInitializerThread.interrupt();
    }
    try {
      appInitializerThread.join();
    } catch (InterruptedException ex) {
      logger.warn("Interrupted before app initializer could finish");
    }
  }

}
</code>


redirect to another page on webform submit using [current-page:query:?] token

Question: I am trying to configure a webform to redirect to another page after submission by including the redirect location in the url:
http://mysite/content/barb?destination=content/discus
According to webform there is a token [current-page:query:?] which I assume can extract the value of destination.  I have including it in the webform redirect to custom URL of the form, but I cant get it to work.
I have tried:

[current-page:query:?]
[current-page:query:?destination]
[current-page:query:destination]

But nothing seems to work. What is the correct way of using this token to get a variable from the URL?
Answer: I've found that no token is required for this...
You can select Confirmation page as the redirect location, then the ?destination= parameter will just work. Not sure that this is a documented feature, though.
See also https://drupal.stackexchange.com/questions/120466/webform-redirect-to-referring-page-on-submit-not-showing-message which highlights a downside to this method.
Answer: I just tried the [current-page:query:destination] token in the Custom URL box, and that works too.
No problems with the confirmation message appearing, either!


dealing with self-referential foreign keys; django mixer

Question: I am getting the typical runtime error of self referencing FKs testing django with fake objects:
In [12]: from mixer.backend.django import mixer

In [13]: x = mixer.blend(ItemGroup)

/home/cchilders/.virtualenvs/clientsite/lib/python3.4/site-packages/django/db/models/fields/related.py in __set__(self, instance, value)
    587             raise ValueError(
    588                 'Cannot assign None: "%s.%s" does not allow null values.' %
--> 589                 (instance._meta.object_name, self.field.name)
    590             )
    591         elif value is not None and not isinstance(value, self.field.rel.to):

ValueError: Mixer (<class 'clientsite.gacl.models.AroGroup'>): Cannot assign None: "AroGroup.parent" does not allow null values.

the model:
class ItemGroup(models.Model):
    parent = models.ForeignKey('self', db_column='parent_id')
    name = models.CharField(max_length=255)
    value = models.CharField(max_length=255, unique=True)

    class Meta:
        db_table = u'item_groups'

    def __str__(self):
        return self.value

    def __repr__(self):
        return '<{} {}: {}>'.format(self.__class__.__name__, self.pk, self.value)

The docs are sparse on referencing yourself as FK. How can you fake an instance that requires on one of itself with django mixer? Thank you
Answer: Try adding null=True to the declaration of the parent field.  There has to be at least one top-level ItemGroup that won't have a parent.


$(v_1,v_2\ldots,v_n)$ is linearly independent. Can $(v_1+u_1,v_2+u_2,\ldots,v_n+u_n)$ remain linearly independent?

Question: Given are $n$-dimensional vector space $\langle R^n;+\mid R\rangle$ and $n$ vectors $(v_1,v_2,\ldots,v_n)$ which are linearly independent, $u_i\in R^n, i=\overline{1,n}.$
Say, $x$ = $(v_1,v_2,\ldots,v_n)$ and $y$ = $(u_1,u_2,\ldots,u_n)$. Then $x+y\in R^n$.
Vectors are both $n$-dimensional.
Q: So, by that way, are the $n$ vectors in $x+y$ linearly independent?
Is there some theorem which relates to this?
Comment: sorry, linearly independent from what?
Or do you mean a basis of $n$ vectors $v_1,...,v_n$?
Comment: I guess it follows.
Comment: @Modestas_S are you assuming that the $u_i$ are also linearly independent?
Answer: The answer is no, even with the extra hypothesis $u_i$ linearly independent
Take for example $u_i = -v_i$. They both are sets of independent vectors, but $x+y=(0,\dots,0)$
Answer: In general the answer is no.
Consider, in the real vector space $\mathbb{R}^2$, $v_1 = (1,0)$ and $v_2 = (0,1)$, which are linearly independent. Consider aldo $u_1 = (0,1)$ and $u_2 = (1,0)$. Clearly the vectors $v_1 + u_1$ and $v_2 + u_2$ are not linearly independent.
Hope this was clear.


Do I need to use a block or form to implement login box, or can I just post to a 'login' url the user details?

Question: I have static HTML for a login box which contains a form with username and password inputs and is part of the site header, which will be on every page ie. this is not a login 'page'.
To integrate this with the Drupal login system, can I point the form action at a certain url to post the login details and perform the login? Thereby, not requiring any Drupal backend form/block/theme coding?
Or do I need to implement my own form, or customise an existing form to achieve this? If so, why is that? What do I need from the Drupal back end to successfully login ie. hidden form fields that need to be passed with the login details etc?
I am trying to implement the site in the cleanest way possible, using my own HTML 5/ CSS 3 markup, so overriding most html so that the tonne of classes Drupal adds, and the extra unnecessary markup are scraped. So, ideally I would like to avoid having to make a login form/block as part of the back end.
Answer: You can print login block in the tpl file. No need to use username/password fields of HTML/CSS.
<?php print drupal_get_form('user_login_block'); ?>

For Registration :
<?php print drupal_get_form('user_register_form'); ?>

Comment: because of security .. you cant submit a login form correctly if you dont use $form['form_build_id']['#id'].
Comment: I want to use my own HTML/CSS because it is much better than Drupal markup. I am asking can I just submit the form variable to a url to successfully login?
Comment: but you can theme login form of drupal accordingly. It is the good practice.
Comment: Why? Where does the login form post to? I want to know why I should/need to use the Drupal login form?
Answer: You can theme your login form using hook_theme in your template.php
function THEMENAME_theme(){
  return array(
  'user_login_block' => array(
      'arguments' => array('form' => NULL),
      'template' => 'user-login-block',
    ),
}

now create user-login-block.tpl.php in your theme. You can use your html and drupal_render($form[ELEMENTS]) in that tpl file.
For example

        Username

        <?php
           $form['name']['#description']='';
           print drupal_render($form['name']);
        ?>

        Password

        <?php print drupal_render($form['pass']);?>

        <?php
            $form['submit']['#attributes']['class']=array('Login');
            print drupal_render($form['submit']);
        ?>

<?php echo drupal_render($form) ?>

Comment: I have seen examples like this. What do the drupal_render functions render? Where does this post the details to? I'd rather just post myself than use Drupal. Or is there a reason I NEED to do this?
Comment: `http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_render/6` mostly used to print form and form elements.


Polynomial distributed lag AR model specification

Question: Generally speaking, polynomial distributed lag (PDL) models deal with independent variables and autoregressive (AR) models deal with dependent variables (their errors), but are there ever occasions where one specifies a lagged term of a independent variable alongside an AR term? I have not come across this too much in the literature and I wasn't sure if it was because it's not a good idea, or if it was because it's too obvious and didn't need addressing. If it is common practice, could someone please share what they feel the most appropriate name of that kind of model would be? Would it be as straightforward as PDLAR?
I would like to hear what a few experts have to say about this.
Comment: What does PDL stand for?
Comment: There are models where lags of both dependent and independent variables are included, e.g. autoregressive distributed lag (ARDL) model. Also, what does PDL stand for?
Comment: Thank you for sharing the info, that explains a lot. PDL is short for polynomial distributed lag, could be finite or infinite.
Answer:
[A]re there ever occasions where one specifies a lagged term of a independent variable alongside an AR term? <...> [C]ould someone please share what they feel the most appropriate name of that kind of model would be?

One model where lags of both dependent and independent variables are included is autoregressive distributed lag (ARDL) model. See e.g. Dave Giles' blog post "ARDL Models - Part I" for some details.
Comment: Very informative, I glued to my eviews screen. Sorry for the late reply. So is it typical for the ARDL model lags to be of the same magnitude? With pdl, one can specify the polynomial order as well as finite or not. I wonder if any of these can be configured with ARDL. I haven't seen this covered yet.
Comment: @ArashHowaida, I do not remember seeing ARDL with infinite lag, and I do not know if this is available in existing software. Regarding the same magnitude, it must depend on the application. You can imagine situations where they could be similar and others where dissimilar. Sorry for not being able to give more definite answers.


PBR with iptables

Question: I know question was answered multiple times, but this situation a bit different.
So here is what I have:

All users must user default gateway on eth0, except one
That one must only use gateway on eth1 and must not under any circumstances use eth0

Separately this things easy to implement, but together... With setup it mostly works: 1002 user goes via eth1 and goes nowehere if it's not available. However, some hosts are still routed via eth0. I have no idea why.
Here is my setup:
user@localhost:~$ ip rule
0:  from all lookup local
1000:   from all fwmark 0x5 lookup 5
2000:   from all fwmark 0x5 lookup 6
32766:  from all lookup main
32767:  from all lookup default`

user@localhost:~$ ip route list table 5
0.0.0.0/1 via 10.10.0.185 dev eth1

user@localhost:~$ ip route list table 6

blackhole 0.0.0.0/1

user@localhost:~$sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

user@localhost:~$ sudo iptables -t nat -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-A POSTROUTING -o eth1 -j MASQUERADE

user@localhost:~$ sudo iptables -t mangle -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-A OUTPUT -m owner --uid-owner 1002 -j MARK --set-xmark 0x5/0xffffffff

Answer: You specified a route of 0.0.0.0/1. This subnet consists of 0.0.0.0 through 127.255.255.255 inclusive. It's not at all clear why you would want to only route half of the possible IP addresses. I suspect you meant to route all of it (e.g. 0.0.0.0/0) instead.
Comment: yup, that was an issue. just noticed that. And pattern of ip address routed via eth0. Apparently, just typing everything here helped me solve it. Thanks.

PBR with iptables


Compute total distance from an ordering of a path

Question: I have a distance matrix and a data.frame of orderings that I want to compute the total distances for each ordering (row).
distance matrix (generated by as.matrix(dist(x, upper=TRUE, diag=TRUE))):
               FOV5.1.T4.C1 FOV5.1.T4.C1.1 FOV5.1.T4.C2 FOV5.1.T4.C2.1
FOV5.1.T4.C1      0.0000000     11.5454430    0.3431676     13.2814257
FOV5.1.T4.C1.1   11.5454430      0.0000000   11.5625031      2.8374444
FOV5.1.T4.C2      0.3431676     11.5625031    0.0000000     13.2407547
FOV5.1.T4.C2.1   13.2814257      2.8374444   13.2407547      0.0000000

ordering (generated by expand.grid()):
            Var1           Var2
1   FOV5.1.T4.C2   FOV5.1.T4.C1
2 FOV5.1.T4.C2.1   FOV5.1.T4.C1
3   FOV5.1.T4.C2 FOV5.1.T4.C1.1
4 FOV5.1.T4.C2.1 FOV5.1.T4.C1.1

Expected Output:
            Var1           Var2          Dist
1   FOV5.1.T4.C2   FOV5.1.T4.C1      0.3431676
2 FOV5.1.T4.C2.1   FOV5.1.T4.C1     13.2814257
3   FOV5.1.T4.C2 FOV5.1.T4.C1.1       ...
4 FOV5.1.T4.C2.1 FOV5.1.T4.C1.1       ...

I would like a total distance column appended to the end of the ordering data frame that would give the total distance from Var1 to VarN.
EDIT: The ultimate goal is to generalize this problem for many orderings (rows) and elements (columns) of the ordering data frame. For example:
distance matrix:
                FOV10.5.T1.C1 FOV10.5.T1.C1.1 FOV10.5.T6.C1 FOV10.5.T6.C1.1 FOV10.5.T7.C2 FOV10.5.T7.C2.1 FOV10.5.T7.C4 FOV10.5.T7.C4.1
FOV10.5.T1.C1        0.000000        9.259314      9.525777        4.920990      8.520076        3.246356     10.429007       12.771907
FOV10.5.T1.C1.1      9.259314        0.000000      2.903446        6.485444      2.604540        6.943048      2.962850       12.658076
FOV10.5.T6.C1        9.525777        2.903446      0.000000        8.185294      1.095356        8.058659      5.763981        9.949294
FOV10.5.T6.C1.1      4.920990        6.485444      8.185294        0.000000      7.233955        1.724583      6.384782       15.156368
FOV10.5.T7.C2        8.520076        2.604540      1.095356        7.233955      0.000000        7.054426      5.528189       10.060419
FOV10.5.T7.C2.1      3.246356        6.943048      8.058659        1.724583      7.054426        0.000000      7.488958       13.938926
FOV10.5.T7.C4       10.429007        2.962850      5.763981        6.384782      5.528189        7.488958      0.000000       15.570799
FOV10.5.T7.C4.1     12.771907       12.658076      9.949294       15.156368     10.060419       13.938926     15.570799        0.000000

ordering:
              Var1            Var2            Var3            Var4   Dist
1    FOV10.5.T1.C1   FOV10.5.T7.C4   FOV10.5.T7.C2   FOV10.5.T6.C1   sum(Var1 --> Var2, Var2 --> Var3, Var3 --> Var4)
2  FOV10.5.T1.C1.1   FOV10.5.T7.C4   FOV10.5.T7.C2   FOV10.5.T6.C1   ...
3    FOV10.5.T1.C1 FOV10.5.T7.C4.1   FOV10.5.T7.C2   FOV10.5.T6.C1   ...
4  FOV10.5.T1.C1.1 FOV10.5.T7.C4.1   FOV10.5.T7.C2   FOV10.5.T6.C1   ...
5    FOV10.5.T1.C1   FOV10.5.T7.C4 FOV10.5.T7.C2.1   FOV10.5.T6.C1
6  FOV10.5.T1.C1.1   FOV10.5.T7.C4 FOV10.5.T7.C2.1   FOV10.5.T6.C1
7    FOV10.5.T1.C1 FOV10.5.T7.C4.1 FOV10.5.T7.C2.1   FOV10.5.T6.C1
8  FOV10.5.T1.C1.1 FOV10.5.T7.C4.1 FOV10.5.T7.C2.1   FOV10.5.T6.C1
9    FOV10.5.T1.C1   FOV10.5.T7.C4   FOV10.5.T7.C2 FOV10.5.T6.C1.1
10 FOV10.5.T1.C1.1   FOV10.5.T7.C4   FOV10.5.T7.C2 FOV10.5.T6.C1.1
11   FOV10.5.T1.C1 FOV10.5.T7.C4.1   FOV10.5.T7.C2 FOV10.5.T6.C1.1
12 FOV10.5.T1.C1.1 FOV10.5.T7.C4.1   FOV10.5.T7.C2 FOV10.5.T6.C1.1
13   FOV10.5.T1.C1   FOV10.5.T7.C4 FOV10.5.T7.C2.1 FOV10.5.T6.C1.1
14 FOV10.5.T1.C1.1   FOV10.5.T7.C4 FOV10.5.T7.C2.1 FOV10.5.T6.C1.1
15   FOV10.5.T1.C1 FOV10.5.T7.C4.1 FOV10.5.T7.C2.1 FOV10.5.T6.C1.1
16 FOV10.5.T1.C1.1 FOV10.5.T7.C4.1 FOV10.5.T7.C2.1 FOV10.5.T6.C1.1

Comment: Can you provide expected output?
Comment: Added expected output to original post!
Answer: require(dplyr)
require(reshape2)

points <- replicate(5, sample(1:100, 2, T)) %>%
            `colnames<-`(letters[1:5])

dists <-  points %>%
            t %>%
            dist %>%
            as.matrix %>%
            melt(value.name = 'dist') %>%
            mutate_if(is.factor, as.character)

paths <- replicate(5, sample(colnames(points), 4, T)) %>%
            as.data.frame %>%
            mutate(tot.dist = NA)

for(i in 1:nrow(paths)){
    d <- numeric(ncol(paths) - 2)
    for(j in 2:(ncol(paths) - 1)){
        d[j - 1] <- dists %>%
                        filter(Var1 == paths[i, j - 1] & Var2 == paths[i, j]) %>%
                        select(dist) %>%
                        unlist
    }
    paths$tot.dist[i] <- sum(d)
}

paths

#   V1 V2 V3 V4 V5  tot.dist
# 1  c  c  e  e  c  99.29753
# 2  a  b  e  d  a 173.82135
# 3  d  e  e  d  a  87.30152
# 4  a  b  a  b  e 251.46679

Comment: Row wise operations tend to be slow. I would try transposing and changing the loop indices accordingly
Comment: This works but unfortunately does not scale well with very large datasets. Do you know if there is a way to modify this for speedup? I noticed that `a --> b` is looked up several times. Is there a way to only look it up once and fill in the matrix accordingly?


Whilst using EntityFramework 6.1.1 Task Extensions 'ToArrayAsync' the await never returns

Question: I have been writing a WebApi service which is async top down and have discovered an odd behavior with one of my entity framework queries. We are using Entity Framework 6.1.1 and the query itself is relatively straightforward:
var companyRoles = await model.Memberships.Include(m => m.Role)
            .Where(m => m.UserProfileId == guid).Select(cr => new { Membership = cr, cr.Role }).ToArrayAsync();

... rest of the method excluded for brevity

Naturally this call is encapsulated in an async Task with an enumerable return type. At the time that the query is executed, we can see the call being made using SQL Profiler (and when captured and executed in isolation returns the expected result), however the ToArrayAsync() materialization in code never returns. We can leave this hanging for several minutes with no discernible error or information.
Contxt: this method itself is called within an async WebApi controller method and it appears that if we remove the async part of the nested method call this query executes and returns fine.
In the above part of the api there is no other database processing, this is the only thread running in the system (this is on my local development machine) and is also consistent in its behaviour.
I've tried removing the 'Select' materialization from the above query and it still fails so it isn't that. Has anyone seen this behavior before? It seems very much related to the async keyword but I get no exceptions or clues. Any suggestions very welcome! SQL Server 2014, VS2013 Update 3, High-End PC (i7). It really looks like a deadlock in its appearance, but I can't see what it would be being deadlocked with!
Any help would be greatly appreciated.
Comment: What does the overall stack of async calls look like, from the top-level application entry point to this EF method?  It's possible that you're deadlocking the synchronization context somewhere along the way.
Comment: Also, be sure to check the value of `httpRuntime.targetFramework` in your web.config; it should be `4.5`.
Comment: httpRuntime.targetFramework definitely set at 4.5 but definitely worth checking thanks.
Answer: Probably you have used await operator outside DbContext using scope.
I had a following method:
    public Task<Entity[]> GetAsync()
    {
        using (var context = new DataContext())
        {
            return context.Entities.Where(e => e.Status == Status.Pending).ToArrayAsync();
        }
    }

I was awaiting for it like this:
await GetAsync()

and this line never returns. Then I've changed the implementation and put await operator inside using(context) scope:
    public async Task<Entity[]> GetAsync()
    {
        using (var context = new DataContext())
        {
            Entity[] es = await context.Entities.Where(e => e.Status == Status.Pending).ToArrayAsync();
            return es;
        }
    }

That solved this issue for me.
Comment: This is a good answer to a different question, but probably not to this question: the OP does correctly use `await`. The question shows what the code looks like: `var companyRoles = await [...].ToArrayAsync();`.
Answer: Since there is no solution to this post then I want to write that I had same problem and got it to work using ToListAsync()
I also had this issue with nested queries and had to make it as two queries.


Como adicionar mais um campo de formulário no wordpress?

Question: Na parte de "adicionar novo" no wordpress tem apenas dois campos de formulário, eu preciso colocar mais, mas é possível fazer isto criando um plugin ?
Comment: Presumo que já esteja usando algum plugin para criar o form, se sim, qual plugin já esta usando?
Comment: Nenhum, só quero criar um plugin para aumentar o formulário do wordpress de cadastro de postagem.
Comment: Entendi, fala do formulário do "Meta" para postagens. Mas que tipos de campos adicionais você gostaria de adicionar?
Comment: um
Answer: Existem 2 plugins relativamente populares para este uso:
Advanced Custom Fields
O plugin Advanced Custom Fields suporta os campos seguintes formatos:
Text, Text Area, Number, Email, Password, WYSIWYG, Image, File, Select, Checkbox, Radio Buttons, True / False, Page Link, Post Object, Relationship, Taxonomy, User, Google Maps, Date Picker, Color Picker, Tab, Message e Customizado por você.

Download

PODS

Download

Nota 1: Esta resposta esta em edição, estou traduzindo os textos
Nota 2: Existe mais plugins para isto, mas uns eram pagos e outros eu não consegui ter certeza do funcionamento, irei editar a resposta conforme puder testar estes outros plugins


Quando usar ANSI e quando usar UTF-8?

Question: É mais vantajoso utilizar um tipo ANSI ao invés de um tipo UTF-8 ou vice-versa? Existe algum ganho em performance ou armazenamento entre os tipos?
Comment: Nem acho que minha resposta seja tão boa, só evitei ser tendencioso como a resposta dada na pergunta que você citou que no fim nem respondeu a pergunta de verdade. http://pt.stackoverflow.com/a/28404/101
Comment: Excelente pergunta, muito mais objetiva que a semi-duplicata que pergunta o porquê de ainda se usar outras coisas, como se UTF-8 fosse solução para tudo. E excelente resposta do @bigown, baseada em fatos, e não em vôo cego (as tais boas práticas).
Comment: Só para fazer o registro: Converti uma tabela do Excel para arquivo TXT com os campos separados por TABS. No arquivo txt os caracteres acentuados apareciam corretamente. Mas quando converti os dados para uma tabela do MySQL (UTF-8) os caracteres acentuados saíram todos bagunçados. Descobri que o arquivo TXT estava definido como UTF-8. Salvei-o, então, como ANSI, joguei no MySQL de novo e os caracteres acentuados apareceram corretamente. Eis ai um exemplo de como o ANSI resolveu o problema.
Answer: TL;DR

UTF-8 é um esquema largamente utilizado ao passo que ANSI é praticamente obsoleto.
ANSI usa um único byte ao passo que UTF-8 usa uma codificação multibyte.
UTF-8 pode representar uma gama de caracteres muito maior que o bastante limitado ANSI.
Pontos de código UTF-8 são uniformemente padronizados enquanto que o ANSI possui muitas diferentes versões.

Diferença entre ANSI e UTF-8
ANSI e UTF-8 são dois esquemas de codificação de caracteres largamente utilizados em um momento ou outro.
A principal diferença entre eles é que UTF-8 foi criado para ser mais ou menos equivalente ao ANSI mas sem todas as muitas desvantagens que este tinha. Ambos os esquemas expandem o conjunto básico de caracteres ASCII, o que significa que até os 127 caracteres iniciais, eles são basicamente equivalentes.
A primeira desvantagem do ANSI é o uso de bytes fixos para representar os caracteres. Em comparação, UTF-8 é mais flexível por ser um esquema de codificação multibyte.
Dependendo das necessidades do usuário, qualquer ponto de código entre 1 e 6 bytes podem ser usados para representar um caracteres. Porque o ANSI usa apenas um byte (ou 8 bits), ele só consegue representar um máximo de 256 caracteres, o que não chega nem perto dos 1.112.064 de caracteres, códigos de controle e slots reservados que o formato Unicode pode representar com o esquema UTF-8.
Usando codificação multibyte torna possível acomodar todos esses pontos de código e ainda assim consumir o mínimo de memória. O primeiro byte do UTF-8 casa exatamente com o ASCII e, por conta disso, os caracteres mais comuns requerem apenas um byte.
Para acomodar mais caracteres, haviam múltiplas páginas ANSI criadas para diferentes idiomas. Você não podia, portanto, usar certos caracteres uma vez que eles não pertenciam às mesmas páginas de codificação.
Isso também requeria ao programa saber de antemão qual página seria usada ou caracteres incorretos apareceriam.
UTF-8 não tem nenhum desses problemas uma vez que possui seu próprio ponto de código.
UTF-8 é superior ao ANSI de todas as maneiras. Não existe motivo para se preferir ANSI ao invés de UTF-8 ao criar aplicações as quais possam ser decodificadas por todos os computadores. A única razão plausível seria a execução de um aplicativo antigo o qual você não tenha um substituto viável para ele.
Fonte: Difference Between
Tradução: Eu, eu mesmo, e nada da Irene :p
Answer:
Quando usar ANSI e quanto usar UTF-8?

Estritamente falando quando você usa UTF-8 está adotando o set de caracteres ANSI. Mas eu acho que você está usando o termo ANSI erroneamente. Não é culpa sua, há muitos anos o termo está sendo usado de forma errada. Provavelmente você está querendo comparar UTF-8 e ISO-8859-1/Latin 1 (que costuma ser confundido com CP1252/Windows-1252 que é outro encoding/charset que serve o mesmo propósito e que tem características essencialmente idênticas).
O primeiro critério para escolher um ou outro é verificar com quem você vai trocar estes dados. Não adianta nada pensar em qual é melhor quando ele é incompatível com a atividade que ele será usado. Determine o requisito da compatibilidade com que será intercambiado e não se preocupe com mais nada. Se você não tem problemas de compatibilidade com nada, use o mais simples.
Se você tem total controle de como será feito o intercâmbio ou tem liberdade de escolha, para evitar conversões procure escolher a forma que as tecnologias usadas por você preferem. Se ainda isso é escolha sua aí vamos analisar outros pontos.

É mais vantajoso utilizar um tipo ANSI ao invés de um tipo UTF-8 ou vice-versa?

Vou começar discordando da resposta do Bruno quando diz que o "ANSI" está praticamente obsoleto. Ainda há muitos casos que ele não só pode ser usado, como é obrigatório. É claro que há uma onda de preferência pelo UTF-8. Isto é inegável. Mas ambos são ferramentas úteis e serão utilizados por muito tempo.
Não há dúvidas que o UTF-8 é mais moderno, mais flexível, mais completo, mais confiável na maioria dos casos e mais popular, mas fica a questão se tudo isto é necessário. A maior vantagem do "ANSI" é a sua simplicidade para a maioria dos casos.
O "ANSI" ainda tem as vantagens de performance e armazenamento discutidas abaixo.
A maior vantagem do UTF-8 é a universalidade (que é relativa, não quer dizer que realmente serve para tudo, serve para todos os caracteres) e isto tem um significado ainda maior conforme ele vai ficando mais popular. Essa universalidade se dá pelo fato de permitir vários bytes para representar 1 caractere, ao mesmo que tempo que isto acaba sendo a sua principal desvantagem, o causador da maioria das dificuldades do encoding. Com mais bytes pode-se representar uma quantidade muito grande caracteres sem recorrer a artifícios. E a flexibilidade permite que o espaço ocupado não seja tão grande apesar de acabar consumindo mais processamento para processar a maioria dos algoritmos.
Mas além de ter uma implementação pesada, muitas vezes com defeitos de tão complexo que é, por definição existe a possibilidade de ambiguidades de formas para representar o mesmo caractere, que causa problemas em comparações (o que você vê não é o que está representado na string) e uma string pode se tornar inválida em casos de perda de parte da informação com truncamento. Não vou nem dizer que usar UTF-8 é extremamente complexo e pouquíssimos programadores sabem usá-lo corretamente. Tudo bem que não precisa entender tudo para o caso que garantidamente usará apenas o simples, mas aí o UTF-8 não é tão vantajoso assim. Curiosamente os povos que mais se beneficiaram com ele são os que mais reclamam dele.
Um dos problemas citados é a confusão em comprimento em bytes da string e o comprimento em caracteres (ou code points como são realmente chamados). A maioria dos programadores não sabe bem o que a função/método Length de uma string retorna. De fato isso pode variar de acordo com a tecnologia usada.
Há outros problemas citados em Por que ainda se usam outras codificações além do UTF-8?.
É possível abstrair o tratamento de codepages do "ANSI" se for necessário. Na imensa maioria das vezes elas não são necessárias, mas se for dá para criar uma estrutura de dados que encapsule e abstraia esse tratamento de forma transparente para o usuário da string. Claro que não é perfeito, não resolve todos os problemas mas resolve um dos problemas citados. Mas o UTF-8 também não resolve todos os problemas. Por que ninguém fez isto (pelo menos nada público e bem conhecido)? Porque não é uma necessidade real na maioria dos casos.
Por fim, de qual versão do UTF-8 estamos falando? É, ele tem versões. Tem retrocompatibilidade entre elas, mas se você tentar pegar algo gerado com uma versão mais nova usando um recurso novo e manipular com uma implementação antiga, terá dificuldades.

Existe algum ganho em performance ou armazenamento entre os tipos?

Certamente o "ANSI" é mais rápido e ocupa menos espaço que o UTF-8. Em casos específicos onde somente caracteres da tabela ASCII (até 127) sejam usados o UTF-8 pode ocupar o mesmo espaço.
Há a garantia que o "ANSI" ocupa 1 byte, o UTF-8 não. Fica claro que o UTF-8 não só a ocupação de espaço é maior mas o tempo para processar também. Quando você pode garantir o tamanho em bytes dos caracteres dá para ser mais eficiente. É possível ter alguns algoritmos mais ou menos eficientes com UTF-8 mas a necessidade de tratar tamanhos diferentes gera um custo adicional. Não existe milagre. Podemos dizer, a grosso modo, que "ANSI" é um array e UTF-8 é uma lista ligada diretamente em sequência. Não há como chegar em um caractere em UTF-8 sem passar por outros caracteres. Mesmo o caractere individual exige uma verificação para saber se há um complemento para ele, possivelmente através de um branch no processador, que é bem caro.
É indiscutível qual ganha em performance. Dá para discutir se ela é importante. A diferença não costuma ser tão grande e outros fatores podem tornar a diferença ainda mais irrisória. Mas também há problemas que requerem a performance extrema.
O espaço ocupado é maior com UTF-8 mas a diferença não costuma ser tão grande (e se for, provavelmente você não tem muita escolha, o que é altamente improvável no mundo ocidental). Mas se existir alguma razão real que o tamanho seja importante, opte pelo "ANSI".
Basicamente a diferença acontecerá nos caracteres acentuados. No "ANSI" o caractere sempre ocupará 1 byte e no UTF-8 ocupará 2 bytes. Não vou comparar nada além dos acentos porque o "ANSI" não conseguirá manipular. Estamos falando de situações onde você tem escolha. Para conhecer a tabela de acentos permitidos, veja na Wikipedia. Note que os caracteres sem acento, ou seja, constantes da tabela ASCII, o UTF-8 ocupará apenas 1 byte. A maioria dos caracteres usados não possuem acento.
O que talvez possa complicar na decisão é o tamanho variável. Existem formatos de arquivos que exigem um tamanho fixo dos campos/linhas. Mas neste caso provavelmente também há o requisito para o encoding e/ou charset.
Conclusão
Lembre-se que o assunto é extremamente complexo, para falar tudo que seria necessário daria um livro inteiro (sem exagero).
Particularmente eu procuro usar o ISO-8859-1 em tudo o que eu faço onde tenho liberdade total. Ele é mais simples, mais fácil, mais eficiente e resolve todos os problemas que eu tenho nos softwares que eu faço. Infelizmente por um motivo ou outro acabo sendo forçado a usar o UTF-8 ou mesmo UTF-16 (este não para arquivos a não ser que realmente seja necessário) em algumas situações. Nenhum grande problema, já foi demonstrado que há vantagens nele também.
Coloquei no GitHub para referência futura.

Quando usar ANSI e quando usar UTF-8?


expected value of fisher distribution

Question: I know that the pdf of an F-distribution is $f_{k,m}(t) = \Gamma(t)=\frac{\Gamma((k+m)/2)}{\Gamma (k/2)\Gamma(m/2)}k^{k/2}m^{m/2}t^{k/2 - 1}(m+kt)^{-(k+m)/2}$
Also, $E(F)=\int xf_{k,m}dx$.
How do you evaluate this integral? Say you have to convert $x*f(k,m)$ to $C * f(k',m')$ where $f(k',m')$ is a pdf itself, which leaves $E(F)=C$ (which I know to be $\frac{m}{m-2}$).
How do I do this? Or can I do it another way? Can somebody please help?
Answer:
Definition. Let $X \sim \chi^2_{k}$ and $Y \sim \chi^2_{m}$ be independent. Then
      $$F = \dfrac{X/k}{Y/m}$$
      follows the $F$-distribution with $(k, m)$ degrees of freedom.

It follows that
$$\mathbb{E}[F] = \dfrac{m}{k}\mathbb{E}\left[\dfrac{X}{Y}\right] = \dfrac{m}{k}\mathbb{E}[X]\mathbb{E}\left[\dfrac{1}{Y}\right]=m\mathbb{E}\left[\dfrac{1}{Y}\right]$$
since $\mathbb{E}[X] = k$. Now use this and this.
Comment: Can you be clearer? The link shows $E(X^k)$. How can I apply? $E(Y^{-1})$?
Comment: @user3886450 $Y$ is $\chi^2$, and the hypothesis of the first link is that $X$ is $\chi^2$. So you can use the same result. I'm not sure how else to explain this.
Comment: @user3886450 I'm assuming you downvoted this. The second link *literally* solves it for you.

expected value of fisher distribution


Canonic form of a quadric

Question: I have a question, how can determine the canonic form of the quadric associated to $F$, where $F$ is a bilinear form $\Bbb R^3\times\Bbb R^3\to\Bbb R $ that its associated matrice is
$A=\left(\begin{matrix}0&0&-1\\
0&-1&0\\
-1&0&0\\
\end{matrix}\right)$?
Another question, what is the base of $\Bbb R^3$ in whic the quadric is in canonic form?
Answer: Find an orthonormal basis $(v_1,v_2,v_3)$ of $\mathbb{R}^3$ such that each $v_k$ is an eigenvector of $A$. If the correcponding eigenvalues are $\lambda_1$, $\lambda_2$, and $\lambda_3$, then the canonical form will be $$(X_1,X_2,X_3)\mapsto\lambda_1{X_1}^2+\lambda_2{X_2}^2+\lambda_3{X_3}^2.$$
Answer: The quadratic form associated to $F$ is $x^TAx$ and since $A$ is symmetric by spectral theorem $A$ can be diagonalized by a basis of orthogonal eigenvectors $v_1,v_2,v_3$ that is
$$M=[v_1\,v_2\,v_3] \implies x=My\quad M^{-1}=M^T$$
and then
$x^TAx=(My)^TA(My)=y^TM^TAMy=y^T(M^{-1}AM)y=y^TDy=\lambda_1y_1^2+\lambda_2y_2^2+\lambda_3y_3^2$
which is the canonical form.
Comment: It's difficult find eigenvectoe with this matrix
Comment: @RobertoDeLaFuente We don't need eigenvectros but only the eigenvalues. I wrote the full derivation to explain why it works!
Comment: Yeah but I need so the basis whic tue basis is in canonic form. What vectors form this basis? I think the eigenvectors! But are difficoult to calculate
Comment: @RobertoDeLaFuente Ah ok you need also that! They are not difficult to find out by $(A-\lambda I)x=0$.
Comment: @RobertoDeLaFuente You can also use that, but it should be useful to try to obtain the result by hands.
Comment: Try to do! Look: I have $-\lamba^2(\lamba-1)$
Comment: @RobertoDeLaFuente Take a look here http://www.wolframalpha.com/input/?i=%7B%7B0,0,-1%7D,%7B0,-1,0%7D,%7B-1,0,0%7D%7D
Comment: @RobertoDeLaFuente Actually, it's quite easy to find eigenvectors for this matrix by inspection: $(0,1,0)^T$ is obviously one, as is $(1,0,1)^T$. A third one can also be found by inspection, but since the matrix is symmetric, you can also generate one by finding a non-zero vector orthogonal to the first two.
Comment: I love you!!!!!
Comment: last thing.
Are u sure that $M^{-1} = M^T$?
Comment: Yes since we can find orthogonal eigenvectors!

Canonic form of a quadric


Get all the file names from supporting folder

Question: I would like to read the the names of the subfolders inside a folder, which I have placed in the supporting files. Does anybody know how to do this, or have a better idea. I just need to have a folder, where i can put subfolder, which will contain three files each and the get the names of those subfolders?
Answer: See the documentation for [NSFileManager enumeratorAtPath:].
In there you'll see sample code that shows how to list the contents of a particular folder.  You can see if it's a folder via [NSFileManager fileExistsAtPath: isDirectory:] and if it's a directory, you can add that to an array or list or whatever you're using to keep track of the subfolders & their names.


Tracking multiple objects in iOS 13

Question: my app uses the example code by Apple to track multiple objects of a video using Vision (in my case, it tracks the path of a barbell during weightlifting exercises), but after updating to iOS 13 the video is not displayed properly. Instead of filling the screen like it used to do, now the video is cropped and you can only see a small portion of it. I've talked to Apple Technical support and they acknowledge the bug, but a fix is not in their plans.
What bugs me the most is that a) landscape videos are working, but not portrait videos and b) the bug only happens in real devices and not in the simulator. See attached the portion of the code used to display the video depending on its proportions (landscape or portrait).
private func scaleImage(to viewSize: CGSize) -> UIImage? {
    guard self.image != nil && self.image.size != CGSize.zero else {
        return nil
    }

    self.imageAreaRect = CGRect.zero

    // There are two possible cases to fully fit self.image into the the ImageTrackingView area:
    // Option 1) image.width = view.width ==> image.height <= view.height
    // Option 2) image.height = view.height ==> image.width <= view.width
    let imageAspectRatio = self.image.size.width / self.image.size.height

    // Check if we're in Option 1) case and initialize self.imageAreaRect accordingly
    let imageSizeOption1 = CGSize(width: viewSize.width, height: floor(viewSize.width / imageAspectRatio))
    if imageSizeOption1.height <= viewSize.height {

        print("Landscape. View size: \(viewSize)")
        let imageX: CGFloat = 0
        let imageY = floor((viewSize.height - imageSizeOption1.height) / 2.0)
        self.imageAreaRect = CGRect(x: imageX,
                                    y: imageY,
                                    width: imageSizeOption1.width,
                                    height: imageSizeOption1.height)

    }

    if self.imageAreaRect == CGRect.zero {
        // Check if we're in Option 2) case if Option 1) didn't work out and initialize imageAreaRect accordingly

        print("portrait. View size: \(viewSize)")
        let imageSizeOption2 = CGSize(width: floor(viewSize.height * imageAspectRatio), height: viewSize.height)
        if imageSizeOption2.width <= viewSize.width {

            let imageX = floor((viewSize.width - imageSizeOption2.width) / 2.0)
            let imageY: CGFloat = 0
            self.imageAreaRect = CGRect(x: imageX,
                                        y: imageY,
                                        width: imageSizeOption2.width,
                                        height: imageSizeOption2.height)

        }
    }

    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(self.imageAreaRect.size, false, 0.0)
    self.image.draw(in: CGRect(x: 0.0, y: 0.0, width: self.imageAreaRect.size.width, height: self.imageAreaRect.size.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

Any help would be very appreciated.
Thanks
Comment: As a side note, I found that the Object tracking feature in iOS 13 is almost broken... it barely works. For a feature I've implemented in iOS 12 I was getting tracking confidence of 0.8-0.99 constantly, where on iOS 13 the confidence never goes above 0.15.
Comment: Thanks for your feedback Andy. I didn't experience that issue: my app basically tracks everything as it used to do. If you are using Apple's sample code as I do, have you tried the workaround I provided in my self-answer?
Answer: after several weeks stalking Apple Technical Support, they came out with a very simple workaround. Basically, you just need to do a conversion via CGImage instead of going directly from CIImage to UIImage.
This is the old code (as you can see in current example in Apple's documentation)
 if let frame = frame {
            let ciImage = CIImage(cvPixelBuffer: frame).transformed(by: transform)
            let uiImage = UIImage(ciImage: ciImage)
            self.trackingView.image = uiImage
        }

And this is the correction
if let frame = frame {
            let ciImage = CIImage(cvPixelBuffer: frame).transformed(by: transform)
            guard let cgImage = CIContext.init().createCGImage(ciImage, from: ciImage.extent) else {
                return
            }
            let uiImage = UIImage(cgImage: cgImage)
            self.trackingView.image = uiImage
        }

Hope this helps!

Tracking multiple objects in iOS 13


How to run vc++ .exe file where MS Visual Studio is not installed?

Question: I developed one application in vc++(console) in Visual Studio 2008 . Now, how can I run its .exe where Visual Studio is not installed? Thank you.
Answer: You need something like the VC++ 2008 redistributable package - http://www.microsoft.com/downloads/details.aspx?familyid=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en
Just ship the package as part of your application installation and deploy it on the target machines.
Comment: @Kishor Kurmar: "it is not working" doesn't provide any useful info. Explain what happens, them people may be able to help you.
Comment: Hi Lingvomir...thanks for reply but it is not working even after installing the redistributable package and .net frame work.
Comment: Is it a release build? The redistributable package only installs the release version libraries. You can't run a debug build this way.
Answer: The whole point of Visual Studio is to create standalone programs.  As long as the machine you'll run the app on all the DLLs and such that the app requires (and has a compatible .net Framework version installed, if you created a C++/CLI app), the exe file should run just fine.
You should be able to just copy the contents of the output directory (where the .exe is) onto another machine and run it.  You may want to look into creating a setup project / installer, though, if you intend for lots of people to use it.
Comment: Hi Chao...thanks for reply but even after installing .net framework its not opening the console(.exe) application.
Comment: @Kishor Kumar: Define "it's not opening the...application".  Unless you get an error, it ran; it may just not have shown anything.  If you get an error, what is it?


Invalid Security Certificate in Exchange

Question: I get ths error message appears whenever anyone on our system opens outlook:

I know very little about our Exchange server but was told that it was once configured differently and from what I've read it is a matter of going into the exchange shell and remove our exchange server from issuing the certificate but I am weary of changing anything on the system that I am unfamiliar with.  I wanted to get some experts eyes on this and see if this indeed seemed to be the proper solution.  Thank you in advance.
Comment: If you post a link to the image, I'll be more than happy to edit your question to include the image. Upload it to somewhere public like imgur.
Comment: http://img228.imageshack.us/img228/5679/unledzi.jpg
Comment: Can you provide the details of the certificate and the details of the production domain in question?
Answer: The certificate issued to Exchange does not have a SN or SAN that matches the FQDN the Outlook client is configured for. Your outlook clients are configured for mail.companyname.com, and your certificate is issued for something different (eg exchange.companyname.com, which obviously doesn't match).
You need one of two things:

The certificate on the Exchange server needs to be reissued and installed to match what the Outlook clients are configured to connect.
The Outlook clients need to be configured for what the Certificate says, which might also entail configuring DNS and/or Exchange to respond to this name as well (depends on what has already been done). Configuring the Outlook clients might also be done through Exchange, depends on what version you're running and how Exchange was setup.

Some of these are easier than others, and much of that depends on what version of Exchange and Outlook you are running as well as where you're getting your certificates from.
Comment: That description helps a lot.  I will look into updating the certificate on the server.  Thank you so much!


Yamaha SY99 floppy disk drive broken. Can I use something else?

Question: The floppy disk drive on my Yamaha SY99 has been broken for over a decade.
As a result I am unable to save anything I do (new sounds or new music) and, once I turn the synth off, the data is gone. Nobody uses floppy disks anymore, anyway.
I have seen kits being sold online to replace the floppy disk drive unit with a USB drive, such as this one or this one but I am concerned replacing it is not a straightforward job. I'm not sure about the reliability of the product either.
Is there a workaround, such as connecting the synth to a PC (e.g. via MIDI cables) with some software that can bridge the gap and let me save/load data, or is purchasing the USB drive kit my only hope?
Comment: More unreliable than a floppy? ;-)
Comment: Of course you could replace the floppy disk drive, but the midi solution (s. my answer) is much more comfortable.
Comment: @AlbrechtHügli I could, then the other problem is, I don't believe anybody even makes floppy disks anymore, let alone the 720k ones, which were the ones used by the SY99. Quite a few of the old ones with all my data on aren't even readable by a PC anymore.
Comment: Transferring stuff back and forth over MIDI, vs. using a USB stick or memory card like a hard drive in the machine itself ... why do you even consider the PC+MIDI option? People have been replacing floppy drives in industrial machines and old computers with Gotek and HxC etc for a long time, it should be pretty straight-forward. Have someone do it for you if you're afraid of opening the case. :)
Comment: @piiperiReinstateMonica as I said above, it's about concern that the product is unreliable also.
Comment: @Vance What sort of reliability issues do you mean? Do you have any links to descriptions? Which products have you been looking at? IMO, transferring stuff back and forth over MIDI just to be able to save and load is a horrible workflow. And if you could have a solid-state hard drive on the device, the MIDI option feels particularly bad. Though I don't know how long the data dumps take in this case. If it's fast and if you have a proper librarian application that can initiate the dump with one click, then it might be OK.
Comment: @piiperiReinstateMonica I have edited the question and added a couple of links. Since these products are not manufactured by Yamaha I am concerned they won't be 100% compatible. Anyway, given the feedback received I think the most effective way to go about this is to try with the cable and the software first. If that does not work go with one of these products.
Answer: Correction: MIDI was never designed initially to transmit sample data, but it was added later as an SDS standard. [This is something I've never worked with, but apparently the SY99 can sample dump over MIDI.]
http://www.4front-tech.com/pguide/midi/midi8.html
If you go that route, maybe something like this SY manager would be useful - http://www.fm-alive.com/pages/SYM.aspx
Otherwise, if you go with the USB kit, I'd ask the kit maker for their instruction sheet/pdf to see what kind of a task it would be.
Note: I've never taken this precise model apart, so this is a generic answer.
Most Yamaha keyboards, certainly of that age, are pretty simple to strip, so long as you've got long screwdrivers [they do tend to put screws in long barrels] I'd recommend an electric driver with long bits, as they never were tempted to put too few screws in anything ;) The casing is unlikely to also be clipped together, it will probably be screws only.
Generally, you're unlikely to find odd springs that suddenly leap out at you, everything will be set pretty tidily within the case.
I'd imagine, if the kit makers did their job right, that the drive swap will be relatively simple, once you've got the 473 screws out.
Edit:
I found a service manual at https://www.manualslib.com/manual/998630/Yamaha-Sy99.html?page=15#manual - you're lucky, a mere 24 screws holding the bottom casing on ;-)

BTW, a quick Google shows lots of these things on Amazon for $150 or so, but according to https://yamahamusicians.com/forum/viewtopic.php?t=7440 there's one you can get for about 35.
eg https://www.amazon.co.uk/Gotek-SFRM72-FU-DL-Floppy-Emulator-Electronic/dp/B01B1G51P0
Comment: Thx for the extensive reply and your comments about quality cables, if that does not work I'll look into this as well.
Answer:
Is there a workaround, such as connecting the synth to a PC (e.g. via MIDI cables) with some software that can bridge the gap and let me save/load data?

Yes. You can save your patches and settings by a midi-cable (midi-in-> USB) on your pc or laptop, e.g. Roland USB - midi interface exchange UM-ONE.

https://www.roland.com/global/products/um-one/
With a free midi software you can also save your entire songs inclusive your settings on your PC.
Edit:
Here's another solution:
Solution with borrowed floppy drive This person had a similar problem. And he was able to copy the Sys-ex data by a borrowed floppy drive. Btw. Diskettes you can still get easily secondhand (e.g. I have hundreds unused, but not thrown away!)
Comment: Maybe so. tbh, it's been over 20 years since I last messed with MIDI data in earnest. I used to work with the head of the entire Yamaha software division.. the guy who wrote [or oversaw] all the in-house editors etc. His chops were significantly better than mine ;)
Comment: Maybe this tool could help:

https://yamahamusicians.com/forum/viewtopic.php?t=6823
Comment: Be careful with those cables. Some of the cheaper ones (especially a very popular one that comes up if you search for a USB MIDI cable on Amazon and is sold under a few different brands) mangle SysEx data (which doesn't matter in most cases but is very important here). Personally if you don't need the extra functionality that MIDI offers I'd go with the option of replacing the floppy disk drive.
Comment: The cheap ones can barely transmit notes, let alone SysEx data. Get one from a known Instrument manufacturer, Roland, Yamaha, Emu, Korg etc. They are guaranteed to be good.
Comment: @Vance Not exactly. It's not like a cheap USB cable. Without getting too technical, USB ports cannot understand MIDI information and MIDI ports cannot understand USB, so a "MIDI to USB" cable has to contain a microchip inside (usually hidden in one of the connectors or in a "box" in the middle of the cable) that "converts" the information from one format to the other.
Comment: @Vance There's only one "correct" way to convert the information and the more expensive cables do it correctly but there's a chinese company that makes a converter chip that's used in a lot of cheaper cables that does it in an incorrect way that works fine for note/music data (keys pressed or released, which is what MIDI is typically used for) but not SysEx data (which is what you need to be able to save and load synth data over MIDI).
Comment: The SY99 is a RAMpler. SysEx will not transmit the sample data.
Comment: Are you sure? http://bobbyblues.recup.ch/sysex_procedure.html ....or
https://yamahamusicians.com/forum/viewtopic.php?t=3349
Comment: OK, the 99 can do a specific sample dump, just not as part of the voice sysex.
Comment: @AlbrechtHügli do you have one or two examples of any such free MIDI software I could use?
Comment: @MichealJohnson I'll keep that in mind. So cheaper cables compromise data transfer, but higher quality ones do not?
Answer: Adding to the excellent previous answers, a different alternative is to try to repair the floppy drive. The problem with floppies, most of the time is with the rubber belt from the motor drive to the disk's rotation axle. As the rubber ages it loses flexibility and gets slack or even broken. Same problem as with old cassette tape decks, vinyl players and even CD players.
If that is indeed the problem, repairing is a straightforward business. There are businesses in Ebay that sell rubber belts to all types of machines. A quick search on ebay returned, for example, this one.
If you're able to open the machine, replacing the belt is a matter of patience and handyness, but not very difficult.
I've done that operation myself a few years ago, only to find the the original belt did not even appear to be damaged, it was just out of place. I replaced it anyway, since I had ordered a new belt and there's no telling when the rubber in the old one would start to crackle. But if you have the patience you may even try to open the machine and see what is happening with the drive before even spending any money.
Comment: That would be a viable option only if 720k floppy disks were still widely available as a storage device which, unfortunately, they are not.
Comment: The OP's issue was with the unit not working, not lack of supllies. Anyway, you're, floppies are quite  hard to come by these days. I was lucky enough a couple of years ago to have a friend who was scrapping his old accounting archive which was still in floppies, believe it or not.