Function is not adding information to my dictionary

Question: So I've got my functions created like so:
def create_contact(contacts, first, last, email, age, phone):
   """
   Creates a contact.
   """

   contacts[(first, last)] = [email, age, phone]

def contains_contact(contacts, first, last):
    """
    Checks to see if the dictionary contains  a contact.
    """
    if (first.lower(), last.lower()) in contacts == True:
        return(True)
    else:
        return(False)

and then at the bottom of my code I have my main function like so:
def main():
   # The Dictionary
   contacts = {}
   # Provided Test Code
   create_contact(contacts, "Katie", "Katz", "firstname.lastname@example.com",
               25, "857-294-2758")
   #Checks to see if item in dictionary exists
   print("Creation of Katie Katz: {}".format(
    "Passed" if contains_contact(contacts, "Katie", "kaTz") else
    "Failed"))

I'm not sure where I'm going wrong. It seems as though the items are not being added to my dictionary. Unsure as to why, maybe I'm attempting this all wrong.
Comment: You don't lower case the names in the key tuple. You can just `print(contacts)` to see the function *is* adding the information. Also your second method should just be `return (first.lower(), last.lower()) in contacts`.
Comment: return in create_contact is missing
Comment: @DineshPundkar it mutates its parameter, to return something as well is not conventional in Python.
Comment: It's just as jonrsharpe put it: python string comparison is case sensitive so the lower case key is different from the not-lowercase one.
Answer: The adding of items to your dict is working fine, however you forgot to convert the first and last name to lowercase in create_contact. You did do it in contains_contact however, which is why your code doesn't work.
def create_contact(contacts, first, last, email, age, phone):
   """
   Creates a contact.
   """

   contacts[(first.lower(), last.lower())] = [email, age, phone]

Additionally, your contains_contact function could be simplified:
def contains_contact(contacts, first, last):
    """
    Checks to see if the dictionary contains  a contact.
    """
    return (first.lower(), last.lower()) in contacts

Comment: You don't need the `()`. It should be like this `contacts[first.lower(), last.lower()] = [email, age, phone]`
Comment: @sdikby You're right, but correcting that wouldn't contribute anything to answering the question. There are a lot of things about the code the OP posted that are suboptimal, but this is not codereview
Comment: @sdikby If you go so far as to suggest the edit, okay, so be it :) However please note that there is a lot of discussion on meta about this, such as [here](https://meta.stackexchange.com/questions/266572/answer-question-or-improve-code). Generally, the consensus seems to be that we can't teach people to write good code by improving it in the answers, it has to be learned _the hard way_, and I think I agree. The most important aspect of an answer on SO is to actually answer the question.
Comment: that's why i commented on your answer and not his. You gave an answer which was accepted. It's worth the little extra effort to remove those `()` and add something like "... they are useless in this case...". I personally like "pythonic"-correct answers.


My Javascript does not execute, does anyone know why?

Question: could you please help me with this code?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to Daily News</title>

<link href="homepage.css" rel="stylesheet" type="text/css" />

<form id="login-form" action="customerLogin.html" method="post" onsubmit="return validate(this)">

     Login:
     <input id="login-boxes" type="text" id="loginid">

      Password:
      <input id="login-boxes" type="password" id="pword">

     <input type="submit" value=" Sign In ">
       <input type="reset" value="Clear form">

  </form>

My Javascript is:
function validate(loginForm)
{
 var booValid = true;
 var strErrorMessage = "";
 var minLength=5;
 var maxLength=10;

 if(loginForm.pword.value.length < minLength)
 {
  strErrorMessage = "password must at least 5 characters\n";
  booValid=false;
 }

 if(loginForm.pword.value.length > maxLength)
 {
  strErrorMessage = "pasword must not more than 10 characters\n";
  booValid=false;
 }

  if(loginForm.loginid.value.indexOf("@") == -1)
 {
  strErrorMessage = "please enter an e-mail address as your login name\n";
  booValid=false;
 }

 if(!booValid)
 {
  alert(strErrorMessage);
 }

 return booValid;
}

I couldn't figure out what was with this code, it doesn't seem to read from javascript at all.
I have no idea why it does not. I've also tried to use only Login Form and javascript then it works and when i put everything together then it doesn't work.
Comment: Yes i think so but i can't change since i have already ticked on User455892.
Comment: I don't mind and I know Armando, he prob doesn't care either. You should be able to uncheck, though. The important thing to remember is learning when to use 'name', 'class', and 'id'
Answer:
You probably want to replace every id= with class=
Instead of your later ids you want to use name
<input id="login-boxes" type="text" id="loginid">
<input id="login-boxes" type="password" id="pword">

to
<input class="login-boxes" type="text"     name="loginid">
<input class="login-boxes" type="password" name="pword">

Answer: Try to change :

<input id="login-boxes" type="password" id="pword">

to
<input id="login-boxes" type="password" name="pword">
and

<input id="login-boxes" type="password" id="pword">

to
<input id="login-boxes" type="password" name="pword">


Golang- Problemas para buildar pacotes usando o shell do OhMyZsh

Question: $ go build src/github.com/LohanGuedes/firstapp Retorna erro:

Mesmo com o caminho correto para a pasta, o comando: go build não concluí a formação do pacote
Atualmente uso o OhMyZsh, segue o conteúdo do .zshrc:
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="/home/lohan/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="spaceship"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"

# Uncomment the following line to automatically update without prompting.
# DISABLE_UPDATE_PROMPT="true"

# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

SPACESHIP_PROMPT_ORDER=(
  user          # Username section
  dir           # Current directory section
  host          # Hostname section
  git           # Git section (git_branch + git_status)
  hg            # Mercurial section (hg_branch  + hg_status)
  exec_time     # Execution time
  line_sep      # Line break
  vi_mode       # Vi-mode indicator
  jobs          # Background jobs indicator
  exit_code     # Exit code section
  char          # Prompt character
)
SPACESHIP_USER_SHOW=always
SPACESHIP_PROMPT_ADD_NEWLINE=false
SPACESHIP_CHAR_SYMBOL="❯"
SPACESHIP_CHAR_SUFFIX=" "

### Added by Zinit's installer
if [[ ! -f $HOME/.zinit/bin/zinit.zsh ]]; then
    print -P "%F{33}▓▒░ %F{220}Installing %F{33}DHARMA%F{220} Initiative Plugin Manager (%F{33}zdharma/zinit%F{220})…%f"
    command mkdir -p "$HOME/.zinit" && command chmod g-rwX "$HOME/.zinit"
    command git clone https://github.com/zdharma/zinit "$HOME/.zinit/bin" && \
        print -P "%F{33}▓▒░ %F{34}Installation successful.%f%b" || \
        print -P "%F{160}▓▒░ The clone has failed.%f%b"
fi

source "$HOME/.zinit/bin/zinit.zsh"
autoload -Uz _zinit
(( ${+_comps} )) && _comps[zinit]=_zinit

# Load a few important annexes, without Turbo
# (this is currently required for annexes)
zinit light-mode for \
    zinit-zsh/z-a-rust \
    zinit-zsh/z-a-as-monitor \
    zinit-zsh/z-a-patch-dl \
    zinit-zsh/z-a-bin-gem-node

### End of Zinit's installer chunk
zinit light zdharma/fast-syntax-highlighting
zinit light zsh-users/zsh-autosuggestions
zinit light zsh-users/zsh-completions

export PATH=$PATH:/usr/local/bin/go
export PATH=$PATH:$GOROOT/bin

export GOPATH=/home/lohan/golib
export PATH=$PATH:$GOPATH/bin

Comment: O que te faz pensar que o problema é no `OhMyZsh`?
Comment: Na verdade, não sei se o problema é o ```OhMyZsh``` porém achei bom deixar claro q uso...
Comment: Configurou corretamente o GOROOT e GOPATH?
Comment: Não sei dizer... configurei sem nenhum tutorial, e acabei de começar com essa linguágem...
Comment: Porém minha pasta Go está localizada em usr/local/bin
Comment: O problema é o GOPATH, https://golang.org/doc/gopath_code.html.
Answer: Na verdade o problema não é no OhMyZsh. Você tem duas escolhas: usar o module ou o gopath.
Eu recomendo o module, basicamente você inicia o module com o go mod init namemodule, leia o getting started para entender melhor, e depois pode rodar o go run vai buscar os pacotes.
Se preferir pode usar o gopath, lembrando que tem que configurar a Workspace.
Answer: Eu passei pelo mesmo problema.
Instalei corretamente seguindo a doc oficial, no /usr/local, adicionei o alias export PATH=$PATH:/usr/local/go/bin no .zshrc, mas ao rodar:

go

ou

go version

me retornava um erro relacionado ao git mesmo rodando o comando fora de um espoco controlado pelo git.
O problema foi junto ao Zinit que cria alguns aliás toda vez que tu abre o terminal com zsh.
Não encontrei uma forma de suprimir ele por config, mas abrindo o a folder do zinit no vsCode:

code $HOME/.local/share/zinit

pesquisando pelo termo git checkout
encontrei essa declaracao alias {gco, go}='git checkout'
dai so mudei pra
alias {gco}='git checkout'
salvei o arquivo e restartei o terminal e gg.
Provável que quando atualizar o package isso volte, se eu entrar uma solução melhor volto aqui :)


Looping over SQL files in directory

Question: I've always thought that looping over sql files in directory in SSIS is easy... But I've got a problem today:
Execute SQL Task isn't executing statements that are in the sql file.
In the sql file I've got delete statement and then insert statement.
SSIS Execute SQL Task component is done after about 2 sec, while executing the same script manually takes usually about 2 minutes, and of course in SSIS it doesn't insert anything.
I checked variable value that is coming from Foreach loop (with full filemane path) and it is ok.
I've got parametrized (by Expression) File Connection with this variable.
What am I doing wrong? Thanks for help.
Answer: Do you have GO after each call within your SQL file?
Example:
// Your insert TSQL code here
GO
// Your delete TSQL code here
GO
// Etc...

