Programmatically retrieve Visual Studio install directory

Question: I know there is a registry key indicating the install directory, but I don't remember what it is off-hand.
I am currently interested in Visual Studio 2008 install directory, though it wouldn't hurt to list others for future reference.
Answer: I use this method to find the installation path of Visual Studio 2010:
    private string GetVisualStudioInstallationPath()
    {
        string installationPath = null;
        if (Environment.Is64BitOperatingSystem)
        {
            installationPath = (string)Registry.GetValue(
               "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\10.0\\",
                "InstallDir",
                null);
        }
        else
        {
            installationPath = (string)Registry.GetValue(
       "HKEY_LOCAL_MACHINE\\SOFTWARE  \\Microsoft\\VisualStudio\\10.0\\",
              "InstallDir",
              null);
        }
        return installationPath;

    }

Comment: This doesn't work if the application doesn't have admin privileges.
Comment: Same here, this isn't populated in Visual Studio Community 2017 15.8.7 either.
Answer: Registry Method
I recommend querying the registry for this information. This gives the actual installation directory without the need for combining paths, and it works for express editions as well. This could be an important distinction depending on what you need to do (e.g. templates get installed to different directories depending on the edition of Visual Studio). The registry locations are as follows (note that Visual Studio is a 32-bit program and will be installed to the 32-bit section of the registry on x64 machines):

Visual Studio: HKLM\SOFTWARE\Microsoft\Visual Studio\Major.Minor:InstallDir
Visual C# Express: HKLM\SOFTWARE\Microsoft\VCSExpress\Major.Minor:InstallDir
Visual Basic Express: HKLM\SOFTWARE\Microsoft\VBExpress\Major.Minor:InstallDir
Visual C++ Express: HKLM\SOFTWARE\Microsoft\VCExpress\Major.Minor:InstallDir

where Major is the major version number, Minor is the minor version number, and the text after the colon is the name of the registry value. For example, the installation directory of Visual Studio 2008 Professional would be located at the HKLM\SOFTWARE\Microsoft\Visual Studio\9.0 key, in the InstallDir value.
Here's a code example that prints the installation directory of several versions of Visual Studio and Visual C# Express:
string visualStudioRegistryKeyPath = @"SOFTWARE\Microsoft\VisualStudio";
string visualCSharpExpressRegistryKeyPath = @"SOFTWARE\Microsoft\VCSExpress";

