Trying to put per mille symbol into plot label usinf matplotlib

Question: I can't figure out how to put the per mille symbol into my plt.ylabel.  anyone know how?
<code>    import numpy as np
    import matplotlib.pyplot as plt
    plt.plot(x,y)

    ax = plt.gca()
    ax.invert_yaxis()

    plt.title("LR04 Benthic $\delta^{18}$O")
    plt.xlabel("Years (ka)")
    plt.ylabel("Benthic $\delta^{18}O (TRYING TO PUT PERMIL SYMBOL HERE)$")
    plt.show()
</code>
Answer: One possible solution:
<code>import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5)
y = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.invert_yaxis()

ax.set_title("LR04 Benthic $\delta^{18}$O")
ax.set_xlabel("Years (ka)")
ax.set_ylabel("Benthic $^o/_{oo}$")
plt.show()
</code>
Comment: not sure if there is an "official" way to do this but this works great


Issue with logout button

Question: I'm trying to implement Facebook Connect login on my web page, and below you have my (poor) try so far.

If being logged out the login button is shown, as supposed.
If clicking the login button the Facebook login popup window appears, as supposed.
If loggin in the popup window disappears, the user gets logged in and the button changes to a logout button.
If clicking the logout button the user gets logged out, BUT!:

The button doesn't get changed to a login button.
Sometimes up to three popup windows (login) opens up.
The function testAPI() gets executed.
Sometimes the following error message is shown in the console: "Refused to display document because display forbidden by X-Frame-Options."

JS:
  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'xxxxxxxxxxxxxxxx', // App ID
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });

    FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        showLogoutButton();
      } else if (response.status === 'not_authorized') {
        showLoginButton();
      } else {
        showLoginButton();
      }
     });
  };

  function showLoginButton() {
    $('#FBButtonDiv').show();

    $('#FBButton').html('Log in Facebook');
    $('#FBButton').on('click', function(){
      login();
    });
  }

  function showLogoutButton() {
    $('#FBButtonDiv').show();

    $('#FBButton').html('Log out Facebook');
    $('#FBButton').on('click', function(){
      logout();
    });
  }

  function login() {
      FB.login(function(response) {
          if (response.authResponse) {
              // connected
              testAPI();
              showLogoutButton();
          } else {
              // cancelled
          }
      });
  }

  function logout() {
    FB.logout(function(response) {
      showLogoutButton();
    });
  }

  function testAPI() {
      console.log('Welcome!  Fetching your information.... ');
      FB.api('/me', function(response) {
          console.log('Good to see you, ' + response.name + '.');
      });
  }

  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));

HTML:
...

<button id="FBButton">Facebook login!</button>

...

CSS:
#FBButtonDiv {
  display: none;
}

So, what can be wrong in my code?
Note: I know the code contains of alot of DRY but I'll do alot of refactoring when I get it to work.
Answer: Not particularly my speciality, JS/FB-API but I would guess:
function logout() {
  FB.logout(function(response) {
    showLogoutButton();
  });
}

Should be:
function logout() {
   FB.logout(function(response) {
     showLoginButton();
   });
}

Because after the response is recieved, the callback should be to show the login button to the now logged out user. Of course you should probably check the response similarly to login to confirm the logout was succesful.
Comment: Thanks a lot, totally missed that :-) Do you have any other ideas regarding the error message as well as the popup window is loaded 2-3 times sometimes?
Comment: As a pure guess I would check the jQuery API to see whether you are actually registering multiple onClick() handlers rather than replacing the last one.

Issue with logout button


Problemas com a utilização do include no Django

Question: Estou com problemas a função include, de acordo com a documentação do django, a sintaxe é  include(module, namespace=None),
include(pattern_list),include((pattern_list, app_namespace), namespace=None).

Código fonte
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
     path('admin/', admin.site.urls),
     path('clientes/', include("cliente.urls", namespace="cliente")),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Erro
path('clientes/', include("cliente.urls", namespace="cliente")),
File "/home/phomint/DjangoProjects/Manager/myvenv/lib/python3.5/site-packages/django/urls/conf.py", line 39, in include

'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured:
Specifying a namespace in include() without providing an app_name is not supported. Set the app_name  attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

Comment: Olhou a documentação da versão certa? As informações da pergunta diferem da documentação da 1.11: https://docs.djangoproject.com/en/1.11/ref/urls/#include
Comment: Olhei sim no meu projeto estou usando a v2.1 e olhei a documentação referente a ela. @AndersonCarlosWoss
Comment: Você precisa incluir o app_name no urls.py do app cliente e não no arquivo urls.py que você deseja colocar o include. Por isso continua dando o erro.
Answer: Conforme você escreveu, a sintaxe pode ser
include((pattern_list, app_namespace), namespace=None)
Então no seu caso:
path('clientes/', include(("cliente.urls", "cliente"), namespace="cliente"))
Answer: No seu arquivo cliente.urls crie uma variável app_name='cliente'.
Exemplo:
"""Arquivos urls.py que está em cliente"""
from django.urls import path
from . import views

app_name='cliente'

urlpatterns = [
    path('', views.index, name='index'),
]