It will not continue if you don't have this.
Comment: No, I don't. I see that if I create File Connection Manager and point to one file it works. But when I put variable from loop into Connection String by Expression it won't go...
Comment: You need to go over an example of using for each loop, or you need to do more troubleshooting and post back. i.e. after the first step into the loop, has it found your file and has ir populated variables as expected?
Comment: I've gone over an example - but it still doesn't work... Yes, after setting breakpoint on the loop it is populating variable with correct filepath (but wiht doubled \\ ex. C:\\SQL\\elo.sql

Looping over SQL files in directory


element RelativeLayout must be declared

Question: I'm getting the error "element RelativeLayout must be declared" and I don't know the reason for its occurrence. How do I get rid of this error, please post suggestions or code snippets. This is my drawer_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/drawer_list_item"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/list_selector">

<ImageView
    android:id="@+id/icon"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:contentDescription="@string/desc_list_item_icon"
    android:src="@drawable/ic_launcher"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_toRightOf="@id/icon"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:textColor="@color/material_blue_grey_900"
    android:gravity="center_vertical"
    android:paddingRight="40dp"/>

<TextView android:id="@+id/counter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/counter_bg"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="8dp"
    android:textColor="@color/material_blue_grey_900"/>

   </RelativeLayout>

Comment: Is the file in `res/layout` folder?
Comment: Try clean build or restart eclipse and check your connection with android SDK tools
Comment: Try to change the id of your RelativeLayout to: android:id="@+id/drawer_list_item"
Comment: @programmer23 not working bro
Comment: @Natix yes it is in res/layout
Answer: I had faced same error because I add added Layout resource  file inside drawable folder instead of layout folder

make sure to put layout files inside layout directory
Comment: Sometimes simpler things make me feel so stupid... Thanks!

element RelativeLayout must be declared


Given conditions on the fraction, can we find a 'best rational approximation'

Question: Just something I thought of and I'm curious about.
Say I tell you

I want to approximate $\pi$ using a rational number. However, I am
  going to tell you that the numerator is to be at most $m$ digits and
  the denominator is to be at most $n$ digits

Given a pair $(m,n)$, we can of course find some approximation to $\pi$. For example, if you give me $(2,1)$, then the answer is $\frac{22}{7}$.
My question is, given any pair $(m,n)$, is there such a thing as a 'best' rational approximation?
If there is such a thing, is it possible to acquire tight bounds for the degree of error in terms of $m$ and $n$?
Comment: Since any such pair has finitely many rational numbers satisfying it we can always find a best one by simply enumerating and checking distances. I've no idea about error bounds, or what to do if you want to find the best one without precomputed knowledge of $\pi$.
Comment: I do wonder if there is a way to find a best one, perhaps algorithmically, without actually enumerating the fraction and checking its value with respect to $\pi$.
Comment: I think that you should only constrain the number of digits in the denominator. The number of digits in the numerator will be determined by the denominator and the actual number. So for $\pi$ it is impossible to find a $(3,1)$ fraction unless you're going to permit "bad" approximations like $\frac{100}{9}$. Having said that, given values for $m$ and $n$ it is possible to determine approximate bounds for your error.
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations) has a section on how to find best rational approximations defined as better approximations than any with smaller denominators based on the continued fraction.  This would be taking the denominator to be like $999$
Answer: I think there are three parts to your question.
Q1) Is there such a thing as a "best rational approximation" to a number given certain constraints to the fraction?
Q2) Is there a way to determine the possible error in such an approximation?
Q3) Can the above be done for $\pi$?
I will attempt to answer the first two of those questions:
A1) Yes. If you know the true value $x$, then you want to minimise the difference between the true value and the estimate $X=\frac pq$.
$$\min_{1 \le q < 10^n , 1\le p<q}\left(|X-x|\right)$$
This looks like a lot of work, searching through all possible fractions, but we can cut down some of the effort by noting that if $\frac pq \approx x$, then $p \approx qx$. We can therefore try to find:
$$\min_{1 \le q < 10^n} \left(\left|\frac {\lfloor qx \rfloor}q -x \right|,\left |\frac {\lceil qx \rceil}q -x \right |\right)$$
This still involves searching through all the possible values of $q$.
A2) For a given value of $n$, the largest possible error is $\frac 1{2(10^n-1)}$, but this only occurs if $x$ is very close to 0 or 1.
A3) The above depends on knowing the true value $x$. If you don't have an approximation for $\pi$ then you can't really answer the question.


how to create an object of the same class in c#?

Question: I need an instance of the same class as another object, but I don't know the exact type. I have the following code.
<code>abstract public class Row{
     .
     .
     .
}

public class User : Row{
    .
    .
    .
}
.
.
.
.
User test = new User();
Open(test);
.
.
.

private Row backup;

public static void Open(Row row){
    .
    .
    .
    db.backup = (Row) Activator.CreateInstance(row.GetType());
    .
    .
    .
}
</code>
But when I run the program it generates NullReferenceException and I don't understand why... I tested it on the debugger and "row" is not null, everything seems right.
I googled it but no luck... however I read comments of people complaining about Activator.CreateInstance being too slow... is that true? what the best way to do this job?
Comment: Your code doesn't compile - you are accessing an instance member (`backup`) from a static method (`Open`).  What is the _exact_ exception you get (and on what line)
Comment: @georgeb is `db` null?
Comment: I have similar code working with no problems. Can you provide more info from the exception? Stacktrace and which line you posted throws it would be good.
Comment: What do you plan to do once you create a `User` object?
Comment: @DStanley: Sorry it actually says: db.backup, so it does compile
Comment: @evanmcdonnal: there is no more information, just the name of the source file and the line in which the exception occurs... nothing useful.
Comment: @georgeb then post your _actual_ code (or at least enough to replicate the problem)
Comment: @georgeb no, it doesn't, because `backup` is still an _instance_ member.
Comment: @georgeb the line number is _very_ useful...
Comment: @georgeb do you mean that's all you have in your log? All exceptions provide a stack trace...
Answer: Sorry it was my mistake... as D Stanley correctly pointed out db was null, and that's the reason why the program threw an exception.
Comment: Glad you figure it out - for future reference the debugger is a GREAT tool to weed out such errors.  And it doesn't hurt to add null-check to your code wither.


Converter DataTable em List C#

Question: Preciso converter o conteúdo do DataTable para uma List, sou novo em C# e não conheço a sintaxe.
public List < VoCliente > ConsutaCliente() {
DataTable tabela = BDOracleCliente.ConsultaCliente();

List < VoCliente > teste = new List < VoCliente > ();

foreach(DataRow row in tabela.Rows) {
 //teste.Add((DataRow)row); ???
 teste = tabela ? ? ?
}

return teste;
}

Comment: Poste também a estrutura da classe e do `DataTable`.
Answer: você pode criar uma extensão para DataTables como a seguinte.:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Dynamic;
using System.Xml.Serialization;
using System.Reflection;
using System.ComponentModel.DataAnnotations.Schema;

public static class DataTableExtensions
{
    private static Dictionary<Type, Dictionary<string, PropertyInfo>> types;

    static DataTableExtensions()
    {
        types = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
    }

    public static List<T> ToList<T>(this DataTable dataTable) where T : class
    {
        if (!types.ContainsKey(typeof(T)))
        {
            types.Add(typeof(T), typeof(T).GetProperties().ToDictionary(x =>
            {
                var column = x.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
                return column == null ? x.Name : column.Name;
            }, x => x));
        }

        var list = new List<T>();
        var columns = dataTable.Columns.Cast<DataColumn>();
        var props =
            from prop in types[typeof(T)]
            join column in columns on prop.Key equals column.ColumnName
            select new {
                PropertyInfo = prop.Value,
                Column = column
            };

        foreach (var row in dataTable.Rows.Cast<DataRow>())
        {
            var item = Activator.CreateInstance<T>() as T;
            foreach(var prop in props)
            {
                var value = row[prop.Column.ColumnName];
                if (value != DBNull.Value)
                    prop.PropertyInfo.SetValue(item, value);
            }
            list.Add(item);
        }
        return list;
    }

    public static List<dynamic> ToList(this DataTable dataTable)
    {
        var list = new List<dynamic>();
        var columns = dataTable.Columns.Cast<DataColumn>();

        foreach (var row in dataTable.Rows.Cast<DataRow>())
        {
            var item = new ExpandoObject() as IDictionary<string, object>;
            foreach(var column in columns)
            {
                var value = row[column.ColumnName];
                item.Add(column.ColumnName, value != DBNull.Value ? value : null);
            }
            list.Add(item);
        }
        return list;
    }
}

Segue um exemplo de Utilização.:
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;

public class Entity
{
    public Guid EntityID { get; set; }
    public String Titulo { get; set; }
    public DateTime DataCriacao { get; set; }
    [Column("Detalhes")]
    public String Descricao { get; set; }
}

public class Program
{
    public static void Main()
    {
        var dataTable = new DataTable();
        dataTable.Columns.Add(new DataColumn() { DataType = typeof(Guid), ColumnName = "EntityID" });
        dataTable.Columns.Add(new DataColumn() { DataType = typeof(String), ColumnName = "Titulo" });
        dataTable.Columns.Add(new DataColumn() { DataType = typeof(DateTime), ColumnName = "DataCriacao" });
        dataTable.Columns.Add(new DataColumn() { DataType = typeof(String), ColumnName = "Detalhes" });

        for (int i = 0; i < 10; i++) {
            var row = dataTable.NewRow();
            row["EntityID"] = Guid.NewGuid();
            row["Titulo"] = "Titulo " + i;
            row["DataCriacao"] = DateTime.Now;
            row["Detalhes"] = "Descricao " + i;
            dataTable.Rows.Add(row);
        }

        var listA = dataTable.ToList<Entity>();
        Console.WriteLine(JsonConvert.SerializeObject(listA, Formatting.Indented));

        var listB = dataTable.ToList();
        Console.WriteLine(JsonConvert.SerializeObject(listB, Formatting.Indented));
    }
}

Segue o output.:
var listA = [
  {
    "EntityID": "1bbd4f4a-1614-4af9-a3f8-0798674502eb",
    "Titulo": "Titulo 0",
    "DataCriacao": "2017-11-07T14:22:51.9708648",
    "Descricao": "Descricao 0"
  },
  {
    "EntityID": "9a2d301e-f5e7-4a70-a5bf-200010a7f665",
    "Titulo": "Titulo 1",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 1"
  },
  {
    "EntityID": "4ac9b4cc-57c2-4c46-b124-4c36638858ef",
    "Titulo": "Titulo 2",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 2"
  },
  {
    "EntityID": "e4609c4c-cbe0-416f-bdcd-f03d17c69046",
    "Titulo": "Titulo 3",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 3"
  },
  {
    "EntityID": "9d8ebc9b-b153-40a2-b9e6-0bbb1e6f08c5",
    "Titulo": "Titulo 4",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 4"
  },
  {
    "EntityID": "ec25f555-3d5e-4355-9d9a-5ab453dde269",
    "Titulo": "Titulo 5",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 5"
  },
  {
    "EntityID": "dea54049-45c5-45ab-8ab4-ef099561aa37",
    "Titulo": "Titulo 6",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 6"
  },
  {
    "EntityID": "58df83fb-e341-479e-b5d5-d7d4b0e14f98",
    "Titulo": "Titulo 7",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 7"
  },
  {
    "EntityID": "97db14e4-fa79-412c-a2ae-913e0ce6824f",
    "Titulo": "Titulo 8",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 8"
  },
  {
    "EntityID": "38e49b63-d3d9-4add-bab2-959c24b3599c",
    "Titulo": "Titulo 9",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Descricao": "Descricao 9"
  }
];
var listB = [
  {
    "EntityID": "1bbd4f4a-1614-4af9-a3f8-0798674502eb",
    "Titulo": "Titulo 0",
    "DataCriacao": "2017-11-07T14:22:51.9708648",
    "Detalhes": "Descricao 0"
  },
  {
    "EntityID": "9a2d301e-f5e7-4a70-a5bf-200010a7f665",
    "Titulo": "Titulo 1",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 1"
  },
  {
    "EntityID": "4ac9b4cc-57c2-4c46-b124-4c36638858ef",
    "Titulo": "Titulo 2",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 2"
  },
  {
    "EntityID": "e4609c4c-cbe0-416f-bdcd-f03d17c69046",
    "Titulo": "Titulo 3",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 3"
  },
  {
    "EntityID": "9d8ebc9b-b153-40a2-b9e6-0bbb1e6f08c5",
    "Titulo": "Titulo 4",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 4"
  },
  {
    "EntityID": "ec25f555-3d5e-4355-9d9a-5ab453dde269",
    "Titulo": "Titulo 5",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 5"
  },
  {
    "EntityID": "dea54049-45c5-45ab-8ab4-ef099561aa37",
    "Titulo": "Titulo 6",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 6"
  },
  {
    "EntityID": "58df83fb-e341-479e-b5d5-d7d4b0e14f98",
    "Titulo": "Titulo 7",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 7"
  },
  {
    "EntityID": "97db14e4-fa79-412c-a2ae-913e0ce6824f",
    "Titulo": "Titulo 8",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 8"
  },
  {
    "EntityID": "38e49b63-d3d9-4add-bab2-959c24b3599c",
    "Titulo": "Titulo 9",
    "DataCriacao": "2017-11-07T14:22:52.0333271",
    "Detalhes": "Descricao 9"
  }
];