List<Version> vsVersions = new List<Version>() { new Version("10.0"), new Version("9.0"), new Version("8.0") };
foreach (var version in vsVersions)
{
    foreach (var isExpress in new bool[] { false, true })
    {
        RegistryKey registryBase32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
        RegistryKey vsVersionRegistryKey = registryBase32.OpenSubKey(
            string.Format(@"{0}\{1}.{2}", (isExpress) ? visualCSharpExpressRegistryKeyPath : visualStudioRegistryKeyPath, version.Major, version.Minor));
        if (vsVersionRegistryKey == null) { continue; }
        Console.WriteLine(vsVersionRegistryKey.GetValue("InstallDir", string.Empty).ToString());
    }

Environment Variable Method
The non-express editions of Visual Studio also write an environment variable that you could check, but it gives the location of the common tools directory, not the installation directory, so you'll have to do some path combining. The format of the environment variable is VS*COMNTOOLS where * is the major and minor version number. For example, the environment variable for Visual Studio 2010 is VS100COMNTOOLS and contains a value like C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools.
Here's some example code to print the environment variable for several versions of Visual Studio:
List<Version> vsVersions = new List<Version>() { new Version("10.0"), new Version("9.0"), new Version("8.0") };
foreach (var version in vsVersions)
{
    Console.WriteLine(Path.Combine(Environment.GetEnvironmentVariable(string.Format("VS{0}{1}COMNTOOLS", version.Major, version.Minor)), @"..\IDE"));
}

Comment: On my machine, there is no InstallDir value for Visual Studio Community 2017 (15.0).
Comment: I think starting with Visual Studio 2017 they stopped with the `VSxxxCOMNTOOLS` variable. I wonder if there is another way without Registry.
Answer: I'm sure there's a registry entry as well but I couldn't easily locate it. There is the VS90COMNTOOLS environment variable that you could use as well.
Comment: For VS2017 the path can be found at HKLM\SOFTWARE\Wow6432Node\Microsoft\Visual Studio\SxS\VS17
Comment: This method doesn't work for the express versions of Visual Studio because the environment variable isn't set. The registry method works for all editions of the software.
Comment: See my answer for the registry key
Comment: Does not work for VS2017 as well since there is not variable defined
Comment: @ApostolisBekiaris Unfortunately, not on all systems. I have two independent systems (x86 and x64) with VS2017 installed, and SxS directory doesn't contain any traces of VS2017 on any of those systems.
Answer: Environment: Thanks to Zeb and Sam for the VS*COMNTOOLS environment variable suggestion. To get to the IDE in PowerShell:
$vs = Join-Path $env:VS90COMNTOOLS '..\IDE\devenv.exe'

Registry: Looks like the registry location is HKLM\Software\Microsoft\VisualStudio, with version-specific subkeys for each install. In PowerShell:
$vsRegPath = 'HKLM:\Software\Microsoft\VisualStudio\9.0'
$vs = (Get-ItemProperty $vsRegPath).InstallDir + 'devenv.exe'

[Adapted from here]
Answer: For Visual Studio 2017 and Visual Studio 2019 there is the Setup API from Microsoft.
In C#, just add the NuGet package "Microsoft.VisualStudio.Setup.Configuration.Interop", and use it in this way:
    try {
        var query = new SetupConfiguration();
        var query2 = (ISetupConfiguration2)query;
        var e = query2.EnumAllInstances();

        var helper = (ISetupHelper)query;

        int fetched;
        var instances = new ISetupInstance[1];
        do {
            e.Next(1, instances, out fetched);
            if (fetched > 0)
                Console.WriteLine(instances[0].GetInstallationPath());
        }
        while (fetched > 0);
        return 0;
    }
    catch (COMException ex) when (ex.HResult == REGDB_E_CLASSNOTREG) {
        Console.WriteLine("The query API is not registered. Assuming no instances are installed.");
        return 0;
    }

You can find more samples for VC, C#, and VB here.
Answer: It is a real problem that all Visual Studio versions have their own location. So the solutions here proposed are not generic. However, Microsoft has made a utility available for free (including the source code) that solved this problem (i.e. annoyance). It is called vswhere.exe and you can download it from here. I am very happy with it, and hopefully it will also do for future releases. It makes the whole discussion on this page redundant.
Answer: Ah, the 64-bit machine part was the issue. It turns out I need to make sure I'm running the PowerShell.exe under the syswow64 directory in order to get the x86 registry keys.
Now that wasn't very fun.
Comment: Same for RegEdit: The keys won't show up if you don't run RegEdit from %WINDIR%\SysWOW64
Answer: Use Environment.GetEnvironmentVariable("VS90COMNTOOLS");.
Also in a 64-bit environment, it works for me.
Answer: Here's a solution to always get the path for the latest version:
$vsEnvVars = (dir Env:).Name -match "VS[0-9]{1,3}COMNTOOLS"
$latestVs = $vsEnvVars | Sort-Object | Select -Last 1
$vsPath = Get-Content Env:\$latestVs

Answer: @Dim-Ka has a great answer. If you were curious how you'd implement this in a batch script, this is how.
@echo off
:: BATCH doesn't have logical or, otherwise I'd use it
SET platform=
IF /I [%PROCESSOR_ARCHITECTURE%]==[amd64] set platform=true
IF /I [%PROCESSOR_ARCHITEW6432%]==[amd64] set platform=true

:: default to VS2012 = 11.0
:: the Environment variable VisualStudioVersion is set by devenv.exe
:: if this batch is a child of devenv.exe external tools, we know which version to look at
if not defined VisualStudioVersion SET VisualStudioVersion=11.0

if defined platform (
set VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\%VisualStudioVersion%
)  ELSE (
set VSREGKEY=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\%VisualStudioVersion%
)
for /f "skip=2 tokens=2,*" %%A in ('reg query "%VSREGKEY%" /v InstallDir') do SET VSINSTALLDIR=%%B

echo %VSINSTALLDIR%

Answer: Here is something I have been updating over the years... (for CudaPAD)
Usage examples:
var vsPath = VS_Tools.GetVSPath(avoidPrereleases:true, requiredWorkload:"NativeDesktop");
var vsPath = VS_Tools.GetVSPath();
var vsPath = VS_Tools.GetVSPath(specificVersion:"15");

The drop-in function:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Setup.Configuration;
using System.IO;
using Microsoft.Win32;

static class VS_Tools
{
    public static string GetVSPath(string specificVersion = "", bool avoidPrereleases = true, string requiredWorkload = "")
    {
        string vsPath = "";
        // Method 1 - use "Microsoft.VisualStudio.Setup.Configuration.SetupConfiguration" method.

        // Note: This code has is a heavily modified version of Heath Stewart's code.
        // original source: (Heath Stewart, May 2016) https://github.com/microsoft/vs-setup-samples/blob/80426ad4ba10b7901c69ac0fc914317eb65deabf/Setup.Configuration.CS/Program.cs
        try
        {
            var e = new SetupConfiguration().EnumAllInstances();

            int fetched;
            var instances = new ISetupInstance[1];
            do
            {
                e.Next(1, instances, out fetched);
                if (fetched > 0)
                {
                    var instance2 = (ISetupInstance2)instances[0];
                    var state = instance2.GetState();

                    // Let's make sure this install is complete.
                    if (state != InstanceState.Complete)
                        continue;

                    // If we have a version to match lets make sure to match it.
                    if (!string.IsNullOrWhiteSpace(specificVersion))
                        if (!instances[0].GetInstallationVersion().StartsWith(specificVersion))
                            continue;

                    // If instances[0] is null then skip
                    var catalog = instances[0] as ISetupInstanceCatalog;
                    if (catalog == null)
                        continue;

                    // If there is not installation path lets skip
                    if ((state & InstanceState.Local) != InstanceState.Local)
                        continue;

                    // Let's make sure it has the required workload - if one was given.
                    if (!string.IsNullOrWhiteSpace(requiredWorkload))
                    {
                        if ((state & InstanceState.Registered) == InstanceState.Registered)
                        {
                            if (!(from package in instance2.GetPackages()
                                    where string.Equals(package.GetType(), "Workload", StringComparison.OrdinalIgnoreCase)
                                    where package.GetId().Contains(requiredWorkload)
                                    orderby package.GetId()
                                    select package).Any())
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // Let's save the installation path and make sure it has a value.
                    vsPath = instance2.GetInstallationPath();
                    if (string.IsNullOrWhiteSpace(vsPath))
                        continue;

                    // If specified, avoid Pre-release if possible
                    if (avoidPrereleases && catalog.IsPrerelease())
                        continue;

                    // We found the one we need - lets get out of here
                    return vsPath;
                }
            }
            while (fetched > 0);
        }
        catch (Exception){ }

        if (string.IsNullOrWhiteSpace(vsPath))
            return vsPath;

        // Fall-back Method: Find the location of visual studio (%VS90COMNTOOLS%\..\..\vc\vcvarsall.bat)
        // Note: This code has is a heavily modified version of Kevin Kibler's code.
        // source: (Kevin Kibler, 2014) http://stackoverflow.com/questions/30504/programmatically-retrieve-visual-studio-install-directory
        List<Version> vsVersions = new List<Version>() { new Version("15.0"), new Version("14.0"),
            new Version("13.0"), new Version("12.0"), new Version("11.0") };
        foreach (var version in vsVersions)
        {
            foreach (var isExpress in new bool[] { false, true })
            {
                RegistryKey registryBase32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                RegistryKey vsVersionRegistryKey = registryBase32.OpenSubKey(
                    string.Format(@"{0}\{1}.{2}",
                    (isExpress) ? @"SOFTWARE\Microsoft\VCSExpress" : @"SOFTWARE\Microsoft\VisualStudio",
                    version.Major, version.Minor));
                if (vsVersionRegistryKey == null) { continue; }
                string path = vsVersionRegistryKey.GetValue("InstallDir", string.Empty).ToString();
                if (!string.IsNullOrEmpty(path))
                {
                    path = Directory.GetParent(path).Parent.Parent.FullName;
                    if (File.Exists(path + @"\VC\bin\cl.exe") && File.Exists(path + @"\VC\vcvarsall.bat"))
                    {
                        vsPath = path;
                        break;
                    }
                }
            }
            if (!string.IsNullOrWhiteSpace(vsPath))
                break;
        }
        return vsPath;
    }
}

Answer: Nowadays, I use the following PowerShell command to get the Visual Studio 2017/2019 path (here with the Common7\IDE suffix, so it mimics the DevEnvDir property):
Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | foreach { Get-ItemProperty $_.PsPath } | where { $_.DisplayName -like '*Visual Studio*' -and $_.InstallLocation.Length -gt 0 } | sort InstallDate -Descending | foreach { (Join-Path $_.InstallLocation 'Common7\IDE') } | where { Test-Path $_ } | select -First 1
If you want to execute it from cmd.exe, the command would look like this:
powershell.exe -ExecutionPolicy Bypass -Command "Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | foreach { Get-ItemProperty $_.PsPath } | where { $_.DisplayName -like '*Visual Studio*' -and $_.InstallLocation.Length -gt 0 } | sort InstallDate -Descending | foreach { (Join-Path $_.InstallLocation 'Common7\IDE') } | where { Test-Path $_ } | select -First 1"
I am using it in a C# project, where I use Rider instead of Visual Studio as my IDE (of course I could have also just manually setup the DevEnvDir property in Rider's settings):
<Target Name="MyTarget" BeforeTargets="Build">
  <Exec Condition="'$(DevEnvDir)' == '' Or '$(DevEnvDir)' == '*Undefined*' Or !Exists('$(DevEnvDir)')"
        Command="powershell.exe -ExecutionPolicy Bypass -Command "Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | foreach { Get-ItemProperty $_.PsPath } | where { $_.DisplayName -like '*Visual Studio*' -and $_.InstallLocation.Length -gt 0 } | sort InstallDate -Descending | foreach { (Join-Path $_.InstallLocation 'Common7\IDE') } | where { Test-Path $_ } | select -First 1""
        ConsoleToMSBuild="true">
    <Output TaskParameter="ConsoleOutput" PropertyName="DevEnvDir" />
  </Exec>
</Target>

I use it to get the path to the VS command prompt batch files (like vcvars64.bat or vcvarsall.bat), so I can invoke them before calling MIDL.exe to generate a type library for my IDL file, so my .NET 5 COM classes can register a type library for themselves when the comhost.dll is being registered via regsvr32.exe.
Answer: Aren't there environment settings?
I have VCToolkitInstallDir and VS71COMNTOOLS although I'm using Visual Studio 2003, I don't know if that changed for later versions. Type "set V" at the command line and see if you have them.
Answer: Note that if you're using Visual Studio Express or Visual C++ Express the keynames contain WDExpress or VCExpress, respectively, instead of VisualStudio.
Comment: If you're not answering the actual question, this would probably be more suitable as a comment.
Comment: Agreed, but there are 3 different answers referring to using the Registry; which do you suggest I add a comment to?
Comment: You could add it to all 3, though at more than 3 I would personally just pick the 3 highest scoring answers. If you're allowed to edit answers, you could even add it in. You could also add it as a comment to the original question but the answer is the best place for it.
Answer: You can read the VSINSTALLDIR environment variable.
Answer: This is the easiest solution I came with. It works for x86 and x64, regardless of VS version:
Use
Environment.GetEnvironmentVariable("VSAPPIDDIR")
To get the IDE folder, such as:
"C:\Program Files\Microsoft Visual Studio\2019\Community\Common7\IDE\" On x86 machine.
You can use that to go to any other directory you want, such as:
Dim x = Environment.GetEnvironmentVariable("VSAPPIDDIR").Trim("\"c, "/"c)
x = System.IO.Path.GetDirectoryName(x)
Dim XsdFile = IO.Path.Combine(x, "Packages\Schemas\html\html_5.xsd")

In x64 machine XsdFile will refer to:
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Packages\Schemas\html\html_5.xsd"
Caution: This sems to work with Community edition only!
Answer: For newer versions of VS it is better to use from Microsoft provided APIs, because install information is no longer maintained in registry correctly.

install Nuget package Microsoft.VisualStudio.Setup.Configuration.Native

do the trick (returned is tuple with version and path of all VS instances):
 private const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);

 public static IEnumerable<(string, string)> GetVisualStudioInstallPaths()
 {
     var result = new List<(string, string)>();

     try
     {
         var query = new SetupConfiguration() as ISetupConfiguration2;
         var e = query.EnumAllInstances();

         int fetched;
         var instances = new ISetupInstance[1];

         do
         {
             e.Next(1, instances, out fetched);

             if (fetched > 0)
             {
                 var instance2 = (ISetupInstance2)instances[0];
                 result.Add((instance2.GetInstallationVersion(), instance2.GetInstallationPath()));
             }
         }
         while (fetched > 0);
     }
     catch (COMException ex) when (ex.HResult == REGDB_E_CLASSNOTREG)
     {
     }
     catch (Exception)
     {
     }

     return result;
 }

Regards


is this relation true?

Question: i found this relation in old notes , it's mentioned with no proof , and i want to know if it's true or false
the relation says ,
$$ \sum_{k=1}^n n^6 =  \frac{n^7}{7} + \frac{n^6}{2} + \frac{5}{2} n^5 - \frac{15}{2}n^4 - \frac{31}{6}n^3 + \frac{11}{21}n - 8 $$
is this relation true or not ?
and how can we prove it ?
i think that using induction " if it is true " will be so so hard !
so , any other ideas ?
Comment: Small typo: It should be $\displaystyle\sum_{k=1}^n k^6$. The sum $\displaystyle\sum_{k=1}^n n^6$ is $n^7$.
Answer: Try it with $n=1$. You get -17, which is clearly incorrect. I don't know how to derive an answer nicely, but you can generate eight points, then draw the 7th degree polynomial through them:
$$\frac{n^7}{7} + \frac{n^6}{2} + \frac{n^5}{2} - \frac{n^3}{6} + \frac{n}{42}$$
Answer: The relation is not correct. You want
$$\sum_{k=1}^n k^6=\frac{1}{7}n^7+\frac{1}{2}n^6+\frac{1}{2}n^5-\frac{1}{6}n^3+\frac{1}{42}n.$$
As with any of these identities, it is possible to verify the result by induction, once you have a correct conjecture. The calculation is mildly unpleasant, but utterly mechanical.
There are various ways to derive the result, if we do not know it in advance.
For a detailed discussion, see Faulhaber's Formula.
Answer: Use $$(r+1)^{n+1}-r^{n+1}=\sum_{0\le s\le n}\binom {n+1}s  r^s$$
to find $\sum_{1\le t \le n}r^s$  for $s=1,2,3,5,6$
For $s=0, \sum_{1\le r \le n}r^0=\sum_{1\le r \le n}1=n$
For $n=2, (r+1)^2-r^2=2r+1$
Put $r=1,2,\cdots,n-1,n$ and add to get $$(n+1)^2-1^2=2\sum_{1\le s\le n}r+\sum_{1\le s\le n}1$$
$$\implies 2\sum_{0\le s\le n}r=(n+1)^2-(n+1)\implies \sum_{0\le s\le n}r=\frac{n(n+1)}2$$
For $n=2+1=3,(r+1)^3-r^3=3r^2+3r+1$
Put $r=1,2,\cdots,n-1,n$ and add to get $$(n+1)^3-1^3$$
$$=3\sum_{1\le s\le n}r^2+3\sum_{1\le s\le n}r+\sum_{1\le s\le n}1$$
$$\implies 3\sum_{0\le s\le n}r^2=(n+1)^3-1-3\sum_{1\le s\le n}r-\sum_{1\le s\le n}1$$
$$=(n+1)^3-1-3\frac{n(n+1)}2-n=\frac{n(n+1)(2n+1)}2$$
and so on

is this relation true?


Oracle record type vs object

Question: I have the below objects:
create type dep_rec_typ as object (did number, dnm varchar2(30));

create type emp_rec_type as object (eid number, enm varchar2(30));

create type emp_tab_typ as table of emp_rec_type;

create type dep_det as object ( dep_det dep_rec_typ
                              , emp_det emp_tab_typ );

When I run the below code using the above objects the code run perfectly.
declare
    v_emp emp_rec_type;
    v_dep dep_rec_typ;
    c_dep_dt dep_det;
begin
    select did, dnm
    into v_dep
    where did = 100;

    select eid, enm
    bulk collect into v_emp
    where did = 100;

    select dep_det(v_dep, v_emp)
    into c_dep_dt
    from   dual;

end;

but when I create the above objects at package level using RECORDS, I am facing error.
Please let me know
1.how I can write the same code without using the objects at database level.
2. Why I am facing error when I create RECORDS at package level.
Note: I can not change the structure of any of the objects.
Comment: what error you have facing? and how could you call it from package level?
Comment: Hi the error I face while using records is PLS-00597
Comment: how could you call it from package level? share your execution code.
Answer: You can declare the objects on package header as global variables using "index by" statement, then you can use it on your blocks the same way you would with the object type.
create or replace package test_types as

  -- Declare the types here
  type type_record is record ( p_id number
                             , p_name varchar2(100));
  type type_tab is table of type_record index by PLS_INTEGER;

  -- Declare the global variables here
  global_rec_type type_record;
  global_tab_type type_tab;

end;

then you can use it like this
begin

    test_types.global_rec_type.p_id   := 10;
    test_types.global_rec_type.p_name := 'Name in record';

  begin
    select 1
         , 'Lucas'
      bulk collect into test_types.global_tab_type
      from dual;
  end;

end;

Its not exacltly an object made of Records and Tables but it have the same results that you want.
Answer: Plain PL/SQL records don't have constructors. Therefore in your example, if dep_det is a record type then there is no such function as dep_det(). You would have to create one, perhaps naming it something like new_dep_det, which takes two arguments and returns a dep_det.

Oracle record type vs object


Python Shell - "Extras" in float subtraction

Question:
Possible Duplicate:
Floating Point Limitations

Using Python 2.7 here.
Can someone explain why this happens in the shell?
>>> 5.2-5.0
0.20000000000000018

Searching yielded things about different scales of numbers not producing the right results (a very small number and a very large number), but that seemed pretty general, and considering the numbers I'm using are of the same scale, I don't think that's why this happens.
EDIT: I suppose I didn't define that the "this thing happening" I meant was that it returns 0.2 ... 018 instead of simply resulting in 0.2. I get that print rounds, and removed the print part in the code snippet, as that was misleading.
Comment: There are really three parts to this question: "Why is `5.2 - 5.0 != 0.2`", "Why does evaluating the expression not do the same as printing it", and "Why/how are the repr and str different"? My answer focuses on part 1, Ashwini Chaudhary's is a perfect answer to part 2, and Martijn Pieters's nicely handles part 3.
Comment: See http://docs.python.org/tutorial/floatingpoint.html . It's a much gentler introduction to the issues than the Goldberg paper.
Answer: You need to understand that 5.2-5.0 really is 0.20000000000000018, not 0.2. The standard explanation for this is found in What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you don't want to read all of that, just accept that 5.2, 5.0, and 0.20000000000000018 are all just approximations, as close as the computer can get to the numbers you really way.
Python has some tricks to allow you to not know what every computer scientist should know and still get away with it. The main trick is that str(f)—that is, the human-readable rendition of a floating-point number—is truncated to 12 significant digits, so str(5.2-5.0) is "0.2", not "0.20000000000000018". But sometimes you need all the precision you can get, so repr(f)—that is, the machine-readable rendition—is not truncated, so repr(5.2-5.0) is "0.20000000000000018".
Now the only thing left to understand is what the interpreter shell does. As Ashwini Chaudhary explains, just evaluating something in the shell prints out its repr, while the print statement prints out its str.
Answer: shell uses repr():
In [1]: print repr(5.2-5.0)
0.20000000000000018

In [2]: print str(5.2-5.0)
0.2

In [3]: print 5.2-5.0
0.2

Comment: I apologize, I didn't make my question very clear. I want to know why 5.2-5.0 doesn't simply result in 0.2?
Answer: The default implementation of float.__str__ limits the output to 12 digits only.
Thus, the least significant digits are dropped and what is left is the value 0.2.
To print more digits (if available), use string formatting:
print '%f' % result  # prints 0.200000

That defaults to 6 digits, but you can specify more precision:
print '%.16f' % result  # prints 0.2000000000000002

Alternatively, python offers a newer string formatting method too:
print '{0:.16f}'.format(result)  # prints 0.2000000000000002

Why python produces the 'imprecise' result in the first place has everything to do with the imprecise nature of floating point arithmetic. Use the decimal module instead if you need more predictable precision:
>>> from decimal import *
>>> getcontext().prec = 1
>>> Decimal(5.2) - Decimal(5.0)
Decimal('0.2')

Answer: Python has two different ways of converting an object to a string, the __str__ and __repr__ methods. __str__ is meant to be a normal string output and is used by print; __repr__ is meant to be a more exact representation and is what is displayed when you don't use print, or when you print the contents of a list or dictionary.  __str__ rounds floating-point values.
As for why the actual result of the subtraction is 0.20000000000000018 rather than 0.2 exactly, it has to do with the internal representation of floating point. It's impossible to represent 5.2 exactly because it's an infinitely repeating binary number. The closest that you can come is approximately 5.20000000000000018.


lm regression in R - inconsistent R² for intercept-free model?

Question: I am carrying a linear regression on some data. One of my variables is a factor (categorical). Using regression with an intercept leads to difficult interpretation, since one of the factor levels is taken as the intercept, and the remaining levels are given relative to that. Removing the intercept give me an effect of each level of the factor, which I what I want.
As far as I know, both models are precisely equivalent. They produce identical predictions (on the training set) - to within ~3e-15. However, their R² scores vary wildly.
<code># MWE
library(car)
int <- lm(fscore ~ 1 + partner.status + conformity + fcategory,
          data = Moore)  #with intercept
nint <- lm(fscore ~ 0 + partner.status + conformity + fcategory,
           data = Moore) #w/o intercept
summary(int)$r.squared
summary(nint)$r.squared  #R² values are not remotely the same
max(predict(int)-predict(nint)) #Predictions are essentially identical
</code>
Why are the models not identical? Is it because R² is a comparision of the model to "no model", and that "no model" corresponds to "y=0" and "y=mean(fscore)", for nint and int, respectively?
Comment: You answered your own question in a rather imprecise manner. R^2 is not about "power" which as a precise meaning in statistics. It is about proportion of the variance explained. Incidentally, that `require(car)` call is superfluous. You used no 'car' functions.
Comment: The dataset "Moore" is from "car", hence the requirement. That was the most convenient dataset I could think of. Word "power" removed.
Comment: Sorry. Did search, but presumerably I searched using the wrong words. R and statisticas question are, for whatever reason, far from uncommon on stackoverflow. Feel free to migrate me. I agree that this makes more sense on CVal. And yes - it turns out that this was not a coding question. But I did not know that; the solution could well have been to know about some "perk" in R.
Answer: Seems like "thinking aloud" on Stackoverflow brings clarity to the mind!
This site has a very clear demonstration of the effect: http://www.ats.ucla.edu/stat/mult_pkg/faq/general/noconstant.htm
Also, investigating the description for "r.squared" in the function documentation explains what it does.
<code>?summary.lm #Value::r.squared
#
#r.squared: R^2, the 'fraction of variance explained by the model',
#              R^2 = 1 - Sum(R[i]^2) / Sum((y[i]- y*)^2),
#           where y* is the mean of y[i] if there is an intercept and
#           zero otherwise.
</code>
Comment: Precicely. `summary.lm` gives the uncentered R-squared for models without intercept and the centered R-squared otherwise, as is appropriate.


Interactive Brokers - TWS API - Minimum Price Increment

Question: I am trying to create a TWS API script which will place an order in the STK market. I found out that there are various market rules, which dictate minimum price increment. I queried the system to find out the marketRuleIds, but I cannot figure out how to interpret the results from reqMarketRule, e.g. the market rule ID 557 provides following results:
Price Increment. LowEdge: 0.000000, Increment: 0.000100
Price Increment. LowEdge: 1.000000, Increment: 0.010000

The market rule ID 26 provides following results:
Price Increment. LowEdge: 0.000000, Increment: 0.010000

And the market rule ID 1916 provides following results:
Price Increment. LowEdge: 0.000000, Increment: 0.000001
Price Increment. LowEdge: 0.001000, Increment: 0.000002
Price Increment. LowEdge: 0.002000, Increment: 0.000005
Price Increment. LowEdge: 0.005000, Increment: 0.000010
Price Increment. LowEdge: 0.010000, Increment: 0.000020
Price Increment. LowEdge: 0.020000, Increment: 0.000050
Price Increment. LowEdge: 0.050000, Increment: 0.000100
Price Increment. LowEdge: 0.100000, Increment: 0.000200
Price Increment. LowEdge: 0.200000, Increment: 0.000500
Price Increment. LowEdge: 0.500000, Increment: 0.001000
Price Increment. LowEdge: 1.000000, Increment: 0.002000
Price Increment. LowEdge: 2.000000, Increment: 0.005000
Price Increment. LowEdge: 5.000000, Increment: 0.010000
Price Increment. LowEdge: 10.000000, Increment: 0.020000
Price Increment. LowEdge: 20.000000, Increment: 0.050000
Price Increment. LowEdge: 50.000000, Increment: 0.100000
Price Increment. LowEdge: 100.000000, Increment: 0.200000
Price Increment. LowEdge: 200.000000, Increment: 0.500000
Price Increment. LowEdge: 500.000000, Increment: 1.000000

When I tried to place a trade for a STK with the market rule 1916 within the TWS application, I could see that the increment is 0.50 GBP, but I am not sure how to track it back to the above output.
Can you please help me to figure it out?
Answer: If you want to determine the price increment, you can get the information from contract details.  The minTick field provides you with the minimum price increment for the contract.  For example, on the contract 'QQQ', the minTick is 0.01, meaning you can submit orders that are in U.S. dollars, 1 penny increments.  An order with something that has more than 2 digits to the right of the decimal point will fail.
Comment: Hm, for US it seems OK, as it shows like you said, but e.g. for UK stock, e.g. `ASCL` trading at `LSE` with `GBP`, the `minTick` was `1e-06` or `0.000001`. When I tried to place an bracket order with take profit of `432.65` the system gave an error:

`ERROR 21 110 The price does not conform to the minimum price variation for this contract.`

When I look at TWS, I can see that the increments are round integers, no decimals for this stock.

Any advice?
Comment: I'm baffled by it also.  When I look at ASCL using the IB TWS software, it's priced in $0.20 increments.  I don't have experience trading non-US contracts with the API.  I wonder if it has something to do with the currency conversion; i.e., the currency associated with the contract is GBP and the minTick is also in GBP.
Answer: I got an answer from Reddit comment on the same question. Thank you, major_domo for your help!
Excerpt from the answer provided:
"
Price Increment. LowEdge: 100.000000, Increment: 0.200000
Price Increment. LowEdge: 200.000000, Increment: 0.500000
Price Increment. LowEdge: 500.000000, Increment: 1.000000

or prices above 100, the minimum increment is 0.2; for prices above 200, the minimum increment is 0.5; for prices above 500, it is 1.
I assume the current price is between 200 and 500 if TWS shows the increment is 0.5.
"
Comment: Are those pence or pounds?  There is a price magnifier field that's supposed to be used but IIRC it's only a factor in the UK.  I don't use it.
Comment: Found the post. BTW, lots of info in that thread.  https://groups.io/g/twsapi/message/45468
Comment: The price in the comment is pounds, but it is a good point, I guess each security type needs to be checked explicitly


Como fazer uma "formatação condicional hierarquizada" no Excel 2010?

Question: eu preciso programar uma "formatação condicional hierarquizada" no Excel 2010, com base em duas entradas: o formato da célula à esquerda e se o valor pertence ou não a um dado intervalo.
Para entender melhor do que eu preciso, suponha que eu esteja na célula B1.
Pude definir a primeira condição, cliquei em  clicando em "Usar uma fórmula para determinar quais células devem ser formatadas" e digitei = CÉL ("formato"; A1) = "P1", pois preciso saber se A1 é ou não uma porcentagem.
Além disso, consigo definir a segunda condição clicando em "Formatar apenas células que contenham" e depois em "entre", por exemplo, 0,5 e 0,6.
O problema é que o intervalo desejado depende do formato da célula à esquerda. Por isso, eu queria definir algo assim:
Se (A1 for porcentagem) E (B1 estiver entre 0,5 e 0,6), aplique o formato selecionado.
Se (A1 não for porcentagem) ED (B1 estiver entre 5 e 6), aplique o formato selecionado.
Tentei selecionar "Use uma fórmula para determinar quais células devem ser formatadas" e digite a fórmula abaixo, mas não funcionou!
= E (CÉL ("formato"; A1) = "P1"; AND ("B1> 0,5"; "B1 <0,6"))
Alguém pode me ajudar?
Desde já, muito obrigado.
Answer: Boa noite amigo, tudo bem?
Verifica como está o seu campo de porcentagem, pois em alguns casos dependendo da quantidade de casas decimais, a função (CÉL + Formato) pode te trazer outros retornos.
Veja o exemplo de vários retornos na imagem abaixo:
Outro ponto, acredito que sua condicional esteja incorreta.
Tente implementar a fórmula conforme abaixo:

Fórmula completa:
<code>=OU(E(OU(CÉL("formato";B7)="P0";CÉL("formato";B7)="P1";);E7>=0,5;E7<=0,6);E(OU(CÉL("formato";B7)="G";CÉL("formato";B7)="F0";CÉL("formato";B7)="F1";);E7>=5;E7<=6))
</code>
Comment: Ajudou muito! Obrigado!


Image won't display in select option (HTML)

Question: for some reason my image won't display in my select option.
<select>
   <option>Option 1</option>
   <option>Option 2</option>
   <option>Option 3</option>
</select>

(Code simplified to understand problem, however, there are no special CSS arguments etc. for the options)
Comment: Does this answer your question? [How to add images in select list?](https://stackoverflow.com/questions/2965971/how-to-add-images-in-select-list)
Comment: SO is not documentation.
Answer: <option>'s specification does not permit the use of non-textual information in its definition. MDN's page for <option> spells this out pretty clearly:

Permitted content
Text, possibly with escaped characters (like é).

Suffice to say that  elements for not meet this standard.
Answer: The <option> element, and therefore the select, can only contain text, not images.


Function/Package issue PL/SQL

Question: I am trying to create a package with four functions. Each function will add a set of numbers and subtract one from the total. I have been having lots of trouble getting the syntax correct. The functions below work on their own, and i try calling the first function at the end.
When I try to create the package i get an error where on line 7, " Encountered the symbol "END" when expecting one of the following: begin function pragma procedure subtype type   current cursor delete exists prior 0.05 seconds"
In the package body it says "name is already in use by an existing object". I don't understand as it has to be declared in the specification of the package anyway, and create or replace should solve this if the error is that there is already a package named functionbyfour.
And finally, when I try to use a function in the package, it says " Encountered the symbol "BEGIN" when expecting one of the following: := . ( @ % ; not null range default character The symbol ";" was substituted for "BEGIN" to continue. ORA-06550: line 5, column 43: PLS-00103: Encountered the symbol "FROM" when expecting one of the following: . ( * % & = - + ; < / > at in is mod remainder not rem  <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset me".
I am using ORACLE EXPRESS edition 11g and am new to PL/SQL(4 weeks).
Any input is greatly appreciated.
CREATE OR REPLACE FUNCTION functionbyfour AS

 FUNCTION functone( first number, second number) RETURN NUMBER ;
 FUNCTION functtwo( first number, second number, third number) RETURN NUMBER ;
 FUNCTION functthree(first number, second number, third number, fourth number) RETURN     NUMBER ;
 FUNCTION functfour( first number, second number, third number, fourth number,fifth   number) RETURN NUMBER ;

END  functionbyfour;
/

CREATE OR REPLACE PACKAGE functionbyfour AS

FUNCTION functone (first number, second number ) RETURN number AS total number;
 BEGIN
total:=first + second – 1;
RETURN total;
DBMS_OUTPUT.PUT_LINE(total);
END functone;

FUNCTION functtwo (first number, second number, third number ) RETURN number AS  total     number;
BEGIN
total:=first + second + third – 1;
RETURN total;
DBMS_OUTPUT.PUT_LINE(total);
END functtwo;

FUNCTION functthree (first number, second number,third number, fourth number )     RETURN     number AS total number;
BEGIN
total:=first + second + third + fourth – 1;
RETURN total;
DBMS_OUTPUT.PUT_LINE(total);
END functthree;

FUNCTION functfour (first number, second number, third number, fourth number, fifth     number ) RETURN number AS total number;
BEGIN
total:=first + second + third + fourth + fifth – 1;
RETURN total;
DBMS_OUTPUT.PUT_LINE(total);
END functfour;

/
BEGIN

SELECT functionbyfour.functone(1,2) FROM DUAL;

END;

/
Answer: You would need to create a package named FunctionByFour (CREATE OR REPLACE PACKAGE)
SQL> ed
Wrote file afiedt.buf

  1  CREATE OR REPLACE PACKAGE functionbyfour AS
  2   FUNCTION functone( first number, second number) RETURN NUMBER ;
  3   FUNCTION functtwo( first number, second number, third number) RETURN NUMBER ;
  4   FUNCTION functthree(first number, second number, third number, fourth number) RETURN     NUMBER ;
  5   FUNCTION functfour( first number, second number, third number, fourth number,fifth   number) RETURN NUMBER ;
  6* END  functionbyfour;
  7  /

Package created.

and then a corresponding package body (CREATE OR REPLACE PACKAGE BODY).  You'll also need an END for the package body (right now, your code ends at the end of the fourth function)
SQL> ed
Wrote file afiedt.buf

  1  CREATE OR REPLACE PACKAGE BODY functionbyfour AS
  2    FUNCTION functone (first number, second number ) RETURN number AS total number;
  3    BEGIN
  4      total:=first + second - 1;
  5      RETURN total;
  6      DBMS_OUTPUT.PUT_LINE(total);
  7    END functone;
  8    FUNCTION functtwo (first number, second number, third number ) RETURN number AS  total     number;
  9    BEGIN
 10      total:=first + second + third - 1;
 11      RETURN total;
 12      DBMS_OUTPUT.PUT_LINE(total);
 13    END functtwo;
 14    FUNCTION functthree (first number, second number,third number, fourth number )     RETURN     number AS total number;
 15    BEGIN
 16      total:=first + second + third + fourth - 1;
 17      RETURN total;
 18      DBMS_OUTPUT.PUT_LINE(total);
 19    END functthree;
 20    FUNCTION functfour (first number, second number, third number, fourth number, fifth     number ) RETURN number AS total number;
 21    BEGIN
 22      total:=first + second + third + fourth + fifth - 1;
 23      RETURN total;
 24      DBMS_OUTPUT.PUT_LINE(total);
 25    END functfour;
 26* END functionbyfour;
SQL> /

Package body created.

Once you've done that, you can use the function
SQL> SELECT functionbyfour.functone(1,2) FROM DUAL;

FUNCTIONBYFOUR.FUNCTONE(1,2)
----------------------------
                           2

If you want to put the SELECT statement in a PL/SQL block, you'd need to declare a local variable and do a SELECT INTO to populate the local variable with the result of the function (you could also just assign the local variable the result of the function call without needing to use a SELECT).
SQL> ed
Wrote file afiedt.buf

  1  DECLARE
  2    l_result NUMBER;
  3  BEGIN
  4    -- First approach
  5    l_result := functionByFour.functOne(1,2);
  6    dbms_output.put_line( l_result );
  7    -- Second approach
  8    SELECT functionByFour.functOne(1,2)
  9      INTO l_result
 10      FROM dual;
 11    dbms_output.put_line( l_result );
 12* END;
 13  /
2
2

PL/SQL procedure successfully completed.

Also, be aware that putting a DBMS_OUTPUT.PUT_LINE after your RETURN statement is pointless.  That code can never be reached.  If you want to print the result to the DBMS_OUTPUT buffer, that would need to come before the RETURN.
Answer:
The line
CREATE OR REPLACE FUNCTION functionbyfour AS

should be
CREATE OR REPLACE PACKAGE functionbyfour AS

The line
CREATE OR REPLACE PACKAGE functionbyfour AS

should be
CREATE OR REPLACE PACKAGE BODY functionbyfour AS

The word second is a key word and you can't use it as a parameter name
You need an
END functionbyfour;

After your END functfour to end the package body
Your dbms_outputs will never be executed as they are after the return
You could do all this in one function
 FUNCTION functall(FIRST NUMBER
                     ,sec NUMBER DEFAULT 0
                     ,third NUMBER DEFAULT 0
                     ,fourth NUMBER DEFAULT 0
                     ,fifth NUMBER DEFAULT 0)
  RETURN NUMBER
AS
  total NUMBER;
BEGIN
  total := first + sec + third + fourth + fifth - 1;

  dbms_output.PUT_LINE(total);

  RETURN total;
END functall;

What a strange thing to want to do? :-)
Comment: thanks for input, not sure about second being a keyword, (its not highlighted and it seems to work). Its an assignment, who knows what goes through the mind of a professor? Your code seems a touch easier, but he said he wanted a package with four functions so i'm not going to argue with him.
Comment: Yeah when I said "can't" I should have said "shouldn't" if you have plsql warnings turned on and check user errors you will get the warning PLW-06010: keyword "SECOND" used as a defined name
Answer: You are confused about standalone programs and packages.
CREATE FUNCTION can only be used to create a standalone functiion.  What you have there should be:
CREATE OR REPLACE PACKAGE functionbyfour AS

A package consists of two parts, a specification and a body.  The spec is the public face of the API, the body is the implementation.  What you have as the package (spec) is the package body.  So change that second chunk of code to start
CREATE OR REPLACE PACKAGE BODY functionbyfour AS

and at least you'll have your program structured correctly.
The Oracle PL/SQL documentation is online, comnprehensive and free.  I urge you to read it.  Find out more.

Function/Package issue PL/SQL


What is the negation of the implication statement

Question: In a course on logic and proofs the professor presented on the following lines to show an example of negation:
$$
\neg (P \Rightarrow Q) \ \ \ \  \Longleftrightarrow \ \ \ \ P \wedge \neg Q
$$
I can't wrap my head around why $\neg (P \Rightarrow Q)$ would be equivalent to the RHS of the above statement. Somehow, we are going from the fact the $P$ does not imply $Q$ to a statement that says that $P$ is true and $Q$ is not, while the LHS statement doesn't say anything about $P$ being true. Is it this line or I that am missing something?
The only logical implication that I can make out of this is that:
$ \exists x. P(x) \Rightarrow \neg Q(x)$
Comment: Have you compared truth tables of LHS and RHS?
Comment: A possible reading of $P \to Q$ is: "it is not the case that P is TRUE and Q is FALSE". Thus, its negation will be: "P is TRUE and Q is FALSE".
Comment: Very strongly related: https://math.stackexchange.com/questions/70736/in-classical-logic-why-is-p-rightarrow-q-true-if-p-is-false-and-q-is-tr
Comment: Use truth tables... $P \to Q$ is FALSE only in case $P$ TRUE and $Q$ FALSE. Thus $\lnot (P \to Q)$ is TRUE only in case $P$ TRUE and $Q$ FALSE.
Comment: I think the fault of my logic was that I thought the negation of imply would be *does not necessarily imply*, while for a single statement $P$ (not $P(x)$ being considered for multiple $x$), the negation implies that if P is true Q cannot be true.
Comment: Basically, nothing changes with quantifiers, provided that you properly negate them... The negation of $\forall x \ (Px \to Qx)$ is $\exists x \ \lnot (Px \to Qx)$ that in turn amounts to: $\exists x \ (Px \land \lnot Qx)$ (which is **not** $\exists x \ (Px \to \lnot Qx)$).
Answer: It's because $A\to B$ is equivalent to $(\lnot A)\lor B$ and the negation of that is equivalent to $A\land \lnot B$.
Answer: One way of putting this that might help is the following: what if I told you, "If the real number $x$ is irrational, then $x^2$ is irrational"? (Logically, writing $\mathbb I$ for the set of irrational numbers, this might look like $x \in \mathbb I \to x^2 \in \mathbb I$.) Of course, what I'm saying is false, so you object: "Actually, that's not true. For example $\sqrt{2}$ is irrational, yet $\sqrt{2}^2 = 2$ is rational." (Logically, this looks like $\sqrt{2} \in \mathbb I \land \neg (\sqrt{2}^2 \in \mathbb I)$.)
Do you see how your negation of my statement gave you the conjunction? Do you agree that giving an example where $x \in \mathbb I$ is false, such as $2 \notin \mathbb I \land 4 \notin \mathbb I$ would not have been a refutation of my statement?
Comment: That makes sense. Note that I secretly used quantifiers in my statement too: what I wrote as $x \in \mathbb I \to x^2 \in \mathbb I$ would more reasonably be written as $\forall x(x \in \mathbb I \to x^2 \in \mathbb I)$, and its negation would then be $\exists x(x \in \mathbb I \land \neg(x^2 \in \mathbb I))$. It's a little easier to explain implications with quantifiers. (See also the responses to a post I linked in the comments.)
Comment: Yes, I see your point. I think where I got caught up was that in your example there are irrational numbers for which both $x \in I \wedge x^2 \in I$, so the statement $P \wedge \neg Q$ is not true for all $x$. From what I understand now is that there is a distinction between $P$, and $P(x)$. I think what I was thinking about in my mind was $\exists x. \neg (P(x) \Rightarrow Q(x))$.
Answer: All of this is loose, in layman's terms...
$P \Rightarrow Q$ means if P occurs, so does Q.  $P$ either happens or it doesn't.  So, either $\neg P$ happens or $P$ does, but the latter means $Q$ does, too.  So, you can write out the truth table that $P \Rightarrow Q$ is the same as $\neg P \vee Q$. Now use DeMorgan's law on $\neg (P \Rightarrow Q)$, which is $\neg (\neg P \vee Q)$ as just explained.  This is your right-hand side.
Answer: Try to do the Venn diagram of P / Q! What does "imply" mean in that setting and what does "not imply" mean?
That helped me atleast.
Comment: Thanks, that was useful to think about!
Answer: In logic, an implication ($P\Rightarrow Q$) is false if and only if the hypothesis ($P$) is true and the conclusion ($Q$) is false.
Answer: Your question concerns a statement made in the field of classical logic.
In this field of study one defines what a statement is and one defines what an implication, negation and conjunction is and thereby lays down the foundation of the theory.
Now I think it is important to emphasize that the only "logical" reason why your stated equivalence holds is that it satisfies the specific definition of equivalence within that set up axiomatic system. One could have defined those notions differently and maybe would not be able to prove the stated equivalence in that new system.
So the only way we can prove this statement is by strictly using the definitions of this system and not by using some kind of intuitive logic. I think it is important to remember that.
Additionally we can then try to find arguments that somehow justify the definitions of classical logic and thereby justify your stated equivalence. (And as others have pointed out we can find many such arguments). But still these arguments are merely a justification of the result and have zero relevance for its actual truth.
Answer: Set this up as a truth table
    \begin{matrix}
    P & Q & P\implies Q & \neg(P\implies Q) \\
    0 & 0 & 1 & 0 \\
    0 & 1 & 1 & 0 \\
    1 & 0 & 0 & 1 \\
    1 & 1 & 1 & 0 \\
    \end{matrix}
From this it is apparent that the far right column, the desired negation, is defined as $P \land  \neg(Q)$
Answer: The logical implication $P \Rightarrow Q$ essentially means that "from $P$ it is allowed to infer $Q$".
That is, we are allowed to infer true or false things from false assumptions, but we aren't allowed to infer false things from true assumptions.


Best email server solutions on Windows

Question: We are currently use mdaemon and we have over than 1000 box of email. mdaemon seen to rich is limit because is always crash.
We are looking for another email server, could be exchange or other, support imap, pop3, smtp, syncrhonize calendar
Did you have some mail server to suggest ?
I need the solutions are compatible with windows server solutions
Comment: Gordano sounds like it may be your best bet.
Answer: ~1000 Mailbox's and a Windows solution. While zimbra and google are good, I'm going to give Microsoft this one.
Exchange & Windows server are built for each other. I've seen an Exchange 2000 server still running on Windows 2000 server up until mid '09... It was only replaced because they wanted to use all the new bells and whistles in Outlook 2007!
So for that volume of users, go Exchange. Server 2008 R2 is a fantastic server OS, and Exchange 2007 will do wonders!
Things to consider with exchange: I'm going to assume that they are already running an active directory environment? Are all users located in the 1 building or spread across several... if several, what is the bandwidth like? All the users will need to use Outlook... Exchange does, however, have a nice Outlook Web Access client.
Exchange works of a MAPI protocol, so if 1000 people have outlook open, that 1000 open connections to your exchange server... make sure exchange has it's own server, and plenty of CPU and memory, not to mention storage!
Whats the budget like for this too? Licensing will be the biggest cost for exchange (next to the hardware).
Comment: How cost an exchange server with all the tool ? If i got 10 000 $ to 15 000 $
Comment: http://www.microsoft.com/exchange/2010/en/us/exchange-2007-how-to-buy.aspx#Pricing

Enterprise edition is $3,999 US to start with and that'll give you about 500 mail box's. Best way to get pricing is to find and call a Microsoft Partner. There should be one close to you. Checkout the partner website! https://partner.microsoft.com

Good luck with the project! it may be an expensive exercise but well worth it. Just make sure you also price up a backup system and anti-virus! The minor details people forget till after the project!
Answer: You should consider Zimbra. It will do every you mentionned.
Comment: Zimbra gets my vote every time this question is asked :)
Comment: I need a microsoft solutions, need a server working on Windows
Answer: You told Antoine you need a Mircosoft solution, and if that is true, it's Exchange all the way. "imap, pop3, smtp, syncrhonize calendar", it does all that as well. There are tons of other options out, but for M$ products it is Exchange.
If you can reach out of M$, look at SmarterMail:
http://www.smartertools.com/SmarterMail/Features/Windows-Mail-Server-Software-Webmail-Exchange-Alternative.aspx
Runs on Windows just fine and it's pretty flexible.
Comment: How much cost Exchange, after installing all tools, antivirus, anti spam ... etc
Comment: http://www.microsoft.com/exchange/2010/en/us/exchange-2007-how-to-buy.aspx

Get a barracuda 400: http://www.barracudanetworks.com/ns/products/spam_specs.php

If it *has* to be MS, you'll need ForeFront: http://www.microsoft.com/forefront/serversecurity/exchange/en/us/pricing-licensing.aspx
Comment: I think i good solutions could be like you said, Microsoft Exchange Standard, and a baracuda solutions. I will test that
Answer: What about google apps enterprise?
Comment: We are mail provider for her client, so if we need to paid, for the box, it's not a good solutions for us
Comment: they do do an authorised resellers program:
http://www.google.com/apps/intl/en/business/resellers/index.html
Answer: Preferred mail system/server for a company?
Answer: Nobody has mentioned this yet, but I'll throw modusMail out there for consideration as well.  It's designed for Windows, is a commercially supported product, and has one of the best spam filters that I have ever seen (and they are constantly pushing down updates to the filters if you're on a support plan).  It has a lot of bells and whistles out of the box and lots of options to customize it.  The only downside is that the webmail application that it ships with is rather weak and does not support any sort of calendar or shared notes, etc. like Exchange does.  It is available as software you can download and install or as a managed appliance you can connect to your network.  It is expensive compared to some of the others mentioned but worth every penny.
Answer: Exchange will do all you need, and will give you Active Directory integration as well (which you really should be using with 1000 mailboxes).  If you've nothing against using Exchange then I think this decision makes itself.
Answer: SmarterMail is honestly the most affordable and a very good solution. See the SmarterTools web site for more information. My web host runs this mail server and it's fast and works great.

Best email server solutions on Windows


How are the 4 tables for revisionable and translatable entities in Drupal 8 meant to be used?

Question: There are 4 tables for each type of entity,

entity
entity_revision
entity_field_data
entity_field_revision

How exactly are the individual tables meant to be used?
Answer: The issue queue always covers the decision making process and git blame usually shows the node ids. In this case:
https://drupal.org/node/1498674 https://drupal.org/node/2057401
This is suboptimal and the multilingual team is working on removing SQL queries touching entity table so that the entity storage class can make decisions on the schemas. This is happening at https://drupal.org/node/2068325


jq command to replace array value with non-json value

Question: I need a jq command to replace array values with non-json standard values i.e. in the following json input I need to replace the "webOrigins" array values with a non-json value, which is a Jinja2 template variable replacement as per the second json block below.
Input (example.json)
{
   "clients": [
     {
        "clientId": "abc",
        "webOrigins": [ "/", "/api" ]
     },
     {
        "clientId": "xyz",
        "webOrigins": [ ]
     }
   ]
}

Desired Output
{
   "clients": [
     {
        "clientId": "abc",
        "webOrigins": {{clients.abc.webOrigins}}
     },
     {
        "clientId": "xyz",
        "webOrigins": {{clients.xyz.webOrigins}}
     }
   ]
}

My current attempt of shell script calling jq to loop through the input json and replace with template variable is this
for clientId in $(jq -r '.clients[] | .clientId' example.json)
do
  jq '(.clients[] | select(.clientId == "'${clientId}'") | .webOrigins) |= {{ clients['\'${clientId}\''].webOrigins | default([]) }}' example.json > tmp.j2; mv -f tmp.j2 example.json