Comment: Apenas criar essa variável não muda nada, tenho que chama lá em algum outro local ?
Comment: Simulei o erro aqui.
Dai quando adiciono `app_name='cliente'` no arquivo `cliente/urls.py` o erro para.
Quando comento a variável `# app_name='cliente'` o erro é igual ao que você postou.
Basicamente só adicionando essa variável deveria funcionar.
O único lugar que encontrei referencia a esse erro foi no `django-rest-framework`, segue referencia:
[Github do django-rest-framework](https://github.com/encode/django-rest-framework/pull/5851).
Comment: Localizei na documentação do Django a referencia ao `app_name`:
[https://docs.djangoproject.com/pt-br/2.1/topics/http/urls/#id5](https://docs.djangoproject.com/pt-br/2.1/topics/http/urls/#id5)
Comment: Então dei uma lida na documentação e tentei mesmo da sua forma, porém o erro continua, com o `include` estou direcionando para o arquivo de urls do clientes e preciso declarar o `namespace` para pode chamar ele na view. Funciona parecido com o `app_name` mas ele é para dar o nome para o próprio arquivo url. @RenatoCruz


tensorflow python expected dense_input to have 2 dimensions, but got array with shape (5, 28, 5)

Question: I am a complete newbie to tensorflow, trying to learn about it and solve a problem.  I tried a lot of tutorials but they all talked about the same classify image or mnist stuff, so I followed the documentation and tried to figure something out.
The goal is to find a pattern to predict the result when the input is [[1000,10, 5, 3, 1744...etc.  There are only 5 cases when the value is 300 400, 500, 600, 700, with shape 28,5 and the result for each is 28,2 list.  The data is loaded from file and assigned to tf.tensor.
Here's my code:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(28, activation=tf.nn.relu, input_shape=(5,)))
model.add(tf.keras.layers.Dense(28, activation=tf.nn.relu, input_shape=(5,)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(28))

model.compile(optimizer='adam',
              loss='mean_squared_error',
              metrics=['accuracy'])

model.fit(newData, newResults, epochs=3, steps_per_epoch=5)

newData:
[[[300, 10, 5, 3, 1744], [300, 10, 5, 5, 2848], [300, 10, 5, 4, 2418], [300, 10, 5, 2, 1152], [300, 10, 5, 3, 1126], [300, 10, 5, 3, 1897], [300, 10, 5, 3, 1089], [300, 10, 5, 2, 1581], [300, 10, 5, 4, 1793], [300, 10, 5, 3, 1525], [300, 10, 5, 2, 1529], [300, 10, 5, 3, 1052], [300, 10, 5, 2, 1556], [300, 10, 5, 3, 1569], [300, 10, 5, 5, 2873], [300, 10, 5, 4, 2269], [300, 10, 5, 3, 3003], [300, 10, 5, 3, 1310], [300, 10, 5, 3, 1464], [300, 10, 5, 3, 2807], [300, 10, 5, 2, 1262], [300, 10, 5, 3, 1734], [300, 10, 5, 2, 2709], [300, 10, 5, 3, 2234], [300, 10, 5, 3, 1961], [300, 10, 5, 2, 1594], [300, 10, 5, 2, 1836], [300, 10, 5, 2, 1345]],
[[400, 10, 5, 3, 1744], [400, 10, 5, 5, 2848], [400, 10, 5, 4, 2418], [400, 10, 5, 2, 1152], [400, 10, 5, 3, 1126], [400, 10, 5, 3, 1897], [400, 10, 5, 3, 1089], [400, 10, 5, 2, 1581], [400, 10, 5, 4, 1793], [400, 10, 5, 3, 1525], [400, 10, 5, 2, 1529], [400, 10, 5, 3, 1052], [400, 10, 5, 2, 1556], [400, 10, 5, 3, 1569], [400, 10, 5, 5, 2873], [400, 10, 5, 4, 2269], [400, 10, 5, 3, 3003], [400, 10, 5, 3, 1310], [400, 10, 5, 3, 1464], [400, 10, 5, 3, 2807], [400, 10, 5, 2, 1262], [400, 10, 5, 3, 1734], [400, 10, 5, 2, 2709], [400, 10, 5, 3, 2234], [400, 10, 5, 3, 1961], [400, 10, 5, 2, 1594], [400, 10, 5, 2, 1836], [400, 10, 5, 2, 1345]],
[[500, 10, 5, 3, 1744], [500, 10, 5, 5, 2848], [500, 10, 5, 4, 2418], [500, 10, 5, 2, 1152], [500, 10, 5, 3, 1126], [500, 10, 5, 3, 1897], [500, 10, 5, 3, 1089], [500, 10, 5, 2, 1581], [500, 10, 5, 4, 1793], [500, 10, 5, 3, 1525], [500, 10, 5, 2, 1529], [500, 10, 5, 3, 1052], [500, 10, 5, 2, 1556], [500, 10, 5, 3, 1569], [500, 10, 5, 5, 2873], [500, 10, 5, 4, 2269], [500, 10, 5, 3, 3003], [500, 10, 5, 3, 1310], [500, 10, 5, 3, 1464], [500, 10, 5, 3, 2807], [500, 10, 5, 2, 1262], [500, 10, 5, 3, 1734], [500, 10, 5, 2, 2709], [500, 10, 5, 3, 2234], [500, 10, 5, 3, 1961], [500, 10, 5, 2, 1594], [500, 10, 5, 2, 1836], [500, 10, 5, 2, 1345]],
[[600, 10, 5, 3, 1744], [600, 10, 5, 5, 2848], [600, 10, 5, 4, 2418], [600, 10, 5, 2, 1152], [600, 10, 5, 3, 1126], [600, 10, 5, 3, 1897], [600, 10, 5, 3, 1089], [600, 10, 5, 2, 1581], [600, 10, 5, 4, 1793], [600, 10, 5, 3, 1525], [600, 10, 5, 2, 1529], [600, 10, 5, 3, 1052], [600, 10, 5, 2, 1556], [600, 10, 5, 3, 1569], [600, 10, 5, 5, 2873], [600, 10, 5, 4, 2269], [600, 10, 5, 3, 3003], [600, 10, 5, 3, 1310], [600, 10, 5, 3, 1464], [600, 10, 5, 3, 2807], [600, 10, 5, 2, 1262], [600, 10, 5, 3, 1734], [600, 10, 5, 2, 2709], [600, 10, 5, 3, 2234], [600, 10, 5, 3, 1961], [600, 10, 5, 2, 1594], [600, 10, 5, 2, 1836], [600, 10, 5, 2, 1345]],
[[700, 10, 5, 3, 1744], [700, 10, 5, 5, 2848], [700, 10, 5, 4, 2418], [700, 10, 5, 2, 1152], [700, 10, 5, 3, 1126], [700, 10, 5, 3, 1897], [700, 10, 5, 3, 1089], [700, 10, 5, 2, 1581], [700, 10, 5, 4, 1793], [700, 10, 5, 3, 1525], [700, 10, 5, 2, 1529], [700, 10, 5, 3, 1052], [700, 10, 5, 2, 1556], [700, 10, 5, 3, 1569], [700, 10, 5, 5, 2873], [700, 10, 5, 4, 2269], [700, 10, 5, 3, 3003], [700, 10, 5, 3, 1310], [700, 10, 5, 3, 1464], [700, 10, 5, 3, 2807], [700, 10, 5, 2, 1262], [700, 10, 5, 3, 1734], [700, 10, 5, 2, 2709], [700, 10, 5, 3, 2234], [700, 10, 5, 3, 1961], [700, 10, 5, 2, 1594], [700, 10, 5, 2, 1836], [700, 10, 5, 2, 1345]]]

newResult:
[[[29.0, 8.92], [52.0, 21.67], [41.0, 14.38], [7.0, 1.49], [26.0, 8.25], [18.0, 4.53], [24.0, 6.61], [21.0, 9.54], [17.0, 5.53], [27.0, 9.61], [11.0, 0.35], [22.0, 8.11], [7.0, 1.22], [36.0, 15.49], [57.0, 31.44], [43.0, 16.52], [34.0, 11.46], [15.0, 2.49], [20.0, 2.34], [16.0, 4.86], [10.0, 0.8], [8.0, 0.4], [1.0, 0.0], [30.0, 7.57], [24.0, 7.21], [5.0, 0.58], [14.0, 0.73], [4.0, 0.15]],
[[45.0, 8.17], [100.0, 43.28], [54.0, 16.05], [10.0, 2.77], [37.0, 8.86], [27.0, 6.12], [33.0, 9.13], [34.0, 14.03], [20.0, 5.06], [45.0, 15.42], [21.0, 0.69], [26.0, 8.83], [11.0, 2.14], [44.0, 17.74], [73.0, 43.39], [43.0, 18.8], [46.0, 21.56], [29.0, 9.16], [21.0, 3.76], [20.0, 7.39], [16.0, 2.54], [1.0, 1.63], [1.0, 0.02], [28.0, 12.14], [30.0, 12.35], [7.0, 1.18], [19.0, 3.29], [4.0, 0.16]],
[[59.0, 18.74], [100.0, 75.18], [69.0, 32.13], [11.0, 3.04], [49.0, 15.76], [30.0, 10.33], [45.0, 14.51], [43.0, 20.82], [37.0, 8.2], [69.0, 24.53], [1.0, 0.3], [38.0, 12.57], [1.0, 3.67], [65.0, 24.77], [91.0, 57.39], [53.0, 18.22], [47.0, 27.07], [34.0, 16.31], [25.0, 5.39], [31.0, 11.5], [23.0, 5.73], [19.0, 4.11], [2.0, 0.11], [35.0, 15.52], [41.0, 18.15], [7.0, 1.48], [25.0, 7.53], [3.0, 0.14]],
[[80.0, 30.29], [100.0, 85.22], [94.0, 52.73], [11.0, 2.45], [72.0, 30.7], [46.0, 14.75], [70.0, 22.81], [50.0, 28.26], [40.0, 14.19], [60.0, 26.82], [14.0, 0.28], [45.0, 19.1], [16.0, 4.72], [82.0, 40.98], [100.0, 78.96], [66.0, 27.05], [67.0, 31.09], [34.0, 16.92], [23.0, 7.03], [48.0, 21.28], [27.0, 8.19], [21.0, 3.95], [2.0, 0.17], [43.0, 19.96], [55.0, 23.54], [8.0, 1.47], [28.0, 12.04], [4.0, 0.13]],
[[95.0, 38.09], [100.0, 92.88], [99.0, 58.96], [13.0, 3.54], [96.0, 45.78], [33.0, 12.05], [87.0, 38.11], [62.0, 34.97], [48.0, 15.49], [84.0, 33.13], [10.0, 0.09], [63.0, 25.52], [16.0, 4.87], [100.0, 55.9], [100.0, 91.32], [90.0, 34.24], [96.0, 45.36], [37.0, 15.13], [27.0, 9.28], [49.0, 26.3], [30.0, 10.92], [22.0, 3.72], [3.0, 0.14], [67.0, 24.82], [73.0, 31.32], [8.0, 1.36], [31.0, 15.03], [4.0, 0.2]]]

Getting this error when I run it:
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1536, in fit
    validation_split=validation_split)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 992, in _standardize_user_data
    class_weight, batch_size)
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1117, in _standardize_weights
    exception_prefix='input')
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 323, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected dense_input to have 2 dimensions, but got array with shape (5, 28, 5)

I know my model definitely has something wrong with it, but I can't quite figure out what.  I have trouble finding information other than the afore mentioned examples.
Answer: The code you've written starts with a Dense layer of 28 neurons expecting an array of shape (*, 5). The error message shows that the shape it is receiving is `(5, 28, 5).
Looking at your data, it is shape (5, 28, 5). Maybe you have an extra set of brackets?
Comment: Can you please elaborate on how my data should look like?  I have 5 samples, and each one has (28, 5).  The results are (28, 2).  All I can find are pieces of how each function work, but I can't find how to put it together.
Comment: Oh, so you're trying to use 2D input. In that case, you should just flatten the samples to 1D (`5, 140`) before you use it and use `input_shape=(140,)`. Those dense layers are fully connected so their topology (1d, 2d, whatever) doesn't really mean anything - every neuron in layer 1 has a connection to every neuron in layer 2.


Numeric Overflow - works when limiting results, not for full query

Question: I'm getting an numeric overflow problem in TD.
<code>`select
a1.account_name,
a1.merch_total_units,
sum(a1.merch_total_units) OVER (order by a1.merch_total_units rows
BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as running_total,
cast (running_total as decimal (8,4))*100/12767296.0000
from sandbox.merchants_total_units a1
group by 1,2,3
order by 3 desc`
</code>
Interestingly, when filter on running total, the query works. Ex:
<code>`select
a1.account_name,
a1.merch_total_units,
sum(a1.merch_total_units) OVER (order by a1.merch_total_units rows
BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as running_total,
cast (running_total as decimal (8,4))*100/12767296.0000
from sandbox.merchants_total_units a1
where a1.merch_total_units > 5000
group by 1,2,3
order by 3 desc`
</code>
I tried changing the #decimal points at every level through the code, doesn't work
Comment: Why is it interesting that when you filter out some data and overflow problem disappears?
Answer: increase the length of decimal
<code>cast (running_total as decimal (18,4))*100/12767296.0000
</code>


What does an element-wise stabiliser mean?

Question:
When a group acts on a set, a lot of important information about the
  action is contained in the stabilizers of particular elements. Recall
  that $G_{u_1,...,u_k}$ denotes the (elementwise) stabilizer in G of
  the elements $u_1, . . . , u_k$.

In this particular case we are talking about a group of automorphisms acting on a set of elements of a field. I believe the "action" of $G$ on the field is just applying an element of $G$ (an automorphism) to a element of the field. (Is this correct?)
But I have no idea what the first paragraph means in particular I have never come across the term elementwise stabiliser? Could it mean the set of all automorphisms of $G$ that map each element of $\{u_1,...,u_k\}$ to itself? Or maybe it is some kind of permutation on these $k$ elements?
Comment: for which structure are this automorphism ?
Comment: I think $G_{u_1, ... , u_k}$ is all the elements of $G$ which map the set $\{u_1, ... , u_k\}$ into itself.
Comment: $G$ is the Galois group of a field extension here.
Comment: @D_S so it's what I said right at the bottom it's the set of all automorphisms of the Galois group that map the $u_1,...,u_k$ into $u_1,...,u_k$? (not necessarily the identity?)
Comment: for which extension?
Comment: $L/K$ for arbitrary $L,K$ fields.
Comment: so you tack G as a groupe of K-automorphism of L and you loock   at the action of G on L, in this cas yes it is one action.
Comment: The elementwise stabilizer is the set of elements in $G$ which sends each $u_i$ to itself (ie not just the set $\{u_1,\ldots,u_k\}$ to itself, but each point in this set to itself).
Answer: If $G$ acts on a set $X$ and $A\subseteq X$ and for some $g\in G$ the set $gA=\{\,ga\mid a\in A\,\}$ happens to equal $A$, the we say that $g$ stabilizes the set $A$. But it may still be the case that $ga\ne a$ for some (or even all) $a\in A$. Under the stronger condition that in fact $ga=a$ for all $a\in A$, we say that $g$ stabilizes $A$ element-wise.
Example: The reflection at a line stabilizes this line point-wise, but it also stabilizes any line perpendicular to it (but not point-wise).
Comment: Could you check the comment I made above is the right in this context?
Comment: @Ryan1010 See also Ashwin Ganesan's comment. Point-wse means that every single point is fixed
Answer: so Let $G=Gal(L/K)$  so $G$ acting on $L$ is correct, and the
element-wise stabilizer of a set $ A=\{u_1,...,u_k\}$ is the
sub-group $\cap_{1\leq i\leq k}G_{u_i}$ that is all element of $G$
which fixe each $u_i$ , $i\in\{1,...,k\}$, it is a sub group of the stabilizer of $A$ ( $st(A)=\{g\in G\mid  g(u_i)\in A, \forall i, 1\leq i\leq k\}$).
Answer: Suppose $G$ acts on a set $S$ and $A$ is a subset of $S$. The set of elements in $G$ which fixes $A$ setwise is $$G_{\{A\}} := \{g \in G: A^g = A\}.$$  The set of elements in $G$ which fixes $A$ pointwise (aka element-wise) is  $$G_{(A)}:=\{g \in G: a^g = a, \mbox{ for all } a \in A\}.$$  Observe that the elements in this latter subgroup must fix each element of $A$  whereas the elements in the first subgroup are required only to permute the elements of $A$ among themselves. Fixing pointwise (ie fixing each point in the set) is a stronger condition than fixing setwise (ie mapping the set to itself).


Custom taxonomy; link with two content types

Question: I've successfully created a new content type ("my_type") and added a taxonomoy into it.
How can I combine this new taxonomy also with the default content type "post", so that I can select it in the default content type backend?
Comment: Hello, msec; welcome on *Drupal Answers*. Are you using Drupal 6 or 7? The answer depends on the version you are using.
Comment: To notice that in Drupal doesn't exist a default content type, and that it is possible to assign more than one vocabulary to a content type. A complete answer is only possible if you report the Drupal version, as the setting page you need to use changes basing on the Drupal version we are talking of.
Comment: @kiamlaluno: Both Drupal 6 and 7 have two content types which are created by default on a new site. They are however called page/story (D6) or page/article (D7) and not post...
Comment: @Bedir Yes, but Drupal doesn't have the concept of default content type; a default content type could be the one selected by default when you create a node, but to create a node you have to explicitly select the content type you want to create.
Answer: Drupal 7
Go to Structure > Content types, select "Manage fields" for the post content type. Either add the existing taxonomy field to it or add a new one. For a new one, choose which vocabulary should be used for this field.
Drupal 6
Go to Admin > Content > Taxonomy, edit your vocabulary. Then under content types, select the content types for which this vocabulary should be displayed.


Juniper SRX refuses to add new ip addresses to ARP (unless)

Question: I have a juniper SRX340 running as default gateway, I have a linux server (virtual machine actually) running debian 8.
juniper ip: 192.168.1.1 Debian ip: 192.168.1.101 (eth0)
I would like to add more ip addresses on my Debian box, so I create a new sub-interface and give it an ip
debian ip2: 192.168.1.102 (eth0:1)
when I do this, I can not ping the juniper box from the new ip address.. and juniper can not ping the new ip address.
I CAN ping other hosts on the same network from the new ip address and they can ping it... all is well.
so.. the new ip address can not see juiper box, and the juniper box can not see the other ip... so then I try something.
I change the ip address of eth0 to be 192.168.1.102 and now I can ping the juniper box, and the juniper box can ping me back.
then I change it back so that eth0: 192.168.1.101 and eth0:1: 192.168.1.101 and now juniper can ping both ip addresses, and both ip addresses can ping juniper.
so.. then I take the test further and add a 3rd interface eth0:2 and give it the ip 192.168.1.103 and I have the same problem... I can not see juniper, and juniper can not see new ip...
again, if I change the original eth0 to use 103 as ip first, then go back, it works again.. this is very confusing.
any suggestions what is going on here?
junos version 15.1X49-D100.6
PS: this was originally posted in the Network Engineering site, but they refused to look at it, I hope that this community can help me more.
edit: more info on request:
<code>interfaces {
        fxp0 {
            unit 0 {
                family inet {
                    address 10.208.20.17/24;
                }
            }
        }
    }
}
node0 {
    system {
        host-name WON-OSLO-FWA;
    }
    interfaces {
        fxp0 {
            unit 0 {
                family inet {
                    address 10.208.20.16/24;
                }
            }
        }
    }
}

reth2 {
    redundant-ether-options {
        redundancy-group 1;
    }
    unit 0 {
        description ORANGE;
        family inet {
            address 192.168.1.1/24;
        }
    }
}
</code>
Comment: would you post SRX config, specifically interface(including ge, fxp ports)?
Answer: I got some help on a juniper forum, and there is a solution (it is not perfect, but it works so I will use it for now).
the solution is to add a static ARP on the juniper.
<code># set interfaces reth2 unit 0 family inet address 192.168.1.1/24 arp 192.168.1.104 mac 01:12:35:03:7a:93
</code>
this worked right away.
I am stil interested to know why juniper does not add these automagically like you would think, but I have a deadline and this will work for me today.


NGINX Proxy Pass multiple folders

Question: I have a NGINX proxy and I want to redirect different folders to different web servers. The issue is that the local servers are looking for absolute paths for images, JS, APIs etc.
How can I make it so there is a rewrite rule or something like it to mitigate the issue?
Below is what I currently have for the server config:
<code>server {
    listen 80;
    listen [::]:80;
    server_name sample.com;

    root /var/www/html;

    location / {
        return 403;

    }

    location /path/ch2 {
        proxy_pass_header Authorization;
        proxy_pass http://10.1.1.50:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffering off;
        client_max_body_size 0;
        proxy_read_timeout 36000s;
        proxy_redirect off;
    }
}
</code>
Comment: Your question is too vauge to answer.
Comment: Please provide request examples.
Comment: The local Servers HTML is referencing the assets, for example the js file using an absolute path as so:

since the proxy 'location' is not served on the root, then it is not able to load the js files etc.
Answer: What we ended up doing is to use the sub_filter
sub_filter "/path/" "/ch2/path/";
sub_filter_once off;
sub_filter_types application/json application/x-javascript application/javascript;

NGINX Proxy Pass multiple folders


Simple way to prevent a Divide By Zero error in SQL

Question: I have a SQL query which used to cause a

Divide By Zero exception

I've wrapped it in a CASE statement to stop this from happening. Is there a simpler way of doing this?
Here's my code:
Percentage =  CASE WHEN AttTotal <> 0 THEN (ClubTotal/AttTotal) * 100 ELSE 0 END

Comment: It depends on how you wan't your query and result to behave when `AttTotal` is 0 or NULL, so there is no general way of doing it. I'd say your query is just fine. Even if you write your query differently using `ISNULL` or `NULLIF` at the end it will likely execute the same.
Comment: Possible duplicate of [How to avoid the "divide by zero" error in SQL?](http://stackoverflow.com/questions/861778/how-to-avoid-the-divide-by-zero-error-in-sql)
Comment: As has been pointed out by others, the logic in this CASE statement doesn't quite make sense to us. See my comment on my answer for a brief explanation and then choose whether you want your original answer or mine. My answer would be a more usual solution.
Answer: A nicer way of doing this is to use NULLIF like this:
Percentage =  100 * ClubTotal / NULLIF(AttTotal, 0)

Comment: This will return `NULL` if `AttTotal = 0`, while the query in question returns 0.
Comment: @NenadZivkovic - Returning `NULL` for a divide by zero error probably makes more mathematical sense anyway though.
Comment: I agree with @Martin Smith. If you have a situation where the ClubTotal is a number and AttTotal is zero, it doesn't make sense to return zero. Or any other number :-) Returning zero implies ClubTotal is zero and AttTotal is more than zero.
Answer: I'm using NULLIF bit differently, because in some cases I do have to return some value. Usually I need to return 0 when there is a divide by zero error. In that case I wrap whole expression in ISNULL. So it would be:
Percentage =  ISNULL(100 * ClubTotal / NULLIF(AttTotal, 0), 0)

The inner part is evaluated to NULL and then ISNULL replaces it with 0.
Answer: Percentage =  IsNull(ClubTotal/NullIf(AttTotal, 0) * 100, 0)

Comment: Agree, I like the one by @Dommer, despite it does not retain original logic too.
Comment: Not quite the same as the query in the question. If the value of `AttTotal` or `ClubTotal` are `NULL` this will now also return `0`.
Answer: In my opinion the CASE statement is exactly the way to go. Rather than calculating something you state the value to return for the case that AttTotal is zero. You could even add another case branch for 0 of 0 being 100%.
Just a side note: I would not return 0 when AttTotal is zero and ClubTotal is greater than zero. NULL might be more appropriate. Or you would create strings (e.g. '10.50%') rather than numbers (e.g. 10.5%), containing "No att. total" in case AttTotal is zero:
PercentageString :=
  CASE
    WHEN AttTotal = 0 AND ClubTotal = 0 then '100%'
    WHEN AttTotal = 0 AND ClubTotal <> 0 THEN 'No att. total'
    ELSE to_char(ClubTotal / AttTotal * 100) || '%'
  END;

Answer: The solution that I found to handle the divide by zero problem is to create a function that I can call upon to deal the situation, as I often have to perform some sort of ratio/ percentage type analysis.  Here's the simple function that I wrote.
Create Function fnRatio(@Numerator decimal(10,2),@Demoninator decimal(10,2))

Returns decimal(10,2)

Begin

Return

Case

      When @Demoninator = 0 then 0.00

      When @Demoninator Is Null then Null

Else

      @Numerator/@Demoninator

End

End
Regards
Jason


Classification of non-commutative, non-cocommutative Hopf algebras

Question: 1. Context
Apparently, Sweedler's Hopf algebra (presented in 1969) was the first known example of a non-commutative, non-cocommutative Hopf algebra.
More generally, the $N^2$-dimensional Taft-Hopf algebra $H_{N^{2}}$ (introduced in 1971) yields a non-commutative, non-cocommutative Hopf algebra for every positive integer $N \neq 1$ (and an appropriate field). Sweedler's Hopf algebra is simply Taft's Hopf algebra $H_4$ over a field $\mathbb k$ (with $\zeta =-1$ and $char(\mathbb k) \neq 2$).
These examples are more or less from the 1970s. I am wondering what the current state of affairs is.
2. Questions

What other non-commutative, non-cocommutative Hopf algebras are known?

I skimmed the wikipedia article on the Pareigis Hopf algebra. It seems that it is a further example of a non-commutative and non-cocommutative Hopf algebra. What is its dimension?

Is there a (complete or partial) classification (up to isomorphism)? What about the subclass of finite-dimensional Hopf algebras?
Comment: I think a classification is quite hopeless. Here are some important examples: https://en.m.wikipedia.org/wiki/Quantum_group#Drinfeld%E2%80%93Jimbo_type_quantum_groups
Comment: I think the Taft Hopf algebra is telling us something important about the discrete Fourier transform, though I can't quite tell what.
Comment: I barely know what Hopf algebras are, but typically, classifying a pathological subclass of objects amounts to classifying the whole class. In other words, do you expect the classification of non-commutative, non-cocommutative Hopf algebras to be substantially easier than the classification of Hopf algbras, period?
Comment: @tomasz No, I don't. As you say, they seem pathological. Most Hopf algebras that I know - e.g. group algebras, universal enveloping algebras, tensor algebras - are either cocommutative or commutative. Sweedler's Hopf algebra was discovered relatively late, so another reason to guess that it actually is not too easy. However, note that my question has three parts. I'd be happy with another example of a non-commutative, non-cocommutative Hopf algebra. By the way, what makes you say: "Typically, classifying a pathological subclass of objects amounts to classifying the whole class"? Experience?
Comment: Well, the way classification theorems I've seen work, they give you a nice classification of the "well-behaved" objects, usually getting progressively more messy as the objects get more ill-behaved, often to the point of completely eluding classification in general (sometimes, provably so).
Comment: Gerstenhaber-Voronov https://arxiv.org/abs/hep-th/9409063 showed that the bar construction of a certain kind of $E_2$ algebra is a bialgebra (so this doesn't count as a proper Hopf algebra), these bar constructions are tensor coalgebras (not cocommutative) and the algebra structure comes from the $E_2$ structure on the starting algebra, so it is not generally commutative. Not what you are looking for, I believe, but it seemed relevant.
Comment: @darijgrinberg That seems interesting! Do you remember what? Do you have any reference? At QiaochuYuan and JustinYoung: Thanks a lot.
Comment: @M.C.: I'm saying this mainly because I know the self-duality of the group ring of a cyclic group is tantamount to the basic properties of the Fourier transform, but the Taft Hopf algebra is a more intricate relative of the group ring of the cyclic group, and is also self-dual (for nontrivial reasons, if I remember correctly -- I have never seen it proven).
Comment: I am literally sitting in a talk now with some of these algebras. Another source of algebras is the Benson-Witherspoon algebras, which are a form of smash product.
Comment: I should also mention that if you make connectivity assumptions, then the bar construction bialgebra I mentioned above will be a proper Hopf algebra (existence of antipode is easy), but connected graded Hopf algebras still seem orthogonal to your interest, I only present this as a tangent.
Answer: Where I would look for examples of non-commutative and non-cocommutative Hopf algebras is the world of quantum groups, where you will find many such examples (that also carry a *-involution)
For example,

The algebra of functions on the Kac-Paljutkin quantum group (dimension eight).
The algebra of functions on a Sekine quantum group (dimension $2n^2$ for a natural number parameter $n$).
The algebra of regular functions on Wang's quantum permutation groups, equal to $F(S_N)$ for $N\leq 3$ but infinite dimensional for $N\geq 4$.

To see more examples see the references here.
I can't answer your second question.
Your third question, perhaps look at the papers of Andruskiewitsch.


Replace integer field value with stars in twig template

Question: I have a Drupal 8 site with a node type exposing a "difficulty level" field which is an integer choosen from a list (1 to 5).
Current onsite display is : "difficulty: 3". I would like to replace the value "3" by three black stars and two white ones to picture "3/5" (done via CSS background images).
In field--field-difficulty.html.twig I have replaced item.content by:
{% for i in range(1, 5) %}
  {% if (loop.index <= item.content) %}
    *
  {% else %}

  {% endif %}
{% endfor %}

But this keep giving me five * displayed, just like if the {% if %} statement was always true.
Can someone give me a hint on this please ?
Answer: For the field template there are two approaches to get the integer number from a field:
Node object
{% set difficulty = element['#object'].field_difficulty.value %}
{% for i in range(1, 5) %}
  {% if i <= difficulty %}

Find the rendered number
You can try to find the number in #markup:
{% if loop.index <= item.content['#markup'] %}

The node object is the better approach, because the way how the number is rendered can change when updating the code or changing the configuration.
Comment: what if you set a variable `{% set difficulty = element['#object'].field_difficulty.value %}` before you start the loop and compare this to `i`, this looks cleaner and is easier to debug?
Comment: Perfect !

Because I wanted it generic in field--list-integer.html.twig template, I had to tweak it a bit to not actually having the field_name in the template.
Here is the full solution I used :
`{% set fieldname = attribute(element['#object'], element['#field_name']) %}
{% for i in range(1, 5) %}
  {% if i <= fieldname.value %}
     *
  {% else %}

  {% endif %}
{% endfor %}`
Comment: Hi !
{{ element['#object'].field_difficulty.value }} does not print the value
{{ item.content['#markup'] }} does print the field value
{{ item.content }} does to

However, none of the {% if ... %} {% else %} work: every solution goes in the if, not in the else, giving me 5/5 rendering no matter the real field value.

Do you have an idea why ? May it be that the value is considered as a string, so the comparison compare an integer (loop.index) with the item.content string ?
Comment: That's the problem with the rendered output, it is supposed to be printed in the browser, not to be used for logic. But you should be able to find the raw value in `#object`. Try {{ element['#object'].id }} to check if you have an object and that the id is the one you are looking for. Then check the correct spelling of the field. You find the machine name of the field when you configure the content type. And twig doesn't need parentheses in if. I've removed them in the answer.
Comment: I have done exactly so. By printing both loop.index, and element['#object'].field_difficulty.value I can see the values are correct and the loop is run correctly.
The whole thing is that if loop.index <= element['#object'].field_difficulty.value is not evaluated properly... always true.
Answer: Maybe add the field value or content to a class, and then use that selector to set a background image.
{% for item in items %}
  {# set a new variable #}
  {% set star_class = 'star' ~ item.content %}
  {# add class to attributes for the item, item.content may not be appropriate here. Use kint/dump to see more info on item variable. #}
  {{ item.content }}
{% endfor %}

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
Then you can apply your background, width, text-indent, display, etc... to allow for the additional widths for styles. Probably done in a pseudo-element.
Comment: This approach would work, but for what I understand it would need 5 different images for the 5 cases: 1/5, 2/5, 3/5... This is why I would rather generate 3 span "active" and 2 "inactive" for representing 3/5 with the CSS background-image technique.
Comment: Or 1 image as a spritesheet.
Comment: Yes, a per choosen solution. The difference is chosen solution needs only a 2 star sprite: one active star, one inactive.


Write a boolean function in template that determines if the logged user is either the node author or admin

Question: How do I write a function to determine if the user is either the node author or admin?
if ( logged user is author || admin ) {
  // …
}

It is for the node template.
Comment: Which template file do you want to alter?
Comment: Based on the title, this question could be one of three things. "How does boolean logic work (in PHP)?", "How do I determine if the user is also the author?", "How do I determine if the user is an admin?". Reading the question removes the first option. Downvoted for two questions in one, and a title that doesn't reflect the question well.
Answer: Put this to template.php file of your theme:
function YOUR_THEME_NAME_preprocess_node(&$variables) {
  global $user;

  if(in_array('administrator', $user->roles) || $variables['node']->uid == $user->uid) {
    $variables['is_admin_or_author'] = TRUE;
  }
  else {
    $variables['is_admin_or_author'] = FALSE;
  }
}

then in your node.tpl.php or node--your-content-type.tpl.php you'll have a variable $is_admin_or_author with either TRUE or FALSE value.
Comment: This is a good answer, assuming that the question was about the node template.
Answer: Instead of checking if the user is the author or admin, it is recommended to check for permissions to perform a certain action. That will make your system more flexible and you're fully taking advantage of the permission system already built into Drupal.
For instance, if you want to show/hide something depending on the permission to edit the current node, you can use this (assuming you're working with node.tpl.php):
function YOUR_THEME_NAME_preprocess_node(&$variables) {
  if (node_access('update', $variables['node'])) {
    $variables['permission_to_edit'] = TRUE;
  }
  else {
    $variables['permission_to_edit'] = FALSE;
  }
}

Now you can use the following in your node.tpl.php:
if ($permission_to_edit) {
  print "You may edit this node!";
}

Comment: Of course this is just an example, there may be other permissions you can check with [user_access](http://api.drupal.org/api/drupal/modules!user!user.module/function/user_access/7) that are more appropriate for your situation. Flag module itself also has functions to check certain permissions (see http://api.lullabot.com/file/contrib/flag/flag.module/7). Anyway, the most important message is this: I would always prefer checking permissions over checking user IDs or roles.
Comment: thanks marc, its useful idea, but its for flag module, to show something even when they aren't allowed to bookmark, so this won't work
Comment: This is the Drupal way: You never check if the user has a specific role, but if the user has a specific permission. The reason is maintainability of the code: Suppose you add more roles, you don't need to rewrite all the `if`-statements because the code would always be `if (user_access('get hamburgers')) { }`.
Comment: well i checked off the ability to flag if their are either author/admin/anonymous, which create flag link will return null. i thought it would be easier this way, to check if they are logged/admin/author than show something else
Answer: global $user;

if ($node->uid == $user->uid || $user->uid == 1) {
  return TRUE;
}
else {
  return FALSE;
}

You can also check for user roles by adding in_array('administrator', array_values($user->roles)) to the if statement if you had a seperate role (webmaster for example).


GridData view filter by date and time

Question: I've got a GridView and I need do filter witch shows me data between dates and times.
     <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ExportDataGrid._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

        Welcome to ASP.NET!

        To learn more about ASP.NET visit www.asp.net.

        DataGrid here

        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value=" 06:00:00 PM"></asp:ListItem>
            <asp:ListItem Value=" 06:00:00 AM"></asp:ListItem>
        </asp:DropDownList>
 <asp:DropDownList ID="DropDownList2" runat="server">
            <asp:ListItem Value=" 06:00:00 PM"></asp:ListItem>
            <asp:ListItem Value=" 06:00:00 AM"></asp:ListItem>
        </asp:DropDownList>

        <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
        <asp:Calendar ID="Calendar2" runat="server"></asp:Calendar>

        <asp:GridView ID="GridView1" runat="server" AllowSorting="True"
            AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
            EmptyDataText="There are no data records to display.">
            <Columns>
                <asp:BoundField DataField="BatchId" HeaderText="BatchId"
                    SortExpression="BatchId" />
                <asp:BoundField DataField="IncTank" HeaderText="IncTank"
                    SortExpression="IncTank" />
                <asp:BoundField DataField="MoblieTank" HeaderText="MoblieTank"
                    SortExpression="MoblieTank" />
                <asp:BoundField DataField="Recipe" HeaderText="Recipe"
                    SortExpression="Recipe" />
                <asp:BoundField DataField="TransferStart" HeaderText="TransferStart"
                    SortExpression="TransferStart" />
                <asp:BoundField DataField="TransferEnd" HeaderText="TransferEnd"
                    SortExpression="TransferEnd" />
                <asp:BoundField DataField="TransferVol" HeaderText="TransferVol"
                    SortExpression="TransferVol" />
                <asp:BoundField DataField="Operator" HeaderText="Operator"
                    SortExpression="Operator" />
                <asp:BoundField DataField="Vessel" HeaderText="Vessel"
                    SortExpression="Vessel" />
                <asp:BoundField DataField="WorkOrder" HeaderText="WorkOrder"
                    SortExpression="WorkOrder" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:DB_user614ConnectionString1 %>"
            ProviderName="<%$ ConnectionStrings:DB_user614ConnectionString1.ProviderName %>"
            SelectCommand="SELECT [BatchId], [IncTank], [MoblieTank], [Recipe], [TransferStart], [TransferEnd], [TransferVol], [Operator], [Vessel], [WorkOrder] FROM [MoblieFilling] WHERE [TransferStart] BETWEEN @TransferStart+@TimeStart AND @TransferEnd+@TimeEnd  ">

        <SelectParameters>
                <asp:ControlParameter ControlID="Calendar1" DefaultValue="9/9/2011 2:30:30 PM" Name="TransferStart"   />
                <asp:ControlParameter ControlID="Calendar2" DefaultValue="9/9/2012 2:30:30 PM" Name="TransferEnd"  />
                <asp:ControlParameter ControlID="DropDownList1"  Name="TimeStart" Type=DateTime DefaultValue="00:00:00" />
 <asp:ControlParameter ControlID="DropDownList2"  Name="TimeEnd" Type=DateTime DefaultValue="00:00:00" />
            </SelectParameters>
        </asp:SqlDataSource>

        You can also find documentation on ASP.NET at MSDN.

</asp:Content>

But this doesn't work. How should I use DropList to select right time? Is a declaration good? or should be different?
Comment: What do you enter in "TransferStart"? What is the result? What is the final sql query sent to db? Also describe your business means.
Answer: You can add AutoPostBack="true" and OnSelectIndexChanged="DropDownList_OnSelectIndexChanged" to your dropdownlist.
void DropDownList_OnSelectIndexChanged(Object sender, EventArgs e)
 {
    var filter =  DropDownList1.SelectedValue;

    //Request your data with citeria
    //Re-bind your GridView
 }

GridData view filter by date and time


Why am I beating Bayes error rate in this simulation?

Question: I am trying to recreate Figure 2.4 from Elements of Statistical Learning, which shows the training error rate, test error rate, and optimal Bayes error rate for binary classification using $k$-nearest neighbors for various values of $k$ in $[1,150]$. The problem is, my test error rates are way too low and are below the Bayes error rate.
The data is generated hierarchically as follows. For group A, ten means $m_k$ are drawn from $N_2((1,0)',I_2)$. Observations are drawn by choosing a mean $m_k$ uniformly at random from $\{m_1,\dotsc,m_{10}\}$, and drawing the observation from $N_2(m_k, I_2/5)$. For group B, the means are drawn from $N_2((0,1)',I_2)$ instead of $N_2((1,0)',I_2)$.
Here is my code for generating training and test data:
<code>library(MASS)  # for mvn sampling "mvrnorm"
library(class) # for k-nearest neighbors "knn"

set.seed(1000)

meansA = mvrnorm(10,c(1,0),diag(rep(1,2)))
meansB = mvrnorm(10,c(0,1),diag(rep(1,2)))
trainingAhidden = sample(10,100,TRUE)
trainingBhidden = sample(10,100,TRUE)
testAhidden = sample(10,5000,TRUE)
testBhidden = sample(10,5000,TRUE)
trainingAdata = t(sapply(trainingAhidden,function(x) mvrnorm(1,meansA[x,],diag(rep(1,2)/5))))
trainingBdata = t(sapply(trainingBhidden,function(x) mvrnorm(1,meansB[x,],diag(rep(1,2)/5))))
testAdata = t(sapply(testAhidden,function(x) mvrnorm(1,meansA[x,],diag(rep(1,2)/5))))
testBdata = t(sapply(testBhidden,function(x) mvrnorm(1,meansB[x,],diag(rep(1,2)/5))))
trainingY = gl(2,100,200)
testY = gl(2,5000,10000)
training = list(X = rbind(trainingAdata,trainingBdata),Y = trainingY)
test = list(X = rbind(testAdata,testBdata), Y = testY)
</code>
Even 9-nearest neighbors gives a test error rate of 0.1388, way below the optimal Bayes error rate of 0.21 given in the book:
<code>> results = knn(training$X,test$X,training$Y,k=9)
> tab = table(results,test$Y)
1 - sum(diag(tab))/sum(tab)
[1] 0.1388
</code>
What have I done wrong?
Answer: The Bayes error rate depends on the particular collection of $m_k$ for the groups A and B.
In your specific case the Bayes error rate is about 0.12
CODE EXAMPLE TO CALCULATE BAYES ERROR RATE
<code># calculating the theoretic distributions on a grid
za <- matrix(rep(0,100*100),100)
zb <- matrix(rep(0,100*100),100)
x <- seq(-4,5,length.out=100)
y <- seq(-4,5,length.out=100)
for (i in 1:100) {
  for (j in 1:100) {
    for (k in 1:10)
    {
      za[i,j] <- za[i,j]+0.1*dmvnorm(c(x[i],y[j]),meansA[k,],diag(rep(1,2)/5))
      zb[i,j] <- zb[i,j]+0.1*dmvnorm(c(x[i],y[j]),meansB[k,],diag(rep(1,2)/5))
    }
  }
}

# doing the integration to obtain the bayes error rate
dx=x[2]-x[1]
dy=y[2]-y[1]
bayes=0

for (i in 1:100) {
  for (j in 1:100) {
    bayes = bayes + 0.5*max(za[i,j],zb[i,j])*dx*dy
  }
}
1 - sum(diag(tab))/sum(tab)
1- bayes

# plotting the knn result with the bayes classifier
plot(test$X,pch=21,col=alpha(c(2,3)[results],0),bg=alpha(c(2,3)[results],1),cex=0.4,xlab="x",ylab="y")
points(training$X,pch=21,col=1,bg=c(2,3)[training$Y])
points(meansA,col=1,pch=21,bg=2,cex=2)
points(meansB,col=1,pch=21,bg=3,cex=2)
contour(x,y,za-zb,level=0,col=1,add=1)

# plotting the theoretic distributions with the bayes classifier
contour(x,y,za,add=0,col=2)
contour(x,y,zb,add=1,col=3)
contour(x,y,za-zb,level=0,col=1,add=1)
</code>
OUTPUT PLOTS
Contours of distributions for class A and B and Bayes classifier which is at values $p(x \vert A) = p(x \vert B)$. The overlap with the specific means (which is different for your example compared to the book) determines the error rate.

results of your 9 nearest neighbours classification. small points are the classified test sample, medium points are the training sample, big points are the 10 means for each class


O CSS não está funcionando em nenhum navegador do meu PC

Question: Boa noite, tenho que fazer um TCC para finalizar meu curso, porém o CSS do meu código não funciona em nenhum navegador. Ele só funcionar se eu puxo ele online da nuvem:

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.1/css/materialize.min.css">

Se eu puxo ele offline do meu pc, não funciona:

<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

Eu testei puxar ele offline pelo pc da minha escola e funcionou, eu acho que deve ser alguma coisa no meu pc. Seu alguém tiver alguma ideia do que seria, poderiam me ajudar por favor?
obs: não é o framework, pois já testei o Uikit também e foi o mesmo problema.
Comment: Eu não sei mas tenta usar so .css ao inves de .min.css
Comment: Qual é a URL que aparece no navegador quando você abre esse html nele?
Answer: Verifique a permissão do arquivo / pasta, talvez não tenha permissão suficiente.
Em linux (Debian, Ubuntu, etc..
Permissão recomendada para diretórios (pastas) é 755
sudo chmod 755 /nome_da_pasta

Já para arquivos é 644
sudo chmod 644 /nome_do_arquivo

Answer: Pode ser que sua pasta não está dando permissão à acesso. Se o endereço e o nome do arquivo da certo.
Faz assim, clica com o botão direito na tua pasta css vai em propriedades e na aba segurança clica em "Editar"
Vai abrir uma nova janela, clica em "Adicionar" digita "todos" seleciona o usuario "Todos" na lista e dá um OK. Nas caixinhas de baixo ativa o "Controle Total". Dá um ok e fecha. Faz um teste para ver.
Comment: Obrigado, eu consegui resolver. Era um problema na digitação do código.
Comment:
Comment: Ah sim, que bom que resolveu, pelo caminho imaginei que estava na raiz mesmo se não já tinha dado a dica heheh. Mas que bom que resolveu.
Answer: Eu consegui resolver o problema, eu teria que adicionar os 2 pontos (..) para mostrar que a pasta "css" estava dentro de outras pastas. Desculpa galera, era uma coisa simples, mas eu fiquei nervoso por causa da pressão do TCC kkkkkkkkk
Eis aqui a resposta:
<link type="text/css" rel="stylesheet" href="../css/materialize.min.css"  media="screen,projection"/>


How to make all links on a mediawiki site absolute

Question: Our SEO advisor suggested to change all links on the site from relative to absolulte. Is there a good way to make it with some changes in localsettings.php or some extension?
If no, where should I make the least possible change in mediawiki code?
Comment: What does that have to do with SEO? Any search engine has to understand relative links and I think it would be stupid to treat relative and absolute links differently.
Comment: I'm sorry, that is not an answer to the question.
Answer: In LocalSettings.php
$wgArticlePath = "//site.com/wiki/$1";


How to "unhook" a hook from a module?

Question: I want to use the email_auto_login module. However it implements a hook_mail_alter which I don't want.
/**
 * Implements hook_mail_alter().
 */
function email_auto_login_mail_alter(&$message) {
  $user = user_load_by_mail($message['to']);

  // Don't add tokens for admin, anonymous or blocked.
  if (!isset($user->uid) || $user->uid == 1 || $user->status == 0) {
    return;
  }

  $token = _email_auto_login_generate_token($user);

  foreach ($message['body'] as &$body) {
    $body = _email_auto_login_add_token($body, $token);
  }
}

Is there a way to remove the hook without modifying the above code? I'm running Drupal7.
Answer: You should be able to do it with hook_module_implements_alter(&$implementations, $hook) in your module. Simply test $hook and if it is the hook you don't want implemented, unset($implementations['email_auto_login']).

How to "unhook" a hook from a module?


How to import title, description and image from website

Question: I would like to have a "Facebook style link commment" feature in Drupal 7. When you enter a URL it will pull the page title, first 100 characters of the main website text and an image.
There is a module called "Facebook Style Micropublisher" but it's Drupal 6 only.
Any other ideas on how this could get accomplished?
Comment: Will you be entering the url in a new node?
Comment: I would enter the URL and the parsed info into fields.  Over the weekend I stumbled across oembed.com (an open format to embed content) and http://embed.ly (a commercial site). There is even a module that seems to support both: http://drupal.org/project/oembed.
Answer: The manual way to do it is to create a custom module that uses drupal_http_request to download the remote URL, then parse through the resulting data to pull out any images, a summary, and the contents of the title tag.
This is a lot harder than it sounds because manually parsing HTML is actually pretty tricky. If you must take this approach, try using simplexml or a library that tries to simplify things for you.
A better approach might be just porting the Drupal 6 module yourself - it's probably less work and you could contribute your code back and possibly get patches from other contributors.


jQuery RegEx in If-statement

Question: I have the following list

Sonata

http://facebook.com

Omega

Rule of Thumb

https://youtube.com

I want to wrap only the text that contains http:// or https:// with the URL link. So, what I am doing currently in jQuery is:
if ($('li.lists:contains(http://)') || ('li.lists:contains(https://)')) {
    $('li.lists:contains(http://)').wrapInner(function () {
        return "";
    });

    $('li.lists:contains(https://)').wrapInner(function () {
        return "";
    });
}

As you can see, just for one character s in link, I have to use or || statement and call the wrapInner() function twice.
Is it possible to acheive this with Regular Expression in jQuery with one liners like
if ($('li.lists:contains(http/?s/://)')) {

OR
$('li.lists:contains(http/?s/://)')

something like this.
JsFiddle for the above codes.
Comment: You could do a `.test()` on the text in the `li`. Eg. `regEx.test(listItem1.text())`. `test()` returns a boolean if the argument passed in passes the regex.
Answer: fiddle Demo
$('li.lists').html(function (_, html) {
    return html.replace(/((?:http|https):\/\/.+)$/g, '$1');
});

fiddle Demo
var urlPattern = new RegExp("(http|https)://");
$('li.lists').filter(function (_, str) {
    return urlPattern.test(str.innerHTML);
}).wrapInner(function () {
    return "";
});

Comment: I am looking for api documentation for `.test()` couldn't find any. May be you know it better, does this work in IE8?
Comment: @JhilkeDai Read [.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)

jQuery RegEx in If-statement


Rule to notify admin by email whenever anyone updates a field in a user profile

Question: I have allowed a certain 'role' to change/edit fields in 'registered' users' fields. I want to receive an email in the admin's inbox detailing these changes using Rules.
I tried and failed!
Any help to achieve this?
i.e.
Subject: [user, who changed the field in a registered user's profile] changed [user, whose profile settings have been changed] profile
Body: [changed by]
[user whose profile was changed]
[value of changed filed in profile]
[value changed at]

Comment: Have you made a new account and received an e-mail? Just want to check that your e-mailing system works and that Rules is indeed the where the issue is at.
Answer: I am giving you the alternate idea instead of using rules,you can use hook_form_alter.
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
 function getCurrentUserRecord()
 {
  $myArray = [];
  $x = db_select('users_field_data','cw')
    ->fields('cw',['name','pass','mail'])
    ->execute()->fetchAll();

  foreach($x as $v){
    $myArray = $v;
  }
  return $myArray;
  }

function nestle_viewalter_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

      if($form_id == "user_form")
       {

            foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
  $form['actions'][$action]['#submit'][] = 'nestle_viewalter_form_submit';
   }
   }
   }

   }
function nestle_viewalter_form_submit(array $form, FormStateInterface $form_state)
{
$records = getCurrentUserRecord();

$field=$form_state->getValues();
$mail = $field[mail];
$name = $field[name];

if($records->name == $name || $records->mail == $mail)  {
    drupal_set_message(t("No changes so far"), 'error');
}
  else{

    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'nestle_viewalter';
    $key = 'update_profile';
    $to = 'email@example.com';
    $send = true;
    $result = $mailManager->mail($module, $key, $to,NULL, $send);

    if ($result['result'] !== true) {
        drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
    }
    else {
        drupal_set_message(t('Your message has been sent.'));
    }

    drupal_set_message(t("Send mail"), 'status');
}
}

  function nestle_viewalter_mail($key, &$message, $params) {
 switch ($key) {
 case 'update_profile':
 $message['from'] = \Drupal::currentUser()->getEmail();
 $message['subject'] = t('Profile updated');
 $message['body'][] = 'this is a test mail from the current user as i have updated my profile.';
 break;
 }
 }

Comment: That was sweet. That makes me to ask you to send me a link which explains IN DETAIL the process of attaching this hook to drupal 8 through module. Thanks in advance.
Comment: Hi Vikram can you help me to make a module named inform_user_changes


How to set Z-index to nested elements?

Question: I have two base DOM elements and two inner elements.

Blue box must overlap grey box.
Blue inner box must overlap blue and grey boxes.
Grey inner box must overlap all other elements.

But it doesn't.

#grey_box {
  width: 200px;
  height: 200px;
  border: solid 1px #ccc;
  background: #ddd;
  position: relative;
  z-index: 10;
}
#blue_box {
  width: 200px;
  height: 200px;
  border: solid 1px #4a7497;
  background: #8daac3;
  position: relative;
  z-index: 20;
  margin-left: 80px;
  margin-top: -50px;
}
#grey_inner_box {
  width: 50px;
  height: 50px;
  background: red;
  position: relative;
  z-index: 200;
  margin-top: 80px;
  margin-left: 150px;
}
#blue_inner_box {
  width: 50px;
  height: 50px;
  background: green;
  position: relative;
  z-index: 100;
  margin-left: 40px;
  margin-top: -40px;
}

grey inner

blue inner

What am I doing wrong?
Comment: why is your blue box green and your grey box red?
Answer: What you want isn't possible.
Once you set an element to position: anything except static, it establishes a new stacking context.
Anything you set the z-index of inside it, is only positioned within it.
Take this for example:

Inside each box, you can put the papers in any order you like. You can put box1 on top of box2 or vice versa, but when you move a box, you take the papers inside the box with it.
If you want to overlap the papers in the different boxes, you need to take them out of the boxes first.
Answer: Remove the z-index from #grey_box. Since #grey_box is beneath all other divs, we dont need z-index there. This helps to bring the #grey_inner_box to top.

#grey_box {
  width: 200px;
  height: 200px;
  border: solid 1px #ccc;
  background: #ddd;
  position: relative;
  /* z-index: 10; */
}
#blue_box {
  width: 200px;
  height: 200px;
  border: solid 1px #4a7497;
  background: #8daac3;
  position: relative;
  z-index: 20;
  margin-left: 80px;
  margin-top: -50px;
}
#grey_inner_box {
  width: 50px;
  height: 50px;
  background: red;
  position: relative;
  z-index: 200;
  margin-top: 110px;
  margin-left: 150px;
}
#blue_inner_box {
  width: 50px;
  height: 50px;
  background: green;
  position: relative;
  z-index: 100;
  margin-left: 40px;
  margin-top: -40px;
}

