If $A$ has a maximum, prove that it only has one.

Question: Let $A\subseteq \mathbb{R}$. We say that a real number $M\in\mathbb{R}$ is a maximum of $A$ if $M$ is an upper bound for $A$ and $M\in A$.
If $A$ has a maximum, prove that it only has one; and prove that if $\max A$ exists, then so does $\sup A$, and $\sup A=\max A$.
To prove that $A$ has only one maximum, I'm pretty sure I have to assume that there are two maximums but then show that they are the same. I'm just confused as to how to do this.
Any help is greatly appreciated. Thank you!
Answer: Let $M$ and $M'$ two maximum of a set $A$ then $M,M'\in A$ and
$$\forall a\in A,\; a\le M$$
so in particular and since $M'\in A$ then we have $M'\le M$. Similarly we get $M\le M'$ hence $M=M'$.
Comment: Similarly, since $\sup A$ is the least upper bound for $A$ and $M$ is an upper bound for $A$, we have $\sup A \leq M$. But $\sup A$ is an upper bound for $A$ and $M \in A$, so $M \leq \sup A$.
Answer: Let $M_1$ and $M_2$ both be maxima of $A$, and suppose $M_1 > M_2$.  Then since $M_2$ is an upper bound of $A$, $M_1 \not \in A$, contradicting the definition of a maximum which requires $M \in A$.
Then suppose $M$ is a maximum of $A$. Then $\forall a \in A: a \leq M$, so that part of the definition of $\sup$ is met by $M$.  Now suppose there were some other value $M' < M$ also meeting that definition.  Since $M\in A$, $M$ cannot be less than or equal to than $M'$. Amd that contradicts the statement about $M'$ also meeting that part of the definition of $\sup A$.  So $M$ is the lowest number such that all members of $A$ are less than or equal to $M$, completing the requirements for $M = \sup A$.


Send "Request new password" email for individual users