done

But fails with the error:
jq: error: syntax error, unexpected '{' (Unix shell quoting issues?) at <top-level>, line 1:
(.clients[] | select(.clientId == "abc") | .webOrigins) |= {{ clients['abc'].webOrigins | default([]) }}
jq: 1 compile error

Of course if I add double quotes around the template variable to make the replacement variable valid json the script works but I need the value to not have quotes.
Comment: Would sth like `jq '.clients[].webOrigins = ""' file | sed 's/""/{{clients.abc.webOrigins}}/g'` do?
Answer: It would be impractical to implement a jq-only solution, but jq can certainly help, e.g. the following works in your case:
jq '.clients[] |= (.webOrigins = "{{clients.\(.clientId).webOrigins}}")' |
    sed '/"webOrigins":/ { s/"[{][{]/{{/; s/[}][}]"$/}}/; }'

Comment: I think you can omit the `[...]` around each brace in the regular expressions; `sed` can tell by context that they aren't part of a bound.
Comment: i ended up going with something like that.


Which headers do I have to supply to NNTP?

Question: This is related to a previous query. Section 1.5 of RFC 5536 mentions that submitted proto-articles may lack some of the mandatory headers that full articles have. Servers will always pass full articles to clients or peers, so they'll fill in missing headers. But what are the optional headers?
Both RFC 5536 and 3977 mention filling in the Message-ID if needed, but not anything else. The examples in 3977 (section 22.214.171.124) imply only From, Newsgroups, and Subject are needed; servers can fill in Message-ID, Date, and Path. That makes sense; is that the actual list?  Is there some official list somewhere, maybe in an obsolete RFC?
Comment: Poking around while reading @AlekseyTsalolikhin answer, I ran across RFC 5537, where Section 3.4.1 confirms my supposition.
Comment: Nice! Thank you for the complete answer.
Answer: The precursors to RFC 5536 are:

https://www.rfc-editor.org/rfc/rfc1036
https://www.rfc-editor.org/rfc/rfc850

RFC 1036 is listed in RFC 5536 (RFC 5536 obsoletes RFC 1036).
RFC 1036 says:
The required header lines are "From", "Date", "Newsgroups", "Subject", "Message-ID", and "Path".
Update: see https://www.rfc-editor.org/rfc/rfc5537 (thanks CTMacUser) which says,
<code>any of the following mandatory header fields MAY be omitted:
   Message-ID, Date, and Path.
</code>
Comment: Posts through the Netnews system must be complete, but some of those required headers can be left out by the poster and filled in by the first server. See my comment on the original post for more.


Time Application Startup

Question: Is there anyway to time how long it takes an Application to start up on the Mac?
We were getting reports of Word 2008 taking a half-hour to launch, and, while we think we've resolved the problem, it would be nice, in the future, to be able to:

verify the veracity of such statements, and
see if any of our changes make a difference.
Comment: Can this question please be moved to Stackoverflow?  I don't seem to be able to flag it or vote for it to be moved.  [In the worst case, I will ask it again.]
Comment: I think this question is okay for Serverfault.
Answer: You can always use the command line, with a command like:
<code>time open -a Word <some_word_doc.docx>
</code>
Edit:
As pointed out, this method will exit as sun as the splash screen appears. Some research led me to an apple doc page explaining how to profile applications launch time (link). You will need the Apple developer tools installed. The method using the Shark tool works even for applications for which we do not have the source code available. From my testings the launch time appears in the chart tab, in the X axis of the chart.
I do not know how accurate this method is, since I'm not an experienced developer in OSX.
Comment: I'm glad I double-check the post.  I'd no idea you'd edited it.  There is an environment variable called NSQuitAfterLaunch mentioned in the article that looks really useful!
Comment: Excellent suggestion.  Unfortunately, it returned as soon as the splash screen came up (and my intention is to time how long it takes until Word is in a useable state).
Comment: Yes, you are right. I was not with my mac when I wrote the reply. See me edit with new information
Answer: How did you solve the issue?  I've seen that in the past on Windows boxes where Normal.dot got corrupted, causing an extremely slow word startup.  The solution was to delete the .dot template, start up word again, and let it recreate that default template
Comment: Our solution involved hoping it was an AFP bug and upgrading our servers and desktops from OS X 10.5.4 to the latest - 10.5.6 at the time.  [We also redirected the Cache folder, but did that some time ago and were still having problems.]  It seems to have resolved the issue, but I'd love to have some stats to know for sure.  See also http://serverfault.com/questions/8715/office-2008-with-network-mobile-accounts