Note que, como o DataTable tem uma coluna com o nome diferente da propriedade na classe, eu precisei decorar a classe com ColumnAttribute.
Comment: @Marconi acredito que ele tenha visto, mas como está começando com `.net/C#`, acredito que não esteja familiarizado com `extensions`, `linq`, `reflection`, `generic`, etc. Talvez se você exponha as suas extensões para `DataTable` como um pacote do `Nuget`, acredito que ele fique mais confortável para utilizar.
Comment: Nossa sua resposta aceita qualquer tipo na conversão? Digo pois estou a implementar um método genérico na extensão de minha DataTable!
Comment: @Marconi, acredito que terá de fazer alguns testes, por exemplo, acabei de adicionar uma pequena correção, caso o valor da celula for `DBNull.Value`. Outra coisa que você pode investigar, é o comportamento desta extensão se o tipo da coluna for diferente do tipo da propriedade no objeto, tipo o DataType da coluna é `System.String` e a propriedade é `System.Int32`. Mas no geral, a solução acima é bem genérica e aceita boa parte dos tipos.
Comment: Deixo meu +1, quero testar e aprender como ela funciona direitinho! Pena que o OP não viu essa resposta.
Answer: Como você não deu detalhe de como está a estrutura de suas colunas do DataTable, e como são as propriedade de VoCliente, eu fiz um exemplo básico com Linq. É Necessário somente ajustar para anteder a sua necessidade.
Preenchendo o DataTable
  DataTable dt = new DataTable();
  DataColumn column;
  DataRow row;

  column = new DataColumn();
  column.DataType = System.Type.GetType("System.Int32");
  column.ColumnName = "id";
  dt.Columns.Add(column);

  column = new DataColumn();
  column.DataType = Type.GetType("System.String");
  column.ColumnName = "item";
  dt.Columns.Add(column);

  for (int i = 0; i < 10; i++) {
   row = dt.NewRow();
   row["id"] = i;
   row["item"] = "item " + i;
   dt.Rows.Add(row);
  }

Classe Item:
 class Item
 {
        public int id { get; set; }
        public string item { get; set; }
 }

Passando o resultado para um List<Item>
  var items = dt.AsEnumerable().Select(linha => new Item
  {
     id = linha.Field<Int32>("id"),
     item = linha.Field<String>("item")
  }).ToList();

Answer: Você pode usar este modelo simples que é mais performático.
public static IEnumerable<T> DataTableToList<T>(this DataTable table) where T : class, new()

{
var objType = typeof(T);
var properties = objType.GetProperties().Where(property => property.CanWrite).ToList();
var list = new List(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
    var obj = new T();

    foreach (PropertyInfo prop in properties)
    {
        var propType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
        var safeValue = row[prop.Name] == null ? null : Convert.ChangeType(row[prop.Name], propType);

        prop.SetValue(obj, safeValue);
    }

    list.Add(obj);
}

return list;

}
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Converter DataTable em List C#


Transition functions for the tautological bundle

Question: Define the tautological bundle over $CP^1$ to be $\tau = \{[a_1, a_2], (z_1, z_2) \in CP^1\times\mathbb{C}^2 | \exists  \lambda \in \mathbb{C} \;\text{such that} \;\lambda (z_1,z_2) = (a_1, a_2) \}.$
Then $\tau$ trivializes over open sets $U_i = \{[a_1,a_2] | a_i \neq 0\}, i=1,2$ where $(\pi, \phi_i):\pi^{-1}(U_1) \rightarrow CP^1\times\mathbb{C}$ is given by $\phi_i([a_1,a_2]) = a_i.$ Note that $(\pi, \phi_1)^{-1}:U_1\times\mathbb{C} \rightarrow \pi^{-1}(U_1)$ is given by $([a_1,a_2], w) \rightarrow ([a_1, a_2], (w, \frac{a_2}{a_1}w)).$
Thus the transition function $T_{12}$ is given by $[a_1, a_2] \rightarrow \frac{a_2}{a_1}.$ Up to homotopy we need only look at the map on the equator of $CP^1 = S^2.$ Since we can identify $U_1$ with $S^2 \setminus \infty = \mathbb{C}$ by $[a_1,a_2] \rightarrow \frac{a_2}{a_1},$ the transition function $T_{12}$ appears to be a degree one map $S^1 \rightarrow S^1.$
Is this right? If so, why is this bundle always denoted $O_\mathbb{P}(-1)?$ Shouldn't it be called $O_\mathbb{P}(1)?$
Answer: If $T_{12}$ has degree $1$ then $T_{21}$ has degree $-1$.  At some stage you just have to make a decision about whether this bundle should be called $\mathcal{O}(1)$ or $\mathcal{O}(-1)$.
Here are three possible (related) reasons why the notation $\mathcal{O}(-1)$ is used for this bundle, or, rather, why $\mathcal{O}(1)$ is used for the bundle whose transition functions are the reciprocals of those for the tautological bundle.  These reasons apply to $\mathbb{CP}^n$ for any $n$, not just to $\mathbb{CP}^1$, but I'll stick to the latter for simplicity.
Firstly, for $m \geq 0$ the bundle $\mathcal{O}(m)$ admits global holomorphic sections other than $0$.  In fact the space of sections is isomorphic to the space of homogeneous degree $m$ polynomials in the homogeneous coordinates $a_1, a_2$.  As an explicit example in the case $m=1$, the polynomial $\alpha_1 a_1 + \alpha_2 a_2$ corresponds to the function $\alpha_1 + \alpha_2 (a_2/a_1)$ in the trivialisation over $U_1$ and to $\alpha_1 (a_1/a_2) + \alpha_2$ in the trivialisation over $U_2$.  This nice correspondence between sections of $\mathcal{O}(m)$ and degree $m$ polynomials is a good reason for the notation to be the way it is.
Secondly, for a collection of (not necessarily distinct) points $P_1, \ldots, P_m$ there is an associated line bundle $\mathcal{O}(P_1+\ldots + P_m)$, whose sections can be thought of as meromorphic functions on $\mathbb{CP}^1$ with at worst a simple pole at each $P_i$; if some of the $P_i$ coincide then higher order poles are allowed, corresponding to the multiplicity of the repeated point.  (More generally for a divisor $D \subset \mathbb{CP}^n$ one can form a line bundle $\mathcal{O}(D)$.)
It turns out that the bundle $\mathcal{O}(P_1 + \ldots +P_m)$ only depends (up to isomorphism) on the value of $m$.  Essentially this is because for any pair of distinct points $Q_1, Q_2 \in \mathbb{CP}^1$ there exists a meromorphic function with a simple pole at $Q_1$, a simple zero at $Q_2$, and no other zeros or poles: an example would be $(z-Q_2)/(z-Q_1)$.  Anyway, if $P$ is your favourite point on $\mathbb{CP}^1$ then $\mathcal{O}(P_1 + \ldots + P_m) \cong \mathcal{O}(mP)$ and this bundle is isomorphic to the one we call $\mathcal{O}(m)$.
Of course you could now say, 'Why did we define $\mathcal{O}(P)$ the way we did; why did we not call that bundle $\mathcal{O}(-P)$ instead?'  Well, for any complex line bundle $L$ on $\mathbb{CP}^1$ we can construct a class $c_1(L) \in H^2(\mathbb{CP}^1)$ called the first Chern class.  This is a purely topological invariant, and is Poincare dual to the zero set of a generic smooth section of $L$.  In the case of $\mathcal{O}(P)$, the point $P$ itself is the zero set of a section (which is transverse to the zero section, so is 'generic'), so is dual to the class $c_1(\mathcal{O}(P))$.  This is nicer than $c_1(\mathcal{O}(P))$ being dual to $-P$.
Thirdly, there is a notion of positivity for line bundles that appears in results like the Kodaira vanishing and embedding theorems.  Usually this is formulated in terms of positive curvature of metrics (which is related the class $c_1(L)$ in reason 2), and a typical consequence is the existence of 'lots' of holomorphic sections (tying in with reason 1).  Happily the bundle $\mathcal{O}(m)$ on $\mathbb{CP}^n$ is positive if and only if $m > 0$.


What is the best position for a Sax reed?