grey inner

blue inner

How to set Z-index to nested elements?


Activity restarts when called from service

Question: I have a service in my app of  a floating button (like facebook messenger)
and when clicked , my activity returns from the background , but it doesn't return in the same way it was when it was minified , it starts over calling onCreate once more , any idea what causes this behavior ?
In my manifest the acivity is with property :
            android:launchMode="singleTask"

and it is called by my service like so :
    Intent i = new Intent(FloatingViewService.this, DrawerActivity2.class);
    i.putExtra("fromController",true);
    i.setFlags(FLAG_FROM_BACKGROUND);
    FloatingViewService.this.startActivity(i);

My main problem is inside the activity i have a webview and it's reloading everytime the button is clicked and calls the activity instead of just staying the same way.
After the update this is my activity in the manifest
        <activity
        android:name=".DrawerActivity2"
        android:configChanges="orientation"
        android:launchMode="singleTop"
        android:screenOrientation="portrait"
        android:theme="@style/OtherTheme"/>

UPDATE 2
It might be worth to mention , it's a library that sits in an app.
I tried this code for opening the activity :
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(intent);

and it opened the first(of the original app) activity and not the one that is open.
any help will be appreaciated
Comment: post your manifest please.
Comment: when do you add singleTask as launchmode? which method is getting called? Oncreate? or onNewIntent?
Comment: Well I didn't override onNewIntent but onCreate is being called everytime
Comment: added more info on question..
Answer: I could only imagine what your FLAG_FROM_BACKGROUND means. And I wonder if it called so cause you had some crashes before with something like "activity could be launched without FLAG_NEW_TASK from applicationContext bla bla". Whatever.
So if you have there Intent.FLAG_ACTIVITY_NEW_TASK you will always get your DrawerActivity2 instantiated in NEW_TASK. It will always be, you know "new one" activity.
And changing launchMode to singleTop won't give expected result. Read about launchModes and Flags here
Note you're not allowed to launch Activity within same TASK with an ApplicationContext(or BaseContext/ContextWrapper that Service extends). For that purpose you have to use Context of an Activity for starting new Activity
And about Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(intent);
Probably it works as expected