Time Application Startup


how to do drag and drop image/file upload using javaScript

Question: javaScript. I want to upload image or file with the help of dropzone. when file uploaded then at a time file should be display..

    <meta charset="utf-8">
    <title>variables</title>

File Upload Drop Zone

    <form id="upload_form" enctype="multipart/form-data" method="post">
      <input type="file" name="file1" id="file1">

      <input type="button" value="Upload File" onclick="uploadFile()">
      <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>

    </form>

can you tell me where i am wrong and what is problems...
can we use upload file with the help of ajax if yes then please send me code how will we upload file and image
Answer: Please refer the tutorial for ajax image upload in PHP:
https://www.formget.com/ajax-image-upload-php/


Tool to generate monthly traffic reports for IIS sites?

Question: We want to calculate a monthly total of uploads and downloads for each of our IIS sites.
Can we generate this from the IIS logs?
Thanks,
Ashley
Answer: I think either Analog or AWStats would be able to give you what you require
Edited to add: Re-reading your question - Do you just want to know about uploads\download of certain files? Or total traffic transferred for your website(s)?
Comment: Thanks Ben, we want just the total traffic for billing purposes.
Comment: No worries, glad it was of use!

There are many options in both tools' configuration files, so you should be able to get the data out that you're after


Showing that if the intersection of all subgroups other than $\langle e \rangle$ is not $\langle e \rangle$, then every element is of finite order