Question: I'm looking for a way for the administrator users to quickly send out a password reset for a specific user. Ideally, this would be a link/check on the account edit.
I have seen and made use of the Mass Password Reset module which works per role, but I need it for individuals too.
At the moment my thought is to make a "reset password" role then have a rule along the lines of: after saving user, if user has "reset password" role, send account recovery email, remove "reset password" role, but that seems pretty convoluted. Am I missing an easy solution?
I am using Drupal 7.
Answer: If you'd create an appropriate view (using Views) of your users, wit whatever filter criteria you'd want, you could use that view to combine it with the Rules Link module. And with that you have the full power of the Rules module available also to implement whatever logic you'd want.
Refer to the accepted answer to "How to show authorized users a link for relevant Views results using the Rules Link module?" for an in depth explanation about using the Rules Link module, related to a scenario which is a variation of your question here (i.e. show a link to unblock blocked users).
Comment: thanks, that makes sense - not too different to my solution but more intuitive  for users i bet
Comment: @user3016811 thank you for your comment, Not sure if I correctly translate it, but maybe you want to consider marking my answer as accepted? Similar to what is mentioned [here](http://drupal.stackexchange.com/help/someone-answers) ...


How do I render  side-by-side?

Question: I'm looking to create a navigation menu with list items rendered in one line.  How do I do this?
Answer: li {
    display: inline;
}

EDIT: I now realize why I felt strange answering with display: inline: because I usually use float: left myself instead, which is anthony-arnold's answer (so to him goes my upvote!).
Anyway, while either method will cause your lis to display in one line, inline elements and floated elements do behave differently. Depending on how you've styled your layout, you may have to choose one or the other.
Comment: Floated elements can still be block-level (in fact, they're ALWAYS treated as block-level) and so you can still apply box model properties like padding and margin to them. Inline elements ignore padding/margin, so float: left is usually the best solution. In fact, if you use BOTH, it will correct a bug in IE6 that causes floated elements to have double margins (though all browsers will still render them as block-level).
Answer: You could also do this, for some situations:

li {
    float: left;
}
Comment: This would not work for odd number of elements
Answer: My favorite way to do it it's by using because it's allow do use width, height, margins and padding:
li { display: inline-block; }

But have some render problem in IE, to fix use (order is important):
li
{
  display: inline-block;
  zoom: 1;
  *display: inline;
}

Answer: One of the best resources on the subject is http://css.maxdesign.com.au/listamatic/ (a little outdated though).
They suggest both li {display: inline;}  and li {float: left;} depending on the effect you want.
Look for example their "Simple horizontal list" http://css.maxdesign.com.au/listamatic/horizontal01.htm
Answer: ul {
    float: right;  to
 go to the Right or Left side
}

ul li {
    display: inline-block;
    padding: 10px;
    margin-top: 5px;
}

If you use the "float:" in the "li", the list will invert the sequency.
Answer: ul {display: inline;}
ul li { list-style: none;display: inline;}

Comment: +1.. I was wondering. Why didn't anyone mention the list-style: none. It is needed right? Or bullet points will appear horizontally.
Answer: You could do:
li {
    float: left;
    display: inline;
}

If you want to maintain it's block characteristics but still need side-by-side, you could do:
li {
    float: left;
    display: inline-block;
}

Comment: Doesn't floating an element automatically cause it to `display: block`? Or is it still overridable?
Comment: @BoltClock: You could use either `display:inline` or `float:left` but using float saves you from display getting screwed up in IE<=7, however, this depends on your html markup, using both together is better in most cases.
Comment: Ah, sounds like an IE issue after all.
Comment: Just to add some clarification, it's actually the addition of display:inline that corrects the IE <= 6 bug. And yes Bolt, floating will cause an element to be treated as display: block. IE6 will do weird things with the margin if you don't in turn specify display: inline (confusing, because IE6 will STILL render it as block-level, just will not screw up the margins).
Answer: you will try this styling
li{
height:20px;
float:left;
list-style-type: none;
width:70px;
padding:3px;
border-right:1px solid #3687AF;
background-color: #015287;
background-repeat: no-repeat;
background-position: center 30px;
}

it will work for u sure...
Answer: you can use float: left;
ul li {
    float: left;
}

How do I render  side-by-side?


Mudar projeto c# .Net 4.6 para .Net4.5

Question: Teria alguma forma de mudar a verão do .Net utilizada no meu projeto para uma versão anterior ?
No meu projeto está com .NET 4.6 e gostaria de voltar para a versão .NET 4.5 sem ter que refaze tudo ?
Comment: E por que faria isto?
Comment: @Maniero Estou tentando subir meu projeto para o servidor onde está rodando a versão 4.5 do .NET e meu projeto esta com a versão 4.6
Comment: O ideal é atualizar o servidor, não acha?
Answer: 1 - Vá em  gerenciador de solução
2 - Clique com o  botão  direito em cima  do  projeto  que deseja
3 - Vá em propiedades

4 - CLique em Aplicativo
5 - Altere a Estrutura de Destino e pronto

Lembrando  que todos os projetos dentro  da solução devem  estar  na mesma  versão  para evitar erros de compilação.
Answer: Abra as propriedades do projeto e altere a opção "Target Framework" para a versão do .NET Framework desejada... Note que se você utilizou alguma funcionalidade do .NET Framework 4.6, ao alterar o target framework para alguma inferior, você vai receber erros de compilação... E não existe uma maneira automática de fazer a conversão do 4.6 para uma inferior (somente ao contrário)...
Mas, se você não utilizou nenhum recurso do .NET 4.6, você não vai ter problema algum...
Answer: Abra o arquivo .csproj e altere a tag <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> com a versão que deseja utilizar.

Mudar projeto c# .Net 4.6 para .Net4.5


Easy but complicated proposition in Fulton's book

Question: W. Fulton's Algebraic Curves: An Introduction to Algebraic Geometry defines the following sets:

I'm trying to prove first the $(V^*)_*=V$, but I'm stuck with a lot of recurrence definitions,  see (Remark: to avoid confusion I'm using the algebraic set $W$, instead of $V$):
$(W^*)_*=V(I_*)=\{p\in \mathbb A^n;f(p)=0,\forall \in f\in I_*\}=\{p\in \mathbb A^n;f(p)=0,\forall \in p;f={g_1f_1}_*+\ldots {g_nf_n}_*,g_i\in k[X_1,\ldots X_n],f_i\in I=I(W^*)\}$
but $I(W^*)=\{h\in k[X_1,\ldots X_n];h(q)=0,\forall q\in W^*=V(I^*)\}$, i.e., $l(q)=0,\forall l\in I^*$, i.e., for every $l=w_1l_1^*+\ldots w_nl_n^*, l(q)=0$, $w_i\in k[X_1,\ldots, X_n], l_i\in I=I(W)$, i.e., $l_i(s)=0$ for every $s\in W$.
I need help
Thanks in advance
Comment: "Easy but complicated..."?
Comment: Dear user, Why don't you first try this for a principal ideal, so you just have *one* polynomial $f$ to think about?  This may make things clearer.  Regards,
Comment: "In Fulton's book..." Fulton has more than one book; could you be more specific?
Comment: @PeterTamaroff it seems easy, we have just to use the definitions above, but becomes complicated because of the large amount of definitions intercorrelated.
Comment: @PeteL.Clark algebraic curves
Answer: Note, if an ideal is being generated by a collection of elements $\{f_i\}$ (e.g. $I_*$ is generated by the elements $F_*$ with $F \in I$), then
$f(p) = 0$ for all $f \in I$ if and only if $f_i(p) = 0$, where $f_i$ runs over the generating set.  So for example there is no need to introduce the $g_i$ in you definition of $V(I_*)$.
Also, note that $W^*$ is the variety cut out by the ideal $I(W)^*$ (by definition), so $I(W^*)$ is equal to the radical of $I(W)^*$.  With a little argument you should be able to get around taking this radical, and hence get yourself in a situation where $I(W^*) = I(W)^*$, which is the ideal generated by $F^*$ with $F \in I(W)$.
At this point you should be reduced to understanding $(F^*)_*$, at which point things will hopefully become clear.

As I suggested in my comment above, you might first want to take the case where $W$ is cut out by a single irred. polynomial $F$.  This will simplify things, but still captures the spirit of the question.
Comment: what do you mean by _where $f_i$ runs over the generating set_?
Comment: @user42912: Dear user, I mean $f(p) = 0$ for all $f \in I$ if and only $f_i(p) = 0$ for each member $f_i$ of the generating set.  Regards,


Triangle, vectors, hard to explain

Question: P is the middle of a median line from vertex A, of ABC triangle. If Q is the point of intersection of lines AC and BP. Find relations of $|\vec{AQ}|$/$|\vec{QC}|$ and $|\vec{BP}|$/$|\vec{PQ}|$

Any suggestions for the title, welcomed.
Answer: We have $M=\tfrac12(B+C)$,
$P=\tfrac12(A+M)$
Expressions for the points
on the lines $AC$ and $BP$ in parametric form are:
\begin{align}
p_{AC}(s)
&=
(1-s)\cdot A+s\cdot C,
\\
p_{BP}(t)
&=
(1-t)\cdot B+t\cdot P.
\end{align}
Since $Q=AC \cap BP$,
\begin{align}
Q&=
p_{AC}(s)
=
p_{BP}(t),
\\
(1-s)\cdot A+s\cdot C
&=
(1-t)\cdot B+t\cdot P.
\end{align}
The last one gives a linear system
of two equations (for $x$ and $y$ coordinates)
in two unknowns $s$ and $t$,
with solution
$s=\tfrac13$,
$t=\tfrac43$ and then the answer is
\begin{align}
\frac{|AQ|}{|QC|}&=\tfrac12
\\
\frac{|BP|}{|PQ|}&=3.
\end{align}

Triangle, vectors, hard to explain


How Kendo grid select row get the selected userID?

Question: Hi i need some help for to get the select row id as i realize i am able to get my ajax from my response however is there a way where i select the row i can display the id selected one ?
Updated by using the new onchange i have make a selected id however i got error still

var dataSource = new kendo.data.DataSource({
  read: {
    url: "https://ecoexchange.dscloud.me:8090/api/get",
    dataType: "JSON",
    method: "GET",
    headers: {
      query: "UserGet(1)",
      // Gets the apikey from the sessionStorage
      apikey: sessionStorage.getItem("apikey")
    }
  },
});

$("#user-list").kendoGrid({
  dataSource: dataSource,
  height: $(window).height() - $("#user-list").position()["top"] - 130,
  selectable: "single, row",
  change: function(e) {
    var selectedRows = this.select();
    var selectedDataItems = [];
    for (var i = 0; i < selectedRows.length; i++) {
      var dataItem = this.dataItem(selectedRows[i]);
      selectedDataItems.push(dataItem);
    }
    // selectedDataItems contains all selected data items
    /* The result can be observed in the DevTools(F12) console of the browser. */
    if (selectedDataItems && selectedDataItems.length > 0) {
      $("#selection")[0].innerHTML = selectedDataItems[0].UserID;
    }
  },

  // width: $(window).width()-$("#customer-list").position()["width"]-10,
  //pageSize: 10,
  scrollable: {
    endless: true,
  },

  columns: [

    {
      field: "",
      title: "Profile",
      headerAttributes: {
        "class": "k-text-center"
      },
      width: 150
    },
    {
      field: "",
      title: "User Name",

    },
  ],

});

$("#user-list tbody").on("click", "tr", function(e) {

  const btns = $('.select-row');

  var rowElement = this;
  var row = $(rowElement);
  var grid = $("#user-list").getKendoGrid();
  if (row.hasClass("k-state-selected")) {
    var selected = grid.select();
    selected = $.grep(selected, function(x) {
      var itemToRemove = grid.dataItem(row);
      var currentItem = grid.dataItem(x);
      return itemToRemove != currentItem
    })

    btns.prop('disabled', true).removeClass('disabled dark');

    grid.clearSelection();

    grid.select(selected);

    e.stopPropagation();
  } else {
    grid.select(row)

    e.stopPropagation();

    btns.prop('disabled', false).removeClass('disabled dark');
  }
});

I am calling my ajax to kendo grid where kendo grid created the grid and the selected row
This is how the page look like

However i have no idea how to select the row display the userID display where then if this is selected when press view details the information be pass into there
This is the response example
[
    {
        "UserID": 1,
        "Name": "Kelyn Wong",
        "Username": "kelynwong",
        "Email": "email@example.com",
        "Picture": null,
        "UserRole": "Approving Admin"
    },
    {
        "UserID": 2,
        "Name": "Kai Jie",
        "Username": "kaijie",
        "Email": "email@example.com",
        "Picture": null,
        "UserRole": "Admin"
    },

This is how the row selected look like when the user select the row

This the whole code from body to script from using ajax to kendo grid

< script >
  /* Call the ajax to load to load to #customer-list tbody */

  $.ajax({
    url: "https://ecoexchange.dscloud.me:8090/api/get",

    method: "GET",
    // In this case, we are going to use headers as
    headers: {
      // The query you're planning to call
      // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
      query: "UserGet(0)",

      // Gets the apikey from the sessionStorage
      apikey: sessionStorage.getItem("apikey")
    },

    success: function(data, xhr, textStatus) {
      //console.log(data)

      const buildTable = data => {
        const table = document.querySelector("#user-list tbody");

        for (let i = 0; i < data.length; i++) {
          let row =
       `

    ${data[i].Name}

        `;
          table.insertAdjacentHTML('beforeEnd', row);
        }
      };
      // Fetch method
      const getData = async(url) => {

        const response = await fetch(url, {
          method: 'GET',
          headers: {
            query: "UserGet(0)",
            // Gets the apikey from the sessionStorage
            apikey: sessionStorage.getItem("apikey")
          }
        });
        const json = await response.json();
        $("#loading-container").hide();
        return buildTable(json);
      };

      /*Error GET http://127.0.0.1:5501/testEnv/view/public/manageCustomers/null 404 (Not Found) */
      /* But code are able to fetch the data */
      getData("https://ecoexchange.dscloud.me:8090/api/get")
    },

    error: function(xhr, textStatus, err) {
      console.log(err);
    }
  });

$(window).on("resize", function(e) {
  console.log("width:", $("#user-list").width(), "height:", $("#user-list").height())
});

$("#user-list").kendoGrid({

  height: $(window).height() - $("#user-list").position()["top"] - 130,
  selectable: "single",
  // width: $(window).width()-$("#customer-list").position()["width"]-10,
  //pageSize: 10,
  scrollable: {
    endless: true,
  },

  columns: [

    {
      field: "",
      title: "Profile",
      headerAttributes: {
        "class": "k-text-center"
      },
      width: 150
    },
    {
      field: "",
      title: "User Name",

    },
  ],

});

$("#user-list tbody").on("click", "tr", function(e) {

  const btns = $('.select-row');

  var rowElement = this;
  var row = $(rowElement);
  var grid = $("#user-list").getKendoGrid();
  if (row.hasClass("k-state-selected")) {
    var selected = grid.select();
    selected = $.grep(selected, function(x) {
      var itemToRemove = grid.dataItem(row);
      var currentItem = grid.dataItem(x);
      return itemToRemove != currentItem
    })

    btns.prop('disabled', true).removeClass('disabled dark');

    grid.clearSelection();

    grid.select(selected);

    e.stopPropagation();
  } else {
    grid.select(row)

    e.stopPropagation();

    btns.prop('disabled', false).removeClass('disabled dark');
  }
});

//

$("#search-user-name").on("keyup change", function() {
    var usernames = $("#search-user-name").val().toLowerCase();

    //console.log(usernames);
    if (usernames == "") {
      $('#user-list tbody tr td.cell-user-name').parent().show();
    } else {
      $("#user-list tbody tr").filter(function() {
        var usernameText = $(this).children("td.cell-user-name").text().toLowerCase();

        $(this).toggle(
          (usernameText.indexOf(usernames) >= 0)
        );
      })

    };

  })

  <
  /script>

        <input class="search-input form-control" placeholder="Name" type="text" name="User Name" id="search-user-name">

      <fieldset class='btn-group'>

        <button onclick="window.location.href='addUsers.html'" id="add" type="button" class="btn btn-primary btn custom mr-1 mb-2" style="border-radius: 5px;">Add </button>

        <button onclick="window.location.href=''" id="edit" type="button" class=" btn-primary btn custom mr-1 mb-2 disabled select-row" style="border-radius: 5px; margin-left: 5px;" disabled>View Details</button>
      </fieldset>

Fetching all users data...

Answer: You can use the change event of the Kendo Grid to get the selected row. See the snippet below for a demo from the Kendo documentation.

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>

    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.3.1207/styles/kendo.default-v2.min.css"/>

    Selection:

Comment: Thanks i see
But here come a question how can i put the datascource to ajax ?
cos i try to  copy this  i realize not getting the thing defined ?
Comment: I've updated the demo to use an external data source. If it isn't what you meant, please clarify your question.
Comment: Thanks but i got undefined through :( not sure why
Comment: May i know where ProductID come from ?

as i have selectedDataItems[0].ProductID;

as i remove it i got undefined
Comment: `productID` is a field in the demo data from Telerik's service. Try replacing it with `userID` if that's the field you are using in your code. Try copying just the `change` event handler to your Grid options object and replace `productID` with the field you are using
Comment: Hi i have updated the new error receive when i use this method it seems that i cant find UserID
Comment: Inside the `change` event handler, add the code `console.log(e);`. Look in the console and see what the object contains.
Comment: This is what i get ?
https://i.imgur.com/0pzzqoE.png
Comment: OK try replacing it with this: `console.log(this.dataItem(this.select()[0]));`.
Comment: I've updated the code snippet with a simpler demo that also writes the selected row's data to the console.
Comment: Sure console.log(this.dataItem(this.select()[0])); i try this i got undefined that mean my dataitem is none ?
Comment: This is what i get Undefined in changes
https://i.imgur.com/v160b3K.png
Comment: Wait i got this  a small width row there this data
https://i.imgur.com/XTwFTJh.png
Comment: In the last image there is data, great!


sscanf saving into vector

Question: The problematic code is:
vector<int> Data(2);
String="ff34";
sscanf(String.c_str(), "%02x%02 ",&Data[0],&Data[1]);

As you can see, I would like to parse String and save the data to my vector Data.
I really don't see why this isn't working.
The values I get are:
Data[0]=255 -> this is OK
Data[1]=0   -> this is what isn't working
I've tried with larger vectors, but I get the same. First place is OK, all other places in the vector are 0.
Comment: Aren't you supposed to use `%02x` corresponding to `&Data[1]`, as well?
Comment: I can't believe what a stupid mistake I've made.  Thanks!
Answer: You need
"%02x%02x" instead of "%02x%02 "
See here
Answer: It's not working because the format specifier isn't properly written. %02 isn't a valid specifier, %02d (for a decimal integer) or %02x (for an hex integer) are.
Answer: The code should be:
vector<int> Data(2);
string String="ff34";
sscanf(String.c_str(), "%02x%02d",&Data[0],&Data[1]);

if 34 is read as decimal integer. And also the supposed type of String is string.
Comment: You are correct however I have no idea why you would consider that the "34" portion is intended to be decimal (and anyone who intentionally wants the string "ff34" to represent two numeric values, one in hex and one in decimal, needs to put down the keyboard, back away from the computer, and never return).
Comment: @mah because hex number usually begins with a `0x`
Comment: Except when they don't, and the "ff" is a pretty clear indication that they don't in this case, no?

sscanf saving into vector


Como apagar o conteudo de um arquivo em c?

Question: Como eu posso apagar o conteudo de um arquivo em c, qual função eu devo usar?
#include <stdio.h>
#include <stdlib.h>

void main(){
    char hello[13] = "Hello World!";
    char path[12] = "arquivo.txt";
    FILE* arquivo;
    arquivo = fopen(path, "a+");
    fprintf(arquivo, hello);
    printf("%s foi adicionado ao arquivo %s", hello, path);

    /*

    arquivo = fopen(path, "w");
    fclose(arquivo);

    */
}

Comment: Abrir o arquivo no modo `w` não apaga o conteúdo anterior?
Comment: E porque não apagar o arquivo pura e simplesmente?
Comment: Todo o conteúdo?
Comment: sim, apagar todo o conteudo de um arquivo de texto
Comment: É literalmente apenas fazer `fopen` com `w` como o @AndersonCarlosWoss disse
Comment: eu ja tentei abrir com o w, mas não apagou
Answer: Para apagar o conteúdo de um arquivo em C basta abrir com o modo w:
fopen(caminho_para_o_arquivo, "w");

Agora no seu caso acontece que já o abriu anteriormente com a+:
void main(){
    ...
    arquivo = fopen(path, "a+");
    ...
    arquivo = fopen(path, "w");
    fclose(arquivo);
}

Por isso a segunda tentativa abertura não apaga o conteúdo. Para corrigir coloque um fclose antes abrir novamente:
    arquivo = fopen(path, "a+");
    fclose(arquivo);
    ...
    arquivo = fopen(path, "w");
    fclose(arquivo);

Ou melhor nem abra para acrescentar conteúdo com a+ já que de seguida vai apagar! Simplifique e deixe somente:
fclose(fopen(path, "w"));

Comment: eu criei esse codigo só para simplificar as coisas, agora funcionou, obrigado Isac


Features, samples, and over-fitting?

Question: I have a data set with 30 samples, 2 classes, and 100,000 features. When I run an SVC classifier on it from SKLearn using stratified cross-validation, the accuracy is barely better than chance.
After running recursive feature elimination with cross validation (RFECV in SKLearn), it reduces the number of features to 5000, which is still a lot. My accuracy increases to 95%.
I assume my model is likely over-fit, given the features/sample ratio. However, wouldn't the model be more over-fit with 100,000 features (even if the majority of these features are noise) than with 5000 features? In which case, why does the accuracy jump greatly with the decrease in features? Is the relationship between #-of-features, over-fitting, and resulting accuracy a non-linear relationship?
Answer: Let's start from a different scenario: a set of points that is not linearly separable.

A projection (mapping) onto a higher dimensional space can allow us linearly separate our data.
Let's stretch this idea. Let's project data onto a extremely high dimensional data. The planar separator in the extremely-high-dimensional space of feature vectors will be a curved (highly non-linear) separator in the low dimensional space. We are therefore very likely introducing over-fitting.
What we have described is a clear trade-off between bias and variance.
I forgot to mention that there's a bound in the parametrization of the separating hyperplanes:

if we are in a space $\mathcal{H}$, the set of hyperplanes is
  parametrized by $dim( \mathcal{H} ) + 1$. However, given the form of
  solution [of the SVM], there are at most $l$ + 1 adjustable parameters (where $l$
  is the number of training samples) (source)

Note that there's a relationship between the number of support vectors and model complexity:

Now, the number of support vectors still depends on how much slack we
  allow, but it also depends on the complexity of our model. Each twist
  and turn in the final model in our input space requires one or more
  support vectors to define. ...
  The number of support vectors can range from very few to every single
  data point if you completely over-fit your data. This tradeoff is
  controlled via C and through the choice of kernel and kernel
  parameters. (source)

This is the higher level big picture on the trade-off and the risk of poor generalization in a high dimensional problem. See the answer below by Dikran Marsupial for a more detailed description of the role of feature selection in this context.
Answer: The SVM (strictly speaking the maximum margin hyperplane) is an approximate implementation of a bound on generalisation performance that is independent of the dimensionality of the feature space.  This means that in principle, the SVM is able to perform well in high dimensional space (i.e. lots of features for a linear SVM).  However, in practice, this is highly dependent on choosing a good value for the regularisation parameter (usually $C$) which controls the trade-off between minimising the error (as measured by the hinge loss) on the training data, and maximising the margin (which maximises bound on generalisation perfomance).  So, the best approach is probably to use a linear classifier, and carefully tune $C$ to minimise the cross-validation error (or the span bound, or radius margin bound), and then have an independent test set for estimating generalisation performance (or as the dataset is small, use nested cross-validation).
The problem with using feature selection is that while the SVM is based on a generalisation bound that helps avoid over-fitting, no such bound applies to the feature selection step (and indeed the feature selection step invalidates the bound on which the SVM is based).  This means feature selection is likely to make generalisation performance worse as you just over-fit the feature selection procedure.
If all that is important is generalisation performance, then don't do any feature selection, and carefully tune $C$ so the model is properly regularised.  For most datasets, that seems to be a good approach, but there are some where feature selection is also beneficial in addition to careful regularisation.
Comment: http://stats.stackexchange.com/questions/35276/svm-overfitting-curse-of-dimensionality - there you gave a very good answer taking a similar perspective.

Features, samples, and over-fitting?


Receber solicitação de mensagem via Whatsapp com webhook

Question: Preciso criar um webhook para responder a uma solicitação vinda do Whatsapp.
Criei a rota webhook no servidor apontando para o meu computador e estou usando o ngrok para testá-la.

Consigo fazer uma solicitação usando o insomnia.

Tenho algumas dúvidas sobre como receber os dados do Whatsapp.
Qual verbose devo usar para obter os dados do Whatsapp?
Como posso ler estes dados recebido?
Answer: Gostaria de entender o motivo de terem votado negativo a minha dúvida, o mas "engraçado" é que infelizmente ninguém soube responder.. Mas vamos lá, pode ser interessante para algum novato.
E espero que quem precise melhore a minha reputação.
Apontei o webhook para o post que estou usando para criar o menu no controller

Dentro da controller você trata os dados recebidos de acordo com o a sua solução.
Mandei um console.log para teste


read upload file in play framework

Question: I'm using play framework 2.1.0, upload files to play-app/upload folder.
then I run play 'start -Dhttp.port=80' to start server.
but when I upload a file to play-app/upload folder, it can not be access immediately.
if I stop the server and start again, then I can access the file.
How can I solve this problem? Thanks a lot.
ps, I route /upload as below:
GET     /upload/*file               controllers.Assets.at(path="/upload", file)

Could it be that static files are loaded once? How can I solve it?
Answer: Preferably create upload folder outside the application's folder and add it's full path like /home/navins/upload-folder/ in application.conf, then you'll be able to access it whole time, also you will be able to upload files there not only with app (ie, by FTP) without need of restarting.
Comment: but I can't directly access the file throughout like http://localhost/upload/xxx.doc
Answer: I think what you need is to define a sort of Remote assets controller. Basically, once a file is uploaded, you put it in a folder that is outside your application's folder. Then, use a controller that will let you access it. Here is an example: http://www.jamesward.com/2012/08/08/edge-caching-with-play2-heroku-cloudfront
Here, James Ward creates a controller to access assets that are stored on cloudfront, what you need to do is to write a similar controller and replace the "content url" with the absolute path to your "Uploaded files directory".
Answer: finally what I've solve it by adding access method in controller:
public static Result view(String filename) {
    File file  = new File(Play.application().path().getAbsolutePath() + "/upload/" + filename);
    return ok(file);
}

then, change route conf, you can access the files by the method.
BTW, if you are using play framework below 2.0, you may user:
    renderBinary(file, ContentType);

read upload file in play framework


Array Formula for column totals

Question: I know how to use an array formula to auto apply a formula down a column, but I was wondering if you could do the same but along a row?
I have tried to apply the sample princple i.e rather than a range for the column, I use the rang for the row, but the sum totals are incorrect. Here is an example of what I am trying to achieve.
There is a colum per month which will auto exapand every month, with the latest month in colum B. These total are used in other sheets, so I want to avpid having to have to rember to update the new row tih sum total: Can the same principle of array formula which auto populates cells in a column, be applied to rows?
Answer:
You may try this in Cell_A5 of the sample datset:
={"total_",bycol(indirect("B2:4"),lambda(Σ,if(counta(Σ)=0,,sum(Σ))))}

added indirect() with an assumption that a new column maybe inserted at column_B to insert new/latest month data
Comment: Thats perfect, thanks so much. So array formula cant be used to expand across a row then?
Comment: yeah arrayformula works across rows as well; its just the use of lambda formulas make it kinda easy-peasy is all!
Comment: Thanks all, so helpful. One last thing that I am trying to do is rather than sum, subtract two values. I have tried altering the formula you provided, but nothing I have tried seems to work. So same principle, except I want to subtract 2 numbers from each other and have the formula work across the row and still work if an additional column is added as the initial solution provided.
Comment: Share a test sheet recreating this scenario and also showcase the expected output(*manually entered*)
Comment: Thanks @rockinfreakshow, thought I wold create it as a new question: https://stackoverflow.com/questions/76693438/auto-expanding-minus-in-column
Answer: There is no reason why an array formula shouldn't expand across a row - you could do this for example:
=ArrayFormula(let(range,indirect("b2:4"),{"Sum",if(indirect("b1:1")="","",sumif(range*0+column(range),column(range),range))}))

...but now that lambdas are available there is no reason to do so!

Array Formula for column totals


Windows Server 2012 Sharepoint 2013 Active Directory - what are the user limitations?

Question: I was wondering if you guys know if there is any limitation as far as how many users I can have on my sharepoint 2013 site if I'm running server 2012 foundation, I think I saw somewhere that there was a 15 user limit on active directory for 2012 foundation but can't confirm if that will indeed apply to just Active Directory or Sharepoint as well.
Any help is much appreciated!
Thanks
Comment: SharePoint (AFAIK) doesn't have it's own user account database, so SharePoint users would in fact be users from AD and it would stand to reason that the number of SharePoint users is limited to the number of AD users.
Comment: Thanks, your comment plus the answer bellow confirms the 15 active directory user limit that applies to SharePoint.
Answer: Windows Server 2012 Foundation
http://technet.microsoft.com/en-us/library/jj679892.aspx

You can use Windows Server 2012 Foundation in either Active Directory® or workgroup environments to create up to 15 user accounts that can access and use the server software. Each user account permits one user, using any device, to access and use your server software with no client access licenses (CALs) required. In the Windows Server 2012 Foundation operating system, you will receive a warning message if you exceed the fifteen-user limit.


For loop construction and code complexity

Question: My group is having some discussion and strong feelings about for loop construction.
I have favored loops like:
   size_t x;
   for (x = 0; x < LIMIT; ++x) {
      if (something) {
          break;
      }
      ...
   }

   // If we found what we're looking for, process it.
   if (x < LIMIT) {
       ...
   }

But others seem to prefer a Boolean flag like:
   size_t x;
   bool found = false;
   for (x = 0; x < LIMIT && !found; ++x) {
      if (something) {
          found = true;
      }
      else {
          ...
      }
   }

   // If we found what we're looking for, process it.
   if (found) {
       ...
   }

(And, where the language allows, using "for (int x = 0; ...".)
The first style has one less variable to keep track of and a simpler loop header.  Albeit at the cost of "overloading" the loop control variable and (some would complain), the use of break.
The second style has clearly defined roles for the variables but a more complex loop condition and loop body (either an else, or a continue after found is set, or a "if (!found)" in the balance of the loop).
I think that the first style wins on code complexity.  I'm looking for opinions from a broader audience.  Pointers to actual research on which is easier to read and maintain would be even better.  "It doesn't matter, take it out of your standard" is a fine answer, too.
OTOH, this may be the wrong question.  I'm beginning to think that the right rule is "if you have to break out of a for, it's really a while."
bool found = false;
x = 0;
while (!found  && x < LIMIT) {
    if (something) {
        found = true;
        ...handle the thing...
    }
    else {
        ...
    }
    ++x;
}

Does what the first two examples do but in fewer lines.  It does divide the initialization, test, and increment of x across three lines, though.
Answer: I'd actually dare to suggest consideration of GOTO to break out of loops in such cases:
   for (size_t x = 0; x < LIMIT && !found; ++x) {
      if (something)
          goto found;

      else {
          ...
      }
    }

    // not found
           ...

      return;

    found:

       ...
      return;

I consider this form to be both succint and readable. It may do some good in many simple cases (say, when there is no common processing in this function, in both found/unfound cases).
And about the general frowning goto receives, I find it to be a common misinterpretation of Dijkstra's original claims: his arguments favoured structured loop clauses, as for or while, over a primitive loop-via-goto, that still had a lot of presence circa 1968.  Even the almighty Knuth eventualy says -

The  new  morality  that  I  propose  may
  perhaps  be  stated  thus:  "Certain  go  to
  statements  which  arise  in  connection  with
  well-understood transformations are  acceptable, provided that the program documentation  explains what the transformation was."

Others here occasionaly think the same.
Comment: Mein Gott! People have been abused here for using break and continue and you do sully forth with a goto - you are brave :-)
Comment: My head is humbly bent-down for the downvotes that are sure to follow.  :)
Comment: In fact, just found accidently another supporter here: http://stackoverflow.com/questions/1258201/will-using-goto-cause-memory-leaks/1258270#1258270
Answer: While I disagree that an extra else really makes the 2nd more complicated, I think it's primarily a matter of aesthetics and keeping to your standard.
Personally, I have a probably irrational dislike of breaks and continues, so I'm MUCH more likely to use the found variable.
Also, note that you CAN add the found variable to the 1st implementation and do
if(something)
{
   found = true;
   break;
}

if you want to avoid the variable overloading problem at the expense of the extra variable, but still want the simple loop terminator...
Answer: The former example duplicates the x < LIMIT condition, whereas the latter doesn't.
With the former, if you want to change that condition, you have to remember to do it in two places.
Comment: Ah, but the second example have the "same" condition twice but expressed differently (!found in the loop header, found in the post condition).  That, to me, is worse because it's harder to notice with a visual or programmatic scan.
Answer: I would prefer a different one altogether:
       for (int x = 0; x < LIMIT; ++x) {
          if (something) {
              // If we found what we're looking for, process it.
              ...
              break;
          }
          ...
       }

It seems you have not any trouble you mention about one or the other... ;-)

no duplication of condition, or readability problem
no additional variable
Comment: +1. Even if the `...` was `return x;` I'd have no problem with this (other than removing the `break;` of course). If `...` is complicated just re-factor it as another method.
Comment: That's interesting.  Of course, sometimes the "..." is "return x" and returning from the middle of a loop feels grody.
Comment: @Chris You saw I didn't change the '...'. This was in a condition already, so it wasn't on the last line of the method. ;-) Anyway, I think the number of returns is another debate...
Answer: I don't have any references to hand (-1! -1!), but I seem to recall that having multiple exit points (from a function, from a loop) has been shown to cause issues with maintainability (I used to know someone who wrote code for the UK military and it was Verboten to do so). But more importantly, as RichieHindle points out, having a duplicate condition is a Bad Thing, it cries out for introducing bugs by changing one and not the other.
If you weren't using the condition later, I wouldn't be bothered either way. Since you are, the second is the way to go.
Comment: A (clearly unsuccessful) joke, e.g., vote this down, he failed to provide references. :-)
Comment: I think I would prefer a simple [citation needed] B-)
Comment: Aah, that makes more sense. I was trying to figure out what (-1) factorial minus 1 factorial was but of course I got stuck on the factorial of a negative number :-)
Answer: This sort of argument has been fought out here before (probably many times) such as in this question.
There are those that will argue that purity of code is all-important and they'll complain bitterly that your first option doesn't have identical post-conditions for all cases.
What I would answer is "Twaddle!". I'm a pragmatist, not a purist. I'm as against too much spaghetti code as much as the next engineer but some of the hideous terminating conditions I've seen in for loops are far worse than using a couple of breaks within your loop.
I will always go for readability of code over "purity" simply because I have to maintain it.
Answer: This looks like a place for a while loop. For loops are Syntactic Sugar on top of a While loop anyway. The general rule is that if you have to break out of a For loop, then use a While loop instead.
Comment: 20+ years, never heard that one, and don't buy it.
Comment: Actually, "if you have to break out of a for loop, then use a while loop instead" is starting to sound good to me.  Arguably, searches should be whiles.
Comment: Whose general rule would that be? Whether you break out or not is irrelevant to the loop construct, unless you rely on the looping variable afterward, which is a Bad Thing.
Comment: I also have never heard of a reason why putting a break in a for loop is a bad thing.  In fact, a for loop with a break is typically what I would recommend when trying to find an element in an array.
Comment: @Jacob: The argument against breaks is that they aren't structured. Structured Programming requires that every block has exactly one entry point and exactly one exit point. break statement do not follow this rule. They're not as bad as goto... It's probably about the same level of "sin" as multiple return statements from a function, which a lot of people also don't care about...
Comment: I would so love to see my old instructors faces if any of them saw these posts promoting breaks inside a loop. :) Sure we can use a hammer to drive in a screw, but maybe we should use a screwdriver instead.
Answer: package com.company;

import java.io.*;
import java.util.Scanner;

public class Main {

// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");

public static void main(String[] args) {
    // write your code here

    boolean itsdone = false;

    String userInputFileName;
    String FirstName = null;
    String LastName = null;
    String user_junk;
    String userOutputFileName;
    String outString;

    int Age = -1;
    int rint = 0;
    int myMAX = 100;
    int MyArr2[] = new int[myMAX];
    int itemCount = 0;
    double average = 0;
    double total = 0;
    boolean ageDone = false;

    Scanner inScan = new Scanner(System.in);

    System.out.println("Enter First Name");

    FirstName = inScan.next();

    System.out.println("Enter Last Name");

    LastName = inScan.next();

    ageDone = false;
    while (!ageDone) {
        System.out.println("Enter Your Age");
        if (inScan.hasNextInt()) {
            Age = inScan.nextInt();
            System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
            ageDone = true;
        } else {
            System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
            user_junk = inScan.next();
            ageDone = false;
        }
    }

    try {
        File outputFile = new File("firstOutFile.txt");

        if (outputFile.createNewFile()){
            System.out.println("firstOutFile.txt was created"); // if file was created
        }
        else {
            System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
        }

        // --------------------------------
        // If the file creation of access permissions to write into it
        // are incorrect the program throws an exception
        //

        if ((outputFile.isFile()|| outputFile.canWrite())){
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));

            fileOut.write("==================================================================");

            fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);

            fileOut.write(NEWLINE +  FirstName + " " + LastName + " " + Age + NEWLINE);

            fileOut.write("==================================================================");

            fileOut.close();

        }
        else {
            throw new IOException();
        }

    } // end of try
    catch (IOException e) { // in case for some reason the output file could not be created
        System.err.format("IOException: %s%n", e);
        e.printStackTrace();
    }
} // end main method
}

Comment: Generally, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Note: it's unclear to me how this addresses the actual question which was asked.
Comment: This is not right solution to described problem.


Split Two Related DataFrame Columns into Two New DataFrames

Question: I basically have 2 related columns in a data frame in python. One of the columns is binary i.e. 1,0,0,1,0 etc and the next column has a related value i.e 200, 34, 124, etc. I want to take all the zero values with their corresponding values in the adjacent column and create a new data frame and do the same for all the ones. An illustration of the columns are below;
Location     Price
1             24
0             200
0             56
0             89
1             101
1             94
1             3

Answer: You can make two new dataframes with just ones and zeros like this, IIUC:
df[df.Location == 0]
#   Location  Price
#1         0    200
#2         0     56
#3         0     89

df[df.Location == 1]
#   Location  Price
#0         1     24
#4         1    101
#5         1     94
#6         1      3


Where can I find a formula chord chart for minor keys?

Question: Where can I find a formula chord chart for minor keys?
All the ones I see in Google images are for major keys. How come?
Comment: I found this http://musictheory.pugetsound.edu/mt21c/DiatonicChordsInMinor.html It's not a formula chart but it spells them all out in Am which is helpful.
Comment: Where can i find X questions are off-topic, but the core question seems to be about minor key harmony so I've closed this question as a dupe the goes over the basics of minor key harmony.
Comment: Lookong for chordcharts formulas: https://www.google.com/search?q=piano+chord+formula+chart+pdf&rlz=1C9BKJA_enCH812CH813&oq=formula+chord+chart&aqs=chrome.2.69i57j0i22i30l4j69i60.15150j0j7&hl=de&sourceid=chrome-mobile&ie=UTF-8#imgrc=_ https://www.google.com/search?q=piano+chord+formula+chart+pdf&rlz=1C9BKJA_enCH812CH813&oq=formula+chord+chart&aqs=chrome.2.69i57j0i22i30l4j69i60.15150j0j7&hl=de&sourceid=chrome-mobile&ie=UTF-8#imgrc=pkn_Te9TyWR-MM   major and minor
Comment: @AlbrechtHügli  Well those are all major. Hence the question.
Comment: No, there are always 2 columns, major and minor.
Comment: @AlbrechtHügli  Yes, they are the minor chord formulas relative to the major key. The formula for a minor chord in a natural minor key would be 1-3-5.
Answer: It's because there's more than one minor scale.
In the natural minor, the chords are the same as the major scale, but they fall on different scale tones:
i=minor
ii=diminished
III=Major
iv=minor
v=minor
VI=Major
VII=Major
Using the harmonic minor scale, any chord with the 7th scale degree changes:
III=augmented
V=Major
vii=diminished
And if you use the melodic minor* any chord with the 6th scale degree can change:
ii=minor
IV=Major
vi=diminished
*often defined as the "melodic minor ascending", but in practice composers may use a raised sixth when the melody is descending
Comment: For clarity it might be good to point out that the changes in harmony for the melodic minor also include the changes mentioned  for the harmonic minor...


Detox Testing: Tracking down Javascript timers causing test framework to wait forever

Question: The Detox test framework, according to the documentation TroubleShooting Synchronization mentions that the test framework will wait and only perform your next test statement when the app is "Idle".
The problem I have right now is that my app never goes idle because there's some timeout that's continuously firing. It could be in my code or third-party code.
Here's an example of the output:

As you can see something is creating a new timer every few milliseconds. What'd I'd like to do is track down which one, I can see the ids but don't know a good way to try and track down exactly where this (setTimeout) id is coming from.

I thought of wrapping the setTimeout function, but not sure what's the best way to proceed with that.
I could eliminate or at least wrap setTimout in my own code, that way, at least determining it's a third-party lib (which still doesn't help solve the problem).
Comment: Not an answer but helped me towards a solution. Inside `./node_modules/detox/src/client/actions/actions.js` there is a class called `CurrentStatus` where the following line was commented out: `//console.log("res:" + JSON.stringify(response, null, 2));` inside the `handle` method. It gives much more robust information about where the timers are being set. Hope that helps. `Detox 11.0.1`
Answer: You could track down setTimeouts easily with:
 // DEV mode only!
 function failOnTimeout(func) {
   const setTimeout = f => {
     throw new Error(`Executing timeout \n ${f.toString()} \n`);
   };

   // A small trick to change scope:
   eval("(" + func.toString() + ")()");
}

So you can do:
 failOnTimeout(someMysteriousFunction);

And will give you stack traces of the first timeout set in that function (synchronously). You can then comment that out and search for the next one.

But instead of trackig down all timeouts, a quick solution could be to just throw an uncatched error to end the process.


How to apply reinforcement learning to combinatorial puzzles?

Question: I want to apply machine learning to a problem I have. It's essentially a kind of combinatorial puzzle where you want to get a high score like in "2048", except that unlike 2048, it is deterministic, you can reverse moves (so you don't 'die', you just get stuck in local minima when the grid is filled), and the number of possible moves in each 'turn' is large.
I was wondering what kind of reinforcement learning would be a good choice for it? I've heard that with Q-learning you need a small space of possible actions to get good performance. I thought an AlphaZero-type algorithm might be good since it's been applied to games with very large action spaces (e.g. Go), but it seems to be used in two-player games and I don't know if you can use it on "single-player" puzzles. Btw I'm also pretty new to ML so any advice would be appreciated.
Comment: Does the game, like 2048, give interim scores? The sparseness of reward is a big factor in choosing RL algorithms. You are asking about an "AlphaZero-type" algorithm - are you aware of how it works (it has a fair bit of detail to understand)?
Comment: If you don't mind the fact that it's non-reinforcement learning, [Pointer networks](https://arxiv.org/abs/1506.03134) may do what you want -- they've been used to solve combinatorial problems such as TSP.
Comment: Yeah, it gives interim scores like 2048. It gives a score after every action. However, it is possible that going for a greedy approach to maximizing score early could lead to a worse score later on.
Answer: First thing to consider, depending on your goals, is whether reinforcement learning (RL) is a good choice for your problem. In combinatorial problems, you may be better off investigating other solvers. There are dozens of potentially useful algorithms that could apply to NP-complete combinatorial problems like the classic travelling salesman problem or knapsack problem.
The fact that you can easily backtrack and re-try suggests one or more global combinatorial or sequence optimisers might be a good first choice. For example simulated annealing is a relatively simple base algorithm that is highly efficient when local changes to a solution can be made and evaluated for low cost. There are many other options - the book Clever Algorithms: Nature-Inspired Programming Recipes describes a broad selection, and is available as a free-to-access HTML version on the site.
Assuming that you still want to apply RL, either because you think it is a good fit, or because one of your goals here is to learn RL techniques, then I think the following applies to your questions from your brief description:

I was wondering what kind of reinforcement learning would be a good choice for it?

They should all work reasonably well in principle, as you have a deterministic environment that you can model and use to drive even simple approaches such as Value Iteration. What will work best depends on the scale of your puzzle, i.e. how many combinations are possible.
Your first problem will be state representation. You need a representation that can enumerate every possible combination. For the simplest tabular RL solvers, all possible enumerations should be able to fit in memory - clearly that only applies to small combinatorial problems that could also fit into memory and be brute-force searched though.
It is likely that a naive approach using Value Iteration or a variant of Q learning will perform about as well as an A* search. That is, better than a brute-force search, but otherwise not particularly well.
One way to improve on this naive approach is to use function approximation for the value functions, which is what the recently successful DQN (for Atari) and AlphaZero do using neural networks. This can help if the combinatorial problem has some underlying data or pattern that would allow for generalisation. Again you need to look at the state representation - this would work poorly if the only data you have is the IDs of objects that you were putting in sequence to get a score.

I've heard that with Q-learning you need a small space of possible actions to get good performance.

Q-learning does suffer from speed and accuracy problems when the number of actions is large. That is because one of the steps involves finding $\text{argmax}_a[Q(S_t,a)]$. In your case you can ignore the accuracy problems (due to over-estimating the reward from the maximising action) as your reward signal is deterministic. However, if you have a very large number of possible actions on each step - e.g. your agent can choose to allocate any remaining item into the sequence to create the combination - then the calculation for this term will be expensive.
Typically when Q-learning would be a problem in this way, you would choose a policy gradient method. The simplest one would be REINFORCE, but more popular are Actor-Critic and deterministic policy gradient algorithms. These algorithms search more directly in policy space.

I thought an AlphaZero-type algorithm might be good since it's been applied to games with very large action spaces (e.g. Go), but it seems to be used in two-player games and I don't know if you can use it on "single-player" puzzles.

AlphaZero combines a stochastic planning process (that tests a tree of "most likely" moves) with an RL approach very similar to Actor-Critic. The algorithm is definitely adaptable to a single-player game, and that should simplify it in a few places.
Again, as with Q-learning, whether or not is would help depends critically on the nature of the elements you are making combinations of in your game, and how you can represent them. For instance, in Go, the layout of the board and the consistent rules for surrounding territory and capturing pieces allow for a representation of the board as a grid of stone positions (plus some other basic features, such as recent plays and logical capture information) to be analysed by a neural network. If you just enumerated all possible board configurations and made AlphaZero learn from the ids of those states, it would fail.
Answer: Your intuition is correct. AlphaZero-like algorithms (Approximate Policy Iteration) can be used for single-player puzzles. In fact, I just wrote a paper on how we used these methods to solve Rubik's Cube.
https://arxiv.org/abs/1805.07470
Comment: Is the code for this paper open sourced? I would love to learn from it!


How to find the smallest $\lambda$ such that all Lasso / Elastic Net coefficients are zero?

Question: In the documentation to R's glmnet package it states that when fitting an elastic net, the glmnet function will use a series of $\lambda$ values starting at the smallest $\lambda$ for which all coefficients are zero. How can I find such a value of $\lambda$?
Comment: are you asking how to find $\lambda$ mathematically or how to find it in `glmnet` model?
Comment: Mathematically.
Comment: Related: https://stats.stackexchange.com/questions/166630/glmnet-compute-maximal-lambda-value
Answer: A lasso solution $\widehat{\beta}(\lambda)$ solves
$$\min_\beta \frac{1}{2}||y-X\beta||_2^2 +\lambda||\beta||_1.$$
and it is well known that we have  $\widehat{\beta}(\lambda)=0$ for all $\lambda \geq \lambda_1$ where $\lambda_1 = \max_j |X_j^Ty|$, which should give you the desired value.
Note that $\lambda_1$ may need a different scaling if the objective function is scaled differently.

Using the cars example with GLMNET:
fit<-glmnet(as.matrix(mtcars[,-1]),mtcars[,1], intercept=FALSE, standardize=FALSE)
1/32*max(abs(t(as.matrix(mtcars[,-1]))%*%mtcars[,1]))/(head(fit$lambda))[1]
This gives the value 1, as expected.
Note that standardize as well as intercept is set to FALSE. If standardize and intercept is set to TRUE, then the value of $\lambda$ is calculated on the scaled regressors.
(In this regards, take a look at https://think-lab.github.io/d/205/#5 for how to perform a proper scaling to get the results you want.):
xy<-scale(mtcars)
fit<-glmnet(as.matrix(mtcars[,-1]),mtcars[,1])
(1/32*max(abs(t(xy[,-1])%*%mtcars[,1]*sqrt(32/31))))/(head(fit$lambda))[1]
This once again gives the value 1...
However I am not sure what glmnet is calculating if intercept = TRUE but standardize = FALSE.

We saw that glmnet with its standard options calculates $\lambda_{1}$ as $$\lambda_{1} = \max_j| \frac{1}{n} \sum_{i=1}^n x_j^*y|$$, where $x_j^* = \frac{x_j-\overline{x_j}}{\sqrt{\frac{1}{n}\sum_{i=1}^n (x_j-\overline{x_j})^2}}.$
It turns out that for an elastic net problem (corresponding to $\alpha \in (0,1]$ in glmnet) its maximum value $\lambda_{1,\alpha}$ is calculated as
$$\lambda_{1,\alpha}= \lambda_{1}/\alpha$$.
Indeed, setting for example $\alpha=0.3$ we have:
aa<-0.3
xy<-scale(mtcars)
fit<-glmnet(as.matrix(mtcars[,-1]),mtcars[,1],a=aa)
1/aa*(1/32*max(abs(t(xy[,-1])%*%mtcars[,1]*sqrt(32/31))))/(head(fit$lambda))[1]
which results once again in an output value of $1$.
That's for the calculations. Note however that the elastic net criterion can be rewritten as a standard lasso problem.
Comment: The question seems to be asking about the case of elastic net. Perhaps it would be worthwhile to include the additional step of the derivation for finding this smallest $\lambda$ in the elastic net case, since this question would be a duplicate otherwise. Also, due to the scaling you use in the lasso definition, it seems like the result should actually be that $\lambda_1=2 \max_j |x_j^T y|$ for the lasso.
Comment: You just have to augment your data - take a look at Lemma 1 of "Regularization and variable selection via the
elastic net" by Zou and Hastie for more details.
Comment: we have: `(1/32*max(abs(t(xy[,-1])%*%xy[,1]*(sd(mtcars[,1])*sqrt(32/31)))))  ==  (1/32*max(abs(t(xy[,-1]*sqrt(32/31))%*%mtcars[,1]))))`
and can conclude that, standardize does only standardize the independent variables s.t. $\sum_{i=1}^{n}x_{ij}^2=n$ but the option doesn't touch the dependent variable.
Comment: Thank you for pointing out my mistake - I adjusted the objective function by the term $\frac{1}{2}$ instead adjusting the $\lambda$.

Besides I added the calculations for the elastic net. Note, that $\alpha \to 0$  or $\alpha= 0$ is a special case (which would result in $\lambda = \infty$). Instead glmnet does its calculations for $\alpha = 0.001$. see its help-file.
Comment: "elastic net criterion can be rewritten as a standard lasso problem."  How?
Comment: Thanks for that - would you happen to know also how this would extend to L0-penalized regression? I asked a question about that here: https://stats.stackexchange.com/questions/416144/minimum-and-maximum-regularization-in-l0-pseudonorm-penalized-regression
Answer: First, I think glmnet will start with a large $\lambda$ instead of a small $\lambda$. Here is the documentation: note, if we want to specify $\lambda$, it is better in decreasing order.

Typical usage is to have the program compute its own lambda sequence based on nlambda and lambda.min.ratio. Supplying a value of lambda overrides this. WARNING: use with care. Do not supply a single value for lambda (for predictions after CV use predict() instead). Supply instead a decreasing sequence of lambda values. glmnet relies on its warms starts for speed, and its often faster to fit a whole path than compute a single fit.

Also, See my question here: Why does `R` `glmnet` need to run with $\lambda$ in decreasing order?

The fitting results contains the lambda value used. Here is an example.
library(glmnet)
fit=glmnet(as.matrix(mtcars[,-1]),mtcars[,1])
head(fit$lambda)
[1] 5.146981 4.689737 4.273114 3.893502 3.547614 3.232454


Non-convergent rearrangement of the terms of a relatively convergent series

Question: Let $\sum_{n=0}^{\infty}{x_{n}}$ be a series in $\mathbb{C}$ that is conditionally convergent (i.e. convergent, but not absolutely). Show that there exists a bijection $\pi : \mathbb{N} \rightarrow \mathbb{N}$ so that the series $\sum_{n=0}^{\infty}{x_{ \pi (n)}}$ does not converge.
We are given these two facts:

Let $(x_{n})_{n}$ be a sequence in $\mathbb{R}$ and let $x_{n}^{+}= \max \{ 0,x_{n} \}$ and $x_{n}^{-}= \max \{ 0,-x_{n} \}$. Then the series $\sum_{n=0}^{\infty}{x_{n}}$ absolutely converges if and only if the series $\sum_{n=0}^{\infty}{x_{n}^{+}}$ and $\sum_{n=0}^{\infty}{x_{n}^{-}}$ both converge.

Let $(x_{n})_{n}$ be a sequence in $\mathbb{C}$ and let $a_{n}=\Re(x_{n})$ and $b_{n}=\Im(x_{n})$. Then the series $\sum_{n=0}^{\infty}{x_{n}}$ absolutely converges if and only if the series $\sum_{n=0}^{\infty}{a_{n}}$ and $\sum_{n=0}^{\infty}{b_{n}}$ both converge absolutely.

Is the following reasoning correct? We know that the new series $\sum_{n=0}^{\infty}{x_{ \pi (n)}}$ does not converge in $\mathbb{C}$. This implies that both $\sum_{n=0}^{\infty}{a_{n}}$ and $\sum_{n=0}^{\infty}{b_{n}}$ do not converge either. It then follows that $\sum_{n=0}^{\infty}{a_{n}^{+}}$, $\sum_{n=0}^{\infty}{a_{n}^{-}}$, $\sum_{n=0}^{\infty}{b_{n}^{+}}$and $\sum_{n=0}^{\infty}{b_{n}^{-}}$ are not convergent.
If this was correct so far, then how can I go on from this? Or is there a "better" solution to this problem?
Comment: @Masacroso: thanks, I edited it!
Comment: @GEdgar: yeah I see now that I wasn't thinking clearly...
Answer: Your reasoning is not quite correct. The fact that $\sum x_{\pi(n)}$ does not converge means that at least one  of the two series
$$
\sum a_{\pi(n)} \qquad \mbox{ and }\qquad
\sum b_{\pi(n)}
$$
diverges (but not necessarily both of them diverge).
A simple proof might
(1) show that conditional convergence of a series $\sum x_n$ in ${\mathbb C}$ implies conditional convergence of at least one of the two series $\sum {\rm Re\,}x_n$, $\sum {\rm Im\,}x_n$ in ${\mathbb R}$ - and then
(2) appeal to Riemann's theorem on conditionally convergent series.


Given the sequence $a_{n+1}=a_n(1-\sqrt{a_n})$ with $a_1\in(0,1)$ show that $b_n=a_1^2+a_2^2+\cdots+a_n^2$ is upper bounded by $a_1$.

Question: Consider the sequence $(a_n)_{n \in \mathbb{N}^*}$ with:
$$a_1 \in (0, 1)$$
$$a_{n+1} = a_n(1 - \sqrt{a_n})$$
and also the sequence $(b_n)_{n \in \mathbb{N}^*}$ with:
$$b_n = a_1^2 + a_2^2 + \cdots + a_n^2$$
I have to show that the sequence $(b_n)$ is upper bounded by $a_1$.
So far I managed to show that $a_n \in (0, 1), \forall a_1 \in (0, 1)$ by induction and also that $(a_n)$ is strictly decreasing. I showed these two things in the hopes that it would somehow help me show what is asked. But I didn't find a way of doing that. It is also quite obvious that the sequence $(b_n)$ is strictly increasing, but yet again I don't know if that will help me in showing that it is upper bounded by $a_1$. So how should I approach this?
Answer: $a_{n+1}=a_n-a_n^{3/2} \leq a_n-a_n^{2}$ because $a_n^{2} <a_n^{3/2}$. Hence $a_n^{2} \leq a_n-a_{n+1}$. Sum this from $n=1$ to $m$ to get $b_m \leq a_1-a_{m+1} \leq a_1$.


How to find "dependency" between categorical variables and the dependent variable, also categorical

Question: Please edit the title if the wording is incorrect
Imagine to have a dataset of recipes that works like this: each row is a recipe, where the ingredients are predictors and the dependent variable would be the cuisine (i.e.: Italian, Chinese, Mexican, ...). E.g.:
<code>   recipe |  ingredient 1  |  ingredient 2  |    ...    |   cuisine
----------+----------------+----------------+-----------+-------------
   pizza  |     dough      |     tomato     |    ...    |   italian
----------+----------------+----------------+-----------+-------------
  burrito |  bread thingy  |    guacamole   |    ...    |   mexican
----------+----------------+----------------+-----------+-------------
carbonara |   spaghetti    |      eggs      |    ...    |   italian
----------+----------------+----------------+-----------+-------------
</code>
and so on...
Logically I can imagine that recipes that include "pasta" and "ragù" are more likely to be Italian, whereas recipes that have "rice" and "soy sauce" could be more easily Chinese. Conversely, if I have "eggs" then I expect that there's no particular cuisine associated to it because all the world uses eggs.
I'm looking for a way to show these relations, to answer questions like: "what are the 2 most important ingredients in Italian cuisine?" or "if I have avocado and garlic, which is the most likely cuisine associated to them?".
I know that the first step would be to one-hot-encode the ingredients, but then I'm lost. I've looked for answers here and elsewhere but most I could find was related to continuous variables.
Keep in mind: I'm not trying to make a ML model for this, I'm just trying to figure out the relationships between ingredients and cuisine. Also, my dataset is much simpler than this (I only have 5 predictor variables with limited choices), but the logic is exactly the same as described.
Btw, not relevant to the question per se, but I'm using python, so if you already have a pre-cooked solution to this predicament feel free to share.
Answer: You can use Bayesian inference to solve your problem.
If you answer the question "what is the proportion of Italian recipes?", you have a prior probability of Italian recipe $P(Italian)$. Also, you can get prior probability of having tomato in recipe $P(tomato)$.
Then, you can calculate $P(Italian|tomato)$ as the proportion of Italian recipes among the recipes that contain tomatoes. In the same way you can get $P(tomato|Italian)$. There are posterior probabilities. By default they should be calculated using Bayes formula:
$$P(Mexican|tomato) = \frac{P(tomato|Mexican)P(Mexican)}{P(tomato)}$$
You can get it directly from your data.
If you want to know what is the most probable cuisine associated with tomato, you can compare $P(Italian|tomato)$, $P(Mexican|tomato)$, $P(other\_cuisine|tomato)$ and choice the max one:
$$answer = \underset{cuisine}{\operatorname{argmax}} P(cuisine|tomato)$$
Also, you can combine any number of hypothesis in Bayes formula, but it can be a little tricky at first:
$$P(cuisine|ingr_1, ..., ingr_n) = \frac{P(ingr_n|cuisine)P(cuisine|ingr_1, ..., ingr_{n-1})}{\sum_{cuisine}^{C}P(ingr_n|cuisine)P(cuisine|ingr_1, ..., ingr_{n-1})}$$
where
$$C = \{Italian, Mexican, other\_cuisine, ...\}$$
Comment: Hi, thanks for the answer. I am somewhat familiar with Bayes inference, but I'm not exactly sure about the last formula, especially the part above where you have `P(cuisine | ingr1, ... ingrn)`. How does it connect with the rest?
Comment: @wtfzambo If you want to know probability of a particular cuisine given more than one ingredient (your example: if I have avocado and garlic, which is the most likely cuisine associated to them?), you need to use Bayes formula for multiple observations - the last formula. The "simple" one can handle only one observation (ingredient). In general you need to calculate the probability recursively, by taking into account additional observation on the each step.
Comment: Ok I understood, I didn't know one could apply Bayes theorem recursively. Thanks, I guess I'll start with the simple inference and then eventually move on to the tricky part if I need.


Redirecting HTTP to HTTPS for multiple subdomains with Apache on Red Hat

Question: I recently added a wildcard SSL certificate to my sites. How can I get it so when a user goes the sites, it forces them to https?
The SSL covers sites in the form of *.staging.domain.com, I need it to make all those sites go to the https version. However, there is also another site on the same server that is *.domain.com which doesn't have SSL and should not redirect to https.
I've looked at using .htaccess files with redirect but not only could I not get it to work, I would like to make it a server wide change and not need a .htaccess file for every site.
I also found another problem where I can only access the https sites inside my office but nowhere else.
Comment: Your "another problem" should be posted as a separate question so an answer to this one which answers the redirect issue can be marked accepted.
Answer: The easiest way of doing this is with .htaccess as you mention. It is possible to put the rewrite rules in the Apache configuration if you prefer. Depending on the layout of your file system and Apache configuration it may also be possible to create a pattern matched <Directory> entry in the configuration that matches all your SSL enabled sites.
A quick search of the net suggests the following should redirect non-SSL requests to https://
<code>RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</code>
If you are accessing from external through a NAT router and http:// works then I would suggest the problem is most likely that port 443 is not forwarded to your web server.
Comment: How do I forward port 443? I have a little bit of experience with Red Hat and Apache, but not enough.
Comment: It sounds like your server is configured correctly. It's the router that connects your network to the Internet that needs configuring to forward port 443. (I'm assuming your server is on a private address on your LAN and you have a NAT router like most offices)
Comment: Are there any other rewrite conditions so I can keep one of the sites from redirecting?
Comment: You could probably add a second negative condition as above but using the %{SERVER_NAME} variable to exclude the host name of your non ssl website. I'm not much of a mod_rewrite expert, have a look on the net for example of using multiple conditions.


Kotlin save indexes of a specific char repeating in a string

Question: String example (not necessary A and B, but not X): AAAXBBXBXBBB
I want to find all occoruncaes of X and save them in an array.
I wrote a function:
<code>val arrayList = ArrayList<Int>()
fun findAllX(str: String){
    for(i in 0 until str.length){
        if(str[i] == 'X'){
            arrayList.add(i)
        }
    }
}
</code>
Result in this example: arrayList that contains integers 3, 6, 8
Is there a better/cleaner way to write this?
Comment: `AAAXBBXBXBBB` this is the string, right? And now you want to get `X` from this string?
Comment: I wanted indexes (positions), like: 3, 6, 8.
Comment: https://stackoverflow.com/questions/5034442/indexes-of-all-occurrences-of-character-in-a-string
Answer: Here is a one-liner:
<code>"AAAXBBXBXBBB".withIndex().filter { it.value == 'X' }.map { it.index }.toTypedArray()
</code>


Optimization of Linear Term Under $ {L}_{1} $, $ {L}_{2} $ and $ {L}_{\infty} $ Inequality Norm Constraints

Question: Problem
Solve for optimal value in the following problem, where $p=1,2$ and $\infty$, respectively.
$$\min_x c^Tx\\
\text{s.t. } \Vert x \Vert_p \leq 1$$
What I Have Done
My TA for convex optimization says that this is a famous and useful result but does not provide more details. I figured out that for $l_{\infty}$-norm, the optimal value is $\Vert c\Vert_1$. However, when it comes to $l_1$ and $l_2$, I do not now what to do.
Can you provide some materials about this problem, thank you in advance.
Comment: Perhaps the TA is hinting at you to use the idea of dual norm https://en.wikipedia.org/wiki/Dual_norm (Mathematical optimization section)
Comment: Are you not supposed to use conventional calculus techniques?
Comment: If $p, q \in [1,\infty]$ are harmonic conjugates (meaning $1/p + 1/q = 1$) then $\|\cdot\|_p$ and $\|\cdot\|_q$ are dual norms of one another. For example $\|\cdot\|_2$ is self_dual; $\|\cdot\|_1$ and $\|\cdot\|_\infty$ form a dual pair; etc. Thus in your problem, the optimal value is $\|c\|_q$, where $q = q(p) = p/(p-1)$, with $q(1) = \infty$
Answer: You wish to minimize $f(x)=\sum_{i=1}^n c_ix_i$ under the condition that
$$\left\{\begin{array}{cccc}
\sum_{i=1}^n |x_i| \leq 1&&&p=1\\
\sum_{i=1}^n x_i^2 \leq 1&&&p=2\\
\max |x_i| \leq 1&&&p=\infty\\
\end{array}\right.
$$
Notice that $\nabla f(x) = c$ for all $x\in \mathbb R^n$, so a minimum must be on the boundary of the domain.
In other words, we need only consider equalities above.

The case $p=2$ is easily dealt with Lagrange multipliers, and we can see that $x=-c/{\lVert c \rVert}_2$.
Another way to see this is via good ol' Cauchy-Schwarz:
$$\left|c^Tx\right| = \left|\langle c, x \rangle\right| \leq {\lVert c \rVert}_2\,{\lVert x \rVert}_2$$
Hence, the best you could possibly do for $p=2$ is $c^Tx = -{\lVert c \rVert}_2\,{\lVert x \rVert}_2 = -{\lVert c \rVert}_2$, where the first equality is only possible if $x$ is a scalar multiple of $c$ and the second equality follows from ${\lVert x \rVert}_2 = 1$.
Therefore, $x=-c/{\lVert c \rVert}_2$.

For the other cases, these boundaries are no longer smooth: they have corners.
Nonetheless, a Lagrange multiplier mentality should still help.
Anytime we're at the boundary, if we're able to move along the boundary in some direction given by $-\nabla f = -c$ (ie, in some direction given by any of its components), we will be sensing a decrease in the value of $f$.
In this manner, we'll either arrive at some $k$-dimensional 'wall' $(0<k<n)$, or at a corner $($in a sense, a '$0$-dimensional wall'$)$ of the boundary.
However, if we arrive at a wall, that's because the wall is perpendicular to $-c$.
Hence, moving along the wall is okay: $f$ does not decrease along the wall, but it does not increase either.
Since every wall contains a corner, we may therefore assume without loss of generality that we have arrived at a corner.
It follows that for $p=1,\infty$ you need only check the corners of your domain.

For $p=1$, the corners are the vectors $\pm e_i$, where $e_i$ is the vector whose $i$-th coordinate is $1$ and all others are $0$.
In this case, $c^T(\pm e_i) = \pm c_i$, so $x$ is chosen so that $i$ maximizes $|c_i|$ and the signal is chosen so that the result is negative, ie
$$x = -\text{sgn}\left(c_{\text{argmax}_i\,|c_i|}\right)\cdot e_{\text{argmax}_i\,|c_i|}$$

For $p=\infty$, the corners are the vectors $(\pm 1, \pm 1, \dots, \pm 1)$.
In this case, it's easy to see that
$$x = \Big(-\text{sgn}(c_1), -\text{sgn}(c_2), \dots, -\text{sgn}(c_n)\Big)$$
Comment: Really like this intuitive explanation, I think I have understood this problem. Thank you!
Comment: Glad to have helped!
Answer: Remark:

this is a minimization problem, the solution should be nonpositive.
The case when $c=0$ is obvious.

We can focus on $c \ne 0$.
When $p=1$, this is a linear programming problem, of which the optimal solution exists at the corner points, which are points with all zeros besides one entry, which is either $1$ or $-1$. Hence the optimal value is $-\max_i |c_i|=-\|c\|_\infty$.
For $p=2$, we can use Langrange multiplier to show that the optimal solution is a multiple of $c$ (recall steepest descent). Hence the optimal point is at $\frac{-c}{\|c\|}$.
Answer: These problems can be solved just with common sense. We don't need Lagrange multipliers or anything fancy.
When $p = 1$, the best thing you can do is put all your weight behind the largest component of $c$. That's how you get the most bang for your buck. So if the component of $c$ that is greatest in magnitude is $c_i$, and $c_i > 0$, then we should take $x$ to be the vector that has a $-1$ in the $i$th position and zeros elsewhere.
When $p = \infty$, the best thing you can do is take the components of $x$ to be $\pm 1$. If $c_i > 0$, then take $x_i = -1$. If $c_i < 0$, then take $x_i = 1$.
When $p = \infty$, take $x$ to be the unit vector that points in the direction opposite $c$.


Passar o nome do item clicado no ListView Android

Question: Tenho um código que eu pego o ID do item clicado no ListViewe passo para um outra Activity, mas eu gostaria de pegar o nome clicado e não o ID.
Meu código:
if (controle != null) {
    controle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
        public void onItemClick(AdapterView<?> av, View v,    int position, long id) {
            Intent it = new Intent(layout_projetos_c.this, layout_projetos_c_info.class);
            it.putExtra("idProjeto", id);
            startActivityForResult(it, 1);

        }
    });
}

E na outra Activity eu pego o valor do id
 long idCli;
 idCli = getIntent().getLongExtra("idProjeto", 0);

Como eu posso pegar o nome do item selecionado ao invés do ID?
Answer: Olá!
Da mesma forma que você passa o id, você poderá passa nome:
Intent it = new Intent(layout_projetos_c.this, layout_projetos_c_info.class);
it.putExtra("idProjeto", 10);
it.putExtra("nomeDoProjeto", "Este e o nome do projeto 10");
startActivityForResult(it, 1);

Na sua outra Activity:
String nome;
long idCli;
idCli = getIntent().getLongExtra("idProjeto", 0);
nome = getIntent().getStringExtra("nomeDoProjeto", "");

Segue um link que poderá ser útil: http://developer.android.com/intl/pt-br/training/basics/firstapp/starting-activity.html
Comment: Obrigado Thiago, mas ainda não consegui resolver meu problema, no meu caso os itens do listView foram puxados de um Database da tabela de projetos que tem alguns campos, entre eles o campo "nome_projeto" esse campo vai para o list. Suponhamos que eu tenha 3 projetos no List "Projeto_A, Projeto_B e Projeto_C" e ao clicar no Projeto_B eu quero que chame uma outra Activity com os dados do projeto_B(nome no caso) como eu posso fazer isso?
Comment: leve seu Id para a Outra Activity, lá vc vai ate o banco e consulta todos os seus dados....


Keep getting "message": "'from' parameter is missing" in Rest API client

Question: I want to send a mail through Mailgu n with Insomnia. This is what I have done:

Created account at mailgun.com
Added a verified recipient:

Opened up Insomnia and added the following configuration:

3.1 This is the complete 'from':
<code>firstname.lastname@example.com&subject=subb&text=sometext
</code>

This is the auth. I got the auth key from Mailgun (Settings -> API Key -> Private API keys)

This is the header:

When I click on 'Send' this is the error:
Answer: Your Form Encoded data shouldn't be one string. It should be all key-value pairs like:


A single procedure needed for every CLR-function?

Question: I'm just playing around a bit with CLR-Assemblies on a SQL2008 server. My first thought was: "Great, now I don't need to add 25 stored procedures and functions to get my main stored procedure readable. I just create one DLL and add all I need in it."
So I just tried a simple HelloWorld example from the MSDN and as an example how to call it I get:
CREATE PROCEDURE hello
AS
EXTERNAL NAME HelloWorld.Procedures.HelloWorld

Is this the only way to call a function in a CLR-Assembly? I want to call it without creating a single stored procedure for every function in my class. Possible?
Comment: I know this is a few years old, but I am curious if I interpreted your question correctly in my answer.
Answer: Simple answer, no! Every CLR stored procedure and stored function needs a T-SQL stored procedure or stored function defintion with the appropriate external name.
Comment: Well, not the answer I wanted to hear, but I guess it's the correct one.
Answer: Well, yes and no. It depends on exactly what you mean by "calling a function".
If you are speaking in terms of calling a method directly from T-SQL, then yes, every exposed method needs a T-SQL wrapper object to act as the bridge between the two (T-SQL and CLR). This interpretation of the question was made in the @Mithrandir's answer.
However, if you are speaking in terms of private / internal methods within your assembly, then no, those don't need the T-SQL wrapper objects. This interpretation is based on this statement:

My first thought was: "Great, now I don't need to add 25 stored procedures and functions to get my main stored procedure readable. I just create one DLL and add all I need in it."

That statement implies that the desire is to have some internal methods that are called by the exposed method(s) so that you don't have so many calls cluttering up the main procedure. The exposed methods (i.e. the ones with the T-SQL wrapper objects) can share utility methods, and can even reference other assemblies, as long as those other assemblies are:

in the same database, and
have the same authorizing User

These utility methods can still do data access using the Context Connection, provided that they are called from methods that are exposed to T-SQL (i.e. have a SqlFunction, SqlProcedure, etc. attribute and a corresponding  T-SQL wrapper object).
You can even create an assembly that has no exposed methods, and contains only code referenced by your other assemblies. In this case, you have the option of using ALTER ASSEMBLY to set the VISIBILITY property to OFF (can't be done via CREATE ASSEMBLY). If you DROP an assembly that references another assembly that has its VISIBILITY set to OFF, then the non-visible assembly will be dropped automatically, just like a cascaded delete via a foreign key.


Show that if $x$ and $y$ are real numbers such that $0<x<1$ and $0<y<1$

Question: I'm new to the page, I was hoping that you could help me solve this example so I can get carried away to do my practice exercises.It's an exercise in inequality, maybe it's not difficult, but as soon as I start the topic I have several doubts.
The exercise is:
Show that if $x$ and $y$ are real numbers such that $$0<x<1$$ and $$0<y<1,$$ then $$xy(1-x)(1-y)\le \frac{1}{16}$$
Thank you for your help to get a better score on my upcoming test.
Comment: Can you show us what you've tried and the specific places in which you're feeling doubtful?
Comment: If $x$ and $y$ are near zero, that inequality is clearly false.
Comment: Hint: this is an application of the ([tag:a.m.-g.m.-inequality]).
Comment: @AaronMontgomery I can upload photos to the platform?
Comment: It's easy to see the reverse is true $$xy(1-x)(1-y)\le \frac{1}{16}$$ with AM-GM.
Comment: $x=y=.1$ then $0.1^2*0.9^2 = .0081< \frac 1{16}$ so you have the equation backwards.  Let $x=\frac 12 \pm e$ and $1-x=1-(\frac 12 \pm e) = \frac 12 \mp e$ and $y= \frac 12 \pm d$ and $1-y=\frac 12 \mp d$ and assume $\frac 12 > e,d\ge 0$.  Then $xy(1-x)(1-y)=(\frac 12 + d)(\frac 12-d)(\frac 12 +e)(\frac 12-e)=(\frac 14 - e^2)(\frac 14 - d^2) = \frac 1{16} -\frac 14e^2 - \frac 14d^2 +\frac 16e^2d^2$.  Can you prove $ -\frac 14e^2 - \frac 14d^2 +\frac 16e^2d^2 \le 0$?
Comment: Find maximum value with two variables. Max value is the for point at center of square is $1/ 2^4$
Answer: HINT: Find maximum of the function $f(x)=x(1-x)$.
This requires no knowledge about AM-GM inequality, as in other solutions. Only basic knowledge about quadratic function is needed.
Answer: Hint: By AM-GM Inequality,
$$x(1-x)y(1-y) \le \left(\frac{x+1-x+y+1-y}{4}\right)^{4}.$$
Answer: The inequality should be reversed.
I may show that $x(1-x) \leq 1/4$. By AM-GM, $x + (1-x) \geq 2\sqrt{x(1-x)}$, implying the above.
As $x,y$ are independent, the inequality follows.
Answer: Another attempt:
$ g(x)=x(1-x)$ ; $f(y)=y(1-y)$.
Note : $x$ and $y$ are independent variables,
$x,y \in (0,1)$.
1) Consider $g'(x)= 1-2x=0$.
Maximum of $g(x)$ is  at $x=1/2$.
2)Likewise:
Maximum of $f(y)$ at $y=1/2$.
3)Maximum of $g(x)f(y)$ at $x=y=1/2$:
$\max (f(x)g(y)) =(1/2)^4= (1/16).$
4) Hence $g(x)f(y) \le 1/(16)$, $x,y \in (0,1)$.


Drupal Isn't Finding My CSS

Question: My stylesheet is mentioned in my .info file, but it's not adding it to the page source and using it. The only style I have in Styles.css is body {background:#444}. I've tried clearing the site's cache as well as my browser's. CSS compression is off. Any ideas?
It's a theme I made from scratch.
info file:
name = PBmedia 14
description = The Site Theme
core = 7.x
engine = phptemplate

; Regions
; --------------------------------
regions[header] = Header
regions[content] = Content
regions[footer] = Footer

; Stylesheets
; --------------------------------
stylesheets[all] [] = html5reset-1.6.1.css
stylesheets[all] [] = styles.css

html.tpl.php
<!DOCTYPE html />

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

page.tpl.php

  <?php if ($main_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t(''))); ?>

  <?php endif; ?>

  <?php print render($page['header']); ?>

<?php print $messages; ?>

    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
    <?php print render($title_suffix); ?>
    <?php if ($tabs): ?>
<?php print render($tabs); ?>
<?php endif; ?>
    <?php print render($page['help']); ?>
    <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
    <?php print render($page['content']); ?>
    <?php print $feed_icons; ?>

  <?php print render($page['footer']); ?>

Comment: In your code above you have an extra space in between `stylesheets[all]` and `[]`.
Comment: Can you give more information on your theme's configuration?
Comment: If you are actually saying `stylesheet[all][]....` that is probably the problem because it should be `stylesheets[all][]....` eg plural
Comment: Ah right! I made them plural, cleared the caches and no change...
Comment: Is styles.css in the root of the theme, or is it in a CSS folder?
Comment: It's in the root.
Comment: Is that little ?> at the top of html.tpl.php a typo?
Comment: Yeah... It had the default page comments.
Comment: The spaces solved it Adam!! Thanks for the help everyone!
Answer: There should not be a space after "[all]" ...
Change:
stylesheets[all] [] = styles.css
to:
stylesheets[all][] = styles.css

Drupal Isn't Finding My CSS


Schedule Windows Updates exclusively on a specific work day (and time)?

Question: On Windows Server (2003/2008): is there a way to schedule Windows Updates (and reboots) exclusively on sundays, 1 a.m. (for example)?
Answer: If you mean on an individual server, you can just set that up in Control Panel - Automatic Updates. It works the same way as on a Windows XP/Vista machine, where you set Automatic - Every Sunday at 1:00 AM
This works on my Windows Server 2003 machines
Comment: And this can be locked down with GP of course.
Comment: Is tehre a similar solution for windows Server 2008 / 12 ?
Answer: There is solution if you would use the WSUS. The WSUS works like a proxy between Microsoft Update Server and you.
The WSUS is able to collect all needed updates (with or without downloading them). Any client computer (or a server machine) receive updates only when they get approved by you. So you could approve all updates on saturdays for the next update time, which is scheduled at 1 a.m.


Web service calling another webservice

Question: So I have a database that fills up when a value is not found inside of it already, basically is a web API written in C# that checks if there is a value inside of it, if its null then calls another web service that will retrieve the data and insert a new record into the database and return the newly created record to the user. The code is like this:
<code>[HttpGet ("{idDocument}")]
public async Task<IActionResult> GetPerson (string idDocument)
{
    // Get the person record from the database
    var person = await repository.GetPersonAsync (idDocument);

    // if the record does not exist, return not found
    if (person == null)
    {
        Person newPerson = await GetNewPersonFromRemoteServer(idDocument);
        var result = mapper.Map<Person, PersonResource>(newPerson);

        return Ok(result);
    }

    // Map the record to a resource to return to user
    var resource = mapper.Map<Person, PersonResource> (person);

    // return record resource to user
    return Ok (resource);
}

private async Task<Person> GetNewPersonFromRemoteServer(string id)
{
    Person newPerson = new Person();
    string address = "http://remoteservice.serv/?id=";
    string fullAddress = address + id;

    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(new Uri(fullAddress));
            string responseMessage = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                Person newPerson = JsonConvert.Deserialize<Person>(responseMessage);

                repository.AddPersonAsync(newPerson);
                await uow.CompleteAsync();

                return newPerson;
            }

            return newPerson;
        }
    }
    catch (Exception ex)
    {
        return newPerson;
    }
}
</code>
But the service is working sometimes and sometimes its returning null even tho if I execute the remote service I get a response with the correct data. I believe it has something to do with the nested async/await methods/functions but I cant seem to figure it out a better solution to my problem. Any help would be greatly appreciated!
Comment: Are `AddPersonAsync` and `CompleteAsync` actually async? Because you do not await them.
Comment: the complete async is awaited, the addPersonasync was async but i turned it synchro to test it, but it seems its not the real issue.
Answer: You have extremely faulty exception handling. Right now you swallow Exceptions. Moreover, you do it with Fatal Exceptions. That is a deadly sin of exception handling and can easily explain any odd behavior.
After a fatal exception your programm should always close. Ignoring them only leads to more followup errors that are impossible to debug or even predict.
You should read up on proper exception handling. Here are two articles I linked often:

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

Web service calling another webservice


make Apache reload skipping vhost on error

Question: have several vhost configured with there own conf file under conf.d. This works fine, but ever so often i have to make changes to one of the files and the reload apache. Is there a way where apache would skip that file if there is an error so that the other sites still goes up on a reload?
This is a prod site (and yes i should test all first, but that is not always practical). It would be nice if I could change the file for domain1.conf do a service httpd restart and then if there is an error in the file that today would cause apache not to start at all it would simply skip that conf file and load start with all the others.
Hope this would work
Regards
Tore
Comment: sure, test every file independently and skip the one giving you errors. Share the script when you're done ;-)
Answer: Simply ensure that your config is correct before you issue a restart/reload
apachectl configtest

configtest :
  Run a configuration file syntax test. It parses the configuration files and either reports Syntax Ok or detailed information about the particular syntax error. This is equivalent to apachectl -t.
Comment: But if the syntax is ok but a path to for example a cert file or a file root file location is wrong will that show?
Comment: create a vhost with some bad paths and test it - I don't think you will fail a syntax test over a bad path.
Comment: Just added a "_" to a cert path and it returned a "does not exist" error, so thats a solved for me! Thanks!