ActiveCollab API v1 cannot change hourly_rates on project

Question: I cannot change the hourly_rate of Project or Client object via API (Using JavaScript/Google Script):
var responseObject = [];
  var payload = {
    "name": "Test project 125",
    "hourly_rates": {"45": 222}
  }
  var response = UrlFetchApp.fetch("https://app.activecollab.com/218040/api/v1/projects", {
                                   "method": "post",
                                   "headers": {
                                   'X-Angie-AuthApiToken': api_token
                                   },
                                   "payload" : payload,
                                   "followRedirects" : true,
                                   "muteHttpExceptions": true
                                   });

  if (response.getResponseCode() == 200) {
    responseObject = JSON.parse(response.getContentText());
  }

  console.log(responseObject);

returns:
hourly_rates={45=100, 24=20, 3=100, 38=50, 17=15, 31=50, 10=100}
I get the same result if i use PUT method. Everything else is saved, but hourly rates not.
Answer: have you tried the ActiveCollab SDK?
I'm not sure which company or which job-type you target.
Once you download the package from git, run composer update
Here's an example:
<?php

/*
 * This library is free software, and it is part of the Active Collab SDK project. Check LICENSE for details.
 *
 * (c) A51 doo <email@example.com>
 */

require_once __DIR__ . '/vendor/autoload.php';

$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'YOUR-EMAIL', 'YOUR-PASSWORD');

// Show all Active Collab 5 and up account that this user has access to
print_r($authenticator->getAccounts());

// Show user details (first name, last name and avatar URL)
print_r($authenticator->getUser());

// Issue a token for account #123456789
$token = $authenticator->issueToken(176178);

if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
    print $token->getUrl() . "\n";
    print $token->getToken() . "\n";
} else {
    print "Invalid response\n";
    die();
}

// Create a client instance
$client = new \ActiveCollab\SDK\Client($token);

// Make a request
print_r($client->get('/job-types/5')->getJson());
try {
    $client->put('/job-types/5', [
        'single' => [
            'default_hourly_rate' => 300
        ]
    ]);

} catch(AppException $e) {
    print $e->getMessage() . '

';
}

This is an example of how to change the hourly rate directly, you can do that from the /projects/ID-OF-THE-PROJECT
Please refer to the API documentation: https://developers.activecollab.com/api-documentation/v1/people/companies/custom-hourly-rates.html
Comment: I am notu sure how the PHP SDK would solve my problem, since this is Javascript / Google Script app.
Comment: The problem is not with default_hourly_rate, but with custom hour rate on the project.
I am using the [documentation](https://developers.activecollab.com/api-documentation/v1/people/companies/custom-hourly-rates.html) where it suggests  `PUT /projects/1` with payload
`{
    "hourly_rates": {
        "1": 250
    }
}
`

(ie I know I have job type with id 1, and I want to change the rate on this project to 250. And this does not work)
Comment: POST request does not work, only PUT. Sending you screenshots of successful PUT request: https://ibb.co/CQmR1vj
https://ibb.co/BtWtL6H
Comment: For some unspecified reason it only works for me if the payload looks like this: `{
    "hourly_rates[45]": 1234,
    "hourly_rates[31]": 4321
  }`
thanks for helping me!


Check if count contains , after every thousand

Question: I have a string which represents count "1,125,854".
I want to check if "," is present after every thousand decimal.
e.g. 125,854 and 1,125,854
I have written following code
import java.text.DecimalFormat;
import java.text.Format;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class CountComma {
    public static void main(String[] args) {
        String str = "1,125,854";
        int count = 0;
        String revStr = new StringBuilder(str).reverse().toString();
        System.out.println("Reverse String: " + revStr);
        List<Integer> format = new ArrayList<Integer>();

        for (char ch : revStr.toCharArray()) {
            System.out.println(ch);
            if (ch == ',') {

                count = count + revStr.indexOf(ch);
                format.add(count);

            }

        }

        System.out.println("Count: " + count);

        System.out.println(format.toString());
    }
}

This code gives output :
Reverse String: 458,521,1
4
5
8
,
5
2
1
,
1
Count: 6
[3, 6]

Could anyone please suggest better way for the same?
Thanks
Comment: What's your problem? Is your code doing what you want it to do or isn't it?
Comment: A better way would be to write a method that returns a boolean true/false depending on whether input is valid or not. Right now, what are you checking? What are you printing?
Comment: Why do you want to do it? do want to parse the string into an int value? If so, see - http://stackoverflow.com/questions/11973383/how-to-parse-number-string-containing-commas-into-an-integer-in-java
Comment: Thanks all for your suggestions. My problem was : "check if a number string has correct comma formatting" Its solved after applying regular expression.("\\d{1,3}(,\\d{3})*")
Answer: If all you want to do is check if a number string has correct comma formatting, then you can use this one-liner:
String str = "1,125,854";
boolean isCorrect = str.matches("\\d{1,3}(,\\d{3})*");

Update:
If you wanted to make the regex more locale agnostic, you could first get the grouping separator for thousands based on the current locale.  For example, if doing this check in a servlet you might try this:
Locale currentLocale = httpServletRequest.getLocale();
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(currentLocale);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
char separator = symbols.getGroupingSeparator();

and then
boolean isCorrect = str.matches("\\d{1,3}(" + separator + "\\d{3})*");

Comment: The anchors are not necessary.
Comment: I don't know where the string will come from and how the OP is going to use that string, but it might be useful to check the locale and use the proper grouping separator instead of comma
Answer: You should really use NumberFormat with the correct Locale:
https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html
 or DecimalFormat constructor that takes a pattern:
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#DecimalFormat-java.lang.String-
The parse method will throw a ParseException when the string does not match the format.
Answer: You can use RegEx for that (tutorial here: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html).
(\d{1,3})(,(\d{3}))*

(fixed my answer as pointed out by Robin Koch)
Comment: The second quantifier has to be `{3}`, otherwise `1,2,34,5` would be matched.


How can I make a link from user account page to its content profile node?

Question: I could make a link from content profile to its user page by this method.
But how can I do the other way round from user account page to content profile?
Answer: Probably content_profile_load is the way to go.
The relevant issue here : http://drupal.org/node/680356


Como ocultar classe ao clicar fora de um input

Question: Tenho uma dúvida com hide() e show() tenho um input que ao ser ativado, deve exibir a classe "resultado" e ao clicar fora do input deve ocultar a classe "resultado" ou até que clique no link dos resultados da pesquisa.

function menuFiltro() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("pesquisa-int");
    filter = input.value.toUpperCase();
    var p = document.getElementById('lista');
    var filhos = p.childNodes;
    for( i = filhos.length - 1; i >= 0; i-- ) {
        if( filhos[i].tagName == 'LI' ) {
            p.removeChild( filhos[i] );
        }
    }
    for (let index = 0; index < document.getElementsByClassName("grupo-menu").length; index++) {
        ul =  document.getElementsByClassName("grupo-menu")[index];
        ul.getElementsByClassName("grupo-menu")[index];
        li = ul.getElementsByTagName("li");
        for (let i = 0; i
 -1) {
                var newLi = document.createElement('li');
                newLi.innerHTML = li[i].innerHTML;
                p.appendChild(newLi);
            }

        }
    }
  }

  <input class="form-control" type="text" id="pesquisa-int" onkeyup="menuFiltro()" placeholder="Pesquisar" title="Pesquisa" autocomplete="off">

Resultado 1

Resultado 2

Resultado 3

Como poderia fazer para que a div "resultado" seja exibida quando o input  estiver selecionado, e fique oculta ao clicar fora input ou até que o link seja clicado?
Answer: Você pode está utilizando jQuery e seus eventos focusin e focusout

$(function() {
  $('#pesquisa-int').focusin(function() {
    $('.resultado').show(); // exibe o conteúdo da div após o input está em foco.
  });
  $('#pesquisa-int').focusout(function() {
    $('.resultado').hide(200); // oculta o conteúdo da div após o input sair do foco.
  });
});

function menuFiltro() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("pesquisa-int");
    filter = input.value.toUpperCase();
    var p = document.getElementById('lista');
    var filhos = p.childNodes;
    for( i = filhos.length - 1; i >= 0; i-- ) {
        if( filhos[i].tagName == 'LI' ) {
            p.removeChild( filhos[i] );
        }
    }
    for (let index = 0; index < document.getElementsByClassName("grupo-menu").length; index++) {
        ul =  document.getElementsByClassName("grupo-menu")[index];
        ul.getElementsByClassName("grupo-menu")[index];
        li = ul.getElementsByTagName("li");
        for (let i = 0; i
 -1) {
                var newLi = document.createElement('li');
                newLi.innerHTML = li[i].innerHTML;
                p.appendChild(newLi);
            }

        }
    }
  }
.resultado {
    display: none;
}

  <input class="form-control" type="text" id="pesquisa-int" onkeyup="menuFiltro()" placeholder="Pesquisar" title="Pesquisa" autocomplete="off">

Resultado 1

Resultado 2

Resultado 3

Comment: é porque não está definido nenhum link no `href` e por a cerquilha não ter nenhuma ação por isso ela oculta.
Comment: Da pra criar uma condição para ocultar somente se clicar em uma tag  ou clicar fora de todo conteúdo.
Comment: utilizei delay $('.resultado').hide(200); e atendeu ao clique sem transição de movimento. Obrigado.
Comment: É esse o caminho, porém ao clicar no link do  o evento oculta a classe antes de executar o link.
Comment: tente colocar um link ai, ao clicar nele será redirecionado automaticamente e a classe ocultada
Comment: Ele fechou antes mesmo com um url definido, só foi com delay $('.resultado').hide(1000);
Comment: Maravilha! mas seria um problema o uso do delay, ou não?
Comment: Ele atrapalha um pouco por conta da animação.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/127247/discussion-between-kim-hanneman-and-gleisin-dev).
Answer: Também dá para fazer esse mostrar ou esconder da classe resultado com base no focus do <input> apenas com JavaScript puro. Para tal precisa de utilizar os eventos focusout, focusin e manipular a propriedade display do mesmo:
const inputPesquisa = document.getElementById("pesquisa-int");
const classeResultado = document.querySelector(".resultado");
const esconderResultado = () => classeResultado.style.display = "none";
const mostrarResultado = () => classeResultado.style.display = "block";
inputPesquisa.addEventListener("focusout", mostrarResultado);
inputPesquisa.addEventListener("focusin", esconderResultado);

Exemplo no seu código:

const inputPesquisa = document.getElementById("pesquisa-int");
const classeResultado = document.querySelector(".resultado");
const esconderResultado = () => classeResultado.style.display = "none";
const mostrarResultado = () => classeResultado.style.display = "block";
inputPesquisa.addEventListener("focusout", mostrarResultado);
inputPesquisa.addEventListener("focusin", esconderResultado);

function menuFiltro() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("pesquisa-int");
    filter = input.value.toUpperCase();
    var p = document.getElementById('lista');
    var filhos = p.childNodes;
    for( i = filhos.length - 1; i >= 0; i-- ) {
        if( filhos[i].tagName == 'LI' ) {
            p.removeChild( filhos[i] );
        }
    }
    for (let index = 0; index < document.getElementsByClassName("grupo-menu").length; index++) {
        ul =  document.getElementsByClassName("grupo-menu")[index];
        ul.getElementsByClassName("grupo-menu")[index];
        li = ul.getElementsByTagName("li");
        for (let i = 0; i
 -1) {
                var newLi = document.createElement('li');
                newLi.innerHTML = li[i].innerHTML;
                p.appendChild(newLi);
            }

        }
    }
  }

  <input class="form-control" type="text" id="pesquisa-int" onkeyup="menuFiltro()" placeholder="Pesquisar" title="Pesquisa" autocomplete="off">

Resultado 1

Resultado 2

Resultado 3


How to interpret weights of a PLS SEM model

Question: I made a PLS SEM model using smartPLS, consisting only of formative constructs. I managed to get weights out of the software, which all had excellent t values. The only thing is, I am not entirely sure how to interpret these values. Unfortunately, the internet cannot provide me with an unambiguously answer. I hope you guys can help me out. This is the model
Answer: You can just interpret the PLS coefficients as generic regression coefficients. But, since the coefficient links two constructs, it's not really necessary to interpret the exact value of the coefficient (such as 0.321). Simply, you can say there is a positive or negative effect of X on Y based on the sign of the coefficient. To check if such effect is statistically significant, you can look at the t-statistic usually using a bootstrap.
A book for reference: https://www.smartpls.com/documentation/learn-pls-sem-and-smartpls/pls-sem-book


Number of $6$ digit numbers which can be formed with $4$ specific different digits such that each digit appears at least once

Question: My problem is that I'm getting different answers with two different approaches:
Approach 1:
I have taken two  cases:
Case 1: $2$ alike, $2$ alike, $2$ different
Number of ways of such a case is $$\binom{4}2\frac{6!}{2!2!}=1080$$
Case 2: $3$ alike, $3$ different
Number of ways of such a case is $$\binom{4}1\frac{6!}{3!}=480$$
Hence total number of numbers which can be formed are $1080+480=1560$.
Approach 2: I am first taking the $4$ digits and placing them in $4$ spaces in the number to be formed which can be done in $\binom{6}44!=360$ ways. Now that I have ensured that each digit has appeared once, I can fill the remaining 2 places in $4^2=16$ ways($4$ ways of filling each space and there are $2$ spaces).
So total ways is $360×16=5760$.
Where am I going wrong in any of my approaches?
Comment: Quick thought: second approach counts double: say you put the 4 digits in the first 4 spots: 1234.. and then place a 2 and a 4 in the last two spots: 123424. Your approach counts this as a different number than putting 1234 in the first, fifth, third, sixth spot and than filling with 2,4. But you get the same number! Hope this example is clear enough...
Comment: First approach does the trick: picking the numbers you'll use double (or three times), number of strings is $6!$, divide out number of amounts of placing the equal digits.
Comment: Your second approach counts each arrangement in which two digits each appear twice four times, once for each way of designating one of the two copies of each repeated digit as the representative of that digit, and each arrangement in which a digit appears three times three times, once for each of the three ways of designating one of the three copies of the repeated digit as the representative of that digit.  Notice that $2 \cdot 2 \cdot 1080 + 3 \cdot 480 = 4 \cdot 1080 + 3 \cdot 480 = 5760$.
Answer: Your first approach works:

Pick the number you will use two or three times using a combination.
There are $6!$ strings in 6 different digits
divide by the amount of possible arrangments for digits you used double.

The second approach counts double: Say you need to choose between the digits ${1,2,3,4}$ and you'll use 2 and 4 two times.

You put 1,2,3,4 in the first four spots, then 2 in the fifth, 4 in the sixth spot. Result: 123424.
You put 1,2,3,4 in the first, fifth, third and sixth spot, then 2 in the second spot and 4 in the fourth spot. Result: 123424

However, you counted those two options as being different in your second approach. This does not happen in your first approach.


Access field data from entity in block plugin

Question: I'm attempting to render certain fields within a block plugin but I'm not sure where to start as far as accessing the fields so I can render them.
I'm able to get the node ids after I perform the query using the following code.
<code>    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post');
    $nids = $query->execute();
</code>
This retrieves the ids that I need based on the query but I don't know how to access custom fields like blog_summary.
I looked into some functions like getFieldDefinitions(). But I'm not sure how to make use of it. I attempted some things using getStorage but I assumed I wouldn't want to go that route since I'm not attempting to make any changes to the nodes I only want to access their fields.
Answer: Try this:
<code>public function build() {
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post');
  $nids = $query->execute();

  $build = [];
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $build[] = $node->blog_summary->view();
  }
  return $build;
}
</code>
Comment: If you have to load the nodes anyway you can do that immediately via:
'    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'blog_post']);'
Comment: You have to add
use Drupal\node\Entity\Node; The node entity is provided by the node module of core.
Comment: I'm receiving an error Fatal error: Class 'Drupal\my_plugin\Plugin\Block\Node not found. I thought it might have to do with the namespace but adding use Drupal\Core\Node at the top didn't work, and I already have use Drupal\Core\Entity
Answer: It depends on what type of fields you want to render. For strings and ints you may just use
<code>$node = Node::load($nid);
$build[] = $node->field_name->value;
</code>
Comment: Use the target_id of your entity_reference like this: $node->get('image_field')->target_id. Then load the Image entity with that target_id.
Comment: No, the target_id is the entity_id of the image entity that the entity reference field in $node points to.
Comment: How would I retrieve an image?
Comment: By target_id do you mean the node id?


Linear regression where the x variable is an index

Question: Say I have two series of values, $x$ and $y$, and I want to calculate their linear regression. If I know that $x$ is just a running index (i.e. $x_i=i$), how can I use this to simplify the normal equations for linear regression?
Specifically, since the slope is just $c_{xy} \cdot {\sigma_y \over \sigma_x} $, if I'd have a simple expression for the correlation $c_{xy}$ (where $x$ is a running index) it'll be enough.
Comment: In practice regression software is very fast and very stable. You could spend more time trying to write efficient code for this special case than you would ever save in practice.
Comment: I know. This is more of a theoretical question.
Comment: It sounds like $y$ is a signal. Therefore, it's likely that you have correlated errors and don't meet the assumptions for linear regression. To find the appropriate test of autocorrelation, or to to find the correct way to measure a linear trend in a signal, a few questions need to be asked of your dataset. This might lead to, for example, an Autocorrelated Errors Model (Ch 16 of Learning and Practicing Econometrics by Griffiths et al, 1993), which is more advanced than the usual simple linear regression and might suit your problem better.
Comment: $y$ is indeed a sort of a signal, and its (rolling) trend-line is only part of the analysis. I tried to keep my question focused.
Answer: Here's what I got by myself:
The definition $c_{xy}⋅{σ_x \over σ_y}$ is already equal to $cov(x,y)\over σ^2_x$, so all we need is a simpler expression for $cov(x,y)$ when $x$ is an index.
Now, $cov(x,y)=∑^N_{i=0}(x_i−\bar x)(y_i−\bar y)$, where $x=i$ in my question.
For simplicity's sake, let's assume that there's an odd number of points (so $N$ is even), so we can reindex them from $−N/2$ to $N/2$ instead of $0$ to $N$.  Let $n=N/2$, we have: $cov(x,y)=∑^n_{i=−n}i(y_i−\bar y) = ∑^n_{i=−n}iy_i$ (the second term in the sum vanishes), which can be further reduced to $cov(x,y) = ∑^n_{i=1}2i \cdot (y_i-y_{-i})$.
Knowing the the variance $\sigma^2$ is equal to ${N^2-1}\over 12$, the result is just $ {12 \over {N^2-1}} \sum^{N/2}_{i=1} 2i \cdot (y_{N/2+i}-y_{N/2-i}) $ (in the original indices).
Comment: Thank you! Readers might also be interested in your explanatino here: https://gis.stackexchange.com/questions/98001/calculating-slope-between-pixels-through-time-using-arcpy/98223#98223
Comment: I implemented this and the calculated slope is not correct
Answer: I tried to figure out how you derived the last part with that $2i$ and I failed.
It seems also you are not considering $N$ or maybe $N-1$ for the covariance.
During my PhD I had faced the same problem and what I had ended up with was:
$\frac{12}{N(N^{2}-1)} \sum_{i=1}^{(N-1)/2} i(y_{i_{0}+i}-y_{i_{0}-i})$
with $ i_{0} $ being the median value's index in the original set.
Those who have problems with your approach can give this a try.
Comment: @Itamar apply your formula to a simple case and go on from there.
Comment: The $N$ vs $N-1$ issue is irrelevant--you are referring to a different formula for a different situation.  Your answer looks incorrect because it doesn't scale properly: for instance, if you were to duplicate all the data the sum would approximately quadruple but the factor in front would become about one-eighth of its original value, shrinking the slope estimate by a factor of 2, whereas duplicating the data ought to produce essentially the same estimate as before.
Comment: I updated the form of how exactly I was using it and it was working. $ i_{o} $ is the index of a median value in the original set. If you have already transformed the indices putting the median index to 0, then this is basically gone. In my case, I had to use the sample covariance. For the population covariance one could go with just $N$. $N$ is the amount of sequential data points in the original set.
Comment: small correction above: * "The index of the median value".

Also, if you were duplicating the data, the increase in the summation would depend on the slope, because on every extra iteration step, the multiplier $i$ not only becomes weighter but also, the difference between the first and last value in the set increases more and more. This approach had been examined next to the normal way of slope computation. And it was always resulting in the same outcome (but faster ofc).
Comment: Maybe you can provide an example of some numbers where this fails to calculate correctly the underlying slope. Cause what I only have is that I remember it was working. (I was using it as a metric to detect convergence within a rolling window of values)
Comment: I actually tried yesterday to apply Mushkin's approach out of curiosity cause it looks more elegant. But I failed. Either I do not understand how his formula works, or it doesn't work.
Comment: You are correct that there are (multiple) errors in their formula (even though the approach is a good one).
Comment: @whuber if you don't want to spend the time/effort to edit it, you can point me to the general direction of the errors and I'll try to edit it clearly myself.