Question: This is problem 2 on page 46 of I. N. Herstein's Topics in Algebra.

Let $G$ be a group such that the intersection of all its subgroups which are different from  $\langle e\rangle$ is a subgroup different from $\langle e\rangle$. Prove that every element in $G$ has finite order.
Comment: [related](http://math.stackexchange.com/questions/879196/a-persisting-element-in-all-subgroups)
Comment: In case MSE doesn't notify you of edits, I've updated my answer.
Answer: Hint: Assume that not every element has finite order; i.e., that there is an element $a$ of infinite order.  What can you say about the intersection of the non-trivial subgroups of the cyclic subgroup $\langle a\rangle$.
Answer: A simpler answer than my previous one:
Consider
$$H=\bigcap_{g\in G} \langle g\rangle$$
The intersection of cyclic groups is cyclic, so either
(1) $H=\langle h\rangle$ with $\text{ord}_G(h)=n<\infty$
(2) $H=\langle h\rangle\cong \Bbb Z$ whence $\langle h^2\rangle$ is a proper subgroup, contradicting that $H$ was the intersection of all cyclic subgroups of $G$.
So the intersection has finite order. Since $n\ne 1$ by assumption, every $g\in G$ has that $\langle h\rangle \le \langle g\rangle$, but every non-identity element of an infinite cyclic group has infinite order, and clearly $h\in\langle g\rangle$ does not, so $|\langle g\rangle|<\infty$
Comment: [Source for the isomorphism claim](https://math.stackexchange.com/questions/1793735/prove-that-if-g-is-cyclic-and-infinite-then-g-is-isomorphic-to-mathbbz)
Comment: https://proofwiki.org/wiki/Subgroups_of_Additive_Group_of_Integers#:~:text=Every%20non%2Dtrivial%20subgroup%20of,has%20the%20form%20nZ.
Answer: Let $a \neq e$ be an element from that intersection. If $a^2=e$, then $a$ has order $2$. Otherwise, $a \in \langle a^2 \rangle$, so $a=a^{2k}$, for some integer $k$, which implies $a^{2k-1}=e$, so $a$ has finite order. Either way $a$ has finite order.
Now let $g \in G$ be arbitrary. Since $a \in \langle g \rangle$, it follows that $g^{\ell}=a$ for some integer $\ell$, so $g^{\ell \cdot \mathrm{ord}(a)}=e$, so the order of $g$ is finite.
Comment: The expression  " if $a$  is not of order $2$, then $a\in \langle a^2 \rangle$" is not correct, perhaps you mean something else?
Comment: @mesel According to the hypothesis, $a$ is contained in **any** nontrivial subgroup of $G.$ If $\mathrm{ord}(a) \neq 2,$ then $\langle a^2 \rangle$ is a nontrivial subgroup of $G$, and so $a \in \langle a^2 \rangle.$
Comment: Now, I see what you mean.


Use Beam files to start an application in Elixir

Question: I am working on Elixir project where i have to register three dependencies say "xxx, yyy & zzz" for the project. I have done deps.get on those repositories and compiled that. But, i checked after compilation no ".app" file is generated for xxx dependency but only beam files. yyy & zzz got compiled with .app files and application got started as well. So, Can i use generated/compiled xxx beam files in mix.exs anyhow to start an application for xxx dependency.Application is defined like below in mix.exs file,
def application do
[applications: [:yyy, :xxx, :zzz],
 mod: {Practice, []}]
end

Answer: If the application has no app file, you do not need to specify it in the applications list as you did in your code snippet. Instead just pass app: false as an option where the dependency is defined.
PS: Please don't double post your issues on Stack Overflow and in the Elixir mailing list. Pick one as both are checked regularly by many developers in the community.


SQL Server 2005 -- Not Able To Export Using Management Studio Express

Question: I heard this was not available with the free express version.
I need to move a moderately sized database to another computer.
How can I most easily accomplish this task?
We are not in a position to buy any software at the moment.
Thanks for any suggestions! :)
Answer: Backup and Restore? Detach and Attach?
Answer: By default there's no tools visible in the IDE but you can access the DTSWizard to do import/export if you've got the SQL with Advanced Services installed (free).
You'll find it in Program Files\Microsoft SQL Server\90\DTS\Binn\DTSWizard.exe - I add it as an External Tool in the Tools menu for ease.
But if you're just moving the whole DB then then joeqwerty's options should do you fine...


Convergence of a series of complex numbers that are dense on the unit circle

Question: Let me introduce my problem: Let $C \subset \mathbb{C}$ be the unit circle of the complex plane and $Z=\left\{ z_n \right\}_{n \in \mathbb{N}} \subset C$ be a dense subset of the unit circle meaning that $\bar{Z}=C$ or otherwise put that for all $c \in C$ there is a subsequence $\left\{z_{n_{k}}\right\}_{k \in \mathbb{N}}$ of $Z$ such that $z_{n_{k}} \xrightarrow{k} c$. I want to know whether the following series converges:
\begin{align*}
\sum_{j\in\mathbb{N}}z_n
\end{align*}
For every $z_j$ on the unit circle there is it's anti-diametric $\hat{z_j}=-z_j$ and for all $\varepsilon>0$ we can find an index $\hat{j}\in\mathbb{N}$ so that $|\hat{z_j}-z_{\hat{j}}|<\varepsilon\Leftrightarrow  |z_j+z_{\hat{j}}|<\varepsilon$.
If we group all members of the sequence this way (pairwise for a given $\varepsilon$) then the sum can be written in the following form:
\begin{align*}
\sum_{j\in\mathbb{N}}z_n=\left(z_1+z_{\hat{1}}\right)+
\left(z_{k_2}+z_{\hat{k_2}}\right)+\ldots
\end{align*}
Then by the triangular inequality:
\begin{align*}
\sum_{j\in\mathbb{N}}z_n \le
|\sum_{j\in\mathbb{N}}z_n| \le
\left|z_1+z_{\hat{1}}\right|+
\left|z_{k_2}+z_{\hat{k_2}}\right|+\ldots \le
\varepsilon + \varepsilon + \ldots
\end{align*}
So this way I don't prove that the series converges. Is there some other way to prove it or it doesn't hold at all? (Anyway I think it was not a good idea to use the absolute value there...).
And a second question on that: If $\left\{a_n\right\}_{n\in \mathbb{N}}$ is a real sequence such that $\sum_{j\in\mathbb{N}}a_n$ converges then $\sum_{j\in\mathbb{N}}a_nz_n$ converges (following the same procedure described above). Can we somehow loosen the conditions on $\left\{a_n\right\}_{n\in \mathbb{N}}$ ? Are there weaker conditions on the sequence $a_n$ so that the series will converge?
Update 1: Does this series converge:
\begin{align*}
\sum_{n\in\mathbb{N}}e^{2\pi\vartheta\alpha}
\end{align*}
with $\alpha\in \mathbb{R} - \mathbb{Q}$ ?
Comment: Let $z_n = e^{2i\pi \theta n}$, with $\theta$ some irrational number. Then $z_n$ is dense on the unit circle and serves your assumptions. But you can easily pick a series of vectors near to $1$, s.t. the series of partial sums diverges into infinity. Doesn't this contradict your postulate? You can make the series convergent of you just choose any order s.t. suceeding elements cancel out each other sufficiently well. But you may miss elements if you construct that sequence.
Answer: Like others have already said, your series is not convergent because the terms don't get smaller as $n \rightarrow \infty$, and this the case no matter how you order your terms.
What you sketched was instead a proof that if we "pack together" some of the terms and rearrange the packs, then we obtain a series $\Sigma (z_{i_n} + z_{j_n})$ which is convergent.
Indeed, you can pick the index sequences $i_n$ and $j_n$ as follows :
Pick $i_n =$ the smallest integer which was not picked for one of the previous $i_k$ or $j_k$ for $k<n$.
Then pick $j_n =$ any index such that $|z_{i_n} + z_{j_n}| < 2^{-n}$ which is not already picked.
$j_n$ exists because of the density hypothesis, and with this procedure, you will pick every element of the sequence (the index $k$ will be picked for $n \le k$ somewhere).
So you can obtain a convergent series.
However, with some other way of packing things, you will get a divergent series, and you can also get a series that converges to any complex number you want.
With this method, your series can do whatever it wants.
There are some kind of series for which no matter how you pack terms together, you will always obtain the same result, they are the absolutely convergent series.
If $\Sigma |z_n|$ is convergent, then no matter how you order or pack your terms, you will obtain the same limit everytime.
But with other series, anything can happen. You can also turn convergent series who are not absolutely convergent into divergent series if you pack/reorder things in a bad way.
Comment: The singular of "series" is "series".
Comment: @joriki : so that's why I had a weird feeling when reading everything else ! I guess you're right (but it still seems weird)
Answer: This certainly wouldn't be absolutely convergent, so it's convergence is dependent on the order of the terms, yet you do not have any specified order.  I can think of an ordering for which the sequence certainly diverges, that is one which starts from the center of the circle and works its way out that looks like:
\begin{align*}
\sum_{j\in\mathbb{N}}(z_j + \hat{z}_j)
\end{align*}
Answer: A necessary condition for a series to converge is that the terms go to zero, so no, the series does not converge.  However, for some dense sequences in the circle there will be summability methods that apply.
I believe that there also exist real sequences $(a_n)_n$ and sequences $(z_n)_n$ dense in the circle such that $\sum a_n$ converges but $\sum a_n z_n$ does not.  To get an example you would have to start with a conditionally convergent series $\sum a_n$ such as the alternating harmonic series $1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\cdots$.  Sorry for not making this rigorous, but if you choose a sequence $(z_n)_n$ dense in the circle such that "enough" of the odd terms are "close enough" to $1$ and "enough" of the even terms are "close enough" to $-1$, then you can make the series diverge.


Como colocar array de imagens em div separados?

Question: Comecei o guia MDN e criei uma galeria de imagem no Codepen - Galeria de imagens, seguindo o tutorial MDN - Javascript construindo blocos.
Depois de criar a galeria de imagens, me senti na necessidade de acrescentar alguns estilos para as imagens da galeria, como colocar as imagens em um circulo. Adicionei border-radius: 50%; e a imagem ficou com oval e não circulo.
Quero colocar cada imagem em uma div para configura o css direto ao div, como faço isso?
Segue o código abaixo:
<code>const displayedImage = document.querySelector('.displayed-img');
const thumbBar = document.querySelector('.thumb-bar');
const images = [`https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic1.jpg`,
                `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic2.jpg`,
                `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic3.jpg`,
                `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic4.jpg`,
                `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic5.jpg`];

for (const image of images) {
  const newImage = document.createElement('img');
  newImage.setAttribute('src', `${image}`);
  thumbBar.appendChild(newImage);
  newImage.addEventListener('click', e => displayedImage.src = e.target.src);
}
</code>
Answer: Respondendo primeiramente sua dúvida de como inserir as imagens dentro de uma div, segue abaixo como fiz:
<code>  const newDiv = document.createElement('div');
  newDiv.classList.add('thumb');
  const newImage = document.createElement('img');
  newImage.setAttribute('src', `${image}`);
  newImage.addEventListener('click', e => displayedImage.src = e.target.src);
  newDiv.appendChild(newImage);
  thumbBar.appendChild(newDiv);
</code>
Eu testei aqui e ficou redondinho as fotos, vou postar o código completo, mas depois você coloca o estilo como você achar melhor, segue o CSS e JS:
CSS:
<code>    img {
  width:auto;
  height:auto;
  max-width:100%;
}
button {
 border: 0;
 background: rgba(150,150,150,0.6);
 text-shadow: 1px 1px 1px white;
 border: 1px solid #999;
 position: absolute;
 cursor: pointer;
 top: 2px;
 left: 2px;
}
.thumb-bar {
  display: flex;
  width: 100%;
  height: 100%;
  gap: 50px;

}

.thumb {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
}

.thumb-bar img {
 cursor: pointer;
 overflow: hidden;
 object-fit: cover;
}
</code>
JS:
<code>    const displayedImage = document.querySelector('.displayed-img');
    const thumbBar = document.querySelector('.thumb-bar');
    const images = [
      `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic1.jpg`,
      `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic2.jpg`,
      `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic3.jpg`,
      `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic4.jpg`,
      `https://raw.githubusercontent.com/risoweb/risoweb.github.io/master/pic5.jpg`
    ];

  for (const image of images) {
    const newDiv = document.createElement('div');
    newDiv.classList.add('thumb');
    const newImage = document.createElement('img');
    newImage.setAttribute('src', `${image}`);
    newImage.addEventListener('click', e => displayedImage.src = e.target.src);
    newDiv.appendChild(newImage);
    thumbBar.appendChild(newDiv);
  }
</code>
Comment: Olá, gostaria de saber se você criou um novo elemento para const newDiv e anexou o div?
Comment: Quando eu crio a variável newDiv eu já uso o método createElement, depois eu usso o classList.add para adicionar a classe 'thumb' nessa div criada. Depois eu crio o elemento da imagem e uso método appendChild na div para inserir a imagem dentro do elemento div, assim para cada div você vai ter uma imagem. Era isso sua dúvida?
Comment: Entendi que você criou uma variável e usou um método, até ai tudo beleza. Não consigo ver  o elemento div que está usando o método appendChild para interagir com o css e arredondar o circulo que esta oval. Gostaria de colocar os div arredondados, como círculos mesmo e mover a imagem para cima ou para baixo conforme a necessidade. Você pode acompanhar no Codepen como está o css, pois acredito que o css faz toda a diferença no estilo deste estudo. https://codepen.io/ilson-ricardo/pen/YzeYGxW?editors=0100
Comment: E o pior que ainda vou flutuar esse div para cima da imagem principal, como estão o botão cinza no alto. Por isso preciso entender perfeitamente esse css, estou faz algumas semanas com o pensamento nesse estudo e já consumi todo energia mental para absorver o JavaScript, espero que depois disso tudo sobre um pouco de energia para estudar os Objetos JavaScript ;)