Question: What is the best position for a Sax reed?  Is it to be level with the front edge of the mouthpiece or slightly ahead or behind the front edge? By how much.  Is this the same for Clarinet too?
I have played flute for about 40 years of various styles - symphonic to folk to rock and Blues.  now I am learning to play sax.
I understood that the reed's edge is to be at or equal to the front edge of the mouthpiece.  However, I have found that if the reed is positioned forward/long of the front edge by about 0.5 mm that there is less squeaking.  Is this my imagination or is it a personal thing that might work for me but not always for everyone.
How does this change the pitch of the instrument, i.e. flatten or sharpen the tones?
Answer: When I am starting a beginner on saxophone or clarinet, I tell the student to align the reed so that it looks like the tip of the reed lines up with the tip of the mouthpiece when the student is holding the mouthpiece with the reed facing them.  In doing so, typically, when viewed from the non-reed side of the mouthpiece, the reed will appear to protrude slightly past the end of the mouthpiece.
That is only a starting position, however.  Pushing the reed farther off the tip of the mouthpiece (so that the reed protrudes farther) will make the reed effectively harder.  The opposite will make the reed effectively softer.  So, it is possible that the reeds you are using are just a little soft for you, and you are adjusting for that with the position on the mouthpiece.  That would explain why you "squeak" less with the reed in the position you have it.
As you gain experience and sophistication with single-reed instruments, you may wish to experiment with different reed brands and/or strengths to find what you think sounds the best.
As far as pitch, moving the reed does not specifically affect the pitch, but there is a tendency for a harder reed to play slightly sharper because you have to use more pressure with the embouchure to get the reed to sound.  If you are wanting to tune your saxophone, though, you should adjust the position of the mouthpiece on the neck rather than trying to do anything with the reed to compensate.
Comment: "you may wish to experiment with different reed brands" - amen! I've had trouble making the lowest notes on my tenor sax since I acquired it a year ago, but only two weeks ago did fine down there with a different brand of reed.  Same stiffness - 2 1/2, but so much nicer to play.
Comment: @DarenW Strength "numbers" have little meaning across brands anyway.  A 2 1/2 Selmer Omega is likely to be quite different in strength from a 2 1/2 Vandoren, for instance.  Also, because the different brands are often cut somewhat differently, it could be that the reed shape makes your new reeds softer in the low register.  To some degree, you can diagnose and fix this issue yourself; see [this answer](http://music.stackexchange.com/a/4150/15) (specifically the "Balancing and strength adjustment" section) for more information.
Answer: I play an Alora Vienna series intermediate grade tenor sax with a generic Usongs #8 metal mouthpiece I found on Amazon for $20, a Rovner leather ligature, and a #5 Fibracell reed.  I've found that I have to position the tip of my reed perfectly with the edge of my mouthpiece and I even have to go so far as to re-mount my reed several times to get the positioning of my ligature correct.  If not I always sqwank out on my low D.  Now I know what you're thinking and no, I'm not a beginning player.  I've been playing reed instruments for 10 years now (sax for the last 2 & 1/2) so it's not my embouchure.  I really think it's the quality of my instrument combined with the type of mouthpiece I have.  As soon as I find the five grand I left in my couch somewhere I'll buy my Cannonball sax though, lol.  My point is, sometimes it's not so much the player or the technique as it is the equipment you have to work with which will determine the best placement of your reed on your mouthpiece.


Question about two definitions of local compactness.

Question: I was looking at the wikipedia definition for local compactness, and it gives various definitions, I am interested in these two:
definition A:
We say a topological space $X$ is locally compact if every point $x$ has a compact neighbourhood.
definition B:
We say a topological space $X$ is locally compact if every point $x$ has a compact local base.

The definition of a compact neighborhood of $x$ is a neighborhood of $x$ that is contained inside a compact set.
The definition of a compact local base of $x$ is a local base consisting of compact neighborhoods.

I think definition $A$ implies definition $B$:
Suppose $x\subseteq U \subseteq K$ is a compact neighbourhood of $x$. Then we can find a compact basis of $x$ by considering the neighbourhoods $U_\alpha \cap U$ with $\alpha \in A$ where the  $U_\alpha$ are any basis of $x$.

Is this correct? The wikipedia page says they aren't equivalent so I am confused.
Comment: What you did is fine.
Comment: It seems they're equivalent though
Comment: First, you should edit your question; there are plenty of cases where you write "compact" instead of "locally compact". Second, the intersection of a compact set and an open set is generally not compact.
Comment: Oh thanks for noticing the mistake. Also, what is the point of your second sentence?
Comment: It all depends on your definition of neighbourhood: there are authors who define $U$ is a neighbourhood of $x$ to mean: there is an open set $O$ with $x\in O\subseteq U$. If you then take `compact neighbourhood' literally - the neighbourhood itself is compact - then A and B are not automatically equivalent.
Answer: Here is an example of a compact $T_1$-space that is locally compact A but not locally compact B, where you want the neighbourhoods themselves to be compact, rather than just contained in some compact set.
Take $\mathbb{Q}\cup\{\pi\}$ topologized as follows: rational numbers get their normal neighbourhoods; the neighbourhoods of $\pi$ are the co-finite sets.
This space is locally compact A because the whole space is compact.
It is not locally compact B, because no rational point has a neighbourhood that is compact in its own right that is disjoint from $\{\pi\}$.
Comment: Great, thanks. I was really interested in the version with the wikipedia definitions, but this is nice also. I guess whoever wrote the article may not have been completely sure as to which definitions should be used.
Comment: @JorgeFernández There are several non-equivalent ones that become equivalent in Hausdorff spaces. It's part of the reason the combination of locally compact plus Hausdorff is so common.
Comment: @HennoBrandsma yes, thats seems like the case. But I think that a very important thing when considering alternatives is the exact definition of "compact neighbourhood"


Connection between sum of normally distributed random variables and mixture of normal distributions

Question: If you have two independent random variables that are normally distributed (not necessarily jointly so), then their sum is also normally distributed, which e.g. means that its excess kurtosis is $0$.
On the other hand in case the mixture of one-dimensional normal distributions the mixture distribution can display non-trivial higher-order moments such as skewness and kurtosis (fat tails) and multi-modality, even in the absence of such features within the components themselves (see also this video for an easy enough example). This means that the result doesn't have to be normally distributed.
My question
How can you reconcile these two results and what is their connection?
Comment: A mixture of two normals is not the sum of two normal random variables. It's a random variable whose PDF and CDF are weighted sums of the individuals PDFs and CDFs.
Comment: If you have suspicions that something might not be true, it's good to look for simple (counter)examples. Consider $X_1$ and $X_2$ independent Bernoulli random variables. A *mixture* of these is still Bernoulli (why?), but the sum of them could, in general, take the value $2$ (in addition to $0$ or $1$). So, clearly they can't be the same thing. :)
Comment: @Max, that's an answer!
Comment: I'll write it up now.
Comment: You don't have to go to higher moments to see that a not all mixtures are normal. Mixtures of normal distributions don't have to be unimodal, although they can be. In addition, since distinct normal distributions have distinct tail asymptotics, you can read off the components from the tails.
Comment: Two independent random variables that are normally distributed **have** a jointly normal distribution. No "not necessarily jointly" but instead ""so that they are also jointly normal".
Answer: It's important to make the distinction between a sum of normal random variables and a mixture of normal random variables.
As an example, consider independent random variables $X_1\sim N(\mu_1,\sigma_1^2)$, $X_2\sim N(\mu_2,\sigma_2^2)$, $\alpha_1\in\left[0,1\right]$, and $\alpha_2=1-\alpha_1$.
Let $Y=X_1+X_2$. $Y$ is the sum of two independent normal random variables. What's the probability that $Y$ is less than or equal to zero, $P(Y\leq0)$? It's simply the probability that a $N(\mu_1+\mu_2,\sigma_1^2+\sigma_2^2)$ random variable is less than or equal to zero because the sum of two independent normal random variables is another normal random variable whose mean is the sum of the means and whose variance is the sum of the variances.
Let $Z$ be a mixture of $X_1$ and $X_2$ with respective weights $\alpha_1$ and $\alpha_2$. Notice that $Z\neq \alpha_1X_1+\alpha_2X_2$. The fact that $Z$ is defined as a mixture with those specific weights means that the CDF of $Z$ is $F_Z(z)=\alpha_1F_1(z)+\alpha_2F_2(z)$, where $F_1$ and $F_2$ are the CDFs of $X_1$ and $X_2$, respectively. So what is the probability that $Z$ is less than or equal to zero, $P(Z\leq0)$? It's $F_Z(0)=\alpha_1F_1(0)+\alpha_2F_2(0)$.
Answer: Max has correctly pointed out the difference between sums of independent normals and mixtures of normals. However, he did not show directly how that answers your question.
Simply stated the two distributions are vastly different. The sum is normally distributed.  A mixture of two or three normals is not. In fact, it will be bimodal when two distributions are included with very different means and nearly equal weights. When one distribution has a high weight and the other is far to the right with a small weight this will induce skewness and possibly kurtosis that is larger than for a normal distribution. In the case of three distributions with the middle having a weight of 0.8 and the other two equally shifted one to the right and the other to the left with a weight of 0.1, each the distribution will be symmetric with heavy tails. Plot some of the densities and the non-normality will be obvious.


K-Medoids swapping inside clusters

Question: I'm a bit confused with concept of K-medoids.
It seems that original algorithm (PAM) describes that swap step should be performed by swaping only one of the medoids with one non-medoid point from the whole dataset (not only in cluster of that medoid), which will lead to smallest error in that moment.
First of all, is my understanding correct?
My original idea (which I implemented) swaps all of the medoids in one iteration, each medoid can be replaced by  a point from its cluster, that leads to smallest error in its cluster. Is this a bad approach?
I was mislead by K-means, which calculates its centroid based only on the points from its cluster, but now I'm not sure if the same logic has sense for K-medoids.
Also, just to add, I implemented K-means++ like initialization, to optimize the procedure.
Answer: K-Medoids is the problem of finding a set of K representative objects of the dataset such to minimize the total dissimilarity of each object from its nearest representer.
The PAM is an approximate solution to this problem that falls in the category of local search algorithms. It is made of two phases:

the BUILD step in which an initial solution is built. It starts by selecting as the first medoid the object with the lowest mean dissimilarity w.r.t. the whole dataset (i.e., the most central object). Iteratively medoids are selected as the objects that further minimize the overall dissimilarity of each object from its nearest medoid.
the SWAP phase in which given the current solution (the set of k medoids) all the neighbour solutions are evaluated. A neighbour solution is constructed by swapping one of the current medoids with one of the non-selected objects. Thus the size of the neighborhood of a given solution is $(n-k)*k$ where $n$ is the total number of objecs of the dataset and $k$ is the number of wanted medoids.

Now, to answer your questions:

Yes, your understanding is correct.
You developed a k-means-like solution to the k-medoids problem. In your case the neighborhood of a given solution varies with the current clustering.

It may be better or worse than PAM, you may compare them evaluating:

How much iterations they take to converge;
The quality of the final solutions;
How long it takes to complete an iteration;
How well both scale with respect of the number of objects and of features in the dataset

If memory serves me right there should also be a paper around about a k-means like k-medoids algorithm.
Comment: Swapping like > A neighbour solution is constructed by swapping one of the current medoids with one of the non-selected objects. actually doesn't make sense to me, but the way the thread starter mentioned it does. Because first you swap, without reassigning any object to other clusters yet, so if you swap with an object outside of the own cluster you could never further minimize the overall dissimilarity of each object from its nearest medoid, because then the medoid would move outside of the radius of the cluster.
Could someone tell me where my misunderstanding would be?
Comment: You are looking for all possible swaps in each single iteration of the algorithm. To evaluate a swap you need to check the assignments and verify that the total dissimilarity is reduced. You take into account also the swaps that destroy the current clustering in the hope of a better solution. If you do not find a better solution, then the algorithm returns the current solution.

K-Medoids swapping inside clusters


I want to make a UI as per diagram. I have to set JButtons in a JFrame, but I don't get the output as shown in the diagram. I tied. What should I do?

Question:
I tried like this...
class Calculator extends JFrame{
    // Here are the attributes
    Calculator(){
    // Here are the frame

    // here are the assign JPanels

    firstPanel.add(buttons[0]);
    secondPanel.add(buttons[1]);

    for (int i = 2; i < 6; i++){
        thirdPanel.add(buttons[i]);
    }

    fourthPanel.add(buttons[6]);
    fifthPanel.add(buttons[7]);

    add(firstPanel,BorderLayout.PAGE_START);
    add(secondPanel,BorderLayout.LINE_START);
    add(thirdPanel,BorderLayout.CENTER);
    add(fourthPanel,BorderLayout.LINE_END);
    add(fifthPanel,BorderLayout.PAGE_END);  `
    }

}

Comment: Try nesting a `GridLayout` in `BorderLayout.CENTER`.
Comment: https://docs.oracle.com/javase/tutorial/uiswing/layout/
Answer: To get the output as shown in the diagram you can try the following
 Calculator(){
        this.setSize(400, 400);
        this.setTitle("this");
        //create first panel with BorderLayout as layout
        JPanel firstPanel=new JPanel(new BorderLayout());
        //Create second Panel with GrdiLayout as layout
        JPanel secondPanel= new JPanel(new GridLayout(2,2));
        //add 4 Buttons to second Panel
        for(Integer i=0;i<4;i++){
            secondPanel.add(new JButton("Button"+i.toString()));
        }
        //Add wnorth,south,west,east buttons to first panel
        firstPanel.add(new JButton("north"),BorderLayout.NORTH);
        firstPanel.add(new JButton("south"),BorderLayout.SOUTH);
        firstPanel.add(new JButton("west"),BorderLayout.WEST);
        firstPanel.add(new JButton("east"),BorderLayout.EAST);
        //add the second panel (containing 4 buttons) to first panel
        firstPanel.add(secondPanel,BorderLayout.CENTER);
        //add first panel to the frame
        this.add(firstPanel);

    }

In main
public static void main (String args[]){

 new Calculator().setVisible(true);

}