The current implementation looks first for a main activity in the
  category Intent.CATEGORY_INFO, and next for a main activity in the
  category Intent.CATEGORY_LAUNCHER. Returns null if neither are found.

Android developers source
And you ask

my activity returns from the background, it starts over calling onCreate once more , any idea what causes this
  behavior ?

My assumption is FLAG_FROM_BACKGROUND:
Intent i = new Intent(FloatingViewService.this, DrawerActivity2.class);
    i.putExtra("fromController",true);
    i.setFlags(FLAG_FROM_BACKGROUND); /*is it really Intent.FLAG_ACTIVITY_NEW_TASK ???*/
    FloatingViewService.this.startActivity(i);

How to fix it ? Probably to startActivity with ActivityContext instead of ApplicationContext. But this is different story to tell. And can't recommend a "good" way of how to implement it.
Comment: A simple way to get the activity context to a service could be that you launch a activity which launches the DrawerActivity2. If you set the launcherActivity noHistory to true and finish it should have the expected result.
Comment: great  answer , Is there a simple way to get the activity context to a service ?
Comment: Are you sure that you really need to have activity within Service ? Is there another way to improve your app ?
If there is no other way as a last resort I would use  Background Activity without any layout. And I probably would save it in Application class as static field. And I would clear that reference when Service called onDestroy()
Comment: well , the service is a floating button that starts when a call comes in , pressing it will cause a return to the dailer , and another to return to the activity and so on ... what would you do in this situation?
Comment: @yanivtwin were you actually able to solve your problem with this answe? What did you change? I don't see anything helpful here. I'm curious.
Answer: You need:
<activity
        android:name=".DrawerActivity2"
        android:launchMode = "singleInstance" />