Async call in API made in Django

Question: I am using DRF with Twilio SMS sending service. I have added this code on some object save - which I do in some of the API calls. But as I can see Django waits for Twilio code to be executed (which probably waits for response) and it takes around 1-2 seconds to get response from Twilio server.
I would like to optimize my API, but I am not sure how should I send a request for Twilio SMS asynchronously. This is my code.
<code>def send_sms_registration(sender, instance, **kwargs):
    start = int(round(time.time() * 1000))

    if not instance.ignore_sms:
        client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

        activation_code = instance.activation_code

        client.messages.create(
            to      = instance.phone_number,
            from_   = DEFAULT_SMS_NAME,
            body    = SMS_REGISTRATION_TEXT + activation_code,
        )

    end = int(round(time.time() * 1000))
    print("send_sms_registration")
    print(end - start)

post_save.connect(send_sms_registration, sender=Person, dispatch_uid="send_sms_registration")
</code>
Thanks for suggestions!
Answer: The API call is not asynchronous, you need to use other methods to make sending SMS async, you can use any of the following:

django-background-tasks: Simple and doesn't require a worker
python-rq: Great for simple async tasks
celery: A more complete solution

Async call in API made in Django


dereferencing pointer to incomplete type with struct ip and also with struct iphdr

Question: hello i'm trying to parse some packets, and when using struct ip i get the: "dereferencing pointer to incomplete type" error message.
So i tryed then with struct iphdr but still have the same problem
Here is the function i'm using for parsing the packet:
PrintPacketInHex(char *mesg, unsigned char *p, int len){
printf(mesg);
while(len--){
printf("%.2X ",*p);
p++;
}
}

/*parse the sniffed packets*/

ParseEthernetHeader(unsigned char *packet, int len){
struct ethhdr *ethernet_header;
struct ip *ip_header;
//+sizeof(struct iphdr)
if(len> sizeof(struct ethhdr)){
ethernet_header = (struct ethhdr*) packet;
packet = packet +16;
ip_header = (struct ip*) packet;

/* first set of 6 bytes are destination MAC*/

PrintPacketInHex("destination MAC : ", ethernet_header->h_dest,6);
printf("\n");

/*scond set of 6 bytes are source MAC */

PrintPacketInHex("source MAC : ", ethernet_header->h_source,6);
printf("\n");

/*last 2 bytes in ethernet header are the protocol in carries */

PrintPacketInHex("protocol: ", (void*)&ethernet_header->h_proto,2);
printf("\n");

/*the next 4 bytes are ip version bytes */

PrintPacketInHex("ip version: ", ip_header->ip_v,4);
printf("\n");

/*the next 4 bytes are internet header length */

PrintPacketInHex("internet header length: ", ip_header->ip_ihl,4);
printf("\n");

/*the next 8 bytes are type of srvice bytes */

PrintPacketInHex("type of service: ", ip_header->ip_tos,8);
printf("\n");

/*the next 8 bytes are total length bytes */

PrintPacketInHex("total length: ", ip_header->ip_len,16);
printf("\n");

/*the next 8 bytes are identification bytes */

PrintPacketInHex("identification: ", ip_header->ip_id,16);
printf("\n");

/*the next 8 bytes are flags bytes

PrintPacketInHex("Flags: ", "flags",3);
printf("\n");*/

/*the next 13 bytes flags and offset bytes */

PrintPacketInHex("offset: ", ip_header->ip_off,16);
printf("\n");

/*the next 8 bytes time to live bytes */
PrintPacketInHex("time to live: ", ip_header->ip_ttl,8);
printf("\n");

/*the next 8 bytes protocol bytes */

PrintPacketInHex("protocol: ", ip_header->ip_p,8);
printf("\n");

/*the next 16 bytes are checksum bytes */

PrintPacketInHex("checksum: ", ip_header->ip_sum,16);
printf("\n");

/*the next 32 bytes source ip adress bytes */

PrintPacketInHex("source ip: ", ip_header->ip_src,32);
printf("\n");

/*the next 32 bytes destination ip adress bytes */

PrintPacketInHex("destination ip: ", ip_header->dip_dst,32);
printf("\n");
}
else printf("packet size too small ! \n");
}

i know that there are other errors in the program but want to solve this problem before looking for other problems.
thank you
Comment: Have you included the header file which defines the structure `ip`?
Comment: Where is `struct ip` defined?
Answer: Your compilation unit must include the definitions of struct ethhdr and struct ip for you to be able to access their members.
Comment: thank you, it was a stupid mistake of mine :D, i forgot to include netinet.h


Interpreting compact letter displays and Tukey multiple comparisons from glmm

Question: I am conducting Tukey HSDs with compact letter displays on a series of glmms. One example is how the presence/absence of ticks on an animal varies based on several parameters (using lme4 in R):
model <- glmer(ticks.pa ~ Month.factor + Perturb3*Sex + Age2+(1|CurrentChip),
               family=binomial, data=temp)

I am then using Tukey HSDs to look post-hoc at differences between specific levels of Month and Perturb3 (both categorical; using multcomp package).  For example:
summary(glht(model,mcp(Month.factor="Tukey")))

Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Tukey Contrasts

Fit: glmer(formula = ticks.pa ~ Month.factor + Perturb3 * Sex + Age2 + (1 | CurrentChip), data = temp, family = binomial)

Linear Hypotheses:

                  Estimate  Std. Error z value   Pr(>|z|)
2 - 1 == 0    16.0812    66.0132   0.244  1.00000
3 - 1 == 0    15.2714    66.0136   0.231  1.00000
5 - 1 == 0    14.6938    66.0132   0.223  1.00000
6 - 1 == 0    14.2554    66.0132   0.216  1.00000
7 - 1 == 0    15.4118    66.0253   0.233  1.00000
8 - 1 == 0   -16.1893    48.4404  -0.334  1.00000
9 - 1 == 0   -18.2058    48.4348  -0.376  1.00000
10 - 1 == 0  -17.4837    48.4350  -0.361  1.00000
11 - 1 == 0  -18.0147    48.4351  -0.372  1.00000
12 - 1 == 0   -1.7331     0.4929  -3.516  0.00728 **
3 - 2 == 0    -0.8098     0.5412  -1.496  0.83237
5 - 2 == 0    -1.3874     0.4859  -2.855  0.06405 .
6 - 2 == 0    -1.8258     0.4832  -3.779  0.00264 **
7 - 2 == 0    -0.6694     1.3943  -0.480  0.99998
8 - 2 == 0   -32.2705    77.9376  -0.414  0.99999
9 - 2 == 0   -34.2869    77.9334  -0.440  0.99999
10 - 2 == 0  -33.5649    77.9337  -0.431  0.99999
11 - 2 == 0  -34.0959    77.9335  -0.437  0.99999
12 - 2 == 0  -17.8143    66.0149  -0.270  1.00000
5 - 3 == 0    -0.5776     0.4841  -1.193  0.95602
6 - 3 == 0    -1.0160     0.4773  -2.129  0.37218
7 - 3 == 0     0.1405     1.3983   0.100  1.00000
8 - 3 == 0   -31.4607    77.9378  -0.404  1.00000
9 - 3 == 0   -33.4771    77.9337  -0.430  0.99999
10 - 3 == 0  -32.7550    77.9340  -0.420  0.99999
11 - 3 == 0  -33.2860    77.9338  -0.427  0.99999
12 - 3 == 0  -17.0044    66.0153  -0.258  1.00000
6 - 5 == 0    -0.4384     0.3786  -1.158  0.96403
7 - 5 == 0     0.7180     1.3258   0.542  0.99993
8 - 5 == 0   -30.8831    77.9375  -0.396  1.00000
9 - 5 == 0   -32.8995    77.9334  -0.422  0.99999
10 - 5 == 0  -32.1775    77.9336  -0.413  0.99999
11 - 5 == 0  -32.7085    77.9335  -0.420  0.99999
12 - 5 == 0  -16.4269    66.0148  -0.249  1.00000
7 - 6 == 0     1.1564     1.3529   0.855  0.99633
8 - 6 == 0   -30.4447    77.9375  -0.391  1.00000
9 - 6 == 0   -32.4611    77.9334  -0.417  0.99999
10 - 6 == 0  -31.7391    77.9337  -0.407  1.00000
11 - 6 == 0  -32.2701    77.9335  -0.414  0.99999
12 - 6 == 0  -15.9885    66.0149  -0.242  1.00000
8 - 7 == 0   -31.6011    77.9478  -0.405  1.00000
9 - 7 == 0   -33.6176    77.9437  -0.431  0.99999
10 - 7 == 0  -32.8955    77.9440  -0.422  0.99999
11 - 7 == 0  -33.4265    77.9438  -0.429  0.99999
12 - 7 == 0  -17.1449    66.0270  -0.260  1.00000
9 - 8 == 0    -2.0164     0.8282  -2.435  0.19535
10 - 8 == 0   -1.2944     0.8088  -1.600  0.76750
11 - 8 == 0   -1.8254     0.9091  -2.008  0.45936
12 - 8 == 0   14.4562    48.4431   0.298  1.00000
10 - 9 == 0    0.7221     0.3530   2.046  0.43147
11 - 9 == 0    0.1911     0.4397   0.435  0.99999
12 - 9 == 0   16.4727    48.4374   0.340  1.00000
11 - 10 == 0  -0.5310     0.4876  -1.089  0.97654
12 - 10 == 0  15.7506    48.4376   0.325  1.00000
12 - 11 == 0  16.2816    48.4377   0.336  1.00000

Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Adjusted p values reported -- single-step method)