Output:


Let $V$ be an inner product space. Prove $\langle x, 0\rangle = \langle 0, x\rangle = 0$ for $x \in V$.

Question: Let $V$ be an inner product space. For $x \in V$, prove $\langle x, 0\rangle = \langle 0, x\rangle = 0$.
Comment: In the future, use \langle and \rangle for the brackets when discussing inner products.
Comment: "What definition of inner product are you using?" he asks, wondering how this is not immediate from said definition...
Answer: A different hint:  $\langle x,0 \rangle = \langle x, x + (-x) \rangle$.
Answer: PROOF: We want to show that $\langle x, 0 \rangle = \langle 0, x\rangle = 0$ for any $x \in V$. Observe that $$\begin{align}\langle x,0\rangle & = \langle x, x + (-x) \rangle\\&=\langle x,x\rangle + \langle x,-x\rangle \\ &=\langle x, x \rangle - \langle x, x\rangle \tag{Factor out $-1$}\\&=0.\end{align}$$ Likewise, $$\begin{align}\langle 0,x\rangle & = \langle x + (-x), x \rangle\\&=\langle x,x\rangle + \langle -x,x\rangle \\ &=\langle x, x \rangle - \langle x, x\rangle \tag{Factor out $-1$}\\&=0.\end{align}$$
Answer: Here's a hint: $\langle x,0\rangle = \langle x,2\cdot 0\rangle$.


Windows Account Locking policy different while editing scheduled task

Question: When I connect (through RDP) on my Windows 2008 R2 server and editing a task from the "Task Scheduler" if I enter a wrong password, the account is immediately locked.
This happens with Domain user and with local admin users.
However when I am looking to the Group Policies Editor (gpedit.msc) I can see the value:
<code>Account lockout threshold: 5 invalid login attempts
</code>
Is there another setting which manage specifically the "Task Scheduler" account locking policy or the problem comes from another part?
Answer: There was an issue where the credentials were sent multiple times and locked out the account. This hotfix addresses that.
Comment: Thanks, it looks a good reason, however it seems we install all Windows Updates regularly. It seems we're in SP1 already and some  updates more. The link is not very clear on how to check if that fix has already been applied or not. Any thoughts?


Is it possible to include switches in traceroute hops?

Question: I was wondering if it's at all possible to make a Dell Powerconnect 2848 switch show when running internal traceroutes. This would help with diagnosing issues and make it far easier to see where issues occur.
According to the datasheet, this particular switch is Layer 2 and 3 aware. I'm not completely sure what that means.
Is this possible?
Answer: No. The hops shown by traceroute show the path that an IP packet follows on a routed (layer 3) network. Routers will show up, and switches will not.
Switches are by their nature a layer 2 device: they receive and forward Ethernet frames, using the destination MAC address to determine the correct destination port. Some switches are also able to function as routers. We call such devices "layer 3 switches." Even a layer 3 switch will not necessarily show up on a traceroute, because much of the traffic passing through such a switch is layer 2 traffic within its own subnet.
In any event, the PowerConnect 2848 is not a layer 3 switch. It is "layer 3 aware" for QoS purposes only.
Comment: Spot on. A device only shows up on traceroute when the forwarding is done by routing across subnets.

One way to identify a switch that could be made to show up on your traceroute is one that can operate routing protocols such as OSPF.
Comment: @Skyhawk, So how do you debug switches?
Comment: @Patrick: Not precisely true - a device shows up on traceroute if it decrements TTL (and then sends ICMP TTL exceeded messages).  Obviously that's mostly devices that do routing across subnets, but it doesn't have to be.
Answer: A layer 2 switch won't show up in a tracert because it's a layer 2 device (a switch) and simply forwards (switches) traffic from one switch port to another based on the layer 2 address of the destination device. Tracert (ICMP) works at layer 3. In order for the switch to show up in tracert it has to be in use as a layer 3 device (a router) and has to be in the layer 3 path between the source and the destination devices.
Comment: Have it actually route between different subnets on different VLANs. Anything else will mean clandestine layer3 functionality applied to the same subnet (aka bridge style firewall), which traceroute would and should not notice (it might notice if you mangle TTL fields in IP headers, which would probably confuse the living daylight out of it :)
Comment: I thought that might be the case, but wondered if there was a way of forcing this kind of function. Thanks!
Comment: Based on what I see, I guess the rule is, "If you can't ping it, you won't be able to see it, either".
Comment: @gbarry - That's not quite right. A switch could certainly have an ip address (for management purposes or for inter-VLAN routing) but a layer 2 switch operates at Layer 2 while tracert and ping (ICMP) operate at Layer 3. Only if the switch is acting as a router (a Layer 3 device) will it show up in tracert and/or ping. For example, a Layer 3 switch configured with multiple VLAN's and inter-VLAN routing will switch Ethernet frames between hosts in the same VLAN and won't show up in a tracert, but it will route IP packets between hosts in different VLAN's and will show up in a tracert.
Answer: Not with the default traceroute program which by definition uses a response from a gateway (see man page):

traceroute tracks the route packets taken from an IP network on their
  way to a given host. It utilizes the IP protocol's time to live (TTL)
  field and attempts to elicit an ICMP TIME_EXCEEDED response from each
  gateway along the path to the host.

If there is not a gateway on the traced path, only Layer 2 devices, the IP will not be reported.
But Cisco has a utility that works on Layer 2.
But this utility is dependent on CDP protocol which :

Cisco Discovery Protocol (CDP) must be enabled on all the devices in
  the network. For the Layer 2 traceroute utility to function properly,
  do not disable CDP. If any devices in the Layer 2 path are transparent
  to CDP, the Layer 2 traceroute utility cannot identify these devices
  on the path.

Check additional information here:
Cisco Layer 2 Traceroute Utility


Distribute files across X number of servers

Question: Any suggestions how I can distribute millions of files from 1 server to X number of other servers? I'm looking more into an algorithm on how to decide which server to send the file to.
Requirements:

no db
perl/python/shell based
ability to run form any box and end up on the same destination server
Comment: Have you looked into distributed filesystems?
Comment: A few people have tuned in with the distributed filesystem, but this doesn't sound like what you want. Can you expand & explain further?
Comment: How big is the collection of these million files? git might work, or rsync.
Comment: To keep things simple for now, we're staying away from any distributed file system.

We have two storage servers with 22TB each, which are nearing capacity(40TB used now). We've ordered additional storage and servers to upgrade and create new storage servers.

I'd like to move some of the existing files onto the other servers.

git won't work for us. rsync is a good transport tool, but I would still need a way to determine which files would go to what servers.
Answer: Perhaps look at a distributed filesystem like GlusterFS.  It sounds like it will meet all your requirements and will probably be more reliable than something that you hack up yourself.
Comment: So, you want to distribute your files, but you don't want a distributed filesystem.  Oh, and redistributing your files == changing your architecture.
Comment: More concerned about redistributing files files when add more capacity. Files are already distributed so it is not a change.
Comment: To keep things simple for now, we're staying away from any distributed file system.

I will look into it but adding/changing the architecture at this point is not an option.
Answer: Despite your impossible requirements, I'll scribble down my thoughts for other people in the future who aren't so hamstrung, based on my experiences doing this for Github.
Distributing data across a number of locations (be they partitions, machines, data centres) based on a hash is a dangerous undertaking, for two reasons:

You're never going to get a balanced distribution of data based on your hash -- not necessarily because the hash isn't balanced (although that is a factor too) but more because the items you're storing aren't equal size.  So you store two items, one 1kB in size the other 1GB in size.  Already you're massively unbalanced.  Try that a few times and all of a sudden you've got big imbalances.
Once your hash-to-server algorithm is in place, you can't change the number of "buckets" (machines, partitions, whatever) to store your data in without a massive amount of pain.  This is because the hash algorithm is used both to decide where to store stuff, and also where to find it again.  If you change the number of servers, then the rule of "where stuff is" changes, and so some of the existing data is expected to be somewhere else.  You end up either having a lengthy offline "rebalance" operation (each server searches for data that, in the new scheme, should be somewhere else, and moves it there) or you have to search for your data on all the fileservers (mmmm, inefficient).