Answer: I think if you use launchMode singleTop and i.setFlags(FLAG_ACTIVITY_NEW_TASK) it should work, but only if the activity is on top of the stack.
If you cannot ensure that the activity is on top of the stack, it is worth a try to set launchMode to singleTask and i.setFlags(FLAG_ACTIVITY_NEW_TASK)


how internally map and flatmap works in java 8

Question: In java 8, when we should go for Stream.map and flat map methods ?
I am bit confused about the use cases. Please give some scenarios to use these two methods.
Comment: Did you go through the javadoc?
Comment: [Difference Between map() and flatMap() in Java](https://www.techiedelight.com/difference-map-flatmap-java/)
Comment: It's like your title and your text ask two different questions? Is the one in the text the question you intended to ask? Please edit your question and clarify and add precision (use the [edit](https://stackoverflow.com/posts/57839338/edit) link).
Answer: Map is used when you want to transform a stream.
For example you have a shopping cart and for each item in your cart you would like to get the item detail or something else.
FlatMap combines the above map operation with a flat operation
Example could be something like you have bunch of orders and would like to know the total count of items sold for all orders. You could use a flatmap operation to get the number of items
Documentation helps btw
Answer: Map is used to transform the object from one stream to another.
For example:
    class User {
        private Long id;

        public Long getId(){
           return id;
       }
}

Consider you have a list of users and your usecase is to get the user id's alone. Here comes advantage of Map.
List<User> users = new ArrayList<>();

List<Long> ids = users.stream().map(user ->
  user.getId() ).collect(Collectors.toList());

FlatMap is also same as Map but it has another advantage of merging the multiple list into single list.
Example:
List<List<String>> stringlist = Arrays.asList( Arrays.asList("a"),
Arrays.asList("b") );

List<String> strings = stringlist.stream().flatMap(Collection::stream)
  .collect(Collectors.toList()));