Warning message: In RET$pfunction("adjusted", ...) : Completion with error > abseps

I understand the general idea of the Tukey HSD, but I am a bit confused as to interpretation of results with respect to the glmm model. How does it account for the other factors in the model (e.g., Sex and Perturb3 here, as well as CurrentChip) in comparing the means for levels of Month? If it is looking strictly at the model coefficients, then the results would only apply to the reference levels of the other variables in the model (sex, age, perturb)? The results are different if I simply use Month.factor + (1|CurrentChip) in the model, so it clearly is not ignoring the other parameters in the model. Is there a better way to assess the differences between months, while accounting for variation in the other variables?
In this instance, only two comparisons are significant: Dec vs Jan (12-1) and Feb vs Jun (6-2). I am then also conducting a compact letter display to visually help discern significantly different means in my plots. Here:
cld(glht(model, linfct=mcp(Month.factor = "Tukey")))

   1    2    3    5    6    7    8    9   10   11   12
"cd" "ad" "ac" "ac" "bc" "ac" "ac" "ac" "ac" "ac" "ab"

For some parasites, the output makes sense to me, but some are like this one for ticks. Based on the original Tukey results, we know that there are differences between 12-1 and 6-2. This makes sense in that neither of those pairs share letters (12 is ab vs 1 is cd; 6 is bc vs 2 is ad). However, I don't really understand how there can be non-consecutive letters for a level. (I am assuming this is a statistical interpretation issue, and not some type of coding issue in R...please correct me if I'm wrong and I can redirect this portion of the question to stackoverflow) The mean for 12 is below that of 1, which makes sense that a and b are lower than c and d. 6 is in between, with bc. Still ok. But how is 2 ad? How can it overlap with the higher and lower groups, but not the middle ones?
Please let me know if any more info is needed, and thanks for any insights!
Comment: I strongly urge you to not use CLDs. They highlight non-findings rather than findings. In significance testing, findings are those cases where the P value is small. But the groupings point to cases where the P value is large — where you CAN'T make a definitive conclusion.
Comment: As a general note, as far as I understand, the "Tukey" in mcp has nothing to do with Tukey HSD; it is simply code to tell the function to make all pairwise comparisons.  You will see at the bottom of your output that the summary function uses a single step adjustment by default... As some general advice for your problem, 1) I would confirm that multcomp handles glmer obects correctly.  I don't know where there is a list of models it supports.  2) That warning message in the output may be important.  I don't know.  (Cont...)
Comment: 3) It's curious to me that for the significant contrasts, the estimate of differences is relatively small, but that the standard error is also small.  Might there be something unbalanced in your data that's driving the smaller standard errors and therefore the results?  4) You might try the emmeans package and see how that handles your model and data.  See ?emmeans::models ...  As to how multcomp accounts for other effects in the model, the [documentation ](https://www.rdocumentation.org/packages/multcomp/versions/1.4-7/topics/glht) gives some details, but mostly refers you to other texts.
Answer: Answer:
You are correct, the letters indicating homogenous subsets appear to look messed up but, in this instance, it is an accurate portrayal of differences detected by pairwise comparisons.
In most cases, compact letter displays (clds) are generated by ordering least squared or marginal means in ascending or descending order and then drawing a series of unbroken lines that unify means for which there are no pairwise differences detected (Gramm et al. 2007). In this case, lines can be converted to letters and vice versa. This is the most common outcome of pairwise assessments. Here is a figure to illustrate:

However, in some instances and especially for comparisons where the standard errors of differences are not homogeneous, drawing these unbroken lines is not possible (Piepho 2000, Gramm et al. 2007). In these cases, letters represent broken lines and result in non-consecutive letters to be generated. Here is a figure to illustrate:

Likely, in part, due to this confusing scenario of non-sequential cld's, the creator of the emmeans package has developed an alternative to compact-letter displays described as "pairwise P-value plot", which displays all the P-values in pairwise comparisons (see function emmeans::pwpp()). It produces a figure that has the estimated marginal means of the groups ranked from largest to smallest on the y-axis and the p-value of the Tukey post-hoc comparison on the x-axis, allowing for a display of pairwise comparisons that range from most different (towards the left side of the figure) to most similar. Here is an example:

References:
Piepho, H.P., 2000. Multiple treatment comparisons in linear models when
the standard error of a difference is not constant. Biometrical Journal 42 (7),
823–835.
Gramm et al. 2007. Algorithms for compact letter displays: comparison and evaluation. Computational Statistics & Data Analysis 52:725-736.
Lenth, R. 2019. Comparisions and contrasts in emmeans (V.18.104.22.168) vignette. URL https://cran.r-project.org/web/packages/emmeans/vignettes/comparisons.html. Accessed Jan 2020.
Answer: Maybe this summary can shed some light on the matter, but also try reading

Piepho,
Hans-Peter
(2018) Letters in Mean Comparisons: What They Do and Don't Mean,
 Agronomy Journal, 110(2), 431-434. DOI:
10.2134/agronj2017.10.0580
(ResearchGate)
Abstract

Letter displays allow efficient reporting of pairwise treatment
comparisons.
It is important to correctly convey the meaning of letters in
captions to tables and graphs displaying treatment means.
The meaning of a letter display can and should be stated in a
single sentence without ambiguity.

Letter displays are often used to report results of all pairwise
comparisons among treatment means in comparative experiments. In
captions to tables and charts using such letter displays, it is
crucial to explain properly what the letters mean. In this paper I
explain what the letters mean and how this meaning can be succinctly
conveyed in a single sentence without ambiguity. This is contrasted to
counter-examples commonly found in publications.


If x is 3 higher than y

Question: I'm doing a program to do a guessing game; I need to be able to make the program give feedback of H or L only if a number is 3 higher than the random number or 3 less.
This is what I currently have
import random
def game3():
    rndnumber = str(random.randint(0,9999)) #gets a number between 0-9999
    while len(rndnumber) < 4:
        rndnumber = '0'+ rndnumber # adds 0s incase the number is less then a 1000
    print(rndnumber) #lets me know that the program generates the right type of number (remove this after testing)
    feedback = 0 #adds a variable
    for x in range(1,11): #makes a loop that runs for 10 times
        print("Attempt",x)
        attempt = input("Guess a number between 0-9999:")#gets the users guess
        feedback = "" #makes a feedback variable
        for y in range(4): #makes a loop that runs for 4 times
            if attempt[y] == rndnumber[y]: #if attempt is the same then add a Y to the number
                feedback += "Y"
            elif attempt[y] < rndnumber[y]:
                feedback += "L"
            elif attempt[y] > rndnumber[y]:
                feedback += "H"
            else:
                feedback += "N"
        print(feedback)
        if  x == 10:
            print("You Lose the correct answer was",rndnumber)
        if feedback == "YYYY" and x > 1:
            print("You win it took",x,"attempts.")
            break; #stops the program
        elif feedback == "YYYY":
            print("You won on your first attempt!")
            break; #stops the program

Comment: Something I realized when I began to learn programming is that there two ways to write things out, name things, reason things, etc: *First*, there is your way. *Then*, there is the right way. When you name your variables, first you'll start with your own names, they may be long but they make sense to you. The problem is that none of the help you get will be in your mental language and you'll have to translate a lot. Eventually, the more popular naming conventions and logical methods will be easier for you. Take my advice and learn the popular way to do things now; It makes learning much easier
Comment: Why are you comparing numbers by comparing individual digits in a loop? Why not just compare the whole number with `if attempt == rndnumber`?
Comment: @Barmar Because he's programming something similar to Mastermind.
Comment: if I compare each number I can then give feedback like below
Guess a number between 0-9999:1523
HLLY
Comment: It needs to start from 0, but have 4 digits.
Answer:
If x is 3 higher than y

if x+3 == y:
    #code

the program give feedback only if a number is 3 higher than the random
  number or 3 less.

if x+3 == y or x-3 == y:
    #give feedback

Source:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html
Answer: You can just use
if attempt == rndnumber + 3 or attempt == rndnumber - 3:
    # Do something...

Comment: When I attempt to do this I get this error

'int' object is not subscriptable
Comment: I'm not sure where that error is coming from - but since you are working with them as strings, you'll need to wrap both variables in an `int` conversion in order to be able to add and subtract 3.
Comment: When I do this, I still get the same error, Would it have to do with having my rndnumber as a str before?
Comment: Can you give the line number that the error message gives you?
Comment: line 13, in game3
    if attempt[y] == rndnumber[y]: #if attempt is the same then add a Y to the number
TypeError: 'int' object is not subscriptable
Comment: Oh, because you are converting to an integer and not converting back. If you want to use `+` and `-` and `*` your variable has to be an integer. But if you want to use `[]` it has to be a string (or a list). So, leave it as a string and just do `if int(attempt) == int(rndnumber) + 3 ...`.
Answer: In line 10 you save a string in the variable attempt.
In line 13 however, you use attempt as a dictionary.
You might want to rethink your whole approach here.
Edit:
Of course I also did a guessing game at one point. While I would definitely use a different approach nowadays, I think it might be helpful for you and build your requirements for your own game in this python 3 code.
import random

print ("Hello! What is your name?")
name = input()
print ("Well,", name, ", I am thinking of a number between 1 and 100.\nTake a guess.")
number = random.randint(1, 100) # create a number between 1 and 100
guess = input() # read user's guess
guess = int(guess)
guessnumber = 1 # first try to guess the number
guessed = False # number isn't guessed yet
while guessed == False:
    if (number == guess):
        print ("Good job,", name + "! You guessed my number in",guessnumber, "guesses!")
        guessed = True
    elif (guess > number):
        print ("Your guess is too high.")
        guess = input("Take another guess: ")
        guess = int(guess)
        guessnumber+=1
    else:
        print ("Your guess is too low.")
        guess = input("Take another guess: ")
        guess = int(guess)
        guessnumber+=1

Comment: I feel as though his code already largely resembles this structure.

If x is 3 higher than y