On the other hand, having a lookup table for all your files makes these problems go away.  When you say "no database", I'm betting you insert an implicit "SQL" before "database".  However, there is a whole other world of databases out there that have nothing to do with SQL, and they are perfect for this situation.  They're known as "key-value stores", and if you're dead keen on going ahead with building this boondoggle yourself, then I'd highly recommend using one (I've got experience with Redis, but they all seem pretty reasonable).
Ultimately, though, if you go ahead with the "all hashes, all the time" system and then hack around the problems inherent in it (there are solutions, just not real awesome ones) all you will end up with, at the end of the day, is a half-assed, botchy, non-feature-complete version of GlusterFS.  If you need a large amount of storage, growable over time, distributed across multiple physical machines, in a single namespace, I really would recommend it over anything you can build yourself.
Answer: If you still want to hack it, do a md5sum on each file and then hash the output to your X boxes..
If you have two boxes:
0*-7* go to box one
8*-f* go to box two...
Or if you have 256 boxes:
00*-0f* go to box one
10*-1f* go to box two..
and so on..
This works best for box counts of powers of two.(2,4,8,16,..)
Keep in mind that shuffling things off is all nice and good, but you'll want
to keep an index somewhere if you also need to retrieve this info.
(where did I put foo.txt??)
A flat file pickle (in python) would work, but it won't scale as well as a DB for large amounts of data..
Comment: 00 to ff..  good catch.
Comment: "00-0f go to box one" means you can address up to 16 servers, not 256.
Answer: Can the other servers also send files? Are you in a "safe" environment?
The Rocks clusters installation process has to fill rack after rack of compute nodes, each one installed on the fly from an initial image. Doing that linearly or through a single server would be a bottleneck. Rocks uses instead a little system called Avalanche, where the install images are served using p2p; as nodes come up, they also become servers that will be used to install new nodes. The result is a tree of servers, and the install images cascade through the racks very quickly. The overall latency is a logarithm of the number of nodes, multiplied by the time to install one node (the base for the logarithm depends on how many other nodes can be served from one that is already installed, log base 20 wouldn't be surprising...).
You could imagine a similar strategy for copying out your files, but only if the destination servers would be willing to trust other servers for their copy.


Como criar evento entre transição de sessões?

Question: Possuo um elemento  em meu .html, onde eu necessito que quando houvesse o evento de onclick no mesmo, ocorreria o efeito de transição de sessão, ou seja:

Com o evento onclick no elemento  automaticamente ele iria transitar entre cada sessão do meu .

O que eu consegui desenvolver foi o seguinte:

Conforme a cada clique no elemento  o mesmo desce a cada sessão.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

     Scroll Down

Comment: Sugiro que leia as diretrizes da comunidade para criar uma [boa pergunta](https://pt.stackoverflow.com/help/how-to-ask), ela esta um pouco confusa e é necessário você postar todo o código referente ao assunto da pergunta, para melhorar a análise dos usuários.
Answer: Você teria que fazer mais ou menos isso:

var secs = document.querySelectorAll('section');
var currentSection = 0;
document.querySelector('#arrow').addEventListener('click', move);

function move(e) {
  if (e.target.classList.contains('next') && currentSection < secs.length) {
    window.scroll({
      top: secs[++currentSection].offsetTop,
      left: 0,
      behavior: 'smooth'
    });
    //    secs[++currentSection].scrollIntoView({ behavior: 'smooth' });
  } else if (currentSection > 0) {
    window.scroll({
      top: secs[--currentSection].offsetTop,
      left: 0,
      behavior: 'smooth'
    });

  }
}
section {
  min-height: 800px;
}

#arrow {
  position: fixed;
  right: 0;
  top: 0;
  background-color: black;
  color: white;
}

#arrow a {
  display: inline-block;
  padding: 10px 20px;
  cursor: pointer;
}

  anterior
  proximo

    Lorem ipsum
 dolor sit amet, consectetur adipisicing elit. Perferendis, earum unde, deleniti id tempore atque in nemo reprehenderit ad odit, nisi blanditiis
 odio pariatur
 non tempora ducimus tenetur nobis quibusdam?

Lorem ipsum dolor sit
 amet, consectetur adipisicing elit. Ducimus cum officia culpa quia id, dicta voluptatem aspernatur reprehenderit repellendus minima, sapiente mollitia dolore magnam delectus, ad eius ut iusto eos?

Lorem ipsum dolor sit
 amet, consectetur adipisicing elit. Consequatur magnam illo possimus rerum ratione. Quos harum dicta nihil illum atque, consequatur
 cupiditate sint fugiat dolores consectetur quasi deserunt repellendus enim.

Utilizando do botão "Proximo" como o seu botão.
Comment: Opa cara obrigado pela resposta eu sou muito iniciante em js meu site nao usa sections e sim div com class section e um id com o numero da section o link está na descrição da pergunta olhando como está estruturado como ficaria seu código em uma versão adaptada para meu código poderia quebrar essa ?
Comment: eu editei a pergunta lá se conseguir me ajudar porque no seu código você adapta a  no meu caso eu uso div
Comment: Aqui: `var secs = document.querySelectorAll('section');` você vai alterar para `var secs = document.querySelectorAll('.section');`
Answer: Existem diversas formas de fazer este tipo de "animação", as quais são:

Utilizar o Jquery (Para os dias de hoje o Jquery esta totalmente antiquado o seu uso)
Utilizar Function (criar uma simples função Javascript + ECMASCRIPT e manipular os id das
)

Eu irei te passar o funcionamento de como eu utilizaria e o qual eu acho correto para os dias de hoje, onde é utilizando a Function, mas para isto, antes eu preciso te explicar sobre o evento Window.location.
Window.location

A propriedade Window.location é somente para leitura e retorna um objeto Location com informações sobre o local atual do documento. Embora Window.location seja um objeto somente de leitura do Location , você também pode atribuir um DOMString a ele. Isso significa que você pode trabalhar com o location como se fosse uma string na maioria dos casos: location = 'http://www.example.com' é sinônimo de location.href = 'http://www.example.com'.
FONTE: MOZZILA DEVELOPER

Neste caso eu utilizarei a propriedade .href do Window.location, onde:
Location.href

É um DOMString contendo o URL inteiro. Se alterado, o documento associado navega para a nova página. Pode ser definido a partir de uma origem diferente do documento associado.
FONTE: MOZZILA DEVELOPER

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ÂNCORAS DE SESSÕES</title>

SEÇÃO (1)

SEÇÃO (2)

SEÇÃO (3)

SEÇÃO (4)

NOTA:

Para animar o scroll até o determinado section você tem duas opções, as quais são:

Desenvolver um Algoritmo

Utilizar Bibliotecas já prontas como por exemplo o ScrollMagic


How to bring data from parent directive to child directive in angular

Question: I have 2 directives as "chart" and "datapoint". Here the chart directive is the parent of the datapoint directive. I am trying to bring some data from parent directive to the children, but it throws an error.
Here is my directives:
"user strict";

angular.module("chartDirective", [])
    .directive('chart', function () {
        return {
                replace:true,
                transclude : true,
                templateUrl : '/views/directiveViews/svg.html',
                controller : function ($scope, $element, $attr) {
                    this.name="Afzil"; //setting up name.
                }
            }
    })

    .directive('datapoint', function () {
        return {
            replace : true,
            require :'^chart',
            template : '<circle cx="20" cy="20" ng-attr-r="{{radius}}" ng-attr-stroke-width="{{strokeWidth}}" fill="#FFF" stroke="#5B90BF" />',
            link : function (scope, element, attr, controller) {
                scope.radius = 4;
                scope.strokeWidth = 3;
                console.log(controller); //trying to console.
            }
        }
    })

The error I am getting is:
https://docs.angularjs.org/error/$injector/unpr?p0=$attrProvider%20%3C-%20$attr
But using this link, I am not able to find a solution. Any one know what the problem is?
Answer: It is because you are trying to pass $attr into your controller.  There is no $attr.  In the link function $attr is the third argument that gives you access to the attributes of the directive.
From the angular directives guide:

Savvy readers may be wondering what the difference is between link and
  controller. The basic difference is that controller can expose an API,
  and link functions can interact with controllers using require.
Best Practice: use controller when you want to expose an API to other
  directives. Otherwise use link.

Here is a demonstration on how to pass attribute values from the parent controller (using require) to the child directive.
Plunker Demo
app.directive('chart', function () {
        return {
                replace:true,
                scope: true,
                controller : function ($scope, $element, $attrs) {
                    this.name="Afzil"; //setting up name.
                    this.myAttrVal = $attrs.myAttr;
                }
            }
    })

    .directive('datapoint', function () {
        return {
            replace : true,
            scope: true,
            require :'^chart',
            template : '
{{valFromChart}}
',
            link : function (scope, element, attr, chart) {
                scope.radius = 4;
                scope.strokeWidth = 3;
                scope.valFromChart = chart.myAttrVal;
                console.log('from chart: ' + chart.myAttrVal); //trying to console.
            }
        }
    })

In the datapoint directive, we pass some arbitrary value as an alias for the controller we have require'ed.  We can then access anything attached to that controller.
Comment: @3gwebtrain   there is, however, `$attrs` (with the `s` at the end) that could be injected into the controller
Comment: yes, it works. and thanks for making to understanding. but in the parent `directive` i have declared a couple of `attrs` still why this issue is? here my directive : `

` I say i have `height` and `width`.
Comment: what exactly are you trying to do?
Comment: `parent controller (using require) ` - is there any other way too..? can you explore...
Comment: Did you see the demo?  I am not sure what you are asking.
Comment: yes. thanks. you say using require approch to get the attrs. i am askig withot or any other way can we consume parents attra from child?
Comment: @3gwebtrain, you don't need `require`. attributes are available both in the controller - via injectable `$attrs` - and in the `link` function as a third parameter.


Opening a file in Windows Explorer from a Windows 8 app?

Question: I want to write a function that, quite simply minimises my Windows 8 immersive app, and opens a file in explorer - preferably if the file is in a folder with multiple files, with the file highlighted.
 public async void OpenFile( string filePath)
 {
     StorageFile File = await StorageFile.GetFileFromApplicationUriAsync
                              (new Uri(filePath, UriKind.RelativeOrAbsolute)); ;

     if (File != null)
     {
         await Launcher.LaunchUriAsync(new Uri(File.Path));
     }
 }

This code gives me a permissions error. Any ideas?
Comment: This is can technically be done by writing a protocol handler which in turn starts Explorer.  Problem is that you cannot get it published through the store so it will be of no use to a store customer.  Scratch the idea, you cannot make this work.
Comment: Have you read this article on File access and permissions? http://msdn.microsoft.com/en-us/library/windows/apps/hh967755.aspx
Comment: @HansPassant If it can be done, I'd like to do it! I'd imagine if there was a generalised way to do this then it would be useful for quite a few internal Windows 8 applications, even if they could not make it to store :)
Comment: @Simon Hans is right that you won't be able to do this in an app published to the windows store. You can use the protocol handler route to make it work in a sideloaded LOB app, however there are costs associated with sideloading that may put it outside your reach. More details may be found [here](http://technet.microsoft.com/en-us/library/hh852635.aspx#SideloadingRequirements)
Answer: As far as I recall it, MS will not allow it.
The app should be design as if it's running in a sandbox, with limited rights.

You can access certain file system locations, like the app install directory, app data locations, and the Downloads folder, with Windows Store apps by default. Apps can also access additional locations through the file picker, or by declaring capabilities.

I've tried the protocol handler approach, but got rejected twice :D
Even if you find a way to do this and still publish, it doesn't mean that MS won't change his mind and remove your app from the store.
Like Hans Passant was saying :

Scratch the idea, you cannot make this work.
Comment: I don't mind about it not being accepted to be honest, this is purely for an internal app from my point of view - so it would not be listed on the Windows 8 store anyway.

Incidentally, you mention you can only access certain file locations - is that written in stone? There's no way to access the contents of any folders other than the KnownFolder location objects? That's such a pain...
Comment: "you mention you can only access certain file locations - is that written in stone?" I'm afraid it is.

If you don't mind not being listed on MS Store, then the protocol handler approach is the best way to go.
But this will imply that you will have to deliver the app update , and the all your users will be required to have a MS developer account (allowing them to install non-store apps).

PS: I am assuming that we are talking about Metro Apps(Win RT).
Answer:
this is purely for an internal app from my point of view

This is the core problem with your intended approach.  There is no concept of an "internal app" in the Windows Store ecosystem.  The only possible way to get a Store app running on another machine is by acquiring a license key that you can only get from the Store.
This is easy to overlook when you are developing a Store app on your dev machine.  It looks like this license key is not required to run and debug your app.  But there actually is one, you get it when Visual Studio pesters you with a dialog once a month to re-acquire your developer license key.  This is a temporary key, good for only one month, and purely meant to give you enough time to get your app running solidly.  There is no mechanism to transfer that key to another machine or keep it (and the program) alive beyond the one month expiration.
You can of course still publish an internal app to the Store.  But you'll be vetted for suitability and stability by the validation procedure like any other Store app.  Not just a mechanical test like WACK performs, there are two people that will test your app before it can be published.  They will not hesitate to reject your app when you do anything to try to work around the sandbox restrictions, including the protocol handler hack.
Once approved, it will be downloadable by any Windows 8 user.  Including a hacker that would be interested in your internal company secrets and practices btw.  Very convenient as well, he won't have to get out of his pajamas.
A typical line-of-business app is still a desktop app for the foreseeable future.