How to get the JRE to bundle with launch4j?

Question: I understand that launch4j doesn't bundle the JRE in the .exe but that you have to place it next to it. My question is, how am I supposed to do that? Is there a way for maven to automatically locate and copy the JRE of the JDK I'm using to build my application and copy it to a given directory?
I've tried doing something like this:
    <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.6</version>
        <executions>
            <execution>
                <id>copy-resources</id>

                <phase>package</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <outputDirectory>${basedir}/target/windows/jre</outputDirectory>
                    <resources>
                        <resource>
                            <directory>${java.home}</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>

but the program doesn't start. It shows a little dialog that immediately disappears (it seems to be blank, but it goes away too quickly for me to really notice it).
Comment: Do you only need to support Windows as a platform?
Comment: @SarelBotha: for now, yes, Windows 7, 8 and 10; 32 and 64 bit.
Comment: Does the maven build output indicate it is trying to copy the directory? try hard-coding the path to the JRE directory.
Comment: When does maven call launch4j? During the package phase? Will this be before your custom execution is called? Maybe change your custom execution to run in the compile phase to make sure it is done first.
Comment: Planning on using the 32 bit JRE for both 32 and 64 bit Windows to simplify this?
Comment: @SarelBotha: if that's the only option, yes. Otherwise, I'd rather give 32 and 64 bit binaries to my customers.
Comment: Updated my answer. I believe it does what you want now.
Comment: Oracle does not want anyone downloading the JRE from them at install time because they want to force everyone to accept the license agreement. I believe for this reason there are no official ways to do this and finding ways to do this are rare. You can use the repository alfresco provides with the older version or host your own private repository and manually update the version from time to time. This is what we do.
Answer: UPDATE: Deleted my previous answer and replacing with tested working example
UPDATE 2: This pom.xml now downloads the JRE tgz and unpacks it and the launch4j exe uses it and it works. I added comments to explain how it works.
I would recommend sticking with just a 32 bit exe and JRE. The only reason to use the 64 bit JRE would be if your program needs to use more than 4 GB of RAM.
Of course now you need an installer that takes all this and installs to Program Files. I've used NSIS for this in the past. There is a learning curve for NSIS but it is not too bad.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.akathist.encc</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>com.oracle.java</groupId>
            <artifactId>jre</artifactId>
            <classifier>win32</classifier>
            <type>tgz</type>
            <version>1.8.0_131</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>

            <id>alfresco</id>
            <url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>unpack-dependencies</goal>
                        </goals>
                        <configuration>
                            <includeGroupIds>com.oracle.java</includeGroupIds>
                            <includeTypes>tgz</includeTypes>
                            <includeArtifactIds>jre</includeArtifactIds>
                            <includeClassifiers>win32</includeClassifiers>
                            <outputDirectory>target/win32</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>

                <groupId>com.akathist.maven.plugins.launch4j</groupId>
                <artifactId>launch4j-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>l4j-clui</id>
                        <phase>package</phase>
                        <goals>
                            <goal>launch4j</goal>
                        </goals>
                        <configuration>
                            <headerType>console</headerType>
                            <outfile>target/encc.exe</outfile>
                            <jar>target/mavenproject1-1.0-SNAPSHOT.jar</jar>
                            <errTitle>encc</errTitle>
                            <classPath>
                                <mainClass>com.akathist.encc.Clui</mainClass>
                                <addDependencies>false</addDependencies>
                                <preCp>anything</preCp>
                            </classPath>
                            <jre>
                                <path>./win32/java</path>
                            </jre>
                            <versionInfo>
                                <fileVersion>18.104.22.168</fileVersion>
                                <txtFileVersion>txt file version?</txtFileVersion>
                                <fileDescription>a description</fileDescription>
                                <copyright>my copyright</copyright>
                                <productVersion>220.127.116.11</productVersion>
                                <txtProductVersion>txt product version</txtProductVersion>
                                <productName>E-N-C-C</productName>
                                <internalName>ccne</internalName>
                                <originalFilename>original.exe</originalFilename>
                            </versionInfo>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

