Object.ReferenceEquals never hit

Question: Can anyone tell me why the following condition does not hit?
List<DateTime> timestamps = new List<DateTime>();
timestamps.Add(DateTime.Parse("8/5/2011 4:34:43 AM"));
timestamps.Add(DateTime.Parse("8/5/2011 4:35:43 AM"));
foreach(DateTime x in timestamps)
{
    if (Object.ReferenceEquals(x, timestamps.First()))
    {
        // Never hit
        Console.WriteLine("hello");
    }
}

Comment: Can you explain why you'd expect two values of a **value** type to be **reference** equal?
Comment: Well hold on a minute. If your intention was to *skip the first element*, then why did you write this code at all? Just write `foreach(DateTime x in timestamps.Skip(1))` and be done with it. *After you fix the equality comparison you will be skipping every element in the list that is equal to the first element, not just skipping the first element.*
Comment: My intention was to skip the first element in the list but didn't realize DateTime was a value type. Thanks for everyone's help!
Comment: Yes you are absolutely right, but by the time I wrote this I just wanna try it out in a different way and thought DateTime was a reference object, and thus used Object.ReferenceEquals instead of == or Equals().
Comment: While it would have worked with reference types (assuming that there could either be no aliases of the same object, or that skipping it would be desired), but would still have been less efficient than the more obvious approaches of `Skip(1)` or indexing starting with index 1.
Comment: Even this returns false: `int i=1;object.ReferenceEquals(i, i);`Here's an article that explains better why `Object.ReferenceEquals` always returns `false` on value types like structs: http://blogs.msdn.com/b/vijaysk/archive/2008/03/19/object-referenceequals-valuevar-valuevar-will-always-return-false.aspx
Answer: Because DateTime is a value type, immutable and so the references will not be equal even though the values are.
Are you meaning to do something like this? Value comparison:
if (DateTime.Compare(x, timestamps.First()) == 0)
{
    // Never hit
    Console.WriteLine("hello");
}

Comment: Immutability is about whether or not a value can change, not about how it is copied, what list.First() is doing, etc. The fact that the value is being copied here says nothing about whether `DateTime` itself is immutable or not. You *could* make a mutable value type, stuff a handful of them into a list, pass that list through the logic in the question, and experience the same failure *because* of everything else you say in your answer. Would you agree?
Comment: @PaulSasik not in the slightest. Strings are immutable, and can be reference equals. Two mutable value types, or the same one boxed two times, cannot be reference equals. Immutability is completely orthogonal to reference identity.
Comment: That's not the way we typically think of immutability in relation to types, but OK. Unrelated to the answer, can you explain why you think even reference types wouldn't evaluate to true in the given snippet, as per your comment? You would agree that for a list of `class Foo`, the first foo in the foreach would be referentially equal to foos.First(), correct?
Comment: So if you had a mutable value type, the references would be equal?
Comment: The question was rhetorical. You mentioned immutability. The point is that even for mutable value types (those evil things), reference equality would not be met.
Comment: @AnthonyPegram: Right, I mentioned immutability because you always get a copy of the value rather than a shallow, reference copy.
Comment: Immutability does actually play a role here: The collection is of value types and when the extension method First is called, it returns a copy of a new value object. That's the reason that even though you seemingly compare an array element to itself, you're not because the returned value is a new copy. Reference values would actually evaluate to true on the reference comparison on the first item comparison, but not subsequently.
Comment: Yes, I agree. The logic in the OP initially confused one of my comments, which I've since removed. Reference types would actually evaluate to true due to the logic but the fact that the condition in the original snippet is never satisfied is because of the immutable nature of the data type being evaluated.
Answer: Value types are passed and compared by value. That's why they're called "value types".
Reference types are passed and compared by reference. That's why they're called "reference types".
DateTime is a value type.
Therefore you are attempting to compare two values by reference. That's not going to work. It will always be false.
Can you explain why you'd expect something different?
Comment: Eric the most likely explanation for someone expecting that sample to return true is that person not knowing the types they are working with are value types.
Comment: Interestingly, does `Object.ReferenceEquals` on two value types then compare the references to the boxes for equality? Is there a useful reason to do that?
Comment: @JamesDunne it would, so `object x = default(DateTime); object y = x; return ReferenceEquals(x, y);` returns true. Not much of a useful reason to do that most of the time though.
Comment: @JamesDunne: Does it compare references of the boxes? Yes. Is that useful? No.
Comment: If the list was an `ArrayList`, and the foreach used `object` as the type, than this would have actually worked. Obviously this makes perfect sense, but it is quite surprising.
Answer: I think that a number of the other answers miss something.
In the case of object.ReferenceEquals(object,object) any value-types are "boxed" to objects and it is these (new) objects which are passed. Consider the following:
DateTime d1 = DateTime.MinValue;
DateTime d2 = d1;
object ob1 = (object)d1; // boxed!
object ob2 = ob1;

// false - the values in d1 and d2 are BOXED to (new) different objects
object.ReferenceEquals(d1, d2);
// false - same as above, although I am not sure sure if a
//         VM implementation could re-use a BOXED object
object.ReferenceEquals(d1, d1);
// true - naturally - BOXED only once at "boxed!" (same object!)
object.ReferenceEquals(ob1, ob2);

Happy coding.

Related: Marc's answer in Value Type Vs Reference Type - Object Class C# where he talks about a boxing conversion.
Answer: They have the same value, but they aren't the same reference.
Take a look at the MSDN entry for Object.ReferenceEquals
Furthermore, even if you had been comparing the same object, you would still not hit it by comparing the references, because DateTime is a structure, that is, it is value type. Value Types, by definition, copy the contained value, not the reference to the object (like Reference Types do).
Comment: But what is passed to a method that takes an `object` as a parameter? (Say, `object.ReferenceEquals(object,object)`) :-)
Answer: Objects get copied first inside ReferenceEquals because they are of value type, so references are never equal.

Object.ReferenceEquals never hit


How do I overwrite the controller for admin/content?

Question: On admin/content, I have created different views for articles and basic pages (the default content types created from Drupal). On admin/content, it shows Content | Article | Basic Page. When I already have Article and Basic page as separate.
On admin/content, I would like to show as Blank means no data instead of showing all data.
I tried the following code.
modules/custom/content/src/Routing/RouteSubscriber.php
namespace Drupal\content\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * Used to alter routes.
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setDefaults(array(
        '_controller' => '\Drupal\content\Controller\ContentOverviewController::overview',
      ));
    }
  }

}

I'm trying to override its default controller, so it show blank.
The code for the controller is the following one.
namespace Drupal\content\Controller;

use Drupal\system\Controller\SystemController;

/**
 * Class ContentOverviewController.
 */
class ContentOverviewController extends SystemController {

  /**
   * Content Overview.
   */
  public function overview($link_id) {

    $build = [
      '#markup' => $this->t('Hello World!'),
    ];
    return $build;
  }

}

The code doesn't seem to work.
I also tried to disable the content view, but that is not needed.
Comment: That's not true. You can disable this view, and make a new view with the same URL.
Comment: You can don't overwrite it
Comment: Did you try add tag **priority**  for your service? May be your service run before **views.route_subscriber** of view module.
Answer: As per documentation:

The \Drupal\example\Routing\RouteSubscriber::alterRoutes method is an event subscriber because it extends RouteSubscriberBase. Therefore, the class must be registered as an event subscriber service.

In your example you also need a content.services.yml:
services:
  content.route_subscriber:
    class: Drupal\content\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Comment: This worked for me. I had to extend a Controller and was missing the routing entry. Once I added it to *.routing.yml it worked. Thanks!
Answer: Check a namespace in your RouteSubscriber.php
You have
namespace Drupal\content\Routing

Should be
namespace Drupal\mcontent\Routing

Because your custom module is mcontent (not content)
Comment: Fixed the things


Anyone use xui? JavaFX?

Question: Warning: Java newbie.
Been looking at XUI for Java. Its looks quite interesting. Sort of liek a WPF way of designing interfaces. But googling around I don't see much other than articles saying it had been released. So is it used much or a bit niche?
Are there other similar frameworks for Java? Was looking at JavaFX but seems to be a general feeling that it has been slow development wise. Are there other frameworks that work in simialr ways? I get the impression Swing/SWT seem to more like WinForms. I'm looking to do something a bit more WPF like. As I said, Java newbie, so I might have this all confused. Seem to be so many UI frameworks its a bit overwhelming working out what to use for a new project.
Answer: If you can't use JavaFx, Take a look http://www.swixml.org.
Answer: JavaFx is a nice framework, it is pretty easy to learn and use. There are also some nice tutorials, doco, API's available, its still only in Preview SDK at the moment, but the next reelase is expected out relativly soon.
I would recommend giving it a try
official javaFx site
suns JavaFX overview
openjfx

Anyone use xui? JavaFX?


How to create a new parent section on the Configuration page?

Question: When one navigates to Manage » Configuration, the page is divided into sections which (in the "Seven" theme at least) shows up in individual boxes. These sections have headings like "People", "Content authoring", "Development", etc.
I am able to create a settings form and place this inside any of the existing sections on the configuration page by associating it with the parent key in hello_world.links.menu.yml.
Example:
hello_world.greeting_form:
  title: 'Salutation settings'
  description: 'Configure the salutation message.'
  route_name: hello_world.greeting_form
  parent: system.admin_config_development

This places a link to the settings form for the "Hello World" module in the "Development" section. This is not where I want to place it.
Instead, I want to create a new section named "Examples", place this new section along with the others on the "Configuration" page, and make this new section the parent of my link to the settings form.
Below is an image of what I want it to look like. There should be a new section, named "Examples" as the section heading, and in that section, there should be a link to the settings form with the text "Salutation settings":
Comment: if that is not the place you want the menu item. Can you share screen shot of where its needed so will update my answer.
Comment: No, that is not where I want it. I've added a screen shot as suggested to better show what I am looking for.
Answer: The yaml-files that do this for the core is located in core/modules/system/. I eventually solved it by copying and adapting the relevant bits from system.routing.ymland system.links.menu.yml.
First, in hello_world.routing.yml, set up the routings we shall need:

hello_world.admin_config_examples:
  path: '/admin/config/examples'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Examples'
  requirements:
    _permission: 'access administration pages'

hello_world.greeting_form:
  path: '/admin/config/examples/salutation-configuration'
  defaults:
    _form: Drupal\hello_world\Form\SalutationConfigurationForm
    _title: 'Salutation configuration'
  requirements:
    _permission: 'administer site configuration'

Then, in hello_world.links.menu.yml, set up menu items. First the item that is going to be link to the section, and then the the menu item that links to the settings form:

hello_world.admin_config_examples:
  title: 'Examples'
  route_name: hello_world.admin_config_examples
  parent: system.admin_config
  weight: 0
hello_world.greeting_form:
  title: 'Salutation settings'
  description: 'Configure the salutation message.'
  route_name: hello_world.greeting_form
  parent: hello_world.admin_config_examples
Comment: you beat me here. yes, that was exact change `system.admin_config` . Glad you figured it out.
Answer: Here is a way to do it.
#example_codes.links.menu.yml
example_codes.base:
  title: 'Example Codes Module'
  parent: system.admin
  description: 'A Module with various Examples.'
  route_name: example_codes.base
  weight: 0

You need to define system.admin as parent.
And in your routing.yml should contain this base route.
#example_codes.routing.yml
example_codes.base:
  path: '/admin/examples-codes'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Example Codes Module'
  requirements:
    _permission: 'administer example codes configurations'

Comment: Thank you for taking time answering. Your code works, but places the link alongside "Configuration" within the admin toolbar. I want a new section to appear on the "Configuration" page. I've added a mock-up image of what it is I try to achieve.


VBA - Como mandar células específicas de uma planilha no corpo de um email

Question: Olá, estou tentando fazer uma aplicação para o meu trabalho em VBA, porém estou tendo dificuldade em mandar somente algumas células no corpo de um email diretamente via outlook.
Private Sub CommandButton1_Click()
Dim v1 As String
Dim data As Date
Dim v2 As String
Dim outmail As Object
Dim texto As String
Dim outapp As Object
Dim intervalo As Range

v1 = TextBox1.Value
data = TextBox2.Value
v2 = TextBox3.Value

Sheets("Demandas").Select

Range("A2") = data
Range("B2") = v2
Range("C2") = v1

Sheets("Demandas").Select
Set intervalo = Range("A2:C2").Select

Set outapp = CreateObject("Outlook.Application")
Set outmail = outapp.createitem(0)

With outmail
    .display
    .to = "email@example.com"
    .cc = ""
    .bcc = ""
    .Subject = "Solicitação de nova demanda"
    .body = intervalo

End With

MsgBox ("Sua solicitação foi concluida")

UserForm1.Hide

End Sub

Na linha:Set intervalo = Range("A2:C2").Select a aplicação sempre dá um erro dizendo que o objeto é obrigatório. Tentei fazer como uma string tambem com a variável texto para anexar as células que eu quero mas deu erro também.
Gostaria de saber se alguem poderia esclarecer isto pra mim, pois estou necessitando muito dessa aplicação.
Obrigado.
Comment: Possível duplicata de [Macro email range + assinatura](https://pt.stackoverflow.com/questions/292574/macro-email-range-assinatura)
Answer: Olá Ecodata espero que te ajude, fiz pequenos ajustes e testei e funcionou!
Segue o trecho de código que você precisa alterar.
Sheets("Demandas").Select
Set intervalo = Range("A2:C2").SpecialCells(xlCellTypeVisible)

Dim textoDaSelecao As String

For Each valor In intervalo
    textoDaSelecao = textoDaSelecao & " " & valor
Next

Set outapp = CreateObject("Outlook.Application")
Set outmail = outapp.createitem(0)

With outmail
    .display
    .to = "firstname.lastname@example.com"
    .cc = ""
    .bcc = ""
    .Subject = "Solicitação de nova demanda"
    .body = Mid(textoDaSelecao, 2)
End With

Comment: Muito obrigado pela ajuda, deu certo!!


How does the FIA keep track of the teams' power unit allocations?

Question: In 2018, F1 teams are allowed only 3 units of the Internal Combustion Engine, MGU-K and MGU-H, and 2 units of Energy Store, Turbocharger and Control Electronics. Gearboxes must also be used for 6 consecutive race weekends (FP3 to Race) before teams could replace them without penalty.
Question is, how does the FIA keep track of these components and make sure that the teams are not changing them between each race weekend?
Answer: Each part of the power unit is affixed with a seal once installed in the car.
These seals are presumably recorded in a system under FIA control. The seals are then checked whenever necessary by the FIA delegates.
A broken seal disallows any further use of a part unless the seal is removed under FIA supervision.
See Article 23.3.d of the FIA Sporting Regulations for detail of the rules for affixing or removing seals.


Approximating $C$ functions with polynomials

Question: Consider the space $X = C([0;1])$ of continous real-valued functions with the usual maximum norm.
So the Weierstrass Approximation Theorem says, that every $u \in X$ can be approximated by polynomials $p_n$, such that:
$\forall \epsilon>0 :\exists \ p_n: sup_{x \in [0;1]} |p_n(x)-u(x)| < \epsilon$
Let's for example consider the function $u(x) = e^{-1/x} \text{ for } x \in (0;1], u(0) = 0.$
One can show that $u$ is in $X$ and also in $C^\infty([0;1])$.
My question is:
Let $p_n$ be polynomials and $p_n \rightarrow u$ in X.
Is there any way to figure out how the coefficients of $p_n$ look like?
Usually for $C^{\infty}$ functions you would try to do a taylor series, but in the case of $u$ you would just get $p_n = 0$ because the derivative $u^{(n)}(0) = 0 \ \forall n  \in \mathbb{N}$.
Also i wonder how you would approximate for example $v(x) = |x-\frac{1}{2}|$?
Thank you for your help :)
Answer: The Weierstrass approximation theorem only says that there are polynomials $p_n$. There are many possible choices for the $p_n$.
There is a constructive proof of the theorem that uses Bernstein polynomials.
For analytic functions the Taylor series also works.


Open mapping theorem and second category