This answer requires an update, there's now a mechanism to publish apps from a dedicated server.  This is called sideloading.  The app still requires a certificate, and it costs big bucks, but can be deployed from a private server controlled by a private company instead of the Microsoft Store server.
An overview is available here.
Comment: @Hans That's not entirely true. Windows 8 does support sideloading of LOB apps on server 2012, enterprise, pro, and RT editions. See [here](http://blogs.technet.com/b/scd-odtsp/archive/2012/09/27/windows-8-sideloading-requirements.aspx) for more details.
Comment: Many thanks for the response. You are, of course, entirely correct. My experience with Windows 8 apps thus far has been so, so frustrating. Inability to access folders, databases, or to do simple things like this make the app store, in my view, barely worth the development effort. I was carrying out this app as a proof of concept for my company prior to developing a number more apps...at this point the API is simply too restrictive and sandboxed though :(
Comment: You can sideload apps on Windows 8. Doing so requires you to get a sideloading key though, which costs like 3000$ for up to 100 tablets.
Comment: Ouch, the price of a number has gone up quite a bit while I wasn't looking.
Comment: @RafałSaltarski can you provide source/proof for that. From what I found (http://technet.microsoft.com/en-us/windows/jj874388.aspx) & (http://www.microsoft.com/licensing/existing-customers/product-activation-results.aspx?Product=side) that is NOT the case. If the machines are domain joined, no side loading key needed. If they are not domain joined either a temp key (which I have personally used) or you can get keys via volume licensing which is pretty cheap.
Answer: There is specific API for this, nobody seems to be aware of:
var success = await Windows.System.Launcher.LaunchFolderAsync(KnownFolders.DocumentsLibrary);

More advanced form of this API takes options:
FolderLauncherOptions options = new FolderLauncherOptions();
options.ItemsToSelect.Add(file1);
bool success = await Windows.System.Launcher.LaunchFolderAsync(folder, options);

You can also set desired view using options.DesiredRemainingView.
https://msdn.microsoft.com/en-us/library/windows/apps/dn889617.aspx


How can I yield multiple pieces of content into an ember.js component template?

Question: The goal is to define a structure of HTML that has more than one block of content that is declared by the caller. For example, a header, body, and content. The resulting markup should be:
My header

My body

My footer

The template instantiating the component would define each of the three sections, My header, My body, and My footer.
With Ruby on Rails, you would use content_for :header to capture the header content from the caller, and yield :header to interpolate it.
Is this possible in ember.js?
Answer: As of ember v1.10, yield accepts parameters. However handlebars doesn't yet allow for inline comparisons of variable values. By defining some properties on the component, we can get pretty close to what rails does.
Per the above example, the component's template would look like:
{{yield header}}

{{yield body}}

{{yield footer}}

And the component definition would resolve the variable arguments to the yield statements:
export default Ember.Component.extend({
  header: {isHeader: true},
  footer: {isFooter: true},
  body:   {isBody: true}
});

This means that {{yield header}} is actually  yielding an object {isHeader: true} to the consuming template. So we can use a nested if/else structure to declare the three sections like this:
{{#my-comp as |section|}}
  {{#if section.isHeader}}
    My header
  {{else if section.isBody}}
    My body
  {{else if section.isFooter}}
    My footer
  {{/if}}
{{/my-comp}}

Comment: This can be further simplified to remove the need for the object definitions in the component. By using the `ember-truth-helpers` addon, you can use `{{yield 'header'}}` in the component template and then `{{#if (eq section 'header')}}` in the consumer template.
Answer: The previous reply may be out-to-date.
There is an accepted RFC for this problem; the Named Templates Block API will support passing multiple blocks to a component.
As of Ember 2.3, Contextual components allows another approach to this case:

Split your component into multiple subcomponents and pass the subcomponents back to the component as block parameters; this setup allows to set the content of each subcomponent block.

Check out the Twiddle - full example.
// my-component.js

{{yield (hash
   header = (component 'my-header')
   content = (component 'my-content')
   footer = (component 'my-footer')
)}}
{{#unless hasBlock}}
   {{my-header}}
   {{my-content}}
   {{my-footer}}
{{/unless}}

// my-{header/content/footer}.js

{{#if hasBlock}}
   {{yield}}
{{else}}
   Default xxxxx
{{/if}}

In this case, you could use the default component content or pass the specific content to any subcomponent like:
{{my-component}}

{{#my-component as |f|}}
  {{f.header}}
  {{#f.content}}
    Custom content
  {{/f.content}}
  {{f.footer}}
{{/my-component}}

{{#my-component as |f|}}
  {{#f.header}}
     Custom header
  {{/f.header}}
  {{#f.content}}
     Custom content
  {{/f.content}}
  {{#f.footer}}
     Custom footer
  {{/f.footer}}
{{/my-component}}

This solution does not force the component API/structure, then the component could be wrongly used if a subcomponent is omitted, added multiple times, or have the wrong order, in these cases the component will generate an undesired content.

Check out the Twiddle - full example.
Comment: This should be the accepted answer for Ember 2.x and 3.x
Comment: Additionally, instead of hardcoding the yielded subcomponents, the parent component `my-component` can accept them as parameters.


Linear transformations with respect to a basis

Question: Problem: I have a question which has a linear map $T: \mathbb{R}^3 \rightarrow \mathbb{R}^3$ defined by $T(x,y,z)=(0,x,y)$. With an ordered basis $F = \{(1,1,1)^T, (1,1,0)^T, (0,1,1)^T\}$ and $E$ the standard basis.
Part of the solution says that $_{F}T_{E}=\begin{pmatrix}0 & 0 & 0\\1 & 1 &0 \\1 & 1 & 1\end{pmatrix}$.
Attempt: However I thought that we know the matrix which takes the standard basis vectors to the their mapping under $T$ is $_{E}T_{E}=\begin{pmatrix}0 & 0 & 0\\1 & 0 &0 \\0 & 1 & 0\end{pmatrix}$. So the $F$ basis vectors must go to $_{E}T_{E}(1,1,1)^T= (0, 1, 1)^T,\hspace{2mm}_{E}T_{E}(1,1,0)^T= (0, 1, 1)^T,\hspace{2mm}_{E}T_{E}(0,1,1)^T= (0, 0, 1)^T$ which are the images represented in the $E$ basis, of the mappings under $T$. So the matrix which takes the $F$ basis vectors w.r.t. $F$ to the image of the $F$ basis vectors w.r.t. $E$ under the transformation (i.e. $_{E} T _{F}$) would be $_{E}T_{F}=\begin{pmatrix}0 & 0 & 0\\1 & 1 &0 \\1 & 1 & 1\end{pmatrix}$.
Why is what I've done the opposite of the solution?
Answer: Consider the coordinate mappings:
$X_F:\mathbb{R}^3\to\mathbb{R}^3$
(sends a vector to its coordinates in the basis F)
and
$X_E:\mathbb{R}^3\to\mathbb{R}^3$
(sends a vector to its coordinates in the basis E).
We note that (since E is the elementary basis and our vector space is just $\mathbb{R}^3$ already) $X_E^{-1}$ is just the identity map $1_{\mathbb{R}^3}$. Write E and F respectively as follows:
$\{E^1,E^2,E^3\}$.
and
$\{F^1,F^2,F^3\}$.
Note that multiplying a 3x3 matrix $M\in M_3(\mathbb{R})$ by $E^j$ will just give us the $j^{th}$ column of M. So we compute $_ET_F$ as follows:
$_ET_FE^j = X_F(T(X_E^{-1}(E^j))) = X_F(T(E^j))$.
Hence:
$_ET_FE^1 = X_F(T(E^1)) = X_F((0,1,0)^T) = (1,1,0)^T$
$_ET_FE^2 = X_F(T(E^2)) = X_F((0,0,1)^T) = (0,1,1)^T$
$_ET_FE^3 = X_F(T(E^3)) = X_F((0,0,0)^T) = X_F(0) = (0,0,0)^T$
so that
$_ET_F = \begin{pmatrix} 1 &0 &0\\ 1 &1 &0\\ 0 &1 &0\end{pmatrix}$.
Comment: Thank you! My lecturer has never explained it like this and now I finally understand it.


How Do I Prove the 6 Letter Thesis Cδδ0δp?

Question: There exists a 1951 paper by C. A. Meredith which proves a completeness meta-theorem for the "C, 0, δ, p" system which has as it's sole axiom Cδδ0δp under uniform substitution for propositional variables, uniform substitution for functorial variables [see here] or this part from A. N. Prior's Formal Logic, and detachment.  There exists another system of the same type which has as it's axioms:
1. CδC00δ1
2. Cδ0Cδ1δp

I've read through a proof by Lukasiewicz which shows that from those two axioms follows:
3. CδC10δ0
4. CδC01δ1
5. CδC11δ1
6. 1

I know how to prove formulas like CδCpqCδpδq and CCpqCCqpCδpδq from the above 6 theses.  And I can tell that if I can prove Cδδ0δ0 and Cδδ0δ1, I can prove Cδδ0δp.  But, from the above 6 formulas, how can we prove something which has two δ's on one side and one δ on the other?  How can we prove Cδδ0δ0 and Cδδ0δ1?  Or can we prove Cδδ0δp without proving those two first?
Comment: @Joffan: Doug is talking about two different systems. One of them has it as an axiom, and he's apparently trying to show that this axiom can be derived as a theorem in the other system.
Comment: @Joffan Brian M. Scott is correct in that I want to show Cδδ0δp as a theorem in the second system.  I've edited this post to say 'thesis' in the title now.
Comment: Actually, my notes indicate that Lukasiewicz's paper that I read says that the axiom CδC00Cδ0p along with the definition CδC00δ1 prove CδC01δ1, CδC10δ0, and CδC11δ1.  1 is still easily derivable.  That said, I haven't seen a proof that the first two formulas lead to formulas 3. through 6.  I think A. N. Prior asserts what I claimed above in his textbook Formal Logic.
Answer: I don't know why I wrote the above axioms when I didn't really care if they had the form CδCxyδz or CδzδCxy, but I suppose the forms I used might provide for a more instructive proof.  Section 2. part I. of Meredith's paper gave me enough hints, along with some previous experience working with this sort of system, to construct a proof.  As a special case of a more general metalogical statement in his paper indicates, if we prove CCCp0δ0CCpδC00δp, CCδ00Cδ0δp, and Cδ0CδC00δp we can prove Cδδ0δp in short order.  Proving Cδ0CδC00δp can get proved from Cδ1δC00 and Cδ0Cδ1δp.  CCδ00Cδ0δp consists of an instance of CCp0Cpq.  How to prove CCCp0δ0CCpδC00δp can get seen from the cases CCC00δ0CC0δC00δ0 which reduces to CC1δ0CC0δC00δ0 which reduces to Cδ0CC0δC00δ0 an instance of CpCqp, and CCC10δ0CC1δC00δ1 which reduces to CCC10δ0CδC00δ1 which reduces to CCC10δ0Cδ1δ1 an instance of CpCqq.  CδpδC1p will make for a useful lemma also.
1 1
2 CδC00δ1
3 CδC01δ1
4 CδC10δ0
5 CδC11δ1
6 Cδ0Cδ1δp

First, we'll transform the axioms from having form CδCxyδz to form CδzδCxy.  A useful, but strictly unnecessary (study steps 9 through 13 closely), lemma is Cpp.
    6 δ/CδC''δ1 * 7
7 CCδC00δ1CCδC11δ1CδCppδ1
    7 * C2-8
8 CCδC11δ1CδCppδ1
    8 * C5-9
9 CδCppδ1
    9 δ/Cδ'δCpp * 10
10 CCδCppδCppCδ1δCpp
    9 δ/CCδCppδ'Cδ1δCpp * 11
11 CCCδCppδCppCδ1δCppCCδCppδ1Cδ1δCpp
    11 * C10-12
12 CCδCppδ1Cδ1δCpp
    12 * C9-13
13 Cδ1δCpp
    13 δ/' * 14
14 C1Cpp
    1 * C14-15
15 Cpp

Now, using 15 repeatedly as follows we'll transform 2. through 5.:
    15 p/δC00 * 16
16 CδC00δC00
    2 δ/Cδ'δC00 * 17
17 CCδC00δC00Cδ1δC00
    17 * C16-18
18 Cδ1δC00
    15 p/δC01 * 19
19 CδC01δC01
    3 δ/Cδ'δC01 * 20
20 CδC01δC01Cδ1δC01
    20 * C19-21
21 Cδ1δC01
    15 p/δC10 * 22
22 CδC10δC10
    4 δ/Cδ'δC10 * 23
23 CCδC10δC10Cδ0δC10
    23 * C22-24
24 Cδ0δC10
    5 δ/Cδ'δC11 * 25
25 CCδC11δC11Cδ1δC11
    15 p/δC11
26 CδC11δC11
    25 * C26-27
27 Cδ1δC11

Now, we'll prove Cδ0CδC00δp.
    18 δ/Cδ0Cδ'δp * 28
28 CCδ0Cδ1δpCδ0CδC00δp
    28 * C6-29
29 Cδ0CδC00δp

Next up CpCqp.
    21 δ/' * 30
30 C1C01
    24 δ/' * 31
31 C0C10
    27 δ/' * 32
32 C1C11
    6 δ/C1C'1, p/q * 33
33 CC1C01CC1C11C1Cq1
    33 * C30-34
34 CC1C11C1Cq1
    34 * C32-35
35 C1Cq1
    30 * C1-36
36 C01
    18 δ/C0' * 37
37 CC01C0C00
    37 * C36-38
38 C0C00
    6 δ/C0C'0, p/q * 39
39 CC0C00CC0C10C0Cq0
    39 * C38-40
40 CC0C10C0Cq0
    40 * C31-41
41 C0Cq0
    6 δ/C'Cq' * 42
42 CC0Cq0CC1Cq1CpCqp
    42 * C41-43
43 CC1Cq1CpCqp
    43 * C35-44
44 CpCqp

To avoid re-numeraling, we'll prove CCδ00Cδ0δ0.
    44 p/Cqq, q/p * 45
45 CCqqCpCqq
    15 p/q * 46
46 Cqq
    45 * C46-47
47 CpCqq
    47 p/Cδ00, q/δ0 * 48
48 CCδ00Cδ0δ0

Now CCp0Cpq.
    18 δ/' * 49
49 C1C00
    18 δ/C'C00 * 50
50 CC1C00CC00C00
    50 * C49-51
51 CC00C00
    18 δ/C'C01 * 52
52 CC1C01CC00C01
    52 * C30-53
53 CC00C01
    6 δ/CC00C0', p/q * 54
54 CCC00C00CCC00C01CC00C0q
    54 * C51-55
55 CCC00C01CC00C0q
    55 * C53-56
56 CC00C0q
    15 p/C10 * 57
57 CC10C10
    47 p/0, q/1 * 58
58 C0C11
    24 δ/C'C11 * 59
59 CC0C11CC10C11
    59 * C58-60
60 CC10C11
    6 δ/CC10C1', p/q * 61
61 CCC10C10CCC10C11CC10C1q
    61 * C57-62
62 CCC10CC11C10C1q
    62 * C60-63
63 CC10C1q
    6 δ/CC'0C'q * 64
64 CCC00C0qCCC10C1qCCp0Cpq
    64 * C56-65
65 CCC10C1qCCp0Cpq
    65 * C63-66
66 CCp0Cpq

Now CδpδC1p
    6 δ/Cδ'δC1' * 67
67 CCδ0δC10CCδ1δC11CδpδC1p
    67 * C24-68
68 CCδ1δC11CδpδC1p
    68 * C27-69
69 CδpδC1p

Now CCC00δ0CC0δC00δ0.  Let $\alpha$ stand for a functorial variable of one argument.
    44 p/δ0, q/C0δC00 * 70
70 Cδ0CC0δC00δ0
    69 p/α0 * 71
71 Cδα0δC1α0
    71 δ/C'CC0δC00δ0 * 72
72 CCα0CC0δC00δ0CC1α0CC0δC00δ0
    72 α/δ * 73
73 CCδ0CC0δC00δ0CC1δ0CC0δC00δ0
    73 * C70-74
74 CC1δ0CC0δC00δ0
    18 δ/CC'δ0CC0δC00δ0 * 75
75 CCC1δ0CC0δC00δ0CCC00δ0CC0δC00δ0
    75 * C74-76
76 CCC00δ0CC0δC00δ0

Now CCC10δ0CC1δC00δ1.
    47 p/CC10δ0, q/δ1 * 77
77 CCC10δ0Cδ1δ1
    18 δ/CCC10δ0Cδ'δ1 * 78
78 CCCC10δ0Cδ1δ1CCC10δ0CδC00δ1
    78 * C77-79
79 CCC10δ0CδC00δ1
    71 δ/CCC10δ0C'δ1 * 80
80 CCCC10δ0Cα0δ1CCC10δ0CC1α0δ1
    80 α/δC'0 * 81
81 CCCC10δ0CδC00δ1CCC10δ0CC1δC00δ1
    81 * C79-82
82 CCC10δ0CC1δC00δ1

Now CCCp0δ0CCpδC00δp
    6 δ/CCC'0δ0CC'δC00δ' * 83
83 CCCC00δ0CC0δC00δ0CCCC10δ0CC1δC00δ1CCCp0δ0CCpδC00δp
    83 * C76-84
84 CCCC10δ0CC1δC00δ1CCCp0δ0CCpδC00δp
    84 * C82-85
85 CCCp0δ0CCpδC00δp

Now Cδδ0δp.
    85 δ/Cδ'δq * 86
86 CCCp0Cδ0δqCCpCδC00δqCδpδq
    86 p/δ0 * 87
87 CCCδ00Cδ0δqCCδ0CδC00δqCδδ0δq
    66 p/δ0, q/δq * 88
88 CCδ00Cδ0δq
    87 * C88-89
89 CCδ0CδC00δqCδδ0δq
    89 q/p * 90
90 CCδ0CδC00δpCδδ0δp
    90 * C29-91
91 Cδδ0δp


Algebraic + purely transcendental

Question: Let $K \subset L$ be an extension of fields of transcendence degree at least $1$. Does there always exist a subfield $K \subset M \subset L$ such that $M/K$ is algebraic and $L/M$ is purely transcendental? If this is not true in general, can some extra conditions on $K$ and $L$ make this work - for example the condition that $L/K$ is finitely generated?
Comment: See here: http://math.stackexchange.com/a/5285/4396
Comment: What if $K$ is algebraically closed?
Comment: THere has to be soemthing more here, right? I mean, if $L/K$ is finite then this can never happen for obvious reasons?
Comment: Suppose that $K$ is the algebraic numbers in $\mathbb{C}$, and let $L$ be the algebraic closure of $K(\pi)$.  Then $L/K$ has transcendence degree $1$, but surely no such field $M$ exists.
Answer: Gastón Burrull's comment contains the important idea: if $K$ is algebraically closed, you are asking whether every extension of $K$ is purely transcendental, which is clearly false. For example, when $K = \mathbb{C}$ the fraction field of $\mathbb{C}[x, y]/(y^2 - x^3 - x)$ cannot be purely transcendental because it is the function field of an elliptic curve (which is not birationally equivalent to $\mathbb{P}^1$).
Comment: Your example is the same as the one given [here](http://math.stackexchange.com/questions/5278/why-is-mathbbqt-sqrtt3-t-not-a-purely-transcendental-extension-of-m) and pointed out by wxu's comment above.

Algebraic + purely transcendental


real data where x causes y and both variables also share correlated unobserved causes

Question: Is there an example in 'causality' discussing a case where 2 variables: x causes y; and at the same time there is correlation between their unobserved causes?
I can think of syntetic examples like:
<code>ug=matrix(nrow=N,c(0.5,0.4,0.4,0.5))
d=matrix(nrow = 500,ncol = 2)
noise=mvrnorm(n=500,rep(0,N),ug)
d[,1]=noise[,1]
d[,2]=sin(d[m,1])+noise[,2]
plot(d[,1],d[,2])
points(d[,1],sin(d[,1]),col="red")
</code>

x causes y, and at the same time their unobserved causes have correlation...
My question is if this is discussed in causality and/or if there is real (non-syntetic) data behaving like this.
Answer: So, let's suppose we have a causal diagram like this:

The $X\to Y$ arrow means $X$ definitely causes $Y,$ and the same for $U_1$ causing $X$ and $U_2$ causing $Y.$ The dotted line between $U_1$ and $U_2$ stands for an unknown causal relationship, but a correlation at the very least. Now, by assumption, $U_1$ and $U_2$ are unobserved. So, as it stands, we cannot be certain that the data we have and the calculations we perform are capturing the true causal relationship between $X$ and $Y.$
There are at least a couple possible solutions. One method is the front door adjustment, which goes like this: suppose you could identify and insert a mediator variable $Z$ in-between $X$ and $Y,$ like this:

Then the front-door adjustment formula is
$$
\newcommand{\doop}{\operatorname{do}}
P(y|\doop(x))=\sum_zP(z|x)\sum_{x'}P(y|x',z)\,P(x').
$$
This allows you to find the true causal effect of $X$ on $Y.$
Another approach is to use an instrumental variable, which we tack on to the back, like this:

What you would then do is:

We regress $X$ and $Y$ on $Z$ separately, yielding the regression equations $y=r_1z+\varepsilon$ and $x=r_2z+\varepsilon,$ respectively. Since $Z$ emits no backdoors, ... $r_1$ equals the total effect of $Z$ on $Y...$ Therefore, the ratio $r_1/r_2$ provides the desired coefficient... - from Causal Inference in Statistics, A Primer, by Pearl, Glymour, and Jewell.
Answer: Poor diet causes poor health. Poverty is a common cause of both.
Chronic obstructive pulmonary disease causes heart disease. Smoking is a cause of both.
The phenomenon you point to is common.
Answer: Yes, this happens quite often in clinical data. To give an example, more severe observed disease status (x) will often cause an increase in treatment time (y). However, both observed disease status and treatment time are generally positively correlated with unobserved disease severity measures.


Sum of two independent Student t variables with same dof is t distributed?

Question: What is the distribution of the difference of two-t-distributions suggests that the sum of two t-distributions is never t distributed.
With t distribution I mean the (non-standardized) t distribution with location and scale parameter.
Now, let $Y_1,Y_2$ be independently t distributed with same dof $\nu$, location $\mu$ and scale $\sigma$.
Then the sum is given by $X = Y_1+Y_2 = (\mu+\sqrt{\nu/V}\sigma Z_1) + (\mu+\sqrt{\nu/V}\sigma Z_2)$, where $V$ is $\chi^2$ distributed with $\nu$ degrees of freedom and $Z_1,Z_2\stackrel{iid}{\sim}N(0,1)$. Since the sum of two independent $N(0,1)$ is $N(0,2)$, it follows that
$X = 2\mu+\sqrt{\nu/V}\sqrt{2}{\sigma}Z$, where $Z\sim N(0,1)$. Thus $X$ is t distributed with unchanged dof, twice the location and new scale $\sqrt{2}\sigma$.
So am I missing something?
Comment: I actually interpret the response there as saying it's not the case in general, not that it can never be the case. But in any case your argument is looks wrong. You used the same $V$ in $Y_1$ and  $Y_2$. You should have different $V$s.
Comment: Thanks! You're right. In fact using the same $V$ in $Y_1$ and $Y_2$ results in a bivariate t distribution for $Y_1$ and $Y_2$! And linear combinations are then t distributed, because the t distribution is an elliptical distribution. Sometimes you miss the forest for the trees...
Answer: I think you are wrong, because the Student-t includes the Gaussian and the Cauchy distribution. It is well known that sum of Cauchy is Cauchy and sum of normal is normal - so there are at least two contradictions!
Comment: This isn't a contradiction at all. You founf two cases where it is true! unfortunately, it is not true in any other case.