UPDATE 3: The sad fact is that there exists no offical or even up-to-date maven repo with the JREs that you want. You could host your own maven repo that has the desired JREs. You will have to update this as new releases are done. It is also a good idea to test with the new version before releasing with it. The third Tuesday of every month is when new Java releases are done. You can set a reminder for this to check if a new version was released and download it. Automating this is a pain because of the license agreement check. This post might help but you probably can't download the tar.gz version of the JRE this way: Java check latest version programmatically
If you want to support multiple platforms then hosting your own maven repo is a good way to go. You can host your own repo and update it with the new JRE tar.gz every time a release is done with this: https://stackoverflow.com/a/29261502/35264
The simplest option is to do what you were aiming for already and just use the JRE that you are building with. This will allow you to support Windows 32 and 64 as long as you build with the 32 bit JRE. You can update this occasionally as you have time to test with the new version. Here is a working pom.xml that does this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.akathist.encc</groupId>
    <artifactId>mavenproject1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <build>
        <plugins>
            <plugin>

                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>

                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/win32/java</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${java.home}</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>

                <groupId>com.akathist.maven.plugins.launch4j</groupId>
                <artifactId>launch4j-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>l4j-clui</id>
                        <phase>package</phase>
                        <goals>
                            <goal>launch4j</goal>
                        </goals>
                        <configuration>
                            <headerType>console</headerType>
                            <outfile>target/encc.exe</outfile>
                            <jar>target/mavenproject1-1.0-SNAPSHOT.jar</jar>
                            <errTitle>encc</errTitle>
                            <classPath>
                                <mainClass>com.akathist.encc.Clui</mainClass>
                                <addDependencies>false</addDependencies>
                                <preCp>anything</preCp>
                            </classPath>
                            <jre>
                                <path>./win32/java</path>
                            </jre>
                            <versionInfo>
                                <fileVersion>18.104.22.168</fileVersion>
                                <txtFileVersion>txt file version?</txtFileVersion>
                                <fileDescription>a description</fileDescription>
                                <copyright>my copyright</copyright>
                                <productVersion>184.108.40.206</productVersion>
                                <txtProductVersion>txt product version</txtProductVersion>
                                <productName>E-N-C-C</productName>
                                <internalName>ccne</internalName>
                                <originalFilename>original.exe</originalFilename>
                            </versionInfo>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Comment: Is gvSIG.confDir supposed to make make it work? Because I'm already configuring launch4j like that. Also, your answer doesn't include how to put the jre in the ../jre path, which is what I'm asking. I've read the question you linked to (and many launch4j questions here in SO as well as elsewhere and I couldn't find anything about sourcing the JRE).
Comment: Not sure what the point of gvSIG.confDir is. I would attack this in two phases. First make it work with the JRE directory manually copied next to the launch4j XML file. Then after that try to make it automatically copy the JRE dir.
Comment: Thank you for the answer Sarel. Unfortunately, it seems that repo is stuck at 1.8.0_133. Already missing some fixes I'm counting on by using 1.8.0_162 (although I don't remember what they were, I just remember needing to upgrade, I might need to do some research here). But also there's no Java 9 or 10. :(
Comment: I updated the answer to address the concerns. Yes, there are pros and cons with the different approaches. You will have to choose based on what you are willing to live with. Java 9 and 10 do not support 32 bit Windows so it will probably be a while before you can make that switch.
Comment: Hello Sarel. Isn't the last example in which you use the JRE you are compiling with the same as mine in the question? That one as in the question, is failing silently.
Comment: I couldn't use the other one because having the `tgz` dependency interferes with shade: `[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project dashman: Error creating shaded jar: error in opening zip file C:\Users\pupeno\.m2\repository\com\oracle\java\jre\1.8.0_131\jre-1.8.0_131-win32.tgz -> [Help 1]`. I'm sure this is trivial to solve, but I'm new to Maven.
Comment: Ok... I think I found a new exception that the jar was throwing and correcting that one made the '.exe' and now it worked. I had the jar working before and the exe not working... I have no idea what changed though :(
Comment: Yes, the last option goes back to what you were trying to do originally.
I think that's the best option in the short term since you want a newer Java version. Then this shade issue should go away. In the future if you use tgz again you can probably tell shade to exclude the tgz because the build process is extracting the tgz anyway. It is not being referenced on the classpath by Java: https://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html . Yes, I am new to maven too. This has been an interesting learning experience.
Comment: The problem you originally had that makes it flash the black command prompt window quickly was that path to the JRE was wrong. If you have in copy-resources ${basedir}/target/windows/jre then you should have in launch4j ./windows/jre
Comment: I don't think so, the binary is in the windows directory too.
Comment: Is there a way we can use the JRE from the installed JDK in our development environment? We can grab the environment variable (${env.JAVA17_HOME}) but I'm not sure how to configure launch4j to use it.
Answer: I believe this is what you are looking for:
<plugin>
  <groupId>com.akathist.maven.plugins.launch4j</groupId>
  <artifactId>launch4j-maven-plugin</artifactId>
  <executions>
    <execution>
      ...
      <configuration>
        ...
        <jre>
          <path>${java.home}</path>
        </jre>
        ...
      </configuration>
    </execution>
  </executions>
</plugin>

Java lets you access JRE path using java.home system property. And you can access java system properties within pom. And you have a plugin that wraps launch4j. Put all of these together and you have the solution.
Comment: No, it doesn't. That will create an exe that expects `${java.home}` to exist on every computer you try to run, that is, on the users of the application. The jre path should be relative to the current path when bundling.
Comment: I think author want a solution that works when computer doesn't have java installed, so he want to bundle JRE to exe.
Comment: This bundles the JRE used by maven in the final exe.
Comment: @pupeno yes, exactly.
Comment: this solution saved my 1.5 days of struggle :)


What happens if you square an RBF kernel function?

Question: Let's say we use a kernel regularization algorithm such as ridge regression to minimize some loss in an RBF kernel:
$$\min_{h \in H} \frac{1}{n} \sum_i (h(x_i) - y(x_i))^2 + ||h||^2_K$$
We get some $h$ in the RBF kernel space. What now happens if we square h? For example, if we look at $h^2$, is it still in an RBF kernel space or not?
Due to the representer theorem we know that $h$ is a sum of kernel products.
A guess is to say that $h(x) = e^{-||x - z||^2/\sigma^2}$, and if we look at $h^2$ we get that $h^2(x) = e^{-2||x - z||^2/\sigma^2}$.
But if $h$ contains two terms: $h(x) = e^{-||x - z||^2/\sigma^2} + e^{-||x - y||^2/\sigma^2}$, and we look at $h^2(x)$ we find that:
$$h^2(x) = e^{-2||x - z||^2/\sigma^2} + e^{-2||x - y||^2/\sigma^2} - 2e^{(-||x-y||^2-||x-z||^2)/\sigma^2}$$
And I can't see now we have two terms, how to rewrite it to a sum of RBF kernel products. So does it stay in the same RBF space? And how about the norm of h?
Answer: To start with, you're slightly off on the representer theorem; it means that $h$ is a linear combination of kernel functions. That is, if your input data points are $\{z_i\}_{i=1}^n$, then
$$
h(x) = \sum_{i=1}^n \alpha_i \, k(x, z_i)
$$
for some real coefficients $\alpha_i$.
Thus
$$
h^2(x) = \left( \sum_i \alpha_i \, k(x, z_i) \right)^2
= \sum_i \sum_j \alpha_i \,\alpha_j\, k(x, z_i) \, k(x, z_j)
,$$
which will be in a given RKHS as long as $k(x, z_i) \, k(x, z_j)$ is in the RKHS.
Now specialize to the class of RBF kernels
$$
k_\sigma(x, z) = \exp\left( - \frac{1}{2 \sigma^2} \lVert x - z \rVert^2 \right)
,$$
and define the corresponding RKHS as $\mathcal H_\sigma$.
(Note that your definition didn't have the 2 in the denominator, which is nonstandard and somewhat misleading; I'll use this one.)
Now, it turns out that:
$$
\begin{align}
k_\sigma(x, z_i) \, k_\sigma(x, z_j)
&= k_{\sqrt{2}\sigma}(z_i, z_j) \, k_{\sigma/\sqrt{2}}\left(x, \frac{z_i + z_j}{2} \right)
\end{align}
.$$
Thus
\begin{align}
h^2(x)
&= \sum_{ij} \underbrace{\alpha_i \alpha_j k_{\sqrt{2}\sigma}(z_i, z_j)}_{\beta_{ij}} \, k_{\sigma/\sqrt{2}}\Big(x, \underbrace{\frac{z_i + z_j}{2}}_{\zeta_{ij}} \Big)
\\&= \sum_{ij} \beta_{ij} \, k_{\sigma/\sqrt{2}}(x, \zeta_{ij})
,\end{align}
and $h^2 \in \mathcal H_{\sigma/\sqrt{2}}$.
In the interest of brevity, define $\tau := \sigma / \sqrt{2}$.
Now, turn to the following paper:

Tanaka, Imai, Kudo, and Miyakoshi, Theoretical analyses on a class of nested RKHS's, ICASSP 2011 (doi, author's pdf)