Negate contextual filters in views

Question: I got a view, which lists nodes of same type, a "Other activities" view, i use this view on a activity node view. However i don't want the node i am currently viewing, to show in the list as well.
So what i did, was to make a contextual filter for nid, and provide a default value of "Content ID of URL", of course now my list only provides me with the currently viewing node.
Isn't there anyway to negate this? So it shows all other nodes, that don't have the nid, og the current?
Answer: There is an option on contextual filters to exclude the resulting value, rather than limiting the search to that value. Turn on this checkbox, and you should have the results you are seeking.
Comment: This was a big help.
Comment: **Note:** This option does not appear in all contexts; for example, when using `Comment count` or the `Global Null` item
Answer: https://www.drupal.org/project/views_negate
Synopsis
The Views Negate module provides a "Not Equal" to condition for textfield and list field in contextual filter. It works same as exclude option of numeric type field.
A checkbox with "Negate" label is added under "MORE" fieldset. By selecing the Negate option, it applies the "not equal" condition or "not in" if selected "Allow multiple values" option.

Negate contextual filters in views


How to store last button clicked and add to listbox

Question: So I'm doing this calculator program and need the numbers, the operator used and the "=" sign to show up in the listbox so "1 + 1 = 2" should show up. I have the calculator working and can move items to the listbox, but can't figure out how to remember the button that was clicked to get the outcome and move it over also.
Option Explicit On
Option Strict On
Option Infer Off

Public Class Form1

Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
    Result.Text = CStr(Val(NumOne.Text) + Val(NumTwo.Text))
End Sub

Private Sub ButtonSub_Click(sender As Object, e As EventArgs) Handles ButtonSub.Click
    Result.Text = CStr(Val(NumOne.Text) - Val(NumTwo.Text))
End Sub

Private Sub ButtonMul_Click(sender As Object, e As EventArgs) Handles ButtonMul.Click
    Result.Text = CStr(Val(NumOne.Text) * Val(NumTwo.Text))
End Sub

Private Sub ButtonDiv_Click(sender As Object, e As EventArgs) Handles ButtonDiv.Click
    Result.Text = CStr(Val(NumOne.Text) / Val(NumTwo.Text))
    'outputs a message box telling the user to correct the division by 0, also displays a blank result box instead of NaN
    If CDbl(NumTwo.Text) = Val(0) Then
        Result.Text = ""
        MessageBox.Show("You cannot divide by 0, please input another number")
    End If

End Sub

Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
    Me.Close()
End Sub

Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
    ListBox1.Items.Add(NumOne.Text & NumTwo.Text & Result.Text)
End Sub

End Class

Answer: As far as you just need to store one character, you can rely on the Tag property of ListBox1 (basically, a black box where you can store anything you want). Sample code:
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
    Result.Text = CStr(Val(NumOne.Text) + Val(NumTwo.Text))
    ListBox1.Tag = "+"
End Sub

Private Sub ButtonSub_Click(sender As Object, e As EventArgs) Handles ButtonSub.Click
    Result.Text = CStr(Val(NumOne.Text) - Val(NumTwo.Text))
    ListBox1.Tag = "-"
End Sub

Private Sub ButtonMul_Click(sender As Object, e As EventArgs) Handles ButtonMul.Click
    Result.Text = CStr(Val(NumOne.Text) * Val(NumTwo.Text))
    ListBox1.Tag = "x"
End Sub

Private Sub ButtonDiv_Click(sender As Object, e As EventArgs) Handles ButtonDiv.Click
    Result.Text = CStr(Val(NumOne.Text) / Val(NumTwo.Text))
    'outputs a message box telling the user to correct the division by 0, also displays a blank result box instead of NaN
    If CDbl(NumTwo.Text) = Val(0) Then
        Result.Text = ""
        MessageBox.Show("You cannot divide by 0, please input another number")
    End If
    ListBox1.Tag = "/"
End Sub

Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
    Me.Close()
End Sub

Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
    ListBox1.Items.Add(NumOne.Text & ListBox1.Tag.ToString() & NumTwo.Text & "=" & Result.Text)
End Sub

Comment: Wow, I was thinking it shouldn't be that difficult. So many little things I still need to learn. I appreciate your input. Now I just need to get the "=" in there, which I figured out thanks.
Comment: @JLM You are welcome. .NET is huge there are always things to learn. If you have the right attitude, you will certainly learn all what is required, don't worry about that :)


Proof related to circle

Question: How can I prove that if two circles, one entirely inside the other, intersect at a point, then that point of intersection must be collinear with the centers of the two circles?
Comment: Welcome to MathSE. What have you tried yourself to prove this? Also, I've taken the liberty of editing your post for clarity. Please ensure I've correctly preserved the intent of your question.
Comment: Can 2 such circles really intersect or should it be $\mathbf{TOUCH}$?
Comment: Only should be TOUCH
Answer: By symmetry: mirror the two circles around the line that joins the centers. This leaves the circles unchanged, and so must remain the intersection, so it is on the axis.
Answer: Let the radii be AB and and PB. So AB  can be written as AP+PB= which proves the collinearity othese 3 points thus both the radii lie on the same line and and the point too. Theres no rigorous proof for this Sorry.

Proof related to circle


To understand a line of PHP code about a connection

Question: What is connection() in the following code?
Code which I do understand completely
if($user->connection($email,$password)){
}