Question: This seems like a fundamental result but I can not solve it of find an solution:
Let $M:X\rightarrow U$ be a bounded linear map between Banach spaces. Show that if the
range of M is a set of second category of U; then the range is all of U.
Comment: This is very confusing to me. Your statement is not true and the title does not seem to involve the question at all. For a counterexample consider something like the diagonal operator $e_n \mapsto e_n/n$ on $\ell^1(\mathbb N)$.
Comment: @Norbert, I usually post as a comment when I think someone meant to ask something different and I'm unsure if I'll be able to answer their actual question.
Comment: Should the title say "second category" instead of "second countable"?
Comment: @JacobSchlather, why don't you post this comment as answer?
Comment: Sorry I wrote it wrong, it is corrected now.
Comment: The title doesn't seem to be at all related to the question.
Comment: I think the [standard proof](http://en.wikipedia.org/wiki/Open_mapping_theorem_%28functional_analysis%29) of the Open Mapping Theorem, where the hypothesis that "$M$ is onto" is replaced by "$\text{Ran}(M)$ is of second category" can be slightly altered to give your result. In fact, more is true: If $X$ is a Banach space, $Y$ is  a normed space,   $M:X\rightarrow Y$ is continuous, linear, and $M(X)$ is of second category, then: 1) $M$ is onto, 2) $M$ is an open mapping, and 3) $Y$ is complete.  This (ever further generalized) is Theorem 2.11 in Walter Rudin's *Functional Analysis*.
Answer: Assume that the range is of second category but the range of $M$ is not $U$. As $M(X)$ is not closed (otherwise $M(X)$ would be of first category, as it's a strict subspace), we can apply this result to $Y=\overline{M(X)}$.
Comment: That was a long one! Is there no easier way?
Comment: I don't know, but what we have to show is strongly related to what is done in the link.


Facebook - Website Integration

Question: I'm integrating facebook for a website that has the ff. flow:

Website has no connect with facebook button on login and sign-up page
After sign-up, user will be ask if he/she wants to connect facebook account with just basic information and email as permissions
If user allowed integration, the facebook user id will be saved.
Facebook user id will be used in FQL

My problem is, with no facebook connect on login and sign-up pages
When I try to do multi-friend selector, if the user currently logged in has not logged in at 'facebook.com',
I'm receiving Fatal error: Uncaught Exception: 102: Requires user session thrown
Which means in order for some facebook integration to work such as inviting friends, user have to be logged in facebook as well.
Is there a way to login both website and facebook.com with just facebook user id saved in the database? Something like, "if I detected this user id, autologin to facebook" in able to create session
P.S I've done facebook integration before and I have no problem because it has facebook connect in login and sign-up page which creates the session needed if the user chooses to login via that button.
Your help will be very much appreciated. I'm stuck.
Answer: When a user authenticates with your site/access your app you can get a user access token that can be used in your subsequent API calls.  It expires when they change their password or revoke/remove your app.
Check out this link for details related to authenticate, the user access token and the callbacks so you can maintain an up to date database: http://developers.facebook.com/docs/authentication/

Facebook - Website Integration


Is virtual machine slower than the underlying physical machine?

Question: This question is quite general, but most specifically I'm interested in knowing if virtual machine running Ubuntu Enterprise Cloud will be any slower than the same physical machine without any virtualization. How much (1%, 5%, 10%)?
Did anyone measure performance difference of web server or db server (virtual VS physical)?
If it depends on configuration, let's imagine two quad core processors, 12 GB of memory and a bunch of SSD disks, running 64-bit ubuntu enterprise server. On top of that, just 1 virtual machine allowed to use all resources available.
Comment: Ubuntu Entreprise Cloud is based on KVM not Xen.
Comment: Antoine, you are right - "The core virtualization strategy has always been KVM-based, although with the development of lib-virt, the management of KVM and Xen hosts is unified." - I will edit out the mention about Xen.
Answer: The typical experience for a general purpose server workload on a bare metal\Type 1 Hypervisor is around 1-5% of CPU overhead and 5-10% Memory overhead, with some additional overhead that varies depending on overall IO load. That is pretty much consistent in my experience for modern Guest OS's running under VMware ESX\ESXi, Microsoft Hyper-V and Xen where the underlying hardware has been appropriately designed. For 64 bit Server operating systems running on hardware that supports the most current cpu hardware virtualization extensions I would expect all Type 1 hypervisors to be heading for that 1% overhead number. KVM's maturity isn't quite up to Xen (or VMware) at this point but I see no reason to think that it would be noticeably worse than them for the example you describe.
For specific use cases though the overall\aggregate "performance" of a virtual environment can exceed bare metal \ discrete servers. Here's an example of a discussion on how a VMware Clustered implentation can be faster\better\cheaper than a bare metal Oracle RAC.  VMware's memory management techniques (especially transparent page sharing) can eliminate the memory overhead almost entirely if you have enough VM's that are similar enough. The important thing in all these cases is that the performance\efficiency benefits that virtualization can deliver will only be realised if you are consolidating multiple VM's onto hosts, your example (1 VM on the host) will always be slower than bare metal to some degree.
While this is all useful the real issues in terms of Server virtualization tend to be centered around management, high availability techniques and scalability. A 2-5% CPU performance margin is not as important as being able to scale efficiently to 20, 40 or however many VM's you need on each host. You can deal with the performance hit by selecting a slightly faster CPU as your baseline, or by adding more nodes in your clusters but if the host can't scale out the number of VM's it can run, or the environment is hard to manage or unreliable then its worthless from a server virtualization perspective.
Comment: You use outdated tech - especially the 5% to 10% memory overhead is old hardware. The newer hardware chips have an overhead of about 2% to 3% if the hyper-visor supports it - and we talk of stuff being a year old being new. AMD and Intel improoved their API for Hyper-Visor memory mapping by then. As you said later, they hit to be pretty transparent (1% target). +1 for pointing out the real benefits.
Comment: I based the 5-10% on what I've seen with VMware and it is based on pre EPT\RVI kit. It makes sense that the improved hardware based virtual memory management in the most recent CPU's would reduce the RAM overhead
Comment: @Tony that's only true if you are not overcommitted - if you are then ESX\ESXi 4 will opt to use small pages, and TPS will kick in. I haven't pushed this to the limit so I can't confirm that it really does work as advertised but it is a sensible approach that should allow over-commit when absolutely required without sacrificing performance when its not. See http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1021095
Comment: @Helvick, if you run win7 or w2k8r2 guest TPS doesn't work much since the guest are aggresively precaching things.
Comment: concerning transparent page sharing, it sucks when you have large memory pages which all new cpu's support. You essentially gain nothing in this case.
Comment: @tony roth, that's true, but you're probably being pedantic since that's not the problem that TPS was designed to address. The performance impact of aggressive precaching is handled by the balloon driver in your hypervisor's guest additions, not by zero page sharing through TPS.
Comment: When we say "overhead is only 1-2%" -- what about when we add 10-50 virtual machines on the one physical one. Now we are adding 10-100% overhead. Right?
Comment: Not necessarily. Hypervisor context switching adds the overhead but it is only relevant if you are doing a lot of context switching. If you have a 10 core system and it is running 10 single vCPU VMs then there will be very little context switching. If you are runnin 50 busy VMs on that same box, then there will be a lot of context switching but your bigger problem then is that you are trying to run 5 times too many VMs. I wrote that 9 years ago and the pervasive adoption of virtualization today bears out the fundamental argument - better manageability is more important than raw performance.
Answer: "Performance" has many aspects. The n00bs measure the boot time of an OS, and say e.g. Windows 2012 is sooooooo great because it boots in 12 sec on real HD, maybe 1 sec on SSD.
But this sort of measure not very useful: performance is equal to OS boot time, but the OS boots once a month so optimizing that doesn't make much sense.
Because it's my daily business I might point out the 4 following parts which made up the "performance"

CPU load
This should be comparable, meaning a task taking 1000 ms on bare metal will execute in 1000 ms process time and probably 1050 ms of clock time in an idle VM environment on the same hardware (some details later). Google the MSDN for processtime and queryperformancecounter and yu can do a thing that can show how much the VM eats up yur CPU time.
SQL performance
SQL performance highly relies on IO to the datastore where the SQL data is stored. I've seen 300% difference between 1'st gen ISCSI which you may find on Buffalo home NAS, then ISCSI with DCE and a real old school FC environment, on all levels. The FC still wins nowadays, because the FC latency is the lowesst archievable  which lead to a "copy" of the FC protocol for TCP/IP datacenter enhancements. Here IOps and latency is vital but also IO bandwidth from the server process to the media - depends if the app tends to No-SQL or to Datawarehousing or is in the middle of that like ERP sytems ... Sage KHK for small enterprises, SAP for the huge ones. Both have a CEO view on enterprise financial statistics and when the CEO hits the button he effectively grants vacations for some days when the IO subsystem of the database has weaknesses.
Filesystem Access
Some applications, like video streaming relies on a guaranteed minimum bandwidth, others rely on max IO throughput like just openeing large files in a hex editor, loading a video project into yur favorite movie making prog. Not a typical situation on a vm.... the IOps may also be important to developers. Developers often make use of VMs because developing environment s are very sensitive and so the temptation to do that in  a VM is high. Compiling a large project often means reading tons of small files, do the compiler stuff and build an EXE and the accompaining components.
Network latency to the client
Here the usability of WYSIWIG progs like word 2010, Openoffice Writer, LaTEX, GSView and others highly rely on the speed - how fast a mouse action gets from the client to the server. Especially in CAD apps this is important.... but also not a LAN issue, it'S remote access over WAN where this is important.

But - and I speak from the perspective of years of consulting - there are users having the admin password (and they're often employees of a BIG company with a BIG budget and a BIG pocketbook) complaining this and that, but it must be clarified which performance compoent is important to them and which is important from the perspective of the application they use.
It's most likely not notepad, but a highly sophisticated application for engineering this and that, which was also very expenssive and should be moved on the VMware, HyperV or Xenapp and it doesn't perform as expected.
But they don't have in mind that it might run on 1.5 GHz Xeons on blades not made for pure CPU performance, they're built for an average, let's say "optimized for $ per CPU cycle" or "CPU cycles per Watt".
And when we talk about tradeoffs and economisations - that mostly leads to overcommitments. Overcommitments lead to lack of ressources where CPU can be handled pretty well, but lack of memory leads to paging, lack of IO in the core routers leads to increased answer times on everything , and transactional overload on any kind of storage might stop every useful app from responding too quickly. Here monitoring is required, but many software vendors are not able to provide such informations....on the other hand a host with ressources of 3 physical servers can most likely handle 8 virtual machines of the same layout like the physical ones...
The CPU tradeoffs on idle systems often leads to systems performing 50% slower than physical systems, on the other hand nobody is able to install the "real world" os and the "real world" app the customer's IT guys want to move into the VM box. And it takes days (maybe weeks but for sure 42 meetings) to make clear that VM technology can offer flexibility by trading pure CPU speed. This is just built into the CPUs on these blade systems hosting nowadays larger VM environments. Also the memory won't be comparable, also some tradeoffs apply. DDR3 1600 CL10 will have higher memory bandwidth than DDR2 800 ECC LLR - and everyone knows that Intel CPUs profit from this in a different way than AMD cpus. But they're rarely used on productive environments, more in whiteboxes or in datacaenters hosted in 3rd world countries who offer datacenter service for 10% of the price a datacenter in your own homeland may bill yu. Thanks to Citrx a datacenter can be everywhere if it's less than 150 ms of latency between the end user and the datacenter.
And the home users perspective....
Last but not least some people wanna throw away Win7 or XP and trade it for a Linux, and then the gaming question comes up because actually only few games are available for Linux and Windows. Gaming relies higly on 3D acceleration. VMWare 6.5 Workstation and the connected free player can handle DirectX 9, meaning a Doom3 in a VM can run on the host graphic card in full screen. Games are mostly 32 bit apps, so they won't eat up more than 3 GB and mostly not more than 3 CPUs (seen on Crysis). Newer VM players and WS can handle higher DirectX versions and probably OpenGL as well... I gamed UT and UT2004 on VMware 6.5, the host had a ATI Radeon 2600 mobile and a T5440 CPU. It was stable at 1280x800 and playable even on network games....
Comment: We like good answers to timeless questions. Welcome to Server Fault!
Answer: I would point out that virtualisation can exceed physical performance in certain situations.
Since the network layer is not limited to gigabit speed (even though the hardware emulation is of a specific lan card), VM's on the same server can communicate between each other at speeds beyond that of multiple phyiscal servers with average network equipment.
Comment: Two pieces of software runing on two VM on the same server won't communicate faster than two softwares under the same OS on one bare metal server.
Answer: Yes. But that is not the question. The difference is normally neglegible (1% to 5%).
Comment: Citation needed.
Comment: It depends on so many factors thatnobody can answer your question. It depends on which hypervisor you have, the server spec, storage and most importantly what else is going on withe the host at the time in question.
Comment: I believe you. But still: can you link a benchmark where someone actually measured it?
Comment: Actually it does not. Natually if you do a lot ot things, the physical machine is shared. But the overhead of the hyper-visor is pretty constant by now, given hardware virtialization. Anturally if you start loading multiple VM's the resulting available powe is shared, but it is - in total - still only slightly less than what the server has.
Comment: the overhead of the hypervisor depends on how much the OS can be enlightened and this does not mean paravirtualized.
Comment: if you run hyper-v with a linux guest, I'd take the amount of guests and multiply by 8% to get the load factor. Now run a w2k8r2 guest then I'd multiply it by 1%. Now run esxi with a linux guest multiply the load by 4% and with any version of windows 5%.  As you know nobody can publish test numbers officially for vmware products, so this is all seat of the pants testing so far.
Comment: @TomTom: Something you need to consider is the impact of virtualized workloads on storage. Specifically, when you take multiple sequential workloads and run them concurrently, you end up with an I/O profile that's essentially random, not sequential. This can have major, major impacts on your performance.
Comment: @tony roth: I'd imagine it would be the other way around: paravirtualized components don't need the static overhead that emulated virtual hardware does. Why do you feel that "enlightening" (which tends to be rather Hyper-V/Windows-specific as a concept) as an approach has more of an impact on reducing hypervisor overhead?
Comment: All I know is that software that I was running on a old Xenon ran around 40% faster  than on the latest virtual server hardware running VMWARE with "12 cores" assigned to the server (vs 4 cores on the server). The bullpoo is real in this thread, virtual is always slower than physical.  But the benefits of virtual are not performance but scalability.
Comment: Your performance comparison may well be irrelevant - the server now may simply be oversubscribed. The performance difference is neglegibe - there is little perforamnce lost on the virtualization layer. THAT does NOT stop incompetent admins or incompetent business people from configuring the server bald or oversubscribing.
Answer: I have been doing some test comparisons of the same software running the same test (.NET-based web application with high volumes of web traffic and considerable SQL Server access).  Here's what I've seen:

The physical machine is better at instantiating classes (which translates to allocating memory at the system level) - this makes sense to me because physical machines do this through memory management hardware and VMs do this through software (with partial hardware assist) (On the VM, the app spent a significant amount of time in its constructors (where the memory is allocated (and nothing else is done), on the physical machine, the constructors weren't even included in the top 1000)
When you are in the middle of a method, the two are about equivalent - this is probably how most of the benchmarks are constructed that show the two "being the same"
When you access a network controller, the physical beats out the VM a little - again, the physical doesn't have very much sitting in between the .NET process and the hardware.  VM adds adds other "stuff" that each transaction needs to travel through.
Really, the same thing applied to disk access (the SQL Server was on another machine) - the difference is very small, but when you add them all up, it is noticeable.  This could have been caused by the slower network access or by a slower disk access.

I can easily see how someone could build benchmarks that prove they are 1% different or the same or where VMs are faster.  Don't include anything where your process takes advantage of the benefits of the local hardware support where the VM needs to simulate it in software.
Comment: This is what I was looking for. +1
Answer: You're trying to compare an operating system, software, and data installed on a certain physical hardware to that same operating system, software, and data installed by itself inside a hypervisor on the same original hardware. This comparison is just not valid, because almost no one does this (at least at first).  Of course that would likely be slower. Thankfully, it completely misses the most common point of why you virtualize servers at all.
A better example here is to look at two (or more!) older servers in your data center.  Look for servers that are performing reasonably well, but are old now and coming up on their refresh cycle.  These servers already perform well on older hardware, and so thanks to Moore's law anything new you get is gonna be way over-spec'd.
So what do you do?  It's simple.  Rather than buying two new servers you buy just one, and then migrate both of your old servers to the same physical new device.  When preparing to purchase your new server, you plan so that you have enough capacity to not only handle the load from both older servers but also any load from the hypervisor (and maybe a little extra, so that you can still get a performance boost and can allow for growth).
In summary: virtual machines provide "good enough" performance for most situations, and help you make better use of your servers to avoid "wasted" computing power.
Now let's stretch this a little further. Since these are old servers, perhaps you were looking at a couple simple $1500 pizza box servers to replace them. Chances are, even one of these pizza boxes could still easily handle the load from both hypothetical older machines... but let's say you decide to spend $7500 or more on some real hardware instead.  Now you have a device that can easily handle as many as a dozen of your existing servers (depending on how you handle storage and networking), with an initial cost of only 5. You also have the benefits of only managing one physical server, decoupling your software from your hardware (ie: hardware refresh is now less likely to need a new windows license or cause downtime), you save a ton on power, and your hypervisor can give you better information on performance than you've had in the past.  Get two of these and depending on how big you are maybe your entire data center is down to just two machines, or perhaps you want to use the second server as a hot standby to tell a better high-availability story.
My point here is that it's not just about performance.  I would never take a perfectly good production server and virtualize it alone to equivalent hardware just because. It's more about cost savings and other benefits you can gain from consolidation, such as high-availability. Realizing these benefits means you're moving servers to different hardware, and that in turn means you need to take the time to size that hardware appropriately, including accounting for the hypervisor penalty. Yes, you might need slightly more computing power in total than if each of those machines were on their own physical device (hint: you actually probably need much less total computing power), but it's gonna be a whole lot cheaper, more energy efficient, and easier to maintaint to run one physical server than it is to run many.
Comment: It's not always about consolidation and cost savings. A hypervisor is a product with many features, many of which have the potential to add business value independently of the reasons that most people virtualize. Consolidation and cost savings may be part of that business value, or they may not. Snapshots, live migration, Storage vMotion, and hardware abstraction may all be part of the business IT strategy.
Comment: @jgold Point taken. You even forgot a big one: high availability.  In my defense, I did mention hardware abstration (sort of) in my last edit, and for someone who's just exploring virtualization from the angle of the original question I think consolidation/cost is the really big point to convey.
Comment: The question asked about a comparison of performance which is an entirely valid aspect to want to investigate about virtualisation, not about why virtualisation is or is not useful.
Answer: I have just upgraded to an SSD (OCZ Vertex 2) and I run my XP VM development environment on it, I am a software developer.  One thing I have noticed is that when I launch a program (one big enough to take time to load), one core of the virtual CPU pegs out.  This happens when loading IE also.  Since the CPU pegs out, I assume the bottleneck is the CPU and not the SSD.  But it seems odd, I have a feeling that if the same thing were done on a physical machine that it would load faster and my feeling is that there is some extra processing overhead VMWare is doing that is consuming CPU on disk access.
One example, I use Delphi and on a physical machine with a regular HDD it can take 20 seconds to start from a cold boot.  In the VM running off an SSD, it loads in 19 seconds from a cold start.  Not much difference, I bet if the SSD were on the physical machine it would load faster.  Howevere I did not check the CPU usage on the physical machine, its possible the CPU were the bottleneck there as well.
But the feel of the VM is that disk access taxes the VM.
Answer: Obviously a virtual machine is slower than the physical machine. But when you're in this scenario you have to evaluate what is optimal to cover your needs. If you need only one system and you need it to be fast, then install it directly to the hardware. In the other side, if you need flexibility, scalability (and all other virtualization benefits :P) deploy a VM. It will be slower, but IMHO in some cases it's justified and the performance is not significantly  slow.
Answer: It seems Microsoft has done some benchmark testing using BizTalk server, and SQL Server in different configurations in this regard. See link below:
http://msdn.microsoft.com/en-us/library/cc768537(v=BTS.10).aspx
Comment: Please cite the conclusions in your answers or this is little more than SPAM for the provided link. Thank you.
Comment: SQL Server performacne Virtual to Physical ratio (using BizTalk:Messaging/Documents processed/Sec metric which seems like reasonably real-world) is quoted to be 88% - using HyperV. Doesn't look good.
Comment: Oh my god, is that a 250MB PDF file? O_O
Answer: Ideally Virtual PC performance is at:
CPU: 96-97% of host
Network: 70-90% of host
Disk: 40-70% of host
Comment: And those numbers come from....
Answer: Sorry to disagree with TomTom.
I've been using VMware Workstation for a while mainly on Windows XP, Windows Vista and now Windows Seven native systems to run different Windows flavors as well as Ubuntu.
Yes, a virtualized environment is slower than a native system and that may be in a range of 5 up to 100 %.
The main problem isn't that much the CPU load but the physical memory lack.
Let's say you've a Windows Seven 64 Ultimate running on a 4 Gb system that when idle needs almost 1.5 Gb and uses ~ 10% of the CPU. Launching the extra layer of VMware will cost you ~ 300 Kb and the CPU loads will climb up to ~ 20%. Then launching a virtual system within VMware will request at a minimum the amount of memory you defined for that virtual machine that is a minimum of 1 Gb for any decent system. Then you'll see the CPU load ~ 60 % if the virtual machine is Ubuntu and ~ 80 % for any flavor of recent Windows OS.
Now, you'll start different apps within that virtual machine.
If the amount of memory you've set for that virtual machine is not enough, the virtualized system will start to swap, then dramatically slowing down its overall performance and responsiveness.
If the sum of the amount of memory you've set for that virtual machine plus the amount of memory needed for your native system is above the amount of memory of your native system, then it's your native system that is going to swap, slowing down both the native and virtualized system.
So, it first depends of the balance of the memory needed for both the native and the virtualized machines.
Now it's almost the same with the CPU load. If a virtualized app needs a huge CPU load, and a native app needs also a huge CPU load, your native system will have to manage the priority and balance the CPU charge between its different apps, the virtualized system being nothing but an app but that phenomenon is a classical CPU load problem that you can trick with app priorities.
So, my first advice if you need to use virtualization is to put a bunch of memory in your machine, whatever the OS you use natively or within a virtual machine.
Just my 2 cents.
Best regards.
Comment: But you are talking about Workstation virtualization not a bare metal Hypervisor which has a fraction of the overheads compared to virtualizing on Windows.  Ubuntu cloud might not quite be a bare metal hypervisor but it hardly uses the reosurces of Windows - it runs on Ubuntu Server which doesn't have a GUI for instance.
Comment: How would Win7 x64 need 1,5 GB (or any cpu time at all) when idle? More like 384-512MB in my experience - the rest is just reserved for I/O caching and will be released if needed elsewhere ^^
Comment: -1: Very poor comparison. VM Workstation is NOT a hypervisor.  Secondly you're talking about running high loads on the host; of course that's going to have an impact on the guest VM.
Comment: @ Oskar

> How would Win7 x64 need 1,5 GB (or any cpu time at all) when idle? More like 384-512MB in my experience

Take a look at this picture http://theliberated7dwarfs.as2.com/pictures/png/W7-Mem.png

Windows 7-64, 4 Gb of RAM, fresh reboot, no application runing but MSFT Essential Security and Kapersky!

Oops: 1.53 Gb of RAM used and an average of 7% of CPU load!

@ TomTom & gravyface

1-The initial question was about generic VM machine, not hypervisor!

2-My crapy technical platform makes the fortune of both MSFT and VMware.

You might like it or not and I won't blame you;)

Kind regards
Comment: Imagine this configuration: 12 GB memory, two quad core processors. On top of that just 1 virtual machine with 11,5 GB memory and all the CPU power. Will there still be some noticable slowdown?
Comment: Notice Michal said *noticeable* slowdown, also. I don't notice a huge slowdown for the tasks we use our servers for. And it depends on system load, network load, etc. but for the most part it's subjective unless something is really rocking the system. I had this conversation with someone re: SSD drive. "They're really really fast," he said. "But after a short time, it becomes the norm for you." Perception. Unless the VM is utterly crawling you probably won't notice much difference. If it's utterly crawling, you have a problem to troubleshoot.
Comment: But it makes perfect sense that, logically, there's *some* slowdown. It's not running natively on bare hardware. The percent slowdown depends on the hypervisor and *what* it's doing, as some techniques affect the performance of what you're doing (some hypervisors may be more efficient handling CPU-bound tasks, others disk tasks, depends on the disk subsystem drivers, etc.) so really you can't find solid numbers on performance until you test your hardware specifically.
Comment: You make totally crap arguments, Dopey. First, you really come up with a crap technical platform - try using a hyper-visor as the poster. Second, you load a lot of things - so you SHARE the machine. THis was not my answer. A good hyper-visor will only use about 3% to 5% of the resources. THis means your machine capacity is 97% - and if you insist on loading 10vm's that naturally gets divided. COmmon sense. DOes not change that the overhead of virtualization is very little.
Comment: for some corner case applications where software scales badly, I've seen benchmarks where the virtualized solution offers better performance than running on the physical hardware. You can run 2 or more VMs with the badly scaling software and get better performance than one instance on the phyical  hardware.
Comment: So, no more comment about Oskar purported memory need under Windows 7 (that I love a lot for its new interface as well as its capability to perform nicely when compared to Vista which by the way I used for 3 years without any damned problem).
Comment: Either, no more comment from TomTom with regard to my initial post responding to a generic virtual machine performance question later edited with hypervisor meanings?
Comment: win7 precaches things/applications etc thus it appears to use more ram, once again this screws with TPS since most modern cpu's enable large memory pages.
Comment: @Dopey, terrible comparison, like comparing a bike to a jumbo jet, workstation is very convenient (I use it myself for testing) but it's like Fisher Price virtualisation compared to ESXi.
Answer: In my experience virtual machines are always a lot slower than physical ones OUT OF THE BOX.
You will only notice it when running applications that hit the disk and tax the CPU a lot. I have run many databases and webservers on virtual machines and as an end user and the feedback from other endusers (ie: accessing the app from a remote web browser) there is quite a big lag when using virtual machines.
Of course a properly configured virtual machine may come to 80% (I don't know the real number) or whatever of the physical machine's speed, but you end up having to really dig deep into what the application is doing and how the virtual machine works. So I guess it is a cost equation of how valuable your time to configure VMs verses just buying and hosting a new server.
For me virtual machines are NOT ABOUT PERFORMANCE, but about being easier to manage and for hosting several low performance VMs of course.
Comment: YOu seem to run really crap virtualization technique. Seriously ;) MS did performance comparisons with Hyper-V and SQL Server - and came up with numbers that are around 3% overhead to the bare metal machine. Naturally this means running only one virtual machine, or accepting that the performance is splitted - but the overhead of virtualization is really low. And it is not ONLY about hosting several low performance VM's. It can also be about ease of maintenance - moving a VM to new hardwar easy, a physical machine may be more complicated.
Comment: Crap out, Zubair. I am no idiot - I was running tests before. I have been moving a lot of stuff over to VM's and barely run anything physical these days. I did a lto of benchmarking myself. Naturally hyper-visors are tricky - people put a lot of servers on a machine and overload it. Most likely actually in the IO area (disc performance). But all that is not intrinsic to a hypervisor. Same with RAM - yes, you need a lot, and yes, the machines simulated still need their amount of RAM to be efficient. But that is not a hyper-visor problem.
Comment: @TomTom. Do you have any links which I could read to learn more about these virtual vs physical performance tests
Comment: @Zubair - Although I'm a 100% VMWare-man myself I have to agree with TomTom on this, I see very little performance drop-off for CPU and memory operations on modern, well configured hardware, yes heavy concurrent mixed read/write IO can be noticibly more impacted than CPU & memory but we're still talking single-digit percentile loss across the board. I manage nearly 1,000 ESXi hosts in a company with over 8,000 and we're confident that only a handful of very heavily IO-bound applications are a bad fit for ESXi.
Comment: @TomTom. I would like to believe you but Microsoft of course have an interest in telling everyonr that their hypervisor is super fast. I know from companies that have tried Microsoft virtualisation AND VmWare that  what Microsoft is saying is just "marketing". Have you actually benchmarked it yourself? If you get 3% overhead then please  let me know your setup as I would like to try it
Comment: I run a lot of stuff on hyper-visor by now, including a 800gigabyte SQL Server application that is prety active recording financial market data. No problem inherent to the hyper-visor. This one has 4 virtual CPU's and currently 8GB ram for the windows instance ;) And the disc io subsystem is non-typical (talk about nearly a dozen physically mapped discs).
Comment: @TomTom don't think MS published anything that shows a 3% difference concerning baremetal vs hypervisor. They did show that VHD's can perform within 3% of physical disk when used as a native disk.  I think you MAY have confused that bench mark with a hypervisor comparision.
Comment: VMware, on the other hand, posted a few performance benchmarks showing that on systems with very high core counts, running several smaller virtualized SQL Server instances and partitioning the database across them ended up being substantially faster than trying to scale the application across all the cores on the physical machine. While this isn't something you see often with things like SQL Server for complexity reasons, this is actually a very common approach with certain applications like Citrix.
Comment: I would also add that companies rarely upgrade VMware hosts, but they could upgrade 1-2 servers more often that seem to need some performance. So what happens is, you end up running 12 year old hardware before you finally upgrade the hosts.   You should really mix/match virtual and bare metal based on the scenario.


Finite integral domains are commutative?

Question: Here, integral domain is a non-zero ring $R$ (not necessarily commutative, and not necessarily contains unity), in which $ab=0$ implies $a=0$ or $b=0$.
Question If $R$ is a finite integral domain, is it necessarily commutative?
Comment: https://www.proofwiki.org/wiki/Finite_Ring_with_No_Proper_Zero_Divisors_is_Field
Comment: It should be remarked that googling "finite integral domain"  gets you several useful answers. It is **always** a good idea to peruse the standard sources of information before asking a question here!
Comment: I did this, but here, I am considering Integral domain not necessarily a commutative ring; hence, after some searches, I posted this problem.
Comment: @ Groups : Is this hold for infinite  Ring $R$ such that $ab = 0$ implies that eithe $a = 0$ or $b = 0$
Comment: @Struggler:Hamiltonian quaternions over reals/ rationals is integral domain which is not commutative.
Comment: @ Groups : Thanks
Answer: The pieces of this proof are already strewn about the site. I think I'll tidy it into a single argument though.
A nonzero finite ring with no nonzero zero divisors has identity.
First of all, left multiplication by a nonzero element makes an injective map. (This is shown multiple times throughout the site, and follows easily from the hypothesis.) Since an injective map on a finite set is surjective, we can solve $ax=b$ whenever $a$ is nonzero.
Given nonzero $a$, there us a $b$ such that $ab=a$. Then $a(b-b^2)=0$
 implies $b=b^2$.
For an arbitrary $c$, $(cb-c)b=0$ implies $cb=c$ for all $c$. Thus the ring has a right identity. Symmetrically, it has a left identity, and these are necessarily equal and are the identity if the ring.
The surjective try argument given above now allows you to show the ring is a division ring.
Finally, the hard part is showing that it is commutative, a result known as Wedderburn's Little Theorem. You can find proofs online and in many books. It takes a bit of work that is not worth reproducing here.


How to turn on pins 13 and 12 at the same time? Assembly

Question: How to turn on pins 13 and 12 at the same time?
ldi r18,0x20  ; bit 5 (pin 13) = high
out 5,r18     ; output to port B

ldi r18,0x10  ; bit 4 (pin 12) = high
out 5,r18     ; output to port B

Answer: Just bitwise OR the values together to set both;
ldi r18,0x30  ; 0x20 (bit 5) OR 0x10 (bit 4) = 0x30 sets bit 4 and 5 high
out 5,r18     ; output to port B

Comment: thank you very much kind sir :) works perfectly, it's my first day writing assembly. Thank you.


Are there any notable cricketing baseballers or baseball-playing cricketers?

Question: Are there any attempts (in history or today) of top-level baseball players (cricketers) having a shot at "higher-level" cricket (baseball) (and perhaps succeeding in some sort of way)? I do not mean demonstration or recreational games and the like, but rather real higher-level competitions.
Comment: @KeerthiKumar Could you please provide references for John Davison's _baseball_ career? At what level did he play baseball?
Comment: Yes, met AB STH, I was a yank that knew a bit about cricket, playing with a wandering village side in the U.K. Didn't really know about AB before this, but he believed he was a better baseball player than cricketer,. The American major league baseball clubs were not scouting
the Antipodes in the 1980's. In the 1990's till today there are a lot of Skippy's playing
both minor and major league baseball in America, mostly pitchers.
Comment: Wikipedia has [several people](http://www.google.com/search?q=%22Australian+cricketers%22+%22Australian+baseball+players%22+site:wikipedia.org) listed in both categories: *Australian cricketers* and *Australian baseball players*.
Comment: I think you forgot about john davison cricketer from canada who also played baseball in USA
Comment: Alan Border insists that he was a better baseball player than cricketer: Sebel Townhouse Bar
1989.Septic.
Comment: This is not a complete answer. Is there any reference to support this?
Answer: Australian cricketer Bill Ponsford was considered a good baseball player in his country.
Answer: Three Australian cricket captains also played baseball for the Mosman Baseball club: Richie Benaud, Allan Border and Ian Chappell. The club also lists the following test cricketers who played for them:

Ian Craig
Neil Harvey
Graham Hole
Gordon F Rorke
David Sincock
Comment: That's fascinating! The cricket is obviously top level, but what about their baseball? My browsing on the Mosman website doesn't reveal "serious" competition. Were they involved in a certain level of league at the times?
Answer: Back in the 19th century, teams of professional baseball stars used to go on tours to England and overseas and play cricket against the locals.  They won most of the time.


Interview question - numbered tiles

Question: Ok, this interview question interested me and I would love to see an explanation!
There are some tiles: 1, 1, 2, 2, 3, 3
They must be placed in a straight line, such that there is one tile between the 1s, two tiles between the 2s and three tiles between the 3s.
E.g. 312132
Now, you could add two 4s: 41312432
But it is impossible to add two 5s.
The question is how to prove this..
What would be the proof, and how would you derive it?
Answer: With tiles labeled $1,1,2,2,\ldots, n,n$ you have to place these at positions $1,2,\ldots, 2n$ such that the positions of the two tiles with label $k$ differ by $k+1$. Hence if $k$ is even, these tiles occupy one odd and one even position, whereas for odd $k$, the pair occupies two positions of equal parity. Hence if $r$ of the odd tile pairs occupy even positions and $\lfloor \frac{n+1}{2}\rfloor-r$ pairs occupy odd positions, we need that these counts are equal, i.e. $\lfloor \frac{n+1}{2}\rfloor=2r$. For $n=5$, the left hand side is odd, hence no such $r$ exists. (It may work again for $n=7$).
Answer: Label the placement positions consecutively with the numbers $1, 2, ..., 10$.
Since the $1$-labeled tiles have to be placed one apart from each other, we can write their positions as $a$ and $a+2$ for some $1 \le a \le 8$.
Similarly, you can write the positions of the $2$-labeled tiles as $b$ and $b+3$ for some $1 \le b \le 7$.
Keeping up with the pattern, the $3$-labeled tiles are at $c$ and $c+4$, the $4$-labeled tiles are at $d$ and $d+5$, and the $5$-labeled tiles are at $e$ and $e+6$.
Now suppose you could successfully place all the pairs of tiles.  This means that each of the placement positions $\{1, 2, ..., 10\}$ is covered by exactly one of the values $\{a, a+2, b, b+3, c, c+4, d, d+5, e, e+6\}$.
So that means that the sum of the values $\{1, 2, ..., 10\}$ is the same as the sum of the values $\{a, a+2, b, b+3, c, c+4, d, d+5, e, e+6\}$:
$$
\begin{align}
\sum \{1, 2, ..., 10\} &= \sum \{a, a+2, b, b+3, c, c+4, d, d+5, e, e+6\} \\
55 &= 2a + 2b + 2c + 2d + 2e + 20 \\
&= 2(a+b+c+d+e) + 20
\end{align}
$$
which implies that
$$
2(a+b+c+d+e) = 35
$$
Since $a$, $b$, $c$, $d$, and $e$ are integers, that's not possible.  So such a placement can't happen.

Interview question - numbered tiles


Is it advisable to try to teach myself double bass?

Question: I'm learning bluegrass bass, at the moment, but I really want to eventually play classical music. However, teachers are incredibly expensive and I cannot afford one right now. Should I try to teach myself now or should I wait until I find/can afford a teacher so I don't teach myself bad habits?
I play over 16 other instruments and I only had a teacher for two; piano and organ.
Answer: Well, the bowed string instruments are certainly among the easiest to get technically wrong. I tried to learn cello for more than one year before taking lessons (at the age of 16, incidentally), and not much came of it. Even incredible musical polymath Rob Scallon's cello stuff, while definitely impressive in a way, is really nothing that could be called good cello playing in a classical sense. So if you eventually want to play classical music, you very likely won't get around some real lessons.
But I agree with Tim: bad habits aren't impossible to get rid of; some of them may hinder you a bit longer than if you'd learned it properly straight away, but among the bad habits you'll learn also a couple of good skills automatically, and most importantly get a rough feeling for the instrument, so I'm pretty sure it's better to start badly than to not start at all before learning properly.

In particular, I do think you can become a decent Bluegrass bassist autodidactically. There certainly are quite a lot good self-taught Rockabilly double bassists around.
Comment: `bowed string instruments are certainly among the easiest` Yay!  `to get technically wrong` ... oh.
Answer: You're obviously a seasoned musician, who maybe doesn't even need to pose the question! Teaching yourself will involve finding the notes with the left hand, and I guess for bluegrass plucking the strings, not arco. The notes should be pretty apparent, so no problems there; I'd get started, and later find a teacher to sort out how to bow, which will be needed for the classical stuff. As a current player, go for it. I don't think any 'bad' habits can't be sorted later, but if you're making some good in-tune music, that's nearly going to be there anyway.
Comment: I'm not really a "seasoned" musician; I'm 17, haha. Thank you for the answer!
Answer: I taught myself the double bass.  But I did buy a text book and could already play the cello!  There is no way you will play classical music without a good left hand technique ( and there are several to choose from).  I see a lot of blue Grass / rockabilly bass players ( and bass guitarists) moving their whole hand up and down the finger board with their fingers bunched like bananas; in classical !usic there are just too many notes to play too far apart for that to work.  After 30 odd years, I cracked and took a couple of lessons (£40) and got past a big block I'd been stuck at for years.  Worth it now and then just for a heads up. Good luck.


How i can assign /32 ip address to openstack nova instance without float ip?

Question: I'm developing a custom panel for my openstack home lab via rest api.
I've investigated Hetzner cloud ip (v4) addressing mechanism and i found it is like this:

It is assigning /32 valid ip v4 address and routing via invalid ip for preventing ip wasting.
Is this possible to implement using neutron?
I've read about dhcp options in ovn but i'm not sure.
( the valid ip address in the picture is not assigned to any server )
Answer: It's possible to set dhcp-options on each port using neutron
neutron port-update p1 --extra-dhcp-opt opt_name=netmask,opt_value=255.255.255.255
neutron port-update p1 --extra-dhcp-opt opt_name=classless-static-route,opt_value="192.168.121.121"

And for Windows machines:
neutron port-update p1 --extra-dhcp-opt opt_name=ms-classless-static-route,opt_value="192.168.121.121"


easy calculus thing that i forgot

Question: Suppose $(s_n)$ is a non- negative sequence in $R$. Suppose $m > n $, then is that true that we must have $ (s_n) \subseteq (s_m ) $ and hence we can conclude $ \inf s_n \geq \inf s_m $. but we know that $h_n = \inf_{ k \geq n } s_k $ is a non-decreasing sequence. What am i doing wrong?
Answer: If $m>n$ then the other inclusion holds. That is, $$\{s_n,s_{n+1},\ldots,s_m,s_{m+1},\ldots\}\supset \{s_m,s_{m+1},\ldots\}$$
Comment: gracias CHE !!!!
Comment: De nada. =) , @DonAnselmo.
Answer: If $m > n$, then there is no reason to assume that $(s_n) \subseteq (s_m)$. Choose $s_n = n$ for each $n$, as an example of when this could fail.
The reverse inclusion is true, however, which is consistent with the other part of your question.

easy calculus thing that i forgot


How to detect window size in Next.js SSR using react hook?

Question: I am building an app using Next.js and react-dates.
I have two component DateRangePicker component and DayPickerRangeController component.
I want to render DateRangePicker when the window's width is bigger than size 1180px, if the size is smaller than this I want to render DayPickerRangeController instead.
Here is the code:
      windowSize > 1180 ?
           <DateRangePicker
             startDatePlaceholderText="Start"
             startDate={startDate}
             startDateId="startDate"
             onDatesChange={handleOnDateChange}
             endDate={endDate}
             endDateId="endDate"
             focusedInput={focus}
             transitionDuration={0}
             onFocusChange={(focusedInput) => {
               if (!focusedInput) {
                 setFocus("startDate")
               } else {
                 setFocus(focusedInput)
                }
               }}
                /> :
             <DayPickerRangeController
               isOutsideRange={day => isInclusivelyBeforeDay(day, moment().add(-1, 'days'))}
               startDate={startDate}
               onDatesChange={handleOnDateChange}
               endDate={endDate}
               focusedInput={focus}
               onFocusChange={(focusedInput) => {
               if (!focusedInput) {
                 setFocus("startDate")
                 } else {
                  setFocus(focusedInput)
                 }
               }}
              />
          }

I normally use react hook with window object to detect window screen width like this
But I found that this way is not available when ssr because ssr rendering does not have window object.
Is there an alternative way I can get window size safely regardless of ssr?
Answer: You can avoid calling your detection function in ssr by adding this code:
// make sure your function is being called in client side only
if (typeof window !== 'undefined') {
  // detect window screen width function
}

full example from your link:
import { useState, useEffect } from 'react';

// Usage
function App() {
  const size = useWindowSize();

  return (

      {size.width}px / {size.height}px

  );
}

// Hook
function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    // only execute all the code below in client side
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    // Add event listener
    window.addEventListener("resize", handleResize);

    // Call handler right away so state gets updated with initial window size
    handleResize();

    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount
  return windowSize;
}

NB: Updated as Sergey Dubovik comment, we dont need to validate windows since useEffect run in client side
Comment: If I'm not mistaken, useEffect only runs on client, so if (typeof window !== 'undefined') condition should not be needed
Comment: If you're writing this in Typescript you might get the TS1251: Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'.

If so, just move the handleResize() function outside the if statement
Comment: If I'm not mistaken, this solutions doesn't work if need the window size on initial page load because width and height are set to undefined
Comment: I found that it is necessary to call the `setWindowSize` directly in `useEffect`, and not just pass it in as an argument to `window.addEventListener`. The event listener on "resize" was not sufficient to populate the window dimensions in the initial load of the page.
Answer: While Darryl RN has provided an absolutely correct answer. I'd like to make a small remark: You don't really need to check for the existence of the window object inside useEffect because useEffect only runs client-side and never server-side, and the window object is always available on the client-side.
Comment: This isn't true because nextjs will lint the code and fail to compile with an error about the variable not existing if the undefined case isn't protected against
Comment: I kept seeing this comment about useEffect not running server-side. yet it looked like thats what was happening. Then i noticed that the code i'd used was passing a function into the initial state useState(() => { dosomethingWithWindow}). which was getting called by serverside renderer. So thanks for the reminder that this was the case.
Comment: If this answer didn't work for you, here's another option: https://stackoverflow.com/a/66696801/332578
Answer: useEffect(()=> {
   window.addEventListener('resize', ()=> {
       console.log(window.innerHeight, window.innerWidth)
   })
}, [])

Answer: For some reason I was getting errors, but this worked for me.
Only for width:
const useWidth = () => {
  const [width, setWidth] = useState(0)
  const handleResize = () => setWidth(window.innerWidth)
  useEffect(() => {
      handleResize()
      window.addEventListener('resize', handleResize)
      return () => window.removeEventListener('resize', handleResize)
      // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return width
}

Answer: here's the solution i'm using: a small npm package found here use-window-size
once installed and imported, all you need to do is use it like this:
const { innerWidth, innerHeight, outerHeight, outerWidth } = useWindowSize();

return (

Window width: {innerWidth}

)

Answer: You can make use of 'use client' for this page and just treat it as a client side component, which it will be.
Client side components
Then you can avoid all the hacks because of SSR otherwise.
Answer: I like Darryl RN's solution. If you are facing an issue that size.width is undefined initially when the page loads, just simply initialise the state with window.innerWidth
const [windowSize, setWindowSize] = useState({
  width: window.innerWidth,
  height: window.innerHeight,
});

Answer: Please pay attention to my answer. Since the solutions above will throw an error and say that the size is not defined or equal to 0, depending on what useState is initialized with at the beginning. And this happens because when the page has already been rendered by the server and any override of components occurs, the hook will show the value undefined. To the extent that this is what is specified in useState. The solution is simple and elegant: just call the function in useEffect. The decision is not mine.
type WindowSize = {
  width: number | undefined;
  height: number | undefined;
};

const useWindowSize = (): WindowSize => {
  const [size, setSize] = useState<WindowSize>({
      width: undefined,
      height: undefined,
  });
  useEffect(() => {
    function handleResize(): void {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    handleResize();
    window.addEventListener("resize", handleResize);
    return (): void => window.removeEventListener("resize",
  handleResize);
  }, []);

  return size;
};


How to prove $|a|-|b| \le ||a|-|b||$.

Question: I can't figure out how to prove this. Intuitively, it seems to be true but I still want to see how one can prove this.
Comment: In general we have $x\leq\max\{x,-x\}=|x|$. Now put $x=|a|-|b|$.
Answer: Note that $c=|a|-|b|$ is just some real number.  For any real number $c$, $c\leq |c|$: if $c\geq 0$ then $c=|c|$, and if $c<0$ then $|c|>0$ so $|c|>c$.  Your inequality is then just $c\leq |c|$ in the case $c=|a|-|b|$.
Comment: This is what I needed, thank you so much. I feel so stupid for not recognizing this
Answer: Do you mean $||a||-||b||\leq ||a-b||$?
if yes, we have
$$a=a-b+b$$
Using the triangular inequality, we get
$$||a||=||a-b+b||\leq ||a-b||+||b||$$
Comment: No, it's not that sorry. But I edited my question... can you look at it now?
Comment: It is a similar approach. Please refer  to @Mark comment , there is what you want
Comment: I am not sure you edited it correctly... $$\forall x \in \mathbb{R}   x\leq |x|$$
In particular for $x=|a|-|b|$
Answer: Try your inequality with $a=1$, $b=-1$.
Comment: Wouldn't that not be a proof because it's just one example?
Comment: If you say "all boxes are white", and I show you a black box, then we know that your assertion was false.
Comment: Sorry, I edited my question... can you please look at my question one more time?
Comment: With the current edit, the question is trivial, and it has been answered by Eric.

How to prove $|a|-|b| \le ||a|-|b||$.


Consequences (and Solutions) of Violating SUTVA in a DID Design

Question: Using a difference-in-differences design, what are the consequences of violating the Stable Unit Treatment Value Assumptions (SUTVA)? I ask this because, in my specific field of research (conflict and conflict management), succesful treatments are strongly recognized as geographically "contagious". As a result, it seems like SUTVA will inherently be violated in any form of causal analysis in this area of study. Can the consequence be stated as simply you will have a biased causal estimate if SUTVA is violated? If so, does violating SUTVA using DID bias the estimated causal effect by over- or underestimating the causal effect?
As for solutions, this Wikipedia article states that inverse probability weighting (IPW) can be used to address spillover concerns. However, the article does not provide any citations for this and, after reading the page, I am still a bit confused of how I would apply IPW to a DID design. So this really leaves me with these questions

How exactly does IPW adjust for the violation of SUTVA?
Does the IPW solution work with DID?
Answer: The IPW allows you to build a model of how units select into treatment. For example, adoption probability can be a declining function of geographic distance from the pilot regions. Then these weights down-weight untreated units with very different probability of adoption when you do the DID comparison. The vanilla DID weights all comparison control units equally.
There is R code, examples, and papers cited here.
The fact that only successful treatments are contagious may still present a problem, but it's hard to say more without lots of detail about the setting and how treatment is assigned. It may work if you can control for lagged outcomes and distance to pilot regions in the assignment equation.


Muitos zeros na modal

Question: Criei uma modal de teste na tentativa de retornar o valor do id para a view  e como tem mais de 5000 registros na consulta, não sei o que acontece.. mas imprime um milhão de zeros na modal, será que alguem sabe o pode ser?
Código da janela inteira:
@extends('adminlte::layouts.app')

@section('htmlheader_title')
    Parceiros Lista
@stop

@section('contentheader_title')

@stop

@section('contentheader_description')

@stop

@section('main-content')

    @php
       use App\Http\Controllers\ClienteEnderecoController;
       $cidades = ClienteEnderecoController::getCidades();
    @endphp

                            INCLUIR ENDEREÇO DO PARCEIRO

                        <input type="text" id="id_request" name="id_request" value="" />
                        <input type="text" id="name_request" name="name_request" value="" />
                        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modalCidade">Abrir Modal</button>

                                        <button type="button" class="close" data-dismiss="modal">×</button>

{{ trans('adminlte_lang::message.title') }} - Selecione uma cidade

                                                NOME
                                                CIDADE

                                            @foreach($cidades as $c)

                                                    {{$c->cidade_nome}}

                                                        <button type="button" class="btn-link" onclick="devolveid('{{$c->cidade_id}}', '{{$c->cidade_nome}}')">{{$c->cidade_nome}}</button>
                                                    	0

                                            @endforeach

                                        <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>

@endsection

Método de busca das cidades:
public static function getCidades(){
   return $array = DB::select(
        "Select
            paises.id as pais_id,
            paises.nome as pais_nome,
            estados.id as estado_id,
            estados.nome as estado_nome,
            cidades.id as cidade_id,
            cidades.nome as cidade_nome
        from cidades
        inner join estados
                  on estados.id = cidades.estado_id
        inner join paises
                  on estados.pais_id = paises.id");
}

Imagem:
Comment: Nunca mexi com o laravel mas no seu código tem um 0 dentro do seu `foreach($cidade as $c)`  `0` deve ser esse o motivo.
Comment: Era isso mesmo! Muito obrigado!
Answer: @extends('adminlte::layouts.app')

@section('htmlheader_title')
    Parceiros Lista
@stop

@section('contentheader_title')

@stop

@section('contentheader_description')

@stop

@section('main-content')

    @php
       use App\Http\Controllers\ClienteEnderecoController;
       $cidades = ClienteEnderecoController::getCidades();
    @endphp

                            INCLUIR ENDEREÇO DO PARCEIRO

                        <input type="text" id="id_request" name="id_request" value="" />
                        <input type="text" id="name_request" name="name_request" value="" />
                        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modalCidade">Abrir Modal</button>

                                        <button type="button" class="close" data-dismiss="modal">×</button>

{{ trans('adminlte_lang::message.title') }} - Selecione uma cidade

                                                NOME
                                                CIDADE

                                            @foreach($cidades as $c)

                                                    {{$c->cidade_nome}}

                                                        <button type="button" class="btn-link" onclick="devolveid('{{$c->cidade_id}}', '{{$c->cidade_nome}}')">{{$c->cidade_nome}}</button>

                                            @endforeach

                                        <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button>

@endsection

Estava sobrando um zero, dentro do laço de repetição.
Comment: Beleza! Só dá um aceite na minha resposta :)
Comment: A não eu não acredito.. eu procurei, procurei e não vi! Muito obrigado mesmo!!!

Muitos zeros na modal


Logging to local file with Application Insights

Question: Can Application Insights log to a local file in the application directory? We have an implementation where each customer who uses our software needs to have a separate instance of Application Insights. Our client software relies on a call to a web service to get the Instrumentation Key. We are running into some issues where we need logging before we get the Instrumentation key.
Can Application Insights log to the local file system? Or can it cache logs such that they can be explored? Thanks.
Answer: You can write own channel for this purpose. Implement ITelemetryChannel and use its Send method to write telemetry to local disk.
class FileChannel : ITelemetryChannel
{
    public MyChannel()
    {
    }

    public bool? DeveloperMode { get; set; }
    public string EndpointAddress { get; set; }

    public void Dispose()
    {

    }

    public void Flush()
    {

    }

    public void Send(ITelemetry item)
    {
        // logic to write item to file..
    }
}

Comment: It took me a few minutes to figure out how to configure the custom channel implementation. I added something like this to the ApplicationInsights.config file.

C:\LOGS\AI\


remove multiple double quotes inside array

Question: I have an array that contains 5 elements and 4 double quotes how do I remove just the double quotes while leaving the rest of the elements.
let arr = ["kot"," "," ",","dart","," "];

Answer: you can make use of String.trim and Array.filter
arr = arr.filter(element => element.trim())
the trim method will remove starting and trailing whitespace, so the " " strings will be converted to "". Empty strings are considered falsy, so they will be removed by the filter function.

let arr = ["ruby","javascript","golang","dart","kotlin"," "," "," "," "];

console.log(arr.filter(e => e.trim()));


Why is the map analytic?

Question: The map $$z\mapsto \frac{z-i}{z+i}$$ is an analytic isomorphism of the upper half-plane $\mathbb{H}$ and the unit disc $D=\lbrace w \in \mathbb{C}||w|<1 \rbrace$ .
So , what I do not undertand is that since $-i \ne \mathbb{H}$ the map is analytic . Analytic means holomorphic .Then I know the function $\frac{z-i}{z+i} $ is continuous , but continuous does not imply holomorphic .
Comment: And your question is… ?
Comment: Why is the map analytic ?
Comment: It can be shown that every holomorphic map is analytic, see e.g. [here](https://math.stackexchange.com/questions/1454436/holomorphic-implies-analytic)
Answer: It is an analytic map because it is the quotient of two analytic maps.

Why is the map analytic?


Is there a way to filter out "John Smith" orders in WooCommerce?

Question: According to this thread on the Shopify site: https://community.shopify.com/c/shopify-discussions/john-smith-from-google-utm-google-shopper-creating-false/td-p/538519/highlight/false/page/6
Google uses a bot to check if prices on your e-commerce store are the same as what is listed in Google Merchant Center or in ads. It uses a bot by the name of "John Smith" with several IP and email addresses to create 'fake' orders which don't actually go through.
But this is not a Shopify-specific issue, as you'll see when reading through that thread and googling the topic. The Shopify thread just seems to be the most comprehensive talk on the problem.
Also, according to the thread above, trying to block the bot will result in Google not being able to verify what it needs to show your product listings through its system. So a bot blocker won't be ideal.
QUESTION:
I'm wondering if there is a way to just filter these "John Smith" orders so that they go to the trash bin once they're done being abandoned, and so that they are not sent to store owners? One company is getting "failed order" notices every day from "John Smith" WooCommerce and it's very annoying.
This issue also affect statistics like conversion rate and cart abandonment rate. That's another question but if there is a solution to that, I'd love to know.
Answer: In WooCommerce orders, you can search orders by customer billing name.
Source: Create a customer search filter on the woocommerce order page
About Cart abandonment: This is not Woocommerce core functionality, so that you need to check your custom plugin which you are using to find the cart abandonment
Comment: I understand this is possible to do manually. I'm trying to automate the process however. Cart abandonment doesn't refer to a WooCommerce functionality. It refers to how users use the shop. All e-commerce shops can have abandoned carts. This is a tracking metric. If you meant something else, let me know.
Comment: If i understand you correct then you need a function that will trash the order which customer name "John Smith" automatically after order is created. Let me know if I am correct, so i will provide code snippet according to that.
Comment: Yes that is correct


Parametric Plot for Ellipse

Question: I have two vectors $a$ and $b$ and want to perform a parametric plot that generates an ellipse out of it. Normally you would do that for:
$$t \mapsto \cos(t) \cdot a + \sin(t) \cdot b$$
But when I look up parametric plot, I only find examples like:
$\sin(t), \cos(t)$
or
$t \cdot \sin(t), 5 \cdot \cos(t)$
These plots are defined through commas, one value for $x$ and one for $y$. But how do I know map the definition above to this comma notation?
Comment: No idea. I'm just letting you know that is usually how the ellipse with center $(0,0)$ and radii $a$ and $b$ is usually parametrized.
Comment: "The definition above" is incorrect; you're only specifying one coordinate.
Comment: @QiaochuYuan seems to make sense, since I want to accomplish with the segment between $m$ and $m + a$, $m + b$, where $m,a,b$ are vectors
Comment: I think you want to write that as $$x  = a \cos t$$ $$y  = b \sin t$$ Then note that $${\left( {\frac{x}{a}} \right)^2} + {\left( {\frac{y}{b}} \right)^2} = 1$$
Comment: @PeterTamaroff Okay, but $a$ and $b$ are vectors, how are these written for plotting purposes? For instance gnuplot?
Comment: @PeterTamaroff Ah the center (0,0) I have given a center with a vector $m$, what does that mean for the equation? Is it then for instance $x = (m + a) \cdot \cos t$ ?
Comment: Just make the shift, $x \mapsto x-h$, yes.
Answer: a and b are vectors (over $\mathbb{R}$), so one can write them as $a=(a_1,a_2)$ and $b = (b_1,b_2)$.
Thus your parameterization is
$t \rightarrow (a_1 \cos(t) + b_1 \sin(t), a_2 \cos(t)+b_2 \sin(t)) $ for $t \in [0,2\pi]$.
That should do the trick. Have a play with the numbers $a_1,..,b_2$ and see what the results are when you plot them!
Comment: $(m_1 + a_1 \cos(t) + b_1 \sin(t), m_2 + a_2 \cos(t) + b_2 \sin(t))$.

Note that you'll always get an ellipse unless $a$ and $b$ are linearly dependent.
Comment: Almost! But how do I change the center from $(0,0)$ to $(m_1,m_2)$ with your equation?

Parametric Plot for Ellipse


Ícones em tamanhos diferentes com Bootstrap

Question: Olá, estou estudando o Bootstrap montando um site OpenCart onde o layout tem ícones padrões.
Fiz um módulo HTML para informações com 3 ícones usando Bootstrap,  mas eles seguem o padrão de tamanho do site (CSS):
.fa {
    font-size: 14px;
}

Quero que este ícones tenham tamanho diferenciado, ficando maiores. Não funciona mesmo usando fa-3x. Veja um exemplo aplicado abaixo.
Como faço isto?
"i class="fa fa-truck fa-3x pull-left fa-border"

Comment: Está importando o [Font Awesome](http://fontawesome.io/get-started/) no seu código? - [Fiddle de exemplo](http://jsfiddle.net/pvL9o4sp/)
Comment: Estes ícones que vc está usando são do font awesome, os do bootstrap vc chama com `glyphicon`, e dá pra mudar o tamanho com `"` p.ex. ou pela CSS usando classes etc.
Answer: Como disse no comentário, estes ícones que vc está utilizando não são do Bootstrap, e sim do fontawesome.
Veja aqui os ícones do Bootstrap.
Esta é a forma básica de usar os ícones do Bootstrap:

Exemplo:

Para alterar o tamanho globalmente, utilizando CSS, faça assim:
i.glyphicon {
    font-size: 3em;
}

Ou utilizando classes:
i.glyphicon.minhaclasse {
    font-size: 6em;
}

Criei um fiddle pra demonstrar.
Também é possível alterar o tamanho utilizando span, como disse no comentário:

No fontawesome (que tem muito mais ícones que o bootstrap, mas vc acabará utilizando duas bibliotecas), é basicamente a mesma coisa, com a diferença de que ele já vem com 5 tamanhos pré-definidos: fa-fa-5x. Exemplo:
 Texto vinculado

Não dá certo colocar o style="font-size: 40px" dentro da tag , mas se vc colocar um tamanho como span e ainda o fa-2x, ele dobrará o tamanho determinado pelo span.
No código abaixo, o ícone terá tamanho equivalente a 80px:

Por fim, como disse o @re22, não se esqueça de importar a biblioteca do FA se for utilizá-lo:
<link rel="stylesheet"href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

Ou faça o download, e importe localmente.
(Editei a resposta de novo pra incluir  a sugestão de como usar CSS pra alterar o tamanho, porque agora com a ajuda desta resposta do SOen funcionou (mas não use span se estiver com o Bootstrap 3.0, use , veja acima o fiddle)).
Comment: Obrigado pela orientação. Vou aplicar no projeto e aprendendo a usar melhor o Bootstrap.
Comment: @OmarAlmeida [nesta pergunta](http://pt.stackoverflow.com/questions/59873/o-que-%c3%a9-e-como-funciona-o-bootstrap) tem várias respostas que podem ajudar no começo com o Bootstrap.


Ghostscript - using a font in a form makes it unavailable

Question: I'm seeing some weird behaviour in Ghostscript 9.06 and am wondering whether it's to do with my PS structure or something else.
We have an embedded font defined and then attempt to setup a form and use it as below. Underneath I also have some lines to put text directly on the page without using a form.
<code>globaldict
begin
true setglobal
/frm_test <<
/FormType 1 /BBox [-842 -842 596 596] /Matrix [1 0 0 1 0 0] /PaintProc { pop
/ArialMT 7.0 selectfont
0 0 moveto
(Test text form) show
}   %endPaintProc
>> /Form defineresource pop
/form_test {/frm_test /Form findresource true setglobal execform false setglobal} bind def
%/form_test {/frm_test /Form findresource execform} bind def
false setglobal
end

gsave
10 820 translate
form_test
grestore

/ArialMT 7.0 selectfont
10 800 moveto
(Test text normal) show
showpage
</code>
The problem here is that the call to form_test trashes the font definition for both cases - Ghostscript cannot find the named font. If I never call form_test then the second case works.
If I swap the /form_test line with the commented out one below it, then it works fine. However what is this line doing? It appears to be forcing the form to operate within the global VM region but I'm not sure why this matters, and why any errors propagate to the following 'selectfont' if they occur.
Why can Acrobat Distiller deal with this - is it correct Postscript or not? Thanks.
Edit: Apparently changing the surrounding commands to save/restore instead of gsave/grestore prevents the problem from impacting the second text, but this doesn't explain why the font is unknown within the Form. Also I believe gsave/grestore should be sufficient as the form should have no side-effect except on the graphics state.
Answer: ArailMT is almost certainly not a 'font' its a TrueType font, unless you have embedded a type 42 definition earlier, its always hard to tell from a fragment of a PostScript program.
Why on earth are you doing everything in global VM ? And using globaldict too ? These are both very bad practices, anything in global VM will not be subject to save and restore, so it eats memory until the end of job.
Actually executing the form in a global VM context is even worse, since it will then store any resources defined in the course of the form in global VM. Since you call 'selectofnt' that will define the font resource, unless it is already present. Because you are running with global VM it will define the font in global VM instead of local VM thereby using up more memory.
The PostScript is 'correct', in the same sense that a C program can be lexically correct, but not do what you expect it to.
If you don't have a good reason to use global VM, then don't, is the simplest answer.
Comment: ArialMT is a Type 1 font but I have also tried it with Type 42 fonts. This file is supplied by a client, it's my job to convert to a PDF but Ghostscript is not working while Distiller is. I've just supplied part of it here to reproduce the problem. The change I mentioned above works, so I'll have to do that. It seems the whole file is in a local save/restore but the forms are global so that explains the issue but not why the distiller works. Just another one of those things I guess.