They show a few interesting facts in their Section 5:
First, $H_\sigma \subset H_\tau$ for all $\tau < \sigma$ (Theorem 5), and moreover $\lVert f \rVert_{\mathcal H_\sigma} \ge \lVert f \rVert_{\mathcal H_\tau}$ for every $f \in \mathcal H_{\sigma}$ (consequence of Theorem 4).
This doesn't tell us anything in particular about whether $h^2 \in H_\sigma$, but it does let us use their Proposition 1 as follows:
Let $\nu := \sqrt{ \sigma^2 + \sigma^2 - (\sigma / \sqrt{2})^2} = \sqrt{3/2} \sigma$. Then
$$\langle k_{\sigma}(\cdot, x), k_{\sigma}(\cdot, y) \rangle_{\mathcal H_{\tau}} = k_\nu(x, y).$$
Thus
\begin{align}
\lVert h \rVert_{\mathcal H_\tau}^2
&= \lVert \sum_i \alpha_i k_\sigma(\cdot, z_i) \rVert_{\mathcal H_\tau}^2
\\&= \sum_{ij} \alpha_i \alpha_j \langle k_\sigma(\cdot, z_i), k_\sigma(\cdot, z_j)\rangle_{\mathcal H_\tau}
\\&= \sum_{ij} \alpha_i \alpha_j k_\nu(z_i, z_j)
\end{align}
whereas
\begin{align}
\lVert h^2 \rVert_{\mathcal H_\tau}^2
&= \lVert \sum_{ij} \beta_{ij} k_\tau(\cdot, \zeta_{ij}) \rVert_{\mathcal H_\tau}^2
\\&= \sum_{abij} \beta_{ab} \beta_{ij} \langle k_\tau(\cdot, \zeta_{ab}), k_\tau(\cdot, \zeta_{ij})\rangle_{\mathcal H_\tau}
\\&= \sum_{abij} \beta_{ab} \beta_{ij} k_\tau(\zeta_{ab}, \zeta_{ij})
\\&= \sum_{abij} \alpha_a \alpha_b \alpha_i \alpha_j k_{\sqrt{2}\sigma}(z_a, z_b) k_{\sqrt{2}\sigma}(z_i, z_j) k_\tau(\zeta_{ab}, \zeta_{ij})
.\end{align}
The diagonal terms ($a = i$, $b = j$) of the latter sum look kind of like the first sum, but the off-diagonals can be either positive or negative, so that doesn't lead to an immediate bound. At least in this form, though, the norms are numerically comparable.
Comment: Excellent answer @Dougal. However, I'm still quite interested in what happens to the norm of $||h||_K$ compared to the norm of $h^2$ in the new kernel $||h^2||_{K'}$, where $K'$ has bandwidth $\frac{\sigma}{\sqrt{2}}$. I wonder are these norms related somehow, or can we bound the norm of $h^2$ using the norm of $h$? However, the derivation gets quite tricky, since in $k(x,z_i)k(x,z_j)$ we get a factor that depends on $exp(||z_i - z_j||)$... which only neatly cancels if $z_i = z_j$.
Comment: @Tom I updated with the equations for the norms, but it didn't really lead anywhere. Note though that norms in different spaces aren't necessarily comparable....
Comment: @Doagal thanks! I also worked it out and it doesn't seem comparable indeed. What confuses me a bit though is the following. Let's say you assume that we are working in a lineair kernel, and a function is bounded in the lineair kernel by some constant $\Theta$. Now if you square this function, it's easy to show it will end up in a polynomial kernel with degree 2 (and $c = 0$, see definition of [link](https://en.wikipedia.org/wiki/Polynomial_kernel)). Now the norm in this kernel is actually the same as in the lineair kernel.
Comment: Since the RBF kernel has an implicit feature mapping, squaring a function in this space could be similar to squaring it in the euclidean kernel - I guess (?). Thus we should be able to construct a polynomial kernel using the feature mapping of the RBF kernel, and in this feature mapping the norm should be the same. However, this doesn't seem to hold, or the feature mapping of this space does not correspond to the RBF kernel with the different parameter $\sigma$... Any ideas?
Comment: @Tom One of the feature mappings for the RBF kernel corresponds to basically the kernel itself, with every point on the space – see the second section of [this answer](http://stats.stackexchange.com/a/145439/9964). If you square that, you end up with the same type of argument as above, though the technicalities are trickier because it's infinite dimensional. I assume other embeddings could be manipulated into the same result, though it's not necessarily as obvious.
Comment: @Tom I just updated the answer to show more about how the two RKHSes and their norms relate to each other.


How can I get the real pointer to a field inside a struct in Go?

Question: I have a struct, say:
type sample struct{
   data []float64
}

Now, I declare a method:
func (s sample) Get() *[]float64{
return &s.data
}

I am trying to append to this slice via the pointer I got via Get()
func main(){
example := sample{[]float64{1,2,3}}

//Here I will append:
pointerToArray := example.Get()
*pointerToArray = append(*pointerToArray, 4)
fmt.Println(example.Get()) // still shows only &{1,2,3}
}

I have a general idea of why this is happening: The function Get is returning the address of its local scope, and I have fixed it by change the struct itself to
type sample struct{
data *[]float64
}

for which the code returns the expected &{1,2,3,4}
Now, for my question:
Is there anyway to get the real pointer to the field in the struct through a getter method without using a pointer field directly in the struct?
Answer: The problem is that you've defined the Get method with a struct receiver, rather than on a pointer. That means when you return &s.data you get the address of the field of receiver, rather than from the original struct. You can fix this simply by using a pointer receiver:
func (s *sample) Get() *[]float64{
    return &s.data
}

Here's a complete runnable example (https://play.golang.org/p/AIj8QOYfx85)
package main

import "fmt"

type sample struct {
    data []float64
}

func (s *sample) Get() *[]float64 {
    return &s.data
}

func main() {
    example := sample{[]float64{1, 2, 3}}

    p := example.Get()
    *p = append(*p, 4)
    fmt.Println(example.Get())
}

Comment: You can't. Perhaps better to make the interface `Append(values ...float64)` rather than expose the pointer, assuming you just want to append to it.
Comment: Hi, just another question if you could help: If I declare an interface to use this Get() method, how would I make sure that this only accepts pointer reciever types? Like in this example I want to append, but if I define an interface for the same, then how do I make sure that only a pointer reciever method implementation type is accepted?


getting strings and string length from a list into a dictionary

Question: my task was to define a function that takes a list of names and returns a dictionary of names + the corresponding length of each string (Name).
The code worked just fine:
    def toDict(namelist):
            lengths = []
            for i in namelist:
                    lengths.append(len(i))
            namedict = dict(zip(namelist, lengths))
            return namedict
            print(namedict)

However, 2nd part of the task was to do it in one line only and I'm getting stuck a bit there... please help.
Answer: One approach is to use a dict comprehension:
namedict = {name: len(name) for name in namelist}

If you need your entire function definition to be on one line, I'd suggest using a lambda:
to_dict = lambda name_list: {n: len(n) for n in name_list}

As mentioned in the comments, even though I personally prefer the lambda approach - and though I feel it's a solid use case for it - it's still possible to use a def and have a normal function on a single line; you'll just need to put the body immediately after the colon : as shown below.
def to_dict(name_list): return {n: len(n) for n in name_list}

Comment: PEP8 style guide says "Always use a `def` statement instead of an assignment statement that binds a `lambda` expression directly to an identifier. [`def`] means that the name of the resulting function object is [the actual name] instead of the generic ``. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)". Character count is a mere three characters longer to get that useful name.
Comment: You don't need a `lambda` to make it one line, you can put `def` and the body on the same line, immediately after the `:` for the `def`, in lieu of going to another line and indenting (it's not the worst thing ever as long as you don't use `;` to put multiple lines on one line): `def to_dict(name_list): return {n: len(n) for n in name_list}`
Comment: The short form of that rule is: "Never name a `lambda`"
Comment: Yep, that's definitely a good point. I also figured you can use `def` and have the func definition on one line, however I personally find it a bit more unwieldy than a lambda. Still, I'll see if I can mention that in the answer.
Answer: Another way:
>>> li = ['one', 'three', 'four']
>>> dict(zip(li, map(len, li)))
{'one': 3, 'three': 5, 'four': 4}

How it works:

map applies the function len to each element in li
zip forms a tuple of name and length
dict takes the tuple and forms a dictionary.


Find the eigenvalues of this matrix

Question: I was wondering if anyone wanted to give a shot at finding the eigenvalues of this $4\times 4$ system. I have tried without success, mainly because I end up having to solve a very nasty cubic polynomial that wolfram seems to be having trouble with as well. There may be some method to solve this that I didn't try, so I wanted to post this here just in case someone could help me out,
$$J(\epsilon)=\begin{bmatrix} -\mu &&0&&0 && -\beta b/\mu\\ 0&& -\sigma && 0&& \beta b/\mu\\0&& \sigma&& -(\phi+d)&& 0\\ 0 &&0&&\alpha&&-(\phi+\epsilon)\end {bmatrix}$$
Thanks!
Comment: Strictly speaking the quartic formula will necessarily give you the answer, but there's no guarantee that it will be nice...
Answer: After removing the obvious eigenvalue $-\mu$, you are indeed left to solve the cubic polynomial
$$ {\lambda}^{3}\mu+ \left( d\mu+\epsilon\,\mu+2\,\mu\,\phi+\mu\,\sigma
 \right) {\lambda}^{2}+ \left( d\epsilon\,\mu+d\mu\,\phi+d\mu\,\sigma+
\epsilon\,\mu\,\phi+\epsilon\,\mu\,\sigma+\mu\,{\phi}^{2}+2\,\mu\,\phi
\,\sigma \right) \lambda-\alpha\,\sigma\,\beta\,b+d\epsilon\,\mu\,
\sigma+d\mu\,\phi\,\sigma+\epsilon\,\mu\,\phi\,\sigma+\mu\,{\phi}^{2}
\sigma
=0$$
which seems to have no special algebraic features: in fact, for suitable values of the parameters I believe it can be any cubic polynomial.  A "closed-form" expression in radicals expressed in terms of all
these parameters will be a nightmare.  In practice, for particular
numerical values of the parameters you may be best off using a
numerical solver, but you can also use the general formula.
Answer: You can do row reduction  of the matrix $$J(\epsilon)=\begin{bmatrix} -\mu &&0&&0 && -\beta b/\mu\\ 0&& -\sigma && 0&& \beta b/\mu\\0&& \sigma&& -(\phi+d)&& 0\\ 0 &&0&&\alpha&&-(\phi+\epsilon)\end {bmatrix}$$
add row 2 and row 3
$$J(\epsilon)=\begin{bmatrix} -\mu &&0&&0 && -\beta b/\mu\\
 0&& -\sigma && 0&& \beta b/\mu\\
 0&& 0&& -(\phi+d)&& \beta b/\mu\\
 0 &&0&&\alpha&&-(\phi+\epsilon)\end {bmatrix}$$
row 3 $\times \alpha /(\phi+d)+$row 4
$$J(\epsilon)=\begin{bmatrix} -\mu &&0&&0 && -\beta b/\mu\\
 0&& -\sigma && 0&& \beta b/\mu\\
 0&& 0&& -(\phi+d)&& \beta b/\mu\\
 0 &&0&&0&&-(\phi+\epsilon)+(\beta b/\mu )(\alpha /(\phi+d))\end {bmatrix}$$
now determinant will be the multiplication of the diagonal elements
$$|J-\lambda I|=(-\mu-\lambda)(-\sigma-\lambda)(-(\phi+d)-\lambda)(-(\beta b/\mu )(\alpha /(\phi+d))-\lambda)=0$$

Find the eigenvalues of this matrix