Let's assume connection() is pseudo-code.
Is the pg_prepare and pg_execute` enough to create the connection?

The line caused me to omit the use of its main code in generating a login system. Subsequently, SOers pointed out severe sequrity holes in my code.
I could not find the explanation for the function connection().
The code seems to be pseudo-code to me, since the connection does not have any attributes to the database, for instance by
Example of how the connection should be formed
     $result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
         WHERE email=$1;");
     $passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));

Comment: Ummm. Your question makes no sense to me at all.
Comment: What exactly is your question?
Answer: $user is an instance of a class.
connection is a method in that class.
$mail & $password are parameters to that method.
This has nothing todo with arrays. what you mean would be:
$foo = array("key" => "value");

maybe this can help you:
http://www.webstockbox.com/php/7-tutorials-on-how-to-create-a-php-login-system/
Answer: I haven't actually used php.net, but this just looks like connection is a method of object $user that takes 2 params.  Nothing to do with arrays.
Comment: sorry masi, reading your questions really suggest you should read some very very basic coding beginners guids.
Comment: This is exactly what that line says.
Comment: I am newbie in PHP, but not in Programming. - PHP's objects seem to be like in Java: http://fi2.php.net/manual/en/language.types.object.php


Validator not working properly

Question: I have a JSF validator which is used to validate input from form.
When I insert simple string or duplicated string it's working properly. But when I don't enter anything the proper message will be This field cannot be empty!" : "  '" + s + "' is not a valid name! but I don't get anything. Can you help me to find the problem into the code logic?
// Validate Datacenter Name
    public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
    {

        String l;
        String s = value.toString().trim();

        if (s != null && s.length() > 18)
        {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "  Value is too long! (18 digits max)", null));
        }

        try
        {
//            l = Long.parseLong(s);
//            if (l > Integer.MAX_VALUE)
//            {
//                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
//                        "  '" + l + "' is too large!", null));
//            }
        }
        catch (NumberFormatException nfe)
        {
            l = null;
        }

        if (s != null)
        {

            if (ds == null)
            {
                throw new SQLException("Can't get data source");
            }

            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs;
            int cnt = 0;
            try
            {
                conn = ds.getConnection();
                ps = conn.prepareStatement("SELECT count(1) from COMPONENTSTATS where NAME = ?");
                ps.setString(1, s);
                rs = ps.executeQuery();

                while (rs.next())
                {
                    cnt = rs.getInt(1);
                }

                if (cnt > 0)
                {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            "  '" + s + "' is already in use!", null));
                }

            }
            catch (SQLException x)
            {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  SQL error!", null));
            }
            finally
            {
                if (ps != null)
                {
                    ps.close();
                }
                if (conn != null)
                {
                    conn.close();
                }
            }
        }
        else
        {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    s.isEmpty() ? "  This field cannot be empty!" : "  '" + s + "' is not a valid name!", null));
        }

    }

Comment: What does "not working properly" mean. What's not working? What do you want your code to do? What _is_ it doing?
Answer: that is because you only check if you s is != null.
change if (s != null) to if (s != null && s.lenght() > 0) and try again.
btw your String s  can't be null, because you initialize it with
String s = value.toString().trim();

and this would cause a NullPointerException if your value would be null.
Answer: Set inputText tag attribute required to true
<h:inputText value="#{backingBean.input}" required="true"
        requiredMessage="Input is empty!">

Validator not working properly


Is Backbone.js really an MVC?

Question: backbone.js has been spoken of as an MVC framework for Javascript.  But is it?
Here is the description of the model, from http://documentcloud.github.com/backbone/

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it:
  conversions, validations, computed properties, and access control. You
  extend Backbone.Model with your domain-specific methods, and Model
  provides a basic set of functionality for managing changes.

Now, that is not my understanding of the model in MVC at all.  In my understanding, the model is just the classes that model the domain, so your Student, School and Teacher objects.  The controller does performs the business logic on them and interacts with the view for display and receiving input.
This understanding is consistent with the various definitions I find on the web, IE http://en.wikipedia.org/wiki/Model_view_controller:

Model–View–Controller (MVC) is a design pattern for computer user
  interfaces that divides an application into three areas of
  responsibility:
the Model: the domain objects or data structures that
  represent the application's state.

So, my question is: is backbone.js really a MVC framework in any sense, or is it more of just a general way of helping you to glue everything together?
Incidentally, the definition of the Model from backbone.js's FAQ appears to differ from the one I quoted above (also from backbone.js http://documentcloud.github.com/backbone/#FAQ-mvc:

Backbone.Model – Like a Rails model minus the class methods. Wraps a row of data in business logic.

So in what sense is backbone.js really an MVC or not?
(Caveat: I am just evaluating backbone.js currently.)
Comment: That's why many people refer to such frameworks as MV*
Comment: I should really downvote this ( But i ain't doing it) this definetly seems like plot for earn rep!! but anyway nobody said Backbone is MVC did they?? **They explain it as a library that provides structure by using Models, Views, Collections and Routers (again no mention of it's resemblance to MVC)** people can't help with wrong assumptions can they??
Comment: Note the types of *logic* that are indicated as part of the model: "conversions, validations, computed properties, and access control." These are all sensible domain object concerns in any MVC application. They are not the same as the application/business logic, such as routing between views, sending updates to a database, etc. which are usually the responsibility of the controller.
Comment: `So in what sense is backbone.js really an MVC or not?` I know it is an old post but IMHO this question is not constructive and does not fit the SO Q&A format. There is no answer to this question only personal opinion and assumptions.
Answer: Backbone is one of those MV* (MV-star). There is no controller because the logic that operates the app is in the View (something like M(V+C) instead).
And there is no unified definition for "Model" as it is used differently across different frameworks in different languages. But commonly, models are just an abstraction of the data storage and optionally have a bit of logic like validation, formatting and state change hooks.
Comment: why would you put logic in the view?
Answer: Its a bit confusing when you try to find the "M" (Model) the "V" (View) and the "C" (Controller).
In that way we can always argue on the terms but what's important is the intend.
Intersecting the "Terms" with the "Intend" :
The "M" :
Backbone Models. The Collections are tied to Models.
The "V" :
The default Underscore.js template represents the "View Intention" of standard MVC
The "C" :
Backbone View is the Controller. Its called View in backbone (like in many others like Django) because it handles the rendering. From MVC point of view its a Controller. Routes are tied with the Views
Now, sometimes just to satisfy the MVC abbreviation some call it "Model View Collections". But that is what should not be said.
Answer: I think you are getting hung up on the names. Not every MVC framework sticks to the same naming convention.  For example, in Django, Controllers are called Views and Views are called Templates.  Backbone follows a similar naming pattern.  Note, Backbone is very flexible on the views part, not enforcing any particular templating library.
As already noted, the logic included in Backbone models is logic that is the concern of the model.  A standard relational database, which is a collection of models (tables), typically cares about the type of data in columns.
Logic that would typically go in your controllers (Backbone's "Views") would be things like handling transient session data, checking user state (authenticated for example, although you wouldn't be doing that in js), binding views to models (Backbone does exactly this, managing where and when models are stored/created based on user actions and binding templates to update on model changes).
So, in summary, Backbone actually sticks pretty well to MVC, much better than most server side "MVC" frameworks which are typically really "PAC" frameworks (Presentation-Abstraction-Control).
Answer: Kind of both. If you're looking at the strict sense of a model; that is, that the model is simply data, then no. But validations, conversions, etc., have been placed there because Backbone is fairly model-centric. From my own experience, I typically treat Backbone models in the traditional sense in that the model is an application's representation of the backend data store, and all it has are accessor methods to manipulate that data.
The point is that though the facilities to validate or perform access control, etc. exist, you can choose to follow a more classical MVC pattern. It's entirely up to you. That's what I love about Backbone is that it gives you an MVC engine on which you build an entire application architecture. If you want to follow the classical MVC design pattern, you can certainly do that. Cheers!
Answer: in backbone.JS MVC stands for MODEL VIEW COLLECTION...
Answer: If you seek controllers in Backbone.js, you probably want to take a look at this: http://chance-an.github.com/backbone-mvc/

Is Backbone.js really an MVC?


Navigation Drawer com duplicidade

Question: Tenho um NavigationDrawer com dois EditText e gostaria que esses dois campos demonstra-se os dados do usuário o nome e email, porém na minha classe TelaPrincipal quando tento jogar a informação para um dos dois campo é demonstrada duas vezes o NavigationDrawer.

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:orientation="vertical"
    android:gravity="bottom">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/telaprincipal_nav_header_et_meuperfil"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="60dp"
        style="@style/TextoMenuDrawerTituloPerfil"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nav_header_telaprincipal_tv_nome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/TextoMenuDrawerTitulo"
            android:text=""
            android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

        <TextView
            android:id="@+id/nav_header_telaprincipal_tv_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            style="@style/TextoMenuDrawerNormal"
            android:text="" />
    </LinearLayout>
</LinearLayout>

Classe Java
public class TelaPrincipal extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //Componentes da Activity
    private Context mContext;
    private DrawerLayout mDrawerLayout;
    private NavigationView navigationView;
    private View mView;
    private TextView tvNome;
    private TextView tvEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.telaprincipal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Titulo da Activity
        setTitle(getString(R.string.telaprincipal_titulo_activity));

        //inicializando as variaveis
        inicializaVariavel();
        inicializaAcao();

        //Método do Navegation Drawer
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.telaprincipal_drawer_aberto, R.string.telaprincipal_drawer_fechado);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        LayoutInflater layoutInflater = getLayoutInflater();
        mView = layoutInflater.inflate(R.layout.nav_header_tela_principal, navigationView, false);

        tvNome = (TextView) mView.findViewById(R.id.nav_header_telaprincipal_tv_nome);
        tvEmail = (TextView) mView.findViewById(R.id.nav_header_telaprincipal_tv_email);

        tvNome.setText("Denis");
        tvNome.setText("email@example.com");

        navigationView.addHeaderView(mView);
    }

Comment: Já observou esse trecho de código? `tvNome.setText("Denis");
        tvNome.setText("firstname.lastname@example.com");`
Comment: Olá Luídne, como eu disse esta duplicando a Navigation Drawer a informação do nome e email esta demonstrando, porém a duplicidade esta errada, vou tentar colocar a imagem do app para facilitar o entendimento.
Answer: Bom dia! Tudo bem? Existem 2 erros no seu código, vamos ver o primeiro:
Você possui no seu layout da tela principal, um NavigationView que você deu o id nav_view então note o seguinte, nele você ja tem definido o header, mas no seu código você está inflando um header a mais! Logo existem dois headers no seu drawer, ou quantos você desejar inflar! Existem duas formas de corrigir isso, use a que você achar melhor:
Forma 1: Simplesmente remova o header que tem dentro do nav_view no layout retirando a linha:
    app:headerLayout="@layout/nav_header_tela_principal"

Mantendo o código exatamente do jeito que está, não terá mais o problema de duplicação do seu header.
Forma 2: Removendo estas linhas de código:
    LayoutInflater layoutInflater = getLayoutInflater();
    mView = layoutInflater.inflate(R.layout.nav_header_tela_principal, navigationView, false);

//O código entre estes dois trechos não deve ser alterado!

    navigationView.addHeaderView(mView);

Substituindo por:
    mView = navigationView.getHeaderView(0);

com isso ele vai obter o primeiro header definido no layout, a partir disso, segue com seu código normalmente.
Qualquer uma das duas formas vai resolver o seu problema.
Ja o seu segundo problema, note que você está definindo o texto do TextView tvNome duas vezes como observado pelo @Luídne!
Comment: Obrigado Furflez resolveu meu problema com a primeira solução.

Navigation Drawer com duplicidade


Display in meteorjs page a json object value with numeric name

Question: I would like to display the value 10 of this object {'1':10}, but I cannot find the right syntax for the template.
Client js code is:
  Template.hello.data = function () {
    return { '1' : 10};
   };

Client html code is:

  {{> hello}}

<template name="hello">

{{data.1}}

</template>

This gives the error:
hello.html:6: Expected IDENTIFIER

{{data.1}}

Of course changing to something like { 'A1' : 10} it works, but I would like to keep the field name '1'.
Comment: I guess that would be `{{data.[1]}}`
Comment: Wouldn't it be `{{data['1']}}`? Does bracket notation work in handlebars html?
Answer: Looks like the data parser is treating the 1 as an integer rather than a string. Try bracket notation (see answer at: https://stackoverflow.com/a/12272511/1327678)
{{data.[1]}}

Comment: I expected `{{data.['1']}}` worked: it gives no error, but does show nothing. `{{data.[1]}}` works.


How to convert degree/mins to decimal in excel?

Question: I've googled it a lot but did not find any solution. I want to convert Lat Long data (degree, min, sec) to decimal in excel.
Traditionally lat long data is like 25°43'21.3", but the database I'm working do not have degree (°) symbol, It has dot(.) instead of degree.For example- 25.43'21.3"
So What will be a script to convert 25.43'21.3" into decimal like- 25.722583333333333 ??
the following code works when data comes with (°) symbol.
    Function Convert_Decimal(Degree_Deg As String) As Double
   ' Declare the variables to be double precision floating-point.
   Dim degrees As Double
   Dim minutes As Double
   Dim seconds As Double
   ' Set degree to value before "°" of Argument Passed.
   degrees = Val(Left(Degree_Deg, InStr(1, Degree_Deg, "°") - 1))
   ' Set minutes to the value between the "°" and the "'"
   ' of the text string for the variable Degree_Deg divided by
   ' 60. The Val function converts the text string to a number.
   minutes = Val(Mid(Degree_Deg, InStr(1, Degree_Deg, "°") + 2, _
             InStr(1, Degree_Deg, "'") - InStr(1, Degree_Deg, _
             "°") - 2)) / 60
    ' Set seconds to the number to the right of "'" that is
    ' converted to a value and then divided by 3600.
    seconds = Val(Mid(Degree_Deg, InStr(1, Degree_Deg, "'") + _
            2, Len(Degree_Deg) - InStr(1, Degree_Deg, "'") - 2)) _
            / 3600
   Convert_Decimal = degrees + minutes + seconds
End Function

Comment: just replace `"°"` with `"."`
Comment: how would replacing work? data contains several dot(.)
Comment: `InStr` will return the position of the first `.` it finds
Answer: This will do it:
Private Const vbQuote As String = """"

Public Sub test()
    Debug.Print answer("25.43'21.3""")
End Sub

Public Function answer(ByVal s As String) As Double
    Dim degrees As Double
    Dim minutes As Double
    Dim seconds As Double

    Dim dotPos As Integer 'position of first dot in the string
    Dim commaPos As Integer 'position of comma in the string
    Dim quotePos As Integer 'position of quote in the string

    dotPos = InStr(s, ".")
    commaPos = InStr(s, "'")
    quotePos = InStr(s, vbQuote)

    If dotPos = 0 Or _
        commaPos = 0 Or _
        quotePos = 0 Or _
        dotPos > commaPos Or _
        commaPos > quotePos Then

        'some error handling here
        Stop
    End If

    degrees = CDbl(Left(s, dotPos - 1))
    minutes = CDbl(Mid(s, dotPos + 1, commaPos - dotPos - 1))
    seconds = CDbl(Mid(s, commaPos + 1, quotePos - commaPos - 1))

    answer = degrees + minutes / 60 + seconds / 3600

End Function

Comment: Thank you very much! But the script returns 0.722583333 orginal value will be 25.722583333, what is wrong with it? I've keep 25.43'21.3" on A1 and type: =answer(A1) on B1 cell. what I've missed?
Comment: Oops. I had misspelt 'degrees' in a few places. All fixed now ;-)


Which is the continous probabilty density function that, given both standard deviation and a finite support, maximizes entropy?

Question: It is fairly known that acorrding to the Entropy definition:
$$
H=-\int p(x) \log (p(x)) dx
$$
The Gaussian or Normal distribution maximizes the value of $H$. Also, if we have a finite Interval with a continous p.d.f. over it, the "flat" or homogeneus distribution gives the bigger Entropy. What happens if we use both restrictions? If we have both a given interval in which the p.d.f must have its support, and the value of the standard deviation is given? Which function maximizes H over this?
Moreover, does the answer converges to the Gaussia as the standard deviation becomes small in comparition to the support, and to the flat if the standard deviation becomes the half width of the support?
Comment: So to clarify, you want to minimize $\int_a^b p(x) \ln p(x) - \lambda_0 (\int_a^b p(x)dx - 1 ) - \lambda_1 (\int_a^b (x-\mu)^2 p(x) dx - \sigma^2)$ as a functional of $p$? Follow the derivation for Gaussian but you get expressions that involve error function of combination of a and b.
Answer: Assuming, WLOG that the support is $[-1,1]$, Lagrange multipliers give $p(x) = \alpha e ^{ \beta x^2}$ where $\alpha, \beta$ are determined by the two restrictions $\int_{-1}^1 p(x)=1$ and $\int_{-1}^1 x^2 p(x)=\sigma^2$.
Notice however that the variance cannot be arbitrary (in this case, $0\le\sigma^2 \le 1$).
The probability, then, corresponds to a truncated gaussian if $\sigma^2 < \sigma^2_0$, a uniform if $\sigma^2 = \sigma^2_0$, and an inverse truncated gaussian if $ \sigma^2_0 <\sigma^2 <1$.


How to interpret interaction between a dummy and a continuous variables in ols?

Question: I am trying to examine the association between maternal education and child school test scores using the following equation.
$$\small{TestScore_i = \beta_0 + \beta_1 EduYrMom_i + \beta_2 FemaleChild_i + \beta_3 EduYrMom_i * FemaleChild_i + \varepsilon_i}$$
where TestScores is the test score of the child, EduYrMom is the years of education of the child's mother, FemaleChild is a binary value which equals 1 if the child is a girl. The following regression coefficients are obtained using Stata's regress command.
<code>    Model 1 Test scores of child

(1a)Years of education of mother    0.028
(1b)Years of education of mother *female child  0.031
Female (=1 if female)   -0.388
Effect of mother's education on female children---- 1a+ 1b  0.059*

Model 2

(2a)Years of education of mother    0.039**
(2b)Years of education of mother *female child  -0.005
Female (=1 if female)   0.091
Effect of mother's education on female children---- 2a+ 2b  0.034

Model 3
(3a)Years of education of mother    0.303***
(3b)Years of education of mother *female child  -0.047
Female (=1 if female)   -0.003
Effect of mother's education on female children---- 3a+ 3b  0.256**

note:  *** p<0.01, ** p<0.05, * p<0.1
</code>
For model 1, it seems that mother's education is positively and significantly associated with test scores of female children, but not for boys.  For model 2, I find that mother's education is significantly associated with test scores of boys only. For model 3, mother's education is significantly and positively associated with the test scores of both boys and girls.
I was wondering whether my interpretations are correct. I am also not sure how to interpret $\beta_3$, the coefficient of the interaction term, which is insignificant for all the 3 models. I look forward to your suggestions.
Monzur
Comment: Do you have female child in the model(s)? What's the difference between the three?
Comment: Yes, the sample has male and female children. I should have been a little more specific, the regression models also control for other variables, which differ between each model.
Answer: You can think of the slope estimate for an interaction ($\beta_{cts \times cat}$) between a continuous and a dummy-coded categorical predictor as the expected difference in the simple slope estimate for the continuous predictor between the group coded as zero and the group coded as one. E.g., in the context of the following model:
$$Y = \beta_0 + \beta_{cat} X_1 + \beta_{cts}X_2 + \beta_{cts \times cat} X_1 \times X_2 + \varepsilon$$
$$\beta_{cts \times cat} = \beta_{cts\ \tiny{simple slope}}\ \small{(when\ X_1\ = 1}) - \beta_{cts\ \tiny{simple slope}}\ \small{(when\ X_1\ = 0})$$
(assuming $X_1$ is dummy-coded). More generally, a significant categorical $\times$ continuous interaction can be understood to mean that the effect of the the continuous predictor depends on the level of categorical predictor. Or, for a one unit increase in $X_1$, the simple slope for $X_2$ will increase by $\beta_{cts \times cat}$.
Note that these relationships could just as easily, but perhaps less intuitively, be conversely phrased: "the simple effect of the categorical predictor depends on the continuous predictor."


Better site and database performance

Question: I'm working on a Drupal community site and I want to ask about these things:

How do I make a Drupal site more secure?
How do I make my site work as fast as possible when there is a lot of visitors and users on the site, and there is a lot of interaction with the database at the same time? How do I maintain the database consistent in this situation?
How do I configure Drupal to work during high server load? How do I configure my server's hardware to work during high load moments?
Answer: 1 - Use captchas and spam filtering; Mollom is a good place to start. There is also  info on hardening Drupal in the drupal handbook, ie. http://drupal.org/writing-secure-code.
2 - For starters, turn on the performance module that comes with Drupal.
3 - This is a big question. I have heard good things about Context HTTP Headers, a module contributed by the White House Drupal team. You can find a comparison table on Caching: Moduls that make Drupal scale.
Comment: Which performance module are you talking about, because D6 doesn't ship with one ?
Comment: I guess it's not technically a module, my bad. But it is found under /admin/settings/performance.
Answer: You've asked a massive question here, which could never be fully answered in the space I have on this text box. The answer is that performance tuning is always specific to your workload and has to be customised as such. Security is also a massive topic in itself. I think the best way to answer this is to point you to some resources, because a lot of people ask these questions.

Sign up to the Drupal security mailing list. You can see the list here and you can sign up to be informed by e-mail whenever a vulnerability is discovered. You can do this by logging in at drupal.org, clicking Edit on your profile, then going to My Newsletters and checking Security announcements. Also, if you're doing any development Writing Secure Code is a must-read. You should also keep an eye on whats going on with your server's security - most Linux distributions will have an e-mail list to keep you informed about the latest security situation. I'm not even going to mention securing your server to begin with, as that's a massive discussion, not relevant to Drupal.
& 3. Obviously, turn on all of the caching options Drupal gives you in the performance section of the admin pages. The Drupal page Server tuning considerations is really excellent and will give you a lot of practical information. Also, APC is installed by a lot of Drupal developers almost immediately and can significantly improve PHP execution time. Finally, to optimise the database a good place to start is by looking at the queries your site is executing and using the MySQL describe command to see what's going on and adding index's in slow spots. More information on this here.
Answer: For a highly trafficked Drupal site, you should tune MySQL for the content that is in stored now. Whatever the version of Drupal, the MySQL layer can have its configuration computed.
You should want to convert all Drupal tables to the InnoDB Storage Engine. It eliminates table locking from all SQL statements affecting your data.
If you already have InnoDB data, and innodb_file_per_table is not enabled, you need to cleanup InnoDB by segmenting each table into its own physical tablespace. It is imperative to do decent MySQL tuning, even if you have a limited hardware. There are many scenarios for doing such InnoDB optimizations.
IMHO, you cannot plan good settings for my.cnf without knowing the amount of data to configure for. You would have to periodically load a current dataset from production into a staging environment, perform optimizations and come away with the numbers to configure in the my.cnf of the production server.
Comment: Does Innodb make the site really faster? In many other answers in this site and else, people are telling that they have negative effects with innodb. Is that true? Can innodb have negatives?
Answer:
Taking all the standard precautions for web server security as read, Drupal should be very secure out of the box. The basic gist is never ever trust user input - if you stick to active contrib modules and drupal core functionality, you shouldn't need to worry about this really, but if you are coding something custom make sure any user input goes through check plain and db_query.
Massive question. Drupal has some good things out of the box, such as CSS and JS aggregation, page caching, etc. Move watchdog to use syslog instead of writing to the database. Use caching wherever appropriate. Look at Boost, Varnish, memcached, block cache. Optimise your pages using yslow recommendations . If you are getting really serious, you may want to look at moving your database server onto a different machine. This list can get really long really fast, but Khalid Bahayeldin at 2bits is an authority - in particular read this presentation for an idea of quick wins.
See number 2!
Answer: 2 & 3 You can have a look at Drupalize.me video: Drupal Performance & Scalability or others Lullabots articles like Configuring Varnish for High-Availability with Multiple Web Servers

Better site and database performance


Render custom fields of Taxonomy page D7

Question: Assume I have a Vocabulary named "Job Titles". This vocabulary contains several custom fields.
"JOB TITLES" (Vocabulary)
 |
 |-- name (Default Field)
 |-- description (Default Field)
 |-- reference_url (Custom Field)
 |-- help_link (Custom Field)

Above vocabulary contains 2 custom fields that I can see when adding or editing a taxonomy term.
My question is, how can I use them on my page.tpl? How can I access them on template.php with hook_page_preprocess() ?
Answer: Unfortunally, I haven't found a good solution yet. I solved temporarily so:
Custom field:
$output = (isset($term->field_FIELDNAME['und'][0]['safe_value']))? $term->field_FIELDNAME['und'][0]['safe_value'] : '' ;

Term's Description:
$output = filter_xss_admin($term->description);

Where $term is:
$tid = (int)arg(2);
$term = taxonomy_term_load($tid);

I repeat, the custom field solution above is not the best practice, and it's also unpredictable, so use it carefully.
Answer: To display text at the bottom of the term page, I added 2 new fields to a taxonomy vocabulary ('field_term_heading' and 'field_term_footer'). I found that it created a rather ungainly nested array. This is what I added to page.tpl.php to display it.
<?php if ( arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) ): ?>

    <?php $page_term = taxonomy_term_load(arg(2));
        if ($page_term->field_footer_heading) {
        print '
'.($page_term->field_footer_heading['und'][0]['safe_value']).'
';
        }
    ?>
    <?php $page_term = taxonomy_term_load(arg(2));
        if ($page_term->field_footer_text) {
        print '
'.($page_term->field_footer_text['und'][0]['safe_value']).'
';
        }
    ?>

    <?php endif; ?>


Savgol filter over dataframe columns

Question: I'm trying to apply a savgol filter from SciPy to smooth my data. I've successfully applied the filter by selecting each column separately, defining a new y value and plotting it. However I wanted to apply the function in a more efficient way across a dataframe.
y0 = alldata_raw.iloc[:,0]
w0 = savgol_filter(y0, 41, 1)

My first thought was to create an empty array, write a for loop apply the function to each column, append it to the array and finally concatenate the array. However I got an error 'TypeError: cannot concatenate object of type ""; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid'
smoothed_array = []
for key,values in alldata_raw.iteritems():
    y = savgol_filter(values, 41, 1)
    smoothed_array.append(y)

alldata_smoothed = pd.concat(smoothed_array, axis=1)

Instead I tried using the pd.apply() function however I'm having issues with that. I have an error message: 'TypeError: expected x and y to have same length'
alldata_smoothed = alldata_raw.apply(savgol_filter(alldata_raw, 41, 1), axis=1)
print(alldata_smoothed)

I'm quite new to python so any advice on how to make each method work and which is preferable would be appreciated!
Answer: In order to use the filter first create a function that takes a single argument - the column data. Then you can apply it to dataframe columns like this:
from scipy.signal import savgol_filter
def my_filter(x):
    return savgol_filter(x, 41, 1)
alldata_smoothed = alldata_raw.apply(my_filter)

You could also go with a lambda function:
alldata_smoothed = alldata_raw.apply(lambda x: savgol_filter(x,41,1))

axis=1 in apply is specified to apply the function to dataframe rows. What you need is the default option axis=0 which means apply it to the columns.
That was pretty general but the docs for savgol_filter tell me that it accepts an axis argument too. So in this specific case you could apply the filter to the whole dataframe at once. This will probably be more performant but I haven't checked =).
alldata_smoothed = pd.DataFrame(savgol_filter(alldata_raw, 41, 1, axis=0),
                                columns=alldata_raw.columns,
                                index=alldata_raw.index)

Savgol filter over dataframe columns


How do I receive the APNS token for iOS?

Question: I've been trying to setup push notifications on iOS 13.4 for a week now and I've been getting nowhere. I setup a blank application with just the minimal amount of code and it still doesn't seem to work. I get the log that the user has granted permissions but I do not receive the APNS token, I do not receive an error and method doesn't even get called. What might I be doing wrong?
I have setup the app id to have push notifications on the certificates and profiles page. I have also setup capabilities to have push notifications, remote notifications and background fetch.
<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

      UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
          UNAuthorizationOptionSound | UNAuthorizationOptionBadge;

      [[UNUserNotificationCenter currentNotificationCenter]
          requestAuthorizationWithOptions:authOptions
          completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if(granted){
          NSLog(@"PERMISSION GRANTED");
        }
        else{
          NSLog(@"PERMISSION GRANTED");
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        });
      }];

    // Override point for customization after application launch.
    return YES;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
  NSLog(@"DEVICE DID REGISTER:");
  NSLog(@"DEVICE TOKEN: %s", deviceToken);
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    NSLog(@"DEVICE DID FAIL TO REGISTER:");
}
</code>
Answer: First check in apple developer account the certificates you have created having your device UDID or not. Also take care of that if you are testing it on simulator than it will not work. You can only check notifications on real devices.
Secondly APNS works when your app is in background mode to fetch notifications in foreground mode we need to make some settings in the app or else need to use third party libraries.
If need to check the complete scenario you can check the link attached below:-
https://www.appcoda.com/push-notification-ios/


Print User Registration Block Through template.php file

Question: I just want to print the user registration block through my template.php file without using the Form Block or Enabling php on my site to use this code:
<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

I have tried the following:
function my_template_form_alter {

      $form = drupal_get_form('user_register_form');
      print drupal_render($form);
}

I want this block to appear on my blocks administration page just like the user login block, so I can place it anywhere I like. Any help as per how to achieve this? Thanks
Answer: You won't need any alters. Just go to the template in which you want to place the registration form and add,
$form = drupal_get_form('user_register_form');
print drupal_render($form);

This will print the user registration form. It's always good to have a check for anonymous users as a wrapper of this output.
Edit #1 (After question update and comments)
I suppose you want to create a block that will appear in your "admin/structure/block" page and you can assign the block in any desired region? - Right? I don't think your question says the same but this can be done in the following way,

Create a hook_block_info() & hook_block_view()
In the hook_block_view() assign the "content" the following,

$form = drupal_get_form('user_register_form');
$block['content'] = drupal_render($form);

I hope this can solve your problem. I haven't tested this yet!
Comment: Apologies, i did not add the function wrapper where this goes to, what function do i add this to? like: function my_templatename_form_alter
Comment: no, just add this in your tpl.php file. That will do.
Comment: I want this block to appear as one of the blocks in my blocks administration page, so i can place it anywhere i want
Comment: Ahh, then you should update your question. Currently it's not clear what you need to do. So please update it so that others can suggest some options too.


Styling Readonly fields in using CSS

Question: I have many forms which has many text input that are read-only.  I am doing this since users are not allowed to edit this anymore but they are allowed to view it.
My problem is the rendering on different browser.  FF is doing fine in rendering this but IE6/IE7/IE8 is not doing any good.  It is graying out the field and does not display well.
Any idea how to better style them in CSS?
.disabled{
    background-color:#9DFBFB;
    color:#191970;
    font-weight:bold;
}

    Data: <input type="text" readonly="readonly" class="disabled" value="Test"/>

Answer: Having a look at Styling form controls revisited it seems like IE6 is not able to style the disabled input, but IE7 and IE8 are.
A workaround can be to add readOnly attribute instead of the disabled one. Haven't tried, though.
Comment: Sharp Look!  Thanks.. I forgot that this is a read only field.  I just set the class name to disable.

Styling Readonly fields in using CSS


How would Facebook measure an AB test whose experimental condition affects the control and experimental groups?

Question: Say FB is testing huge, horribly intrusive ads for retirement homes on 90% of its users (call them group A).  This angers most people in group A besides 80+ year old users.  As a result, most of group A leaves FB permanently.  Of course, FB users communicate with each other, so when most of group A leaves, many group B users leave as well.
FB is ultimately left with 80+ year olds who are seeing retirement home ads and some 80+ year olds who do not see them.  So, the people in group A who see the ads generate 150% more profit than those in group B.  FB might conclude that the ads succeeded, except, the overall profitability of facebook has dropped 90%.
3 questions:
Is this AB test even valid to begin with?
Regardless of your answer to the above, assuming you had to do this test, how would you account for the non-independence of the groups when you interpret the results?
Does the answer to any of the above change if the test is more subtle, yet still may affect both the experimental and control groups?  E.g., FB forces 10% of users to have an inbox that flashes bright colors and induces seizures.  So some of those people leave and convince a few of their friends in the control group to leave, but the sample sizes are so small, FB's overall profitability does not decrease significantly as a result of the test.
Answer: This is a very interesting question, but one without an entirely satisfactory answer. The speculative content certainly increases as you go down.
One problem with randomized experiments is that they are not valid in the presence of what economists call "general equilibrium effects," which are interactions among individuals induced by the treatment being studied. The statisticians named this problem Stable Unit Treatment Value Assumption (SUTVA) violation. It has been recognized at least since Heckman and Smith's 1993 JEP paper, and probably even earlier in the context of other large-scale social experiments like the Job Training Partnership Act or the literature on unionization in the 60s. Without additional structure, experimental evidence simply cannot tell you what the true effect would be. That is the answer to question number one.
How might one patch up the experimental data? One solution is to make explicit, strong assumptions about how the world works. Heckman, Lochner and Taber's paper on tuition policy is a nice example of this approach. My casual empiricism suggests that most firms do not have the patience for this sort of thing.
So how might a firm like FB handle evaluation issues like this? This solution is a bit of a cop-out: limit the size of the treatment group to far below 80%, maybe combined with clever sampling of social clusters (rather than individuals). Both of these minimizes the GE spillovers, and the effect of a full roll-out would presumably be larger for two-sided platform reasons you mention. If the preliminary partial equilibrium numbers look bad, the feature never sees the light of day outside the test. If the results are not significant, you just let the experiment run a bit longer. This doesn't give you the long-run effect, only a lower bound on it. But that might be sufficient to make the right business decision.
There's also a small literature on binary regressor mis-classification error. The experimental estimate is biased towards zero since some control group members are actually "treated", but there are some ways to fix it using an instrumental variables since the probability of mis-classification depends on network membership. I don't know of any existing literature that tries exactly this.
Another way to deal with this is that the spillover actually takes places on FB. If a treated member announces the reasons for his abandonment of the platform in his status, FB knows exactly who saw it. Some other statistical adjustment may be possible if those folks follow.


Como usar o su renomeado

Question: Alguém sabe como faço pra usar o root no prompt/terminal, porem com o su renomeado pra suu?
eu tentei digitar suu - no terminal não deu.
Comment: Não ficou clara sua dúvida, pra que este suu ?
Answer: Se foi o que eu entendi, com seu usuário logado digita "su", no seu caso que renomeou "suu" coloca a sua senha de root, assim vc fica com as permissão de root. Se bem que o correto é eles usarem o comando 'sudo' para realizar operações com privilégio de root.
Caso precisar no console use "sudo konqueror"
que abrirá o gerenciador de arquivos com privilégios de root. aí pode renomear..etc..etc.

Como usar o su renomeado


Extreme points of the set of positive regular borel measures on a compact Hausdorff space

Question: I have some troubles with a specific proof of a (Bochner-type) theorem in Rudin's book "Functional Analysis".
More specifically, let $X$ denote a compact Hausdorff-Space and let $M$ denote the set of positive regular Borel measures $\mu$ on $X$ satisfying $\mu(X)\leq 1$.
It is stated that the unit masses concentrated at the different points of $X$ are the extreme points of $M$. I can see that these are indeed extreme points - however, I am stuck arguing that these are the only extreme points of $M$.
Answer: If $0<\mu(X)<1$, then the decomposition $\mu=\frac12((1+\epsilon)\mu+(1-\epsilon)\mu)$, with $\epsilon$ sufficiently small, shows that $\mu$ is not extreme.
I'm not sure if you allow $\mu(X)=0$ but if you do, this measure is also an extreme point.
Finally, suppose $\mu(X)=1$. If there is a set $A\subset X$ with $0<\mu(A)<1$, write
$$\mu=\frac12\left\{[(1+\epsilon)\mu_{|A}+(1-\delta)\mu_{|A^c}]+[(1-\epsilon)\mu+(1+\delta)\mu_{|A^c}]\right\} $$
where $\epsilon,\delta$ are small and are chosen so that the total measure in each square bracket is $1$.
It remains to consider the case when  $\mu(A)\in \{0,1\}$ for every measurable set $A$. Let $S$ be the set of points $x$ such that every neighborhood of $x$ has positive measure. By assumption, this measure is $1$. It follows that $S$ cannot have more than one point. It cannot be empty either, for then $\mu$ would be identically zero. Thus, $S$ is a single point $\{x_0\}$. Use regularity of the measure to obtain $\mu(\{x_0\})=1$.
Comment: That's a question by the OP again posted as an answer: Thanks a lot! I have two additional questions - if you don't mind:

1) Why is the set S measureable? 2) Is it true that every point in a compact Haussdorf-Space has a countable! fundamental system of neighbourhoods? (That would be clear to me, if the space were in addition metrizable)


Enum me retornando null pointer

Question: Meu Enum está retornando Null Pointer ao relizar essa call:
  System.out.println(DefinicaoSCM.getDefinicaoSCMPorDisciplina(Disciplina.IMPLEMENTACAO));

Implementação:
public enum DefinicaoSCM
{
   DESCONHECIDO(null, "NA", "NA"),
   IMPLANTACAO(Disciplina.IMPLANTACAO, "ipl_", "/Implantacao"),
   IMPLEMENTACAO(Disciplina.IMPLEMENTACAO, "imp_", "/Implementacao", "/Documentacao", "/Implantacao"),
   INTERFACE_GRAFICA(Disciplina.INTERFACE_GRAFICA, "ifg_", "/Design"),
   PROJETO(Disciplina.PROJETO, "prj_", "/Projeto"),
   REQUISITO(Disciplina.REQUISITO, "req_", "/Requisitos"),
   TESTE(Disciplina.TESTE, "tst_", "/Teste");

   private static Map<Disciplina, DefinicaoSCM> definicaoSCMPorDisciplina;
   private Disciplina disciplina;

   public static DefinicaoSCM getDefinicaoSCMPorDisciplina(Disciplina disciplina)
   {
      return definicaoSCMPorDisciplina.get(disciplina);
   }

Comment: `definicaoSCMPorDisciplina` não está instanciado.
Comment: Pode postar o seu código inteiro dessa classe? Em especial gostaria de saber do construtor e como o `definicaoSCMPorDisciplina` é instanciado e populado.
Comment: Apesar de não ter o código completo, já tive problemas em usar um Map num Enum antes. Sugiro tentar com um ImmutableMap do Guava. Vou procurar o que eu fiz pra resolver e posto o código depois.
Answer: Para utilizar um Map em um Enum, só consegui utilizando o ImmutableMap do Guava, no seu exemplo, ficaria como abaixo:
private static final Map<Disciplina, DefinicaoSCM> definicaoSCMPorDisciplina = ImmutableMap.<Disciplina, DefinicaoSCM>builder()
                    .put(Disciplina.IMPLANTACAO, new DefinicaoSCM())
                    .put(Disciplina.INTERFACE_GRAFICA, new DefinicaoSCM())
                    .put(Disciplina.PROJETO, new DefinicaoSCM())
                    .put(Disciplina.REQUISITO, new DefinicaoSCM())
                    .put(Disciplina.TESTE, new DefinicaoSCM())
                    .build();

O acesso ao Map continua da mesma maneira .get(key).
Comment: Caracas, muito bom! Muito obrigado meu amigo!

Enum me retornando null pointer


Obter o maior valor de uma array em Lua

Question: Estou a utilizar código Lua e quero obter o valor maior de um array.
Exemplo:
tem_array = {10,2,3,20,1}

Utilizei este código abaixo, mas obtenho o número de elementos e não o máximo:
max = math.max(unpack(tem_array))

Comment: pra mim funcionou: http://ideone.com/ipUIuD
Comment: Você pode utilizar um algoritmo de ordenação crescente e pegar o último elemento.
Answer: O código postado por você funciona como o esperado.
tem_array = {10, 2, 3, 20, 1}
arraymax = math.max(unpack(tem_array))

print (arraymax) -- 20

DEMO
Um outro modo é classificar os elementos através do sort() para colocar os elementos em ordem crescente e pegar o último valor.
tem_array = {10, 2, 3, 20, 1}
table.sort(tem_array, function(a,b) return a<b end)

print (tem_array[#tem_array]) -- 20

Ou utilizar o comportamento padrão do sort():
tem_array = {10, 2, 3, 20, 1}
table.sort(tem_array)

print (tem_array[#tem_array]) -- 20

DEMO
Answer: tem_array = {10,2,3,20,1}
table.sort(tem_array, function(a,b) return a > b end)
print(tem_array[1])

Obter o maior valor de uma array em Lua


How do I locate the server on which my configured CRM 2011 email router is installed?

Question: From the machine on which Dynamics CRM is installed, where is the pointer that tells me where the associated email router is installed?
Comment: Hey there, what have you already tried? What is the requirement you are trying to solve?
Comment: e-mails are not being sent for a particular CRM deployment, so I wanted to take a look at the CRM email router, but I had no idea where to find it because the email router is located on another virtual machine
Answer: There is no specific pointer. The E-Mail router is not registered as a service for the deployment, so it will not be listed in the Deployment Manager.
As it connects to the CRM with Web Services, the CRM itself does not know whether an E-Mail Router does exist or not. There is not a registration on the CRM side. You have to tell the Router, where it finds its CRM deployment(s) and Mail Server (s).
Comment: So if emails are not being sent by a CRM deployment and googling all says to go check the email router and you don't know which machine hosts the email router, do you have any tips for figuring it out?
Comment: @TimPartridge if you really have absolutly no clue, you would have to look into the trace files for example. Maybe you will find some hint there


Python stripping characters(words) out of a string

Question: I have a string
string = "Friday07:48 AM"

How do I get rid of "Friday"? I could simply use a replace() function but this string could also be any other day of the week. So it could look like:
string = "Sunday07:48 AM"

How do I only get "07:48 AM"?
Answer: We can utilize the fact that every day of the week in English ends in the substring 'day' to locate that within your string, and then go from three indices farther from where 'day' starts until the end of your string.
date_str = "Friday07:48 AM"
new_str = date_str[date_str.index('day')+3:]
new_str # '07:48 AM'

As an aside, never name a string 'string' or 'str', because those are special words in Python.
Comment: `string` is a Python module, but `str` is the string type in python and is also a bad variable name
Comment: @PeterGibson Derp, ty. I rely on my IDE too much for that stuff.
Comment: No problem, I only mention it as I've been bitten by that bug before ;)
Answer: Well for everything except Saturday and Wednesday you could just grab it by:
day = string[0:6]
but in the all cases IF the time stamp in the front always holds the same index you could:
day = string[:-8]
Try it in the shell
Answer: How about using regular expressions?
import re
re.search("([a-z]+)(.*)",string,flags=re.I).group(2)

Comment: That just seems to give me "Friday". I'm looking for "07:48 AM".
Comment: I gave you the wrong group id.  Try group 2 and you will get the correct result


24 hour notation for Time Field

Question: I'm using Time Field to make a field in my event content type for the begin and endtime in of the event.
I know that when you outpout the time field via views, you can output it as 24h notation, which works fine. But I want to output the time using php in a tpl file
using the row object.
So I have php code in my views tpl file that says:
    <?php $uur  = $row->field_field_evenement_uur[0]['rendered']['#time']['value_formatted'];
          $uur .= ' - ';
          $uur .= $row->field_field_evenement_uur[0]['rendered']['#time']['value2_formatted'];
?>

First thing that came to mind of course was go to admin/structure/types/manage/my_content_type/fields/my_time_field and set the field formatting to 24h notation. It simply looks though like it's not part of the configuration.
Then I debugged my $row output in my view to discover this other way to get a rawer sort of value for the time. This way I would write code like:
$row->field_field_evenement_uur[0]['raw']['value'];
So that would output the time value like 51600. I've been looking for some formatter functions that I could wrap around this value and get me a 24hour notation, even from php.net but it's all seeming like it has to do with the date(); function.
Answer: I totally looked past the display fields part of the field configuration of fields ui. That's exactly where you can set it to output 24hr notation.

24 hour notation for Time Field


Rule from SVM results

Question: I am using Support Vector Machines from "e1071" package in R.
For standard IRIS data the code is:
data(iris);
attach(iris);
x <- subset(iris, select = -Species);
y <- Species;
model <- svm(x, y)

After that using function predict() I can get a prediction with the trained model for any data from the test Set.
However the question for me is:
ow can I get the real rule of finding a class for samples from Test Set?
Support Vector Machines determines high-dimensional hyperplane which divides data into classes. From literature I found that classifier (hypersurface) is in the simplest case defined by weights (W) and parameter (B). However for nonlinear cases one need transformation $x \rightarrow f_{i}(x)$.
Can anyone give any example of extracting the real rule from any package with SVM (preferably in R)?
Answer: For non-linear SVMs you can't extract a simple relation of features that provides the classification rule. That's the whole point around the kernel trick and the representation of the problem in the dual.
In other words, your classification rule is not based on some relation of the features, but on the similarity of the unlabelled sample to some of the labelled examples of the training set - not all of them only the Support Vectors. The similarity is defined using the kernel function.

Rule from SVM results


CodeIgniter 4 delete Post Method

Question: Good Day all
before this get removes i must note that i have tried searching for this but i still cant understand why this is not working
Please can someone help me with this i tried doing this for a few weeks now and i cannot figure out why my delete button does not work i did it on the code igniter3 and it work but i canot seem to get it to work as i am still learning and is new all i want to do is delete a post with a button that i have created ! that all please explain what i did wrong so i can learn this is just a test project to teach myself code igniter 4 thank you so much
sorry for my bad english
so here is my code
Model (Newsmodel.php)
<?php

namespace App\Models;

use CodeIgniter\Model;

class NewsModel extends Model
{
 protected $table = 'news';

 protected $allowedFields = ['title', 'slug', 'body'];

 public function getNews($slug = false)
 {
  if ($slug === false) {
   return $this->findAll();
  }

  return $this->asArray()
   ->where(['slug' => $slug])
   ->first();
 }
}

here is Controller(News.php)
<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Controller;

class News extends Controller
{
 public function index()
 {
  $model = new NewsModel();

  $data = [
   'news' => $model->getNews(),
   'title' => 'News archive',
  ];

  echo view('templates/header', $data);
  echo view('news/overview', $data);
  echo view('templates/footer', $data);
 }

 public function view($slug = null)
 {
  $model = new NewsModel();

  $data['news'] = $model->getNews($slug);

  if (empty($data['news'])) {
   throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item: ' . $slug);
  }

  $data['title'] = $data['news']['title'];

  echo view('templates/header', $data);
  echo view('news/view', $data);
  echo view('templates/footer', $data);
 }
 public function create()
 {
  $model = new NewsModel();

  if ($this->request->getMethod() === 'post' && $this->validate([
   'title' => 'required|min_length[3]|max_length[255]',
   'body' => 'required',
  ])) {
   $model->save([
    'title' => $this->request->getPost('title'),
    'slug' => url_title($this->request->getPost('title'), '-', true),
    'body' => $this->request->getPost('body'),
   ]);

   echo view('news/success');

  } else {
   echo view('templates/header', ['title' => 'Create a news item']);
   echo view('news/create');
   echo view('templates/footer');
  }
 }
}

View(view.php)

<?=esc($news['title'])?>

<?=esc($news['body'])?>

<button>Delete</button>

i have tried the following in my controller
and it didint delete it from my database but i also did not get an error! it just redirects me to my succes page.
public function delete($id = null)
{
$model = new NewsModel();

$model->delete([
 $model->where('id', $id)->delete(),
]);

return view('news/delete');
}

i have also tried this
   public function delete()
 {
  $model = new NewsModel();

  if ($this->request->getMethod() === 'post') {
   $model->delete([
    'title' => $this->request->getPost('title'),
    'body' => $this->request->getPost('body'),
   ]);
   echo view('news/delete');
  }

DB set up
DB NAME= toets
TABLE= news
id|title|slug|body

Comment: simply try `$model->where('id', $id)->delete();` and have a look at this docu: https://codeigniter4.github.io/userguide/models/model.html#deleting-data
Comment: i get an error undefined variable $id

however if i pass in

 $model->where('id', 1)->delete(); it deletes the post with id 1 but how can i make it so i is dynamic and it can delete the post i am on for example if im at post 3 it should delete post 3 not post 1
Comment: You can add a hidden input field that holds the post_id. And in your Controller do something like this: `$id = $this->request->getVar('your_post_id'); ... `.
Comment: no i tried doesint work but thanks anyway
Comment: well i fix it thank you sir
Answer: i changed my view button to
<a href="<?= '/news/delete/' . esc($news['id']) ?>">Delete

and in  my controller i made
 public function delete($id)
{
    $model = new NewsModel();
    $model->where('id', (int) $id)->delete();

    return view('news/delete');
}

Comment: Why not: `Delete`

CodeIgniter 4 delete Post Method


UTFDataFormatException - encoded string too long

Question: In my mobile app I have an object implementing PropertyBusinessObject which contains numerous other objects also implementing this interface. This object structure is populated by JSON data I am getting back from my server. When I try to write this object to Storage with writeObject() I get the above error. The stacktrace shows it originating in the com.codename1.io.Util.writeObject() method where it is writing UTF-8 (limited to 64k). The developer guide does not reference any potential issues with Storage and recommends it over FileSystemStorage. My question is, is there a workaround/update for this? Would I have to revert to writing out the object structure to the filesystem? Thanks.
Answer: If you have a ridiculously long string e.g. to represent the contents of the file I would suggest rethinking that. Strings are inefficient in Codename One since we need to copy their representation into the iOS native layer. Also writing them to UTF is very wasteful if what you need is a binary representation. I suggest using a byte array.
Serializing to storage is a simple approach. It works great for small objects. If you have larger objects you might want to store them individually. You can also serialize to/from JSON so your storage data is readable.
Comment: Thanks @Shai. Storage was working well but broke now when I did include some binary data which can be stored separately. Will take your suggestion/approach. Great platform btw, find what you've done with CN1 a real benefit to what I want to achieve.
Comment: Thanks! Be sure to spread the word around: https://www.codenameone.com/blog/how-you-can-help-spread-codenameone.html


PHP cannot print to network printer

Question: I have a server with ip 192.168.0.1, then I have a computer with ip 192.168.0.3 which access the server. I have a printer EPSON TM-U220 connected to 192.168.0.3, then I tried to print from the server to the printer using php command
copy($file, '//192.168.0.3/printername');

but it doesn't work, then I tried another function:
exec("print /d:\\\\192.168.0.3\\printername $file");
exec("copy $file \\\\192.168.0.3\\printername");

It says "unable to initialize device \\192.168.0.3\printername".
My computer and server run on windows7.
I already shared the printer to my server, I can test print page from the server.
how do I print to my network printer using PHP?
Thanks
Comment: Have you seen this topic? -> http://stackoverflow.com/questions/12300589/use-printer-via-php
Comment: it uses php_printer, and i dont have it as i use php 5.5.. i cant find php_printer.dll for php 5.5
Answer: After going some researches, I found a solution to my problem.
Run services.msc then double click Appache Service. At tab Log On, choose This account, then fill in the credential of the server.
After that, restart your appache..
My problem is solved after doing this..
Comment: Please provide the solution you found.
Answer: Following erkape#s solution, I got auto printing for Laravel with Crystal Reports XI right:
$printname="\\\\SERVERBEKASI\\Canon iP2700 series (Copy 3)";
$driver='"winspool"';
$port='"Ne07:"';
$creport->SelectPrinter("winspool",$printname,$port);
$creport->PrintOut(fal`enter code here`se,1);

The solution on my system (Windows 7) looks like this:

create a new account as the administrator, set a password
Run services.msc, double-click Apache Service. At tab Log On, choose your new account, then fill in the credential of the server.
Restart Apache. Done

PHP cannot print to network printer


Remove Eclipse indentation for non-curly-brackets if statement

Question: I would like to remove the indentation for non-curly-brackets if statements in Eclipse (Java EE).
I know this is bad practice, but there is so much going on in my Java file, and every time I format it using Ecliplse's formatter, it makes the code look uglier than ugly.Thanks in advance.
Comment: If it makes your code look uglier than ugly, then *perhaps* your methods are too large. Your phrase "so much going on" would indicate that there is no
"perhaps" about that. So rather than trying to squeeze an `if` statement down to one line, you should learn to write better code.
Comment: @Andreas give me a way to DM you and try to write better code xD
Answer: Do you want that your non-curly-brackets if statements like follows?
<code>if(true) return 0;
</code>
Then go Window -> Preferences -> Java -> Code Style -> Formatter -> Edit (Active profile) -> rename it -> Control Statements -> select "Keep 'then' statement on same line", "Keep 'else' statement..." and "Keep 'else if' on one line"; and press Ok.
I hope that helps.


Como usar o pattern para delimitar um número mínimo em um input text?

Question: Olá, preciso definir que o número mínimo inserido em um input do tipo text seja o número 5, tentei da seguinte forma:
<input type="text" name="someName" id="someId" required="required" pattern="(([1-9]?[0-9]?[5-9]?)|([0-9]?[5-9]?)|([5-9]?))"/>

http://jsfiddle.net/hiperportal/Qa5xS/2/
Porém não está funcionando, apenas funciona se digitado 04, e não somente 4.
Obs.: número mínimo 5, número máximo 999.
Obrigado.
Answer: Isso provavelmente resolverá.
 <input type="text" name="someName" id="someId" required="required" pattern="((^[5-9]$)|(^[1-9][0-9]?[0-9]$))"/>

Teste o HTML no jsfiddle.net
Explicação da expressão:
((^[5-9]$)|(^[1-9][0-9]?[0-9]$))

^  inicio da lista
[5-9] pega qualquer valor de 5 a 9
$ fim da lista
| "ou". Assim permite procurar na proxima regex caso a primeira falhe
^[1-9][0-9] isso pega qualquer valor de 10 a 99 (*)
[0-9]$ = opcional ai pega qualquer coisa  de 1 a 9 que seja o ultimo caracter da lista.

(*) - o ? quer dizer opcional. Quando colocado assim dentro de ^[1-9][0-9]?[0-9]$  quer dizer que a verficação do meio é opcional, o que permite numeros entre 10 e 99.
Comment: Obrigado, funcionou perfeitamente. Agradeço pelas explicações.


N-dimensional generalization of vector curl from elements of Jacobian

Question: I want to determine whether a certain n-dimensional, simply-connected vector field is conservative. I can very easily calculate its Jacobian in numerical form.
In 3 dimensions, the problem is easy: the Jacobian is a 3x3 matrix, and the curl can be obtained from its elements:
[jacobian[2,1] - jacobian[1,2],  jacobian[0,2] - jacobian[2,0],  jacobian[1,0] - jacobian[0,1]]
A curl of zero would mean that the vector field is conservative.
But what if my Jacobian has 100 elements? The curl is only defined for 3 dimensions, but is there a formula for some high-dimensional generalization?
Comment: In 3 dimensions zero curl is not sufficient for a vector field to be conservative. It is also needed that the domain of the vector field is simply connected.
Comment: It's always simply-connected in my case.
Comment: OK, so see my response.
Answer: On a simply connected region of $\mathbb{R}^n$ the condition is that, in your notation, jacobian[i,j]=jacobian[j,i] for any i,j. This generalizes your curl condition.
Explanation: your vector field corresponds to a $1$-form $\omega$, and the vector field is conservative if and only if $\omega=d\phi$ for some $0$-form $\phi$. If the base is simply connected, then this is equivalent to $d\omega=0$. Now $d\omega$ is a $2$-form, and the local coordinates with respect to the standard basis are the differences jacobian[i,j]-jacobian[j,i] for distinct i,j.
Comment: @Tarrare: No. Changing the order of coordinates corresponds to applying a permutation on the rows and the same permutation on the columns of the Jacobian. So symmetricity is preserved. In general, the exterior derivative $d\omega$ is a notion independent of the basis. See https://en.wikipedia.org/wiki/Exterior_derivative
Comment: Makes sense - so for n dimensions, we just need to test the Jacobian for symmetricity?
Comment: And what would happen if I decided to switch a exchange the order of a couple of coordinates in my basis? Wouldn't that stop the Jacobian being symmetric?
Comment: Fantastic, thanks- that makes total sense.