I have a Skywin oud, 11 strings. Do the pegs need to be in a certain order, like in length?

Question: So I'm not sure if my oud came strung correctly,they look a bit worn but it came with 6 pairs of replacement strings and one 11th string.
What if while restringing, I took all the pegs out without noting their original place, could I put the pegs back on the oud in any order?
Comment: That's a bad idea for *any* string instrument.  First, you don't want to completely detension  the instrument, so replace strings one at a time.  Next, as Tim says,  pegs are fitted (and "settle in" with use), so swapping them around can only lead to trouble.
Comment: It would make sense that they went back from whence they came. It sounds like it's been around a fair few years, so the fit for each will have been established.
Answer: You say that your oud pegs are of different length.
The length of the peg is determined by the thickness of the string and the distance between the nut and the bridge of the oud. Thicker strings require longer pegs to provide enough space for winding and adjusting the tension, while thinner strings can use shorter pegs.
It is important to use the correct length peg for each string to ensure that the string is properly secured and can be tuned accurately. Using a peg that is too short or too long can cause the string to slip or not hold tension properly, resulting in an out-of-tune instrument.
Since the bridge is fixed, you can remove all the strings for a short period of time, but restring and retension as soon as you can.


Constructing P-value for replicates in linear model in R

Question: Say I have two repeats of the same predictor measurements of continuous nature and a single continuous dependable. How can I compute a single p-value for the association of the predictor with the dependable.
Here an example:
input <- data.frame(
Dependent = c(10, 15, 20, 25, 30),
R1 = c(5, 7, 10, 12, 15) + rnorm(5, mean = 0, sd = 2),
R2 = c(5, 7, 10, 12, 15) + rnorm(5, mean = 0, sd = 2)
)

Currently, I get two p-values but I would like to report a single p-value for the null hypothesis of no association of predictor with dependable.
Repeats here are defined in a medical/biological sense. The same type of measurement was performed on two different days. The goal is to link these measurements to a different type of measurement that was only collected once. Each row of the data.frame constitutes paired observations and as such can be compared.
Comment: Why are you having "repeats" of the same predictor? In this case they are not actually repeats...they are two randomly simulated variables with no correlation to each other or the dependent variable. I'm guessing this doesn't fit whatever use case you are considering if this is supposed to resemble data you are currently working with. I would clarify what "repeats" are here and perhaps add some explanation about why you think this is an issue. Otherwise its hard to answer this question directly.
Comment: Suggested edits attempted.
Answer: I am not sure what you mean by "replicate" here, but when I ran your code, I got four p values. One for the intercept, one for R1, one for R2 and one for the whole model. This last was printed under the table of parameter estimates.
Call:
lm(formula = Dep ~ R1 + R2, data = input)
Residuals:
    Min      1Q  Median      3Q     Max
-3.3060 -0.6317 -0.0152  0.6468  3.2581

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.02794    0.03153  -0.886   0.3758
R1           0.05818    0.03215   1.809   0.0707 .
R2           0.01715    0.03117   0.550   0.5823
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.9966 on 997 degrees of freedom
Multiple R-squared:  0.00351,   Adjusted R-squared:  0.001511
F-statistic: 1.756 on 2 and 997 DF,  p-value: 0.1733

This is exactly what I expected.
Comment: It's testing whether the F statistic is 0, which is roughly like asking if the whole model is sig.
Comment: Thank you for reply. Replicates here are two independent experiments of the same type. Thanks for pointing out the p-value for the whole model. Could you help me understand which null hypothesis is tested by the p-value of the whole model?


checkable menu items

Question: i  have a contextmenu. how can i make it checkable?
System.Windows.Controls.MenuItem does not contain a definition for IsCheckable.
Answer: I think it already is checkable. At least according to msdn:
http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.ischeckable%28v=VS.85%29.aspx

checkable menu items


Woothemes flexslider Arrow not displaying

Question: I am using flexslider and but I just have a problem in terms of its navigation arrow. It's not displaying the right way even if I already put the font source to the right folder.
I used the flex slider in my wordpress theme and here is a screenshot of the arrow.

Here is the css file jsfiddle.net/fdeZd/
Any kind of help is much appreciated. Thanks a lot.
Answer: I solved the problem by simply putting the font folder of flex slider inside my css folder where my flex slider.css can be found. That solved my problem.
Answer: I had the same issue. The arrows were displayed as in your screenshot no matter where I placed the font files.
I even tried absolute links á la "src:url('d:/myProject/fonts/flexslider-icon.eot');" and it still didn't work. I think it has something to do
with the font itself.
But good news: I used the following workaround:
I'm using font Arial and the two symbols "<" and ">".
You have to adjust the file flexslider.css the following way:
This line:
.flex-direction-nav a:before {
    font-family:"flexslider-icon";
    font-size: 40px;
    line-height:1;
    display: inline-block;
    content:'\f001';
}

has to be replaced by the following one:
.flex-direction-nav a:before {
    font-family:"Arial";
    font-size: 40px;
    line-height:1;
    display: inline-block;
    content:'<';
}

And this line:
.flex-direction-nav a.flex-next:before {
    content:'\f002';
}

has to be replaced by the following one:
.flex-direction-nav a.flex-next:before {
    content:'>';
}

Hope this helps.
Cheers,
Michael
Answer: You should check existing files:

flexslider-icon.eot

flexslider-icon.svg

flexslider-icon.ttf

flexslider-icon.woff
in including directory (in flexslider.css line: 15)


eval_set on XGBClassifier

Question: can someone explain what does the eval_set parameter do on the XGBClassifier?
I thought that by using eval_set, the algorithm would do some sort of grid search and find the best model to fit on train and test on the "eval_set" but I realize that both codes bellow produce basically the same log loss - so it seems unnecessary to use eval_set
model = XGBClassifier(objective='multi:softprob', n_estimators=500)
model.fit(X_train, y_train)
preds = model.predict_proba(X_valid)
log_loss(y_valid, preds)
#logloss: 0.8119

ad
model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)],
        eval_metric = 'mlogloss',early_stopping_rounds=25, verbose=True)

best_iter = model.best_iteration
y_valid_pred = model.predict_proba(X_valid, ntree_limit = best_iter)
log_loss(y_valid, y_valid_pred)
#logloss: 0.8118

thanks
Answer: I don't know which version of xgboost you were using, but in my set-up it makes a difference.
I'm using xgboost ver. 0.6a2, and sklearn 0.18.1.
When I run:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier

# create a synthetic data set
X, y = make_classification(n_samples=2500, n_features=45, n_informative=5, n_redundant=25)
X_train, X_val, y_train, y_val = train_test_split(X, y, train_size=.8, random_state=0)

xgb_clf = XGBClassifier()
xgb_clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_val, y_val)], early_stopping_rounds=10, verbose=True)

I get the following output (only a few first lines):

[0]   validation_0-error:0.0735   validation_1-error:0.106
Multiple eval metrics have been passed: 'validation_1-error' will be used for early stopping.
Will train until validation_1-error hasn't improved in 10 rounds.
[1]   validation_0-error:0.0725   validation_1-error:0.09
...

So, in other words, the last pair (X,y) from eval_set is used for early stopping. And it seems to behave reasonably -- I'm getting different (better) results on the validation set when I use early stopping.
BTW, the metric used for early stopping is by default the same as the objective (defaults to 'binomial:logistic' in the provided example), but you can use a different metric, for example:
xgb_clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_val, y_val)], eval_metric='auc', early_stopping_rounds=10, verbose=True)

Note, however, that the objective stays the same, it's only the criterion used in early stopping that's changed (it's now based on the area under the Sensitivity-Specificity curve).
You can monitor two different types of metrics, like so:
xgb_clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_val, y_val)], eval_metric=['logloss', 'auc'], early_stopping_rounds=10, verbose=True)

And, like with eval_set, the last element ('auc') shall be used for deciding when to stop early.
Comment: The metric used for early stopping is not the same as the `objective`, but instead in your case is `error` the default for a classification task. See discussion about `eval_metric` here https://xgboost.readthedocs.io/en/latest/parameter.html?highlight=error#learning-task-parameters

eval_set on XGBClassifier


Create a new route for a bond alias

Question: I have an IP address in my linux box 18.104.22.168 that is eth0:1. Alias of eth0.
I want to create a route from that IP to an external 188.8.131.52 IP in another box.
How can I do it? Do I need netmask and gateway?
Comment: Please explain in more detail what it is you want to achieve by this.
Comment: I want to create a route between two IP addresses and set a discrete MTU value for that route.
Answer: Routes in IP networking are always target oriented. There is an option to do source routing, but it is hardly ever used nowadays.
Simply define a new static route (using the route add -net command), and define the metric for that route. The problem now is that unless your linux box is a router for 188.8.131.52 (i.e. all traffic for 184.108.40.206 must pass through this linux box), then traffic will simply go directly there, and your route won't have any effect. In order to make sure your traffic does go through 18.104.22.168, you must then set up a route on your source machine that makes 188.8.131.52 the router. You can do this with
route add -host 22.214.171.124 gw 184.108.40.206 mss <size>

Comment: the box is not a router for 126.96.36.199. So I guess that I need to use route add -net 22.214.171.124 gw 184.108.40.206 mss 1500 (please note -net and not -host)

Create a new route for a bond alias


Migrated data via XML doesn't import to nodes

Question: Link to my previous question, which has info on data structure etc.
Now I've gotten my XML read into Migrate and content type and fields set up right (I think), but now I can't get the nodes to save. The import has the correct number of nodes, but they don't ever get imported. The wine examples in the documentation didn't say anything about using prepareRow() or anything when you are using XML. Where are my nodes? Can I pull out that data with Views even if nodes don't import? My end use for this is to arrange everything with Views.
EDIT
Here is my class:
<?php

class ItemNodeMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('itemnode', array('default')));
$this->description = t('Grab data in XML');

// There isn't a consistent way to automatically identify appropriate "fields"
// from an XML feed, so we pass an explicit list of source fields
$fields = array(
   'id' => 'ID',
   'type' => t('Description of producer'),
   'Owner' => t('Owner'),
   'Text' => t('Text'),
   'modifiedAt' => 'Date last changed',
);

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'id' => array(
      'type' => 'varchar',
      'length' => 6,
      'not null' => TRUE,
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

// This can also be an URL instead of a file path.
$xml_folder = 'http://example.com/item/';
$list_url = 'http://example.com/CompanyID/Items.xml';
// Each ID retrieved from the list URL will be plugged into :id in the
// item URL to fetch the specific objects.
$item_url = $xml_folder . ':id/desc.xml';

$this->source = new MigrateSourceList(new MigrateListXML($list_url),
  new MigrateItemXML($item_url), $fields);

$this->destination = new MigrateDestinationNode('migrate_module_itemnode');

$this->addFieldMapping('id', 'id')
     ->xpath('/@id');
$this->addFieldMapping('body', 'Text')
     ->xpath('/Text');
$this->addFieldMapping('type', 'type')
     ->xpath('/@type');
$this->addFieldMapping('owner', 'Owner')
     ->xpath('/@Owner');
$this->addFieldMapping('created', 'modifiedAt')
     ->xpath('/@modifiedAt');

}
}

EDIT2:
I have determined that my problem lies here:
    $this->map = new MigrateSQLMap($this->machineName,
         array(
                 'id' => array(
                 'type' => 'varchar',
                 'length' => 6,
                 'not null' => TRUE,
               )
         ),
         MigrateDestinationNode::getKeySchema()
    );

This isn't correctly mapping to my source's ID, which lies at Item/@id. How can I correct this?
Comment: show us your migrate class, you should just need to setup a proper `MigrateDestination` value. Such as MigrateDestinationNode, or MigrateDestinationEntity, or MigrateDestinationTable.
Comment: Aha. So I think the problem is that my ListXML file has the IDs I need to grab at /Example/Item/@id, and I am not accessing the ID as I need to, and that's what's keeping the files from importing as nodes. Do I have to write another source handler or something?
Answer: As per this issue -- I think you need to tell MigrateSourceList where your item id's are, as an example (from isssue):
    // As with MigrateSourceMultiItems, this applies where there is not a separate
    // list of IDs to process - the source XML file is entirely self-contained.
    // For the ID path, and xpath for each component, we can use the full xpath
    // syntax as usual. However, the syntax to select the elements that correspond
    // to objects to import is more limited. It must be a fully-qualified path
    // to the element (i.e., /producers/producer rather than just //producer).
//  $item_xpath = '/producers/producer';  // relative to document
    $item_xpath = '/FMPXMLRESULT/RESULTSET/ROW';
//  $item_ID_xpath = 'sourceid';          // relative to item_xpath
    $item_ID_xpath = 'COL[1]/DATA';

    $this->source = new MigrateSourceXML($items_url, $item_xpath, $item_ID_xpath,
      $fields);

You only have 3 values in your constructor. I haven't done alot with migrating XML (just CSV and SQL). This issue is for D7 -- I think it should apply to D6.
Comment: That's what I had to do. I made a clone of `MigrateSourceList` where it could look inside of Item for /@id and problem was solved.


Interpreting multinomial logistic regression output in R

Question: I am trying to perform multinomial logistic regression on my data which is as below(just the header).

"category" is my target variable and all other variables are independent variables. category has values like 1,2,3,4,5,6,7,8,9. My main motive is to predict category from independent variables.
Here is summary of my data set.

I used following command to perform multinomial logistic regression:
<code>> mod=multinom(category~hlen+iplen+ipttl+iptype+tcpsport+tcpdport+tcpsec+tcpack+tcpwindow+tcpchksum+date_time, data=train)
</code>

I got the following output but i don't know how to interpret it?

What should be the starting point or is there other way to do so? (For example I know how to interpret linear and logistic regression output to create regression equations)
Please right click any image and select view to see it clearly.
Thank you,
Comment: Please replace the images with the actual text.
Answer: Multinomial logistic regression works like a series of logistic regressions, each one comparing two levels of your dependant variable. Here, category 1 is the reference category.
For example, consider the case where you only have values where category is 1 or 5. (Recode that to 0 and 1, so that you can perform logistic regression.) The coefficients of line 5 of your output represent the variable coefficients such a logistic regression would yield.
Comment: Thanks mzuba, So is it correct to write logit for category 2 as(considering intercept as "ß0", hlen coefficient as "ß1",iplen coefficient as "ß2" and so on....): logit(p)=ß0+ß1(hlen)+ß3(iplen)+ß4(ipttl)-ß5(iptype)-ß6(tcpsport)-ß7(tcpdport)-ß8(tcpsec)-ß9(tcpack)-ß10(tcpwindow)+ß11(tcpchksum)+ß12(date_time) The values of ß1,ß2,ß3...so on, I can get from above output?
Comment: log[p(category=2)/p(category=1)]=ß0+ß1(hlen)+ß3(iplen)+ß4(ipttl)-ß5(iptype)-ß6(tcpsport)-ß7(tcpdport)-ß8(tcpsec)-ß9(tcpack)-ß10(tcpwindow)+ß11(tcpchksum)+ß12(date_time) The values of ß1,ß2,ß3...so on, I can get from above output? p=probability
Comment: Yes. The intercept values is you B1, B2 and so on values


Variability of residuals

Question: Let assume we have a computer system that produces events in the form (x,y,z,e= (0|1)) where x,y,z are some states variables and e defines if some event happened or not. The random process generating those events follows an unknown distribution. Function F'(x,y,z) is our model and defines the probability of e happening.
I have millions of events which I bin by month and value of x then I calculate mean(e) and mean(F'(x,y,z)). Also for every bin I will calculate its residual (predicted - realised probability), at this point each bin has >10k, <100k events.
The results I receive are quite good but I see quite big variability in the residuals. For some months residuals are close to 0, for some I see 1% difference in probability in very few cases I see 10%. This variability disappears when I just bin by month and leave out x, in such cases each bin will have millions of events inside.
How I can capture/explain that variability in my residuals, maybe I can produce confidence intervals, maybe there are some other techniques which I am not aware of.
Answer: One issue with your approach is that you aren't using a proper scoring rule. That is, your "residual" metric can't be expected to give the best scores to the models that give the most accurate probability estimates.
Furthermore, it sounds like you're using an aggregation scheme that allows errors in one direction to cancel out errors in the other direction, which is no good if you're trying to estimate the magnitude of error rather than the bias.

Variability of residuals


Jquery Webservice in ASP.NET

Question: I am working with ASP.NET 4.0 framework. In one web page, I have to call web service using Jquery as
<code>     var serviceurl = 'http://www.websitename.com/webservicename';
         $.ajax({
                type: "POST",
                url: serviceurl + 'WebServiceName',
                data: "{'Parameters': '" + parameter+ "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    ShowAfterSuccess(msg);
                },
                error: AjaxFailed
            });
</code>
It works fine, if i mention url as "http://www.websiteName.com" but when i put URL as "websitename.com" it doent call webservice.
but it works well only in Google Chrome with "websiteName.com" I dont knw what is the issue with that....whether there is problem in my webservice calling or in URL..
Answer: You must ensure that you are not violating the same origin policy restriction. The best way to ensure this is to use relative urls:
<code>var serviceurl = '/webservicename';
</code>
You must ensure that the domain hosting this javascript matches exactly the domain that you are sending your AJAX call to (including the protocol).

Jquery Webservice in ASP.NET


How to install Linux system on remote server?

Question: I've 2 remote HP Proliant DL180 G6 servers with HP Integrated Lights Out enabled on both and I have to install RHEL5 on these servers.
I try to do it with ILO - mounted ISO file from local hard drive as Virtual CD-ROM, and performed installation from ILO console. OS installation on the first server was successful.
But I have to make 3 tries to achive this.
The channel between me and the servers is too slow - they are in datacenter. The installation takes a long time - 5-6 hours. So sometimes Virtual CD accidently unmounts and installation hangs.
How can I perform the installation on the other server in more convinient way?
Answer: I like the other answers, but you could also try loop mounting all the RHEL iso's (on one of the servers you already have configured), and then serving them up with http - I believe RHEL lets you choose http server. This worked for me - and I could just let it go for hours and not worry about a thing.
Answer: Now that you have one installed, put the files on there and perform the installation from that source.
Comment: Can you be more explicit? Do you mean that I need to upload RHEL distrib on the server 1, make them accessible by ftp and then perform installation on server 2 with ILO virtual media, but from the nearby ftp-source?
Comment: That is one possibility, yes. HTTP and NFS also work.
Comment: What will happen, when virtual media becomes unavailable during network installation?
Comment: Why would it become unavailable?
Comment: Network break, for example. I experienced this when perform installation from mounted virtual cdrom.
Comment: If the network breaks between the two remote machines then you REALLY REALLY REALLY need to find a new provider...
Comment: How can I start installation from the server 1 to server 2? I have no GUI on server 1, so I can't start ILO web console from it.
Comment: You... don't. You start the installation on server 2, and point it to server 1 for the media.
Comment: How can I start installation on server 2 without mounting booting CD?
Comment: Other than PXE you can't, but once the installer is up and running you no longer need the 80-120MB netinstall image. You may want to review the installation methods in the documentation.
Comment: You have to make an install with a smalled DVD iso. Use a RH network install media, they are much much lighter than the typical install DVD and you probably won't have your performance problem anymore. You still have to export the rest of the install files from your first server.
Comment: Ignacio, could you please summarize all the information from comments in your answer, so other people can view it as single piece?
Answer: RHEL supports installation via kickstart and netboot
the way it works is very efficient - you rsync
into the datacenter a RHEL repository, then you need
to boot with a net image (see into the repo directory
images) your server, you will be asked about the method
of installation - choose http and point to your local
repo (you can use a remote repo but will be slower)
and the rest is interactive.
if you don't want to be asked just point to a kickstart
file.
I use it that way with kickstart and cfengine.
Answer: The best solution might be to mail the datacentre some DVDs and ask them to insert them into the drives.
They will charge for this, but it could be cheaper in the long run.


Hide a CCK fieldgroup using #states in hook_form_alter()?

Question: I have a custom module, and I am trying to hide a CCK fieldgroup using "#states" when a certain item is selected in a drop-down select list.
I have tried using states from within hook_form_alter(), like so:
$form['group_mygroup']['#states']['invisible'] = array(
  ':input[name="field_trigger[' . LANGUAGE_NONE. ']"]' => array( 'value' => 'hide' ),
);

This doesn't seem to do anything.
I have looked at changing the weight of my module as per various sites like http://proofgroup.com/blog/2008/dec/modifying_cck_fieldgroups_hook_form_alter.
but still to no avail. I can hide all the form elements within the fieldgroup using states but not the field group itself. Does anyone have any idea?
Comment: For future viewers: [@andriy-malish' answer](http://drupal.stackexchange.com/a/34667/52651) is the correct one.
Answer:
/**
 * Implements hook_field_group_build_pre_render_alter.
 */
function mymodule_field_group_build_pre_render_alter(&$element) {
  if (isset($element['#form_id'])) {
    if ($element['#form_id'] == 'mynodetype_node_form') {
      $element['group_myfieldgroup']['#states'] = array(
        'visible' => array(
          ':input[name="field_myfield[und]"]' => array('checked' => TRUE),
        )
      );
      $element['group_myfieldgroup']['#id'] = 'group_myfieldgroup';
    }
  }
}

I use this hook to hide my field group. It's visible only if the checkbox field_myfield is checked.
To explore $element variable in this hook I used
die('
'.print_r($element, 1).'
');

instead of dpm().
Hope it helped :)
Answer: Fieldgroups aren't defined in the root of $form. It seems you should use not $form['group_mygroup'], but $form['#fieldgroups']['group_mygroup'].
Answer: You can look at the example module to see how they hide fieldsets. Based on that I think your code should be:
$form['group_mygroup']['#states'] = array(
  'invisible' => array(
    ':input[name="field_trigger"]' => array('value' => 'hide'),
  ),
),

Comment: Thanks for your suggestion. Though that's the same as my code only declared slightly different. I can hide fieldsets if I declare the form and fieldset using the FAPI. My issue is that it doesn't work with CCK field groups within hook_form_alter().


Linear Operators and Convergence

Question: I am struggling with this question from my Differential Equations course:

If $T$ is a linear transformation on $\mathbb{R}^n$ with $||T-I||<1$, prove that $T$ is invertible and that the series S= $\sum_{k=0}^{\infty}(I-T)^k$ converges absolutely to $T^{-1}$.

It's safe to assume $T$ is square ($n \times n$) matrix.
From what I understand:

A series $\sum_0^{\infty}a_n$ is called absolutely convergent if $\sum_0^{\infty}|a_n|$ is convergent.
A need to first prove that $T$ is invertible. Once I do, I need to show $||S-T^{-1}||<\epsilon$ for some $k$ greater than $N$ large.

For simplicity, let's define $A = T-I$. By hypotheses, we can assume $||T-I||<1$ is true. Now
\begin{array}
a T - I = \begin{bmatrix}
t_{11}-1&t_{12} & \dots & t_{1n}\\
t_{21} & t_{22} - 1 & \dots & t_{2n}\\
\vdots\\
t_{n1} & t_{n2} & \dots & t_{nn}-1
\end{bmatrix}
\end{array}
Now in this case, the operator norms of this linear transformation: $$||A||=\text{max}_{|\vec{x}|\leq 1}||A\vec{x}|| \leq \sqrt{n}\mathcal{l} < 1$$
Where $\mathcal{l}$ is the maximum length of the rows of $A$.
This is where I get confused. Where would I continue from here to prove $T$ is invertible?
Now, to show that $S$ converged absolutely, I wanted to use a geometric series since $||A||<1$. Thus $$\sum_{k=0}^{\infty}||A||^k=\frac{1}{1-||A||}$$ This implies that $S$ converges. The problem is, I am not sure how to prove that $S$ does indeed converge to $T^{-1}$.
Any suggestions or comments? If you need me to clarify something, please let me know.

Thank you once again for reading this post. I humbly thank you in advance for any assistance or guidance you may provide.
Answer: Hint.
Note $$S_n= \sum_{k=0}^{n}(I-T)^k.$$ As $\Vert T-I \Vert <1$, $S_n$ converges absolutely to $S$. Now you have
$$S_n . (I-(I-T))= S_n . T= I -(I-T)^{n+1}$$ And $(I-T)^n \to 0$ as $n \to \infty$.
You finally get $$S.T=I$$ as the map $A \mapsto A.T$ is continuous.

Linear Operators and Convergence


I would like to display only the teaser view of nodes

Question: I hope someone can help me. Here's my issue:
I'd like to create a content type - let's call it News Story.
Amongst its other attributes, this content type will have a taxonomy field.
I would like to be able to create a number of views around my site to display a subset of the News Story content, based on its taxonomy value.
However, I do not want the News Story to generate a standalone node/page - I only want the news stories to appear in views of news stories.
Have you done this before? How did you do it?
I'd be really grateful for your help.
Thanks
Comment: you should take a look at the rabbithole module. with it you can redirect detail pages to any url you like
Answer: One solution would be to use the Rules module.
Add a new rule and set this:
Condition:

Node is of type: News Story
Custom PHP: check display_id == full
User rôle: not admin/editor (so you can still view/edit if you're not anonymous)

Action:

Redirect to the page you want (404 or your news list for example)
Answer: In fact in the end I used the Rabbit Hole module:
https://drupal.org/project/rabbit_hole
...as suggested by Alex. It pretty much exactly met my use case.

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

@todo description of how I used it.
Comment: Hello. Please remove "thank you" from your answer, or it might be deleted as not an answer. At the same time, could you add a few words of description how rabbit hole meets your use case? I mean, even if it meets it exactly, you can post an excerpt from module's project page.


MSBUILD - Como publicar vários projetos de uma unica Solution (OSGI)

Question: estou precisando de uma ajuda para publicar meus projetos.
Estou utilizando OSGI para modular minha aplicação, com consequência na minha solution existe varias aplicações WEB.

Ex: Solution A
<code> 1. Aplicação 1
 2. Aplicação 2
 3. Aplicação 3
 4. Aplicação Principal
</code>

Essas aplicações não tem nenhum referencia entre si, mas preciso que todas as aplicações fiquem dentro de um pasta ("Plugins") dentro da Rais da "Aplicação Pai" na hora da publicação.
Obs. Preciso dessas aplicações com todos os arquivos necessários (Views, Script ... Etc, ) não pode ser só o binário pois são aplicações Web
Answer: Você pode tentar via linha de comando:
<code>msbuild example.sln /p:Configuration=Test;DeployOnBuild=true;PublishProfile=Test.example.pubxml /MaxCpuCount:8
</code>
A ideia é criar um bach (bat) para fazer esta publicação. O bacana é que se em algum projeto você mudar alguma configuração de publicação (arquivo .pubxml), isto irá refletir no bat.


If $\phi$ is in $\mathcal S$ and $\phi(0)=0$, is $\int_0^1 \nabla \phi(tx)dt$ in $\mathcal S$ too?

Question: Let $\phi\in\mathcal S(\mathbb R^n)$ be a Schwartz function vanishing at $0$. Then the FTC implies
$$ \phi(x) = x\cdot \int_0^1 \nabla \phi (tx)\ dt.$$
Let this integral term be $\psi(x) := \int_0^1 \nabla \phi(tx)dt$. Is it true that  $\psi$ is (component-wise) a Schwartz function?
It is at least $C^\infty$. I tried for a while to come up with counterexamples and failed. I have proved it in dimension $1$, but I need a replacement for division in higher dimensions?
The result is false for arbitrary functions $p$ that solve $\phi(x)= x\cdot p(x)$, even if $\phi$ is Schwartz ($0 = \binom x y \cdot \binom {-y}x$). Also, $\psi$ is not Schwartz if the condition $\phi(0)=0$ is dropped, as then (in 1D) $\psi(x)= \frac{\phi(x)-\phi(0)}x\sim\frac{\phi(0)}x$ for large $x$ which is not enough decay. So a positive proof would need to use something about Schwartz functions and something about vanishing at zero (the two assumptions).
I can provide a detailed attempt if wanted; in fact I have deleted many "answers" after noticing errors. In particular I have tried merely using the Schwartz seminorms to bound the integral, but it seems that either many factors of $t^{-1}$ appear which make the integral diverge, or (trying to treat $t\ll 1$ separately) I am unable to achieve large decay. Of course, as previously mentioned, the issue at $t=0$ should be somehow resolved with the vanishing at $x=0$.
This comes out of trying to understand what the correct fix for a typo in M Zworski's Semiclassical Analysis p.32 (Screenshot,Google books link), in a proof that the Fourier Transform is an automorphism of $\mathcal S$. The online errata (screenshot copy) says to set $\phi(0)=0$, but I'm unsure if the preceeding paragraph is correct with this correction (and in any case, it is stated that $\psi$ may not be in $\mathcal S$ without proof.)
Thoughts appreciated!

 Zworski, Maciej, Semiclassical analysis, Graduate Studies in Mathematics 138. Providence, RI: American Mathematical Society (AMS) (ISBN 978-0-8218-8320-4/hbk). xii, 431 p. (2012). ZBL1252.58001.
Answer: Now I have come to the conclusion that it is not true:
Take $\phi(x,y) = -y e^{-(x^2+y^2)/2},$ which is in $\mathcal{S}(\mathbb{R}^2)$ and satisfies $\phi(0,0)=0.$ Then $\partial_x\phi(x,y) = xy e^{-(x^2+y^2)/2}$ so
the $x$-component of $\psi$ is
$$
\psi_x(x,y)
= \int_0^1 t^2xy e^{-t^2(x^2+y^2)/2} \, dt
= \{ s:= t\sqrt{x^2+y^2} \}
\\
= xy\int_0^{\sqrt{x^2+y^2}} \frac{s^2}{x^2+y^2} e^{-s^2/2} \, \frac{ds}{\sqrt{x^2+y^2}}
\\
= \frac{xy}{(x^2+y^2)^{3/2}}\int_0^{\sqrt{x^2+y^2}} s^2 e^{-s^2/2} \, ds
.
$$
Now study $\psi_x(x,y)$ along $(x,y)=(r,r),$ i.e.
$$
\psi_x(r,r)
= \frac{2^{-3/2}}{r} \int_0^{\sqrt{2}r} s^2 e^{-s^2/2} \, ds
.
$$
As $r\to\infty$ this will have the asymptotic behavior
$$
\psi_x(r,r)
\sim \frac{2^{-3/2}}{r} \int_0^{\infty} s^2 e^{-s^2/2} \, ds
= \frac{2^{-3/2}}{r} \sqrt{\frac{\pi}{2}}
$$
which does not tend to $0$ fast enough,
so $\psi_x \not\in \mathcal{S}(\mathbb{R}^2).$
Comment: you're right. I wrote my answer too quick.
Comment: this is perfect, I tried many variants of this but could not get it to work!


css auto width floating issue

Question: Please check out this image

blah blah

blah blah

CSS part:
 .main{min-width:1200px}
    .left{width:400px ; height:auto ; float:left }
    .right{width:auto ; height:auto ;float:left }

I hope friends, you have got an idea from the image. Please help me.
I am dynamically inserting data into right div and when its width exceeds 800px, it comes down the left div. But instead of that I want a horizontal scrollbar to view the content. One solution may be, removing float:left from right div. But still it causes problem.
Comment: Welcome to SO! It would be more helpful if you could post a link to the page or create a fiddle (jsfiddle.net), so we can work on the problem.
Comment: I have created a fiddle, I dont want the right part to come down the left http://jsfiddle.net/vinay49/fbeJc/
Answer: on floated elements, height:auto means the height of the content (the default for floated elements). try with height:100%

css auto width floating issue


How to make get for drupal behaviors to run only once?

Question: Drupal.behaviors.js_mod = {
attach: function (context, settings) {
     //$('body', context).append(chart);
    // $( '#drupal-myradar', context ).once
     $.get( "/web/js/mod", function( data ) {
        console.log(data);
      });
}

    }
})(jQuery, Drupal, drupalSettings);

Essentially this code is running multiple times while grabbing information from my controller code. I only want this to print out once to the console when the page is loaded.
Answer: If your script is high-level, which is most likely, then only run it when the context is equal to the document.
I found this trick in the autologout module and use it almost everywhere now:
Drupal.behaviors.dosomething = {
  attach: function attach(context, settings) {
    if (context !== document) {
        return;
    }
    // Do stuff here but still use .once when attaching behaviors.
  ...

Comment: This solution makes the assumption that the behavior is present at DOM ready, which in my experience is not guaranteed with BigPipe module (which is enabled by default).
Comment: This is a great solution for me. Nice work.
Answer: This works as designed. Behaviors attach runs multiple times, but the scope provided in context changes. So check if the element is in context and apply once() to get the element only one time:
 Drupal.behaviors.js_mod = {
    attach: function attach(context, settings) {
      var $myradar = $(context).find('#drupal-myradar').once('js_mod');
      if ($myradar.length) {
        ...

Comment: There is no need for `var $myradar = $(context).find()...if($myradar...)`, this can be simplified into one line: `$('.my_selector', context).once('my_once_token').each( ...do stuff... )`
Answer: That would do :
(function($, Drupal, drupalSettings) {
    let onlyOnce;
    Drupal.behaviors.js_mod = {
      attach: function (context, settings) {
          if (!onlyOnce) {
            onlyOnce = true;
            //$('body', context).append(chart);
            // $( '#drupal-myradar', context ).once
            $.get( "/web/js/mod", function( data ) {
              console.log(data);
            });
          }
       }
     }
})(jQuery, Drupal, drupalSettings);


Alguma ajuda no exercicio de funcao (python)

Question: O exercicio fala o seguinte :
"Escreva uma função que recebe um inteiro positivo m e devolve 1 se m é primo, 0 em caso contrário."
Minha tentativa :
edit: Então , realizada as modificações o programa ainda não está devolvendo os valores de 1 ou 0 ( caso o numero seja impar ou par).
m = int(input("Digite um numero inteiro:"))

def recebe_m(m):

  n_divisores = 0
  i = 1

  while(i <= m):
      if(m%i==0):
          n_divisores = n_divisores + 1

  i = i+1

  if(n_divisores==2):
      return(1)
 else:
      return(0)

  print(recebe_m(m))

obs : eu optei por deixar o i <= m , espero que nao tenha problema.
Eu estou estou recebendo o seguinte erro do python :

UnboundLocalError: local variable 'i' referenced before assignment
Comment: E como testou? Tem como postar o código no [Repl.it](https://repl.it)? Eu testei aqui com as indetações corretas e retornou 0 e 1 como esperado.
Comment: Sim, ajustando todas as indentações incorretas.
Comment: Seu código está com a indentação toda errada. Você está tentando executar o código exatamente assim ou só foi falha na formatação do mesmo ao postá-lo aqui?
Comment: Acho que estou falhando em postar o código aqui Anderson, não sei direito como faz.
Comment: Eu testei e nao deu certo. O que você fez ? Copiou o códio e colocou no Repl.it ?
Comment: Eu consegui agora. Eu estava copiando do meu próprio texto , quando eu copiei do seu deu certo. O que será que errei ? Somente a identação ?       edit: acho que descobri o que eu errei.O i = i +1 está fora do if.
Answer: Você precisa declarar a variável i dentro da função recebe_m. O mesmo problema irá ocorrer com a variável n_divisores, declare a mesma dentro da função.
m = int(input("Digite um numero inteiro:"))
def recebe_m(m):
     n_divisores = 0
     i = 1
     while(i <= m/2):
        if(m%i==0):
           n_divisores = n_divisores + 1

        i = i+1

    if(n_divisores==1):
        return(1)
    else:
        return(0)
print(recebe_m(m))

Além disso, como o amigo da outra resposta disse, você está tentando dividir por 0 na primeira iteração do seu loop while, corrija isso e inicialize i com 1.
O problema do seu código é com escopo de variáveis. Em python caso você declare uma variável num escopo mais interno, e a mesma variável exista num escopo global, a variável do escopo mais interna será a utilizada pelo python para fazer os cálculos.
No seu código você tenta declarar e incrementar uma variável na mesma linha num caso que a variável i não existe no escopo interno ainda, isso que ocasiona o erro. O mesmo vale para n_divisores.
Para entender melhor:
x = 10
def func():
    x = 5
    print(x)
func() # printa 5
print(x) # printa 10, x com valor 5 morreu.

Edit: Assim como o @Anderson disse, não é necessário checar todos os números e sim apenas a metade deles (i <=m/2)
Comment: Acho que entendi algumas das alterações , mas o programa ainda não está devolvendo os valores 1 ou 0. Isso eu ainda nao entendi o porque .Eu nao entendi tame por que (n_divisores==1) , tambem. (isso seria porque voce dividiu o m por 2 ?)
Comment: @user158657 eu mudei alguma coisa no codigo e ta dando erro pra mim, também vou dar uma olhada aqui. E sim, é porque eu dividi m por 2, dai o criterio pra ser primo é ele ser divisivel apenas por 1 (ter apenas um divisor). No meu caso era erro de identação, veja funcionando no [replit](https://repl.it/Iv9w/1)
Comment: @user158657 se tiver conseguido resolver seu problema com a ajuda de alguma das respostas, marque a que mais ajudou como "respondida" pra sinalizar que sua duvida foi sanada.
Answer: Pelo oq pude perceber, vc teria a intenção um [int]%0 no primeiro caso? Não se divide por zero haha (a n ser q queira abrir um buraco negro rsrs)
Você precisa declarar a variável n_divisores dentro do def
o codigo fica:
m = int(input("Numero: "))
def recebe_m(m):
    cont=0
    for x in range(1,m+1):
        if(m%x==0):
            cont+=1
    if(cont==2):
        return(1)
    else:
        return (0)

print(recebe_m(m))

Answer: Procurei deixar a função o mais simples possível
Você não precisa contabilizar os divisores, se existir qualquer divisor entre 1 e a metade dele mesmo, você já pode definir que o número não é primo.
A função as seguir percorre todos os números de 2 até m/2, e se achar algum divisor retorna 0, se ele terminar o loop sem encontrar nenhum ele retorna 1
m = int(input("Digite um numero inteiro:"))

def recebe_m(m):
  for i in range(2, int(m/2)):
    if m%i==0:
      return(0)

  return(1)

print(recebe_m(m))

Comment: "Não de o peixe, ensine a pescar"
Comment: E o maior divisor possível de um número é a metade dele, então não há porquê fazer o `range` até `m-1`, pode ser apenas até `int(m/2)`.
Comment: Coloquei a explicação para ele entender o código


Two DHCP servers giving static addresses in a network

Question: I have a network having two servers that are occasionally booted. I wish to maintain DHCP services even during a boot of one server.
One of the servers currently has a DHCP server that gives static IP addresses. It gives addresses only to users with an allowed MAC address, and each user has a fixed IP. No dynamic IPs are there.
Is it possible in this setup to run two DHCP servers in the same network in different servers for redundancy? I'm not looking for a solution where the IP address sets of two servers are disjoint; I'm looking for a solution where the IP addresses both servers give are static and the same.
I am mostly interested about the general concept: can DHCP as a protocol support two DHCP servers giving same static IP addresses? Do clients get confused if they get a response from two servers with the same lease IP address? This is why I didn't specify what DHCP server I am using. I am specifically not requesting instructions for host / server configuration.
I originally asked this in Network Engineering, but they seem to have a habit of closing perfectly valid non host / server configuration related network engineering related questions using some unknown random algorithm, saying that the question is about host / server configuration (which it isn't; it's about the protocol) and the question is about a protocol above OSI layer 4 (which it is, but then again they have numerous DHCP questions there and not all get closed).
Comment: https://kb.isc.org/article/AA-00502/0/A-Basic-Guide-to-Configuring-DHCP-Failover.html
Comment: Have you tried it out?  My gut tells me that you might trigger network protections in smarter network gear, and the hosts may prefer to seek out an IP from their previous DHCP server, but the worst case I see is that one of the DHCP servers is ineffective, meaning no redundancy.  I suspect it will work okay.  Ensuring the DHCP servers stay in sync may be the hard part.
Comment: No, I haven't tried it yet. Not sure if production network is the proper location for such a trial... On a trial network, such as Linux containers / network namespaces, it could be tried with little difficulty. Perhaps I'll do that.
Comment: DHCP can handle this. ISC DHCPD, for example, has [documentation describing how this could be set up](https://kb.isc.org/article/AA-00502/0/A-Basic-Guide-to-Configuring-DHCP-Failover.html). I've not tried it, though, so I don't class this as a proper "answer". (Ah. Just noticed yoonix has referenced the same document.)
Comment: Related: https://paulroberts69.wordpress.com/2011/10/27/isc-dhcp-failover-is-just-too-complex/ and https://tools.ietf.org/html/draft-ietf-dhc-failover-12 -- it seems it's not an RFC but rather an Internet draft.
Answer: A couple of things:
To say that these reserved ip addresses are not dynamically assigned is inaccurate. They are dynamically assigned. The point is that they are reserved ip addresses so that the DHCP client is always dynamically assigned the same ip address. These are not statically assigned ip addresses. They are dynamically assigned, reserved ip addresses.
There's nothing stopping you from creating the same reservations on both DHCP servers. This doesn't require any special configuration of DHCP (at least in Windows DHCP server). A DHCP client that has a reservation will acquire it's ip address from one of the two DHCP servers. It doesn't matter which. During the client renewal phase (T1) the client will attempt to renew the ip address from the DHCP server that assigned the ip address to the client. If the client is unable to renew the ip address from the DHCP server that assigned the ip address to the client (because the DHCP server is down) then the client will release the ip address and attempt to acquire an ip address from any DHCP server. The second DHCP server will then service the client, and because it has the same reservation for the client, will assign the client the same ip address that the first DHCP server assigned. This process will operate the same way during the rebinding phase (T2).
Answer: I do this myself.  I use two VMs running FreeBSD.  Each VM runs the FreeBSD port of ISC's DHCP server (https://www.isc.org/downloads/dhcp/).  That software can have two (and no more) servers in a high availability pairing.  Each one communicates with the other.  If they're both running, they provide load balancing.  If only one is running, it realizes it and immediately takes over all services.
I have to keep some configurations in sync between the servers myself.  To do this, I use an rsync command and have carefully put some configurations (e.g. static IP mappings, DHCP dynamic pools, etc.) in one set of files while placing anything specific to each host in a different file which I don't rsync.
Any time I need to make a change, I just edit the files on one server, restart the DHCP server process, watch the logs until I'm sure it is running correctly (5 - 120 seconds), and then rsync the files over.  I use an SSH key on root on the other server, to make the rsync a tiny bit easier, but that isn't necessary.  Then I SSH over to the other host and restart it's DHCP server process, watch the logs, and so on.
Thanks to writing documentation with a checklist, this whole process can take me as little as 3 - 5 minutes.
Lastly, and perhaps most easily overlooked, I have an extra ip helper-address command in my network's core switch.  The first command points to the first DHCP server's IP address and the second command points to the second DHCP server's IP address.  Individual network clients will get an answer from one or the other DHCP server, since both servers are in contact with each other and coordinate things between themselves.
I can post some more details and examples, if you're interested.  There is some decent documentation from ISC themselves, too.  Really, the big "tricks" are synchronizing the configuration between the two ISC-DHCP instances and using two DHCP forwarding commands in your topology, e.g. "ip helper-address" in Cisco's iOS products.


Algebraic operations with tensor products and direct sums.

Question: When first learning about tensor products and direct sums of vector spaces,
the analogy of multiplication and addition of vector spaces is sometimes used to help with the intuition.
If we look at the bases of the considered vector spaces,
this analogy seems most intuitive:

the basis of the direct product of $U$ and $V$ is the concatenation of the bases of $U$ and $V$; and
the basis of $U\otimes V$ is the set of all products $u\otimes v$, where $u$ is in the basis of $U$ and $v$ is in the basis of $V$.

This made me wonder,
how far can this analogy of addition and multiplication be taken?
More precisely: letting $F$ be a field and $\mathbf V_F$ be the set of all vector spaces over $F$,
it is clear that $\oplus$ and $\otimes$ define binary operations on $\mathbf V_F$,
and that these operations are closed,
in that given $U,V\in\mathbf V_F$,
both $U\oplus V$ and $U\otimes V$ gives back an element in $\mathbf V_F$.
If we stretch the concept of two elements in $\mathbf V_F$ being equal to mean that they are isomorphic as vector spaces,
then we see that $\oplus$ and $\otimes$ have some properties that the usual $+$ and $\cdot$
have, such as commutativity and associativity, and neutral elements (i.e., $\{0\}\oplus V\cong V$, and $F\otimes V\cong V$).
So then my question would be: Do we have all of the usual properties of addition and multiplication, such as inverse elements, or distributivity? In other words, can $(\mathbf V_F,\oplus,\otimes)$ be seen as a ring? And if not, which properties hold and which doesn't?
Given how natural this question feels for me, it seems that this must have already been investigated by someone.
Comment: One has to be very careful with constructions such as "the **set** of all vector spaces".
Comment: Just an observation: for a given vector space $V,\ \oplus$ and $\otimes$ can be used to build the "free algebra" $\bigoplus_{i=0}^{+\infty} V^{\otimes n}$ (where $V^{\otimes n}$ is a notation for the $n$ fold tensor product of $V$)
Answer: You're right-- this sort of question is studied a lot.  As you have defined things, you're looking at a  semiring, instead of a ring  because there are no additive inverses to the direct sum operation.  Of course distributivity goes through, since $L \otimes (K \oplus J) \cong L \otimes K \oplus L \otimes J$ via $l \otimes(j \oplus k) \mapsto l \otimes j \oplus l \otimes k$.
In fact your semiring is isomorphic to the natural numbers $\mathbb N$ via the map $V \mapsto {\rm dim} \ V$.
Say you wanted to get a ring out instead of a semiring-- there is a canonical procedure (or free functor $F$) that turns any semiring into a ring in a universal way.   Applying it to your semiring you would get something isomorphic to $\mathbb Z$
Now we see that for vector spaces over a field, this ring is a bit boring since it just captures dimension.  But you could do the same thing for modules over a ring, and all of a sudden things become much more interesting.  Or you could do it for vector bundles over some sort of space, for instance an algebraic variety. This ring was first introduced by Grothendieck to prove his version of the Riemann Roch Theorem.  All these things often go under the name of $K$-theory, which you should totally check out to learn more!
Comment: You get $\mathbb{N}$ by considering finite-dimensional vector spaces. In general, you will get $\mathsf{Card}$, the semiring of cardinal numbers.
Comment: wouldn't quotience possibly work as inverse to direct sum?
Answer: Vector spaces with $\oplus$ and $\otimes$ do not form a semiring, since associativity etc. do not hold - the laws only hold up to isomorphism. These isomorphisms fit together in a certain way, and what we get is called a $2$-semiring or $2$-rig. Just like a semiring is a "fusion" of two monoids (one being commutative), a $2$-semiring is a "fusion" of two monoidal categories (one being symmetric). Every $2$-semiring induces a semiring by considering the "set" of isomorphism classes. This process of taking isomorphism classes is called decategorification. The reverse process is called categorification. Roughly, categorification produces more structure (which can be very useful), and decategorification "destroys" structure (which might simplify calculations). For example the $2$-semiring of vector spaces over $K$ has much more structure than its underlying semiring, which identifies (via $\dim$) with the class of cardinal numbers $\mathsf{Card}$ with the usual cardinal arithmetics. The $2$-semiring "knows" the group $\mathrm{Aut}(K^n)=\mathrm{GL}_n(K)$, but the underlying semiring does not.


What's the point of polynomial regression?

Question: I understand that, ostensibly, polynomial regression is useful for extending the linearity assumption in least squares regression. It can model nonlinear relationships between a predictor and response.
But, it seems that it only works with a model limited to a single predictor.
For an example, I'm working with the Boston housing dataset. It has information on median income in 500 parcels throughout Boston, described by thirteen variables.
It is unreasonable to expect the relationship can be summarized by just one of those variables. I suppose that makes it unreasonable to also expect it to be summarized by a polynomial regression with just one of those variables?
Am I wrong? Is my assumption that a polynomial regression is largely limited to one predictor off-base?
Comment: Yes you're wrong
Comment: Search for "multiple linear regression".
Comment: Great, tell me more!
Comment: Related- https://stats.stackexchange.com/questions/387477/what-is-the-consequence-from-building-polynomial-regression-with-multiple-ind-v?noredirect=1#comment727848_387477
Comment: Why do you think that it is largely limited to one predictor? Watch a Youtube video on splines
Comment: all the examples for fitting polynomial regression and splines show the case of one predictor. how do you decide the correct power for multiple predictors? that must also add some multicollinearity, right?
Answer: You can run multiple linear regression, where you relate an outcome to multiple predictors. For instance, you could have two predictors:
$$ y = \beta_0+\beta_1x_1 + \beta_2x_2 + \epsilon. $$
To model nonlinearities in the predictors, you can simply polynomially transform either or both predictors separately, e.g.:
$$ y = \beta_0+\beta_{11}x_1 + \beta_{12}x_1^2
+\beta_{21}x_2 + \beta_{22}x_2^2 + \beta_{23}x_2^3+ \epsilon. $$
Or you can include interaction terms, like:
$$ y = \beta_0+\beta_{11}x_1 + \beta_{12}x_1^2
+\beta_{21}x_2 + \beta_{22}x_2^2 + \beta_{23}x_2^3
+ \gamma_{11}x_1x_2 + \gamma_{12}x_1x_2^2 + \epsilon. $$
Splines are pretty much always better than straight polynomials, just like in the single predictor case.
And yes, it can be hard to determine how many knots your splines should have, just like in the single predictor case.
Answer: First of all, as other have pointed out, polynomial regression can be applied in either univariate or multivariate situations --- it is not limited to univariate regression.  Polynomial functions can operate on several variables, and this includes polynomial terms in each of those variables, plus interaction terms.
As to usefulness, the main reason that polynomial regression is such a useful model form is that it is actually a type of linear regression (i.e., it is linear with respect to the coefficients in the model) but it can be used to give an arbitrarily close approximation to a wide variety of non-linear functions (i.e., notlinear with respect to the explanatory variables, but still linear with respect to the coefficients).  This aspect of the model comes from the method of Taylor approximation.  For a wide class of non-linear functions $f$ taken over our limited data range, you can approximate the function up to an arbitrary level of accuracy by the polynomial:
$$f_{(k)}(x|a) = \sum_{i=1}^k \frac{1}{k!} (x-a)^k \frac{d^kf}{dx^k}(a),$$
where $a \in \mathbb{R}$ is a chosen base point.  (Note that the Taylor approximation can be extended to multiple variables, and so it can be used to yield a multivariate polynomial regression.)  Taylor polynomials are polynomial approximations to non-linear functions, so they form the justification for why polynomial regression is regarded as a standard model form that can model a broad class of relationships reasonably well.
Now, it is important to note that in polynomial regression we are limited in the degree of the polynomial we can use, and the number of interaction terms between different explanatory variables, by the fact that we have a limited data set and we don't want to lose too many degrees-of-freedom.  If we have a large number of data points relative to the number of variables then it is possible to fit polynomial regression to a reasonably high degree, and this will generally give you a good approximation to a wide class of functions that are non-linear with respect to the explanatory variables.  (A notable exception to this is periodic functions, which are better approximated by Fourier approximation, which gives you periodic regression.)
Comment: I would say the Stone Weierstrass theorem is more relevant https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem


Step Definition Java - Selenium WebDriver find element from search result

Question: I'm new to Selenium Webdriver automation using Java and still learning.
In my step definition RetailTakePayment.java class, I'm trying to find element containing specific that text appears in the search result (on a popup) but for some reason I have been unable to locate and click it. I have search around and have not been very lucky. Hence, posting my questions for some guidance.
I hope these help.
Salesforce Page Vehicle Lookup:

Popup - Lookup Search Result:

My HTML:

Two Frames in my HTML:

My Step Definition:
@Given("^user complete payment precheck$")
    public void user_complete_payment_precheck() throws Throwable {

        // inserting installer and preferred date
        driver.findElement(By.id("page:frm:main:jobsInfo:jobsRepeat2:0:j_id164")).sendKeys("Test");
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/table/tbody/tr/td[2]/form/div[1]/div/div/div/div[2]/div[5]/div[2]/table/tbody/tr[1]/td/table/tbody/tr/td[4]/span/span")).click();

        // searching and selecting vehicle
        // click on lookup
        driver.findElement(By.xpath("//img[@alt='Vehicle Lookup (New Window)']")).click();
        Thread.sleep(2000);

        // window switch handler
        String parentWindowHandler = driver.getWindowHandle();
        String subWindowHandler = null;

                Set<String> handles = driver.getWindowHandles();
                Iterator<String> iterator = handles.iterator();
                while (iterator.hasNext()) {
                    subWindowHandler = iterator.next();
                }
                driver.switchTo().window(subWindowHandler);

        // switch by frame
        driver.switchTo().frame(0);

        // searching - this worked!!!
        driver.findElement(By.xpath("//form[@id='theForm']/div/div[2]/input")).sendKeys("autod2018");
        Thread.sleep(1000);
        driver.findElement(By.name("go")).click();
        Thread.sleep(2000);

        // searching for vehicle - STILL NOT WORKING....
        driver.findElement(By.xpath("//div[contains(text(),'BMW-1 SERIES-AUTOd2018')]")).click();
        // driver.findElement(By.xpath("/html/body/div[1]/div[3]/div/div/div[2]/div/div[2]/table/tbody/tr[2]/th/a")).click();

        // switching back to the parent window - works!
        driver.switchTo().window(parentWindowHandler);

        // save record
        driver.findElement(By.xpath("/html/body/div[1]/div[2]/table/tbody/tr/td[2]/form/div[1]/div/div/div/div[1]/table/tbody/tr/td[2]/input[1]")).click();

    }

I get this error message:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[contains(text(),'BMW-1 SERIES-AUTOd2018')]"}
  (Session info: chrome=69.0.3497.100)
  (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z'
System info: host: 'TR-UXB0509', ip: '10.175.139.35', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578737 (49da6702b16031..., userDataDir: C:\Users\qureshiz\AppData\L...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:57721}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 69.0.3497.100, webStorageEnabled: true}
Session ID: 6282cc65ad89a6e8dd4fe4b996269b19
*** Element info: {Using=xpath, value=//div[contains(text(),'BMW-1 SERIES-AUTOd2018')]}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:322)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:424)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:314)
    at stepDefinitions.RetailTakePayment.user_complete_payment_precheck(RetailTakePayment.java:64)
    at ?.Given user complete payment precheck(C:/Users/qureshiz/ECLIPSE/Workspace/MultipleFeaturesAndSteps/src/test/resources/features/RetailJourney.feature:69)

Other xpath tried but all have failed:
//valid xpath-1 - from ranorex selocity - didnt work
driver.findElement(By.xpath("/html//div[@id='Vehicle__c_body']/table[@class='list']//a[@href='#']")).click();

//valid xpath-2 - custom xpath - didn't work
driver.findElement(By.xpath("//*[text()='BMW-1 SERIES-AUTOd2018']")).click();

//valid xpath-3 - from chrome - didn't work
driver.findElement(By.xpath("//*[@id=\"Vehicle__c_body\"]/table/tbody/tr[2]/th/a")).click();

//valid xpath 4 - from firefox - didn't work
driver.findElement(By.xpath("/html/body/div/div[3]/div/div/div[2]/div/div[2]/table/tbody/tr[2]/th/a")).click();

Comment: it means xpath is not correct . can u show html inspection of the element u r trying to locate ?
Comment: Your XPath is incorrect show your HTML so we can easily resolve your issue.
Comment: Thanks both , I have added snapshot of my HTML.
Comment: You switch to a frame before type words for search: `driver.switchTo().frame(0);`,  If the search result table is not in the same frame as the search form, you need to switch to correct frame which the result table insides.
Comment: Hi @yong , I'm switching first because I'm searching for the word in the child frame.
Comment: Can you provide the html as a code snippet rather than a screenshot?  Would make figuring out your problem easier.
Comment: Hi all, Sorry, I have just noticed that search results are appearing in another frame (see attached). I'm trying to switch to 'resultsFrame' and getting an error that no frame found. @anonygoose my html is really large and i'm unable to add it here. Hence, the reason why I ended up doing the screenshot.
Answer: Because the search form and result table are in different frame, you need to switch to corresponding frame before interact with element inside it.
 // switch to search form frame
 driver.switchTo().frame(0);

 // enter search keywords and click go
 ...

 // switch back to topmost frame in the current window.
 // this is very important, you can't directly switch to result table frame
 // from search form frame ( because it's not includes the result table frame).
 // Most of time, we back to the top frame, then jump into other frame.
 driver.switchTo().defaultContent();

 // then switch to result table frame
 driver.switchTo().frame(<index_or_name_of_result_table_frame>);

Comment: Hi Yong, you were right. Search results were in separate frame. There are two frames 'searchFrame' and 'resultsFrame'. I have to swtich to `driver.switchTo().frame(0);` or `driver.switchTo().frame("searchFrame");` before I do the search. But I have not been able to switch to results frame now for some reason. Any suggestions?
Comment: This worked perfectly! I can't vote it though. Thank you yong.

// first switching to search frame `driver.switchTo().frame("searchFrame");`
// then switching to topmost frame `driver.switchTo().defaultContent();`
// lastly switching to results frame `driver.switchTo().frame("resultsFrame");`
Comment: If it's your expected answer, please accept as your question answer.
Answer: try:
driver.findElement(By.xpath("//a[contains(text(),'AUTOd2018')]")).click();

the current code is looking for div element:
driver.findElement(By.xpath("//**div**[contains(text(),'BMW-1 SERIES-AUTOd2018')]")).click();

The html provided has a element name
BMW-1 SERIES-AUTOd2018

Comment: I think i have tried this before, just did it again still can't locate it:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[contains(text(),'AUTOd2018')]"}
Comment: have you tested the xpath in firebug. Chrome Developer console run this: document.evaluate("//p[contains(text(),'AUTOd2018')]", document, null, XPathResult.ANY_TYPE, null).iterateNext()
Comment: No. Unfortunately, In my test environment firefox v62 firebug is not compatible.
Comment: try firefox developer console
Comment: I didn't get a chance to try them in firefox dev console but the one i have tested have been validated (i have just added them to the description)
Comment: Just noticed the element is inside a FRAME, Selenium gives you access to the content of one frame at any time. Two examples of Selenium Frames: https://stackoverflow.com/questions/52664902/step-definition-java-selenium-webdriver-find-element-containing-text-and-click/52666602#52666602 or https://stackoverflow.com/questions/20069737/how-to-identify-and-switch-to-the-frame-in-selenium-webdriver-when-frame-does-no


Two Node Apps, One Nginx Server

Question: I'm very new to using Nginx, but it doesn't seem that complicated. I have two node apps (using forever), one running on port 2368 (domainA) and the other on 2367 (sub.domainB).
domainA works as expected. But sub.domainB reports a 502 error.
Here are my configuration files:
Server is running Ubuntu 15.04
/etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        server_names_hash_bucket_size 64;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

etc/nginx/sites-available/domainA.com
server {
    listen 80;

    server_name domainA.com;

    location / {
        proxy_pass http://my_ip:2368;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

etc/nginx/sites-enabled/sub.domainB.com
server {
    listen 80;

    server_name sub.domainB.com;

    location / {
        proxy_pass http://my_ip:2367;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Comment: You need to start the service that's supposed to listen on port 2367.
Comment: It is, but pointed at the wrong IP. Your comment pointed me in the right direction however. Will update with my own answer momentarily.
Answer: The configuration above was correct, however, in my application I was pointing to 127.0.0.1 in the production environment for the node app located at sub.domainB.com. Changing this to the ip address of the machine (like the other node app) fixed the issue.

Two Node Apps, One Nginx Server


show running applications (alt-tab program list)

Question: Found the solution here: http://blogs.msdn.com/b/oldnewthing/archive/2007/10/08/5351207.aspx

I'm trying to go a list of running applications, i found on several forums this solution:
Process[] processes = Process.GetProcesses();
foreach (var proc in processes)
{
     if (!string.IsNullOrEmpty(proc.MainWindowTitle))
        Console.WriteLine(proc.MainWindowTitle);
}

exept this is not giving me the same list as when you press alt-tab. For example: firefox, explorer, and iexplore all return an empty/null MainWindowTitle. Is there another way to access this list? Maybe thru a windowsAPI?
I'm am using Windows 7 32bit
Thank you in advanced.
Comment: possible duplicate of [Enumerate windows like alt-tab does](http://stackoverflow.com/questions/210504/enumerate-windows-like-alt-tab-does)
Comment: http://www.eggheadcafe.com/tutorials/csharp/cb972d77-0892-4bf7-834d-c23b6dd5c03a/c--get-the-all-running-processes-and-applications.aspx

it may help you
Comment: Also see the [accepted answer](http://stackoverflow.com/a/210519/21567) which references a blog entry of Raymond Chen, that gives details.
Answer: There are no hidden processes on Windows. Only processes you do not have (security) rights to see.
have a look at the below:
Retrieve a complete processes list using C#
Comment: I can see all the processes, but i cannot retreive the mainwindowtitle.
Answer: Try this (taken from here), but I'm not sure it solves your problem:
static void Main(string[] args)
{
    GetProcesses();
    GetApplications();
    Console.Read();
}
public static void GetProcesses()
{
    StringBuilder sb = new StringBuilder();
    ManagementClass MgmtClass = new ManagementClass("Win32_Process");

    foreach (ManagementObject mo in MgmtClass.GetInstances())
        Console.WriteLine("Name:" + mo["Name"] + "ID:" + mo["ProcessId"]);

    Console.WriteLine();
}

public static void GetApplications()
{
    StringBuilder sb = new StringBuilder();
    foreach (Process p in Process.GetProcesses("."))
        try
        {
            if (p.MainWindowTitle.Length > 0)
            {
                Console.WriteLine("Window Title:" + p.MainWindowTitle.ToString());
                Console.WriteLine("Process Name:" + p.ProcessName.ToString());
                Console.WriteLine("Window Handle:" + p.MainWindowHandle.ToString());
                Console.WriteLine("Memory Allocation:" + p.PrivateMemorySize64.ToString());
            }
        }
        catch { }
}

Comment: Thank you, but it doesn't solve my problem. I am seeing all the processes but the getapplications function only gives me one running program (its own process).


Menu de opções com botão direito do mouse em datagrid

Question: Estou precisando criar um menu com algumas opções para que, quando for selecionado um registro em uma datagrid e clicar com o botão direito sobre esse registro apareça um menu com as opções para aquele registro.
Comment: Sim e qual é a sua dúvida?
Comment: Como criar esse menu @ramaral
Answer: Para declarar um context menu para a sua GridView acrescente esse código à declaração dela:
<DataGrid.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Titulo do menu" Click="metodo_a_chamar">
            <MenuItem.Icon>
                <Image Width="12" Height="12" Source="caminho_da_imagem" />
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
</DataGrid.ContextMenu>

Acrescente um <MenuItem/> por cada item que o menu deva conter.
Veja mais na documentação.
Comment: Show de bola, em ajudando como sempre.Obrigado @ramaral
Comment: como faço para o menu aparecer quando eu selecionar apenas uma linha? Pois minha opção será de acordo com a linha selecionada (nesse meu caso, só quero acrescentar a opção para excluir apenas).
Comment: Para responder teria que fazer alguns testes, imagino como isso possa ser feito mas não tenho uma resposta pronta. Sugiro que crie uma nova pergunta, assim outras pessoas poderão também responder.
Comment: Fiz outra pergunta, de qualquer forma, muito obrigado!
Comment: Quando eu tiver tempo e se ninguém responder, eu respondo.


Converting XML using XSL (having nested tags)

Question: I have an XML something like...
<?xml version='1.0' encoding='utf-8'?>
<HL7Message>
    <MSH>
        <MSH.1>|</MSH.1>
        <MSH.2>^~\&</MSH.2>
        <MSH.3>
            <MSH.3.1>ST01</MSH.3.1>
        </MSH.3>
        <MSH.4>
            <MSH.4.1>A</MSH.4.1>
        </MSH.4>
        <MSH.5>
            <MSH.5.1>HC</MSH.5.1>
            <MSH.5.2>HC2</MSH.5.2>
        </MSH.5>
    </MSH>
</HL7Message>

which I want to convert into following format so that it can be accepted by solr..
<add>
<doc>
  <field name="MSH.1">|</field>
  <field name="MSH.2">^~\&</field>
  <field name="MSH.3.1">ST01</field>
  <field name="MSH.4.1">A</field>
  <field name="MSH.5.1">HC</field>
  <field name="MSH.5.2">HC2</field>
</doc>
</add>

Now I have created one XSLT as below..
<?xml version='1.0' encoding='utf-8'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*" />
<xsl:template match="MSH">
<add><doc>
<xsl:apply-templates select="MSH"/>
<xsl:for-each select="*">
<xsl:element name="field">

<xsl:attribute name="name"><xsl:value-of select="node()"/</xsl:attribute>
<xsl:value-of select="."/>
</xsl:element>

</xsl:for-each>
</doc></add>
</xsl:template>
</xsl:stylesheet>

but It is right now converting to following format..
<add>
<doc>
  <field name="MSH.1">|</field>
  <field name="MSH.2">^~\&</field>
  <field name="MSH.3">ST01</field>
  <field name="MSH.4">A</field>
  ***<field name="MSH.5">HCHC2</field>***
</doc>
</add>

as we can see MSH 5.1 and MSH 5.2 are getting combined which is other than I am expecting..
If anyone can help or guide me where I am making mistake, it would be greatly appreciated.. Thanks in advance.
Answer: Instead of selecting just the direct child elements of the MSH element, you should probably select any descendant elements which don't have any child elements themselves.
<xsl:for-each select=".//*[not(*)]">

So, this will select MSH.5.1 and MSH.5.2 for example, but not MSH.5 itself.
Try this XSLT (which I have also simplified with Attribute Value Templates to create the @name attribute)
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*" />

<xsl:template match="MSH">
  <add>
  <doc>
    <xsl:for-each select=".//*[not(*)]">
      <field name="{name()}">
        <xsl:value-of select="."/>
      </field>
    </xsl:for-each>
  </doc>
  </add>
</xsl:template>
</xsl:stylesheet>

Comment: this is just perfect. I really appreciate the help.


How do I redirect a controller to a particular vocabulary overview?

Question: I want to redirect my controller to a specific vocabulary page.
I redirect my controller using this code.
use Drupal\Core\Url;

public function importTypes() {
  $liste_types = $this->getListTypes();

    $batch = [
      'title' => t('Importation des types'),
      'operations' => [],
      'finished' => '\Drupal\zotero\Controller\ZoteroController::importOver',
    ];

    foreach ($liste_types as $type) {
      $batch['operations'][] = ['\Drupal\zotero\Controller\ZoteroController::create_term_from_zotero',[$type['localized']]];
    }

    batch_set($batch);
    return batch_process(\Url::fromInternalUri('admin/structure/taxonomy/manage/my_voca_id/overview'));
}

It throws this error.

Error: Class 'Url' not found
Answer: The error you are getting is because you are trying to access a method of the \Url class, but that class doesn't exist. The class you are trying to use is \Drupal\Core\Url, which is different from the \Url class. (Different namespace means different class.)
As you already added the use Drupal\Core\Url; line in your code, you just reference that class as in Url::fromInternalUri() (without \).
In your case, since you are already using an internal path, the last two lines of the code you are showing could simply be the following ones.
batch_set($batch);
return batch_process('admin/structure/taxonomy/manage/my_voca_id/overview');

In fact, batch_process() accepts two kinds of values, for the first parameter:

A path
A Url object

As example of call to batch_process() and redirect, see LocaleController::checkTranslation(), which a method of a controller defined from a module.
  $this->moduleHandler()->loadInclude('locale', 'inc', 'locale.compare');

  // Check translation status of all translatable project in all languages.
  // First we clear the cached list of projects. Although not strictly
  // necessary, this is helpful in case the project list is out of sync.
  locale_translation_flush_projects();
  locale_translation_check_projects();

  // Execute a batch if required. A batch is only used when remote files
  // are checked.
  if (batch_get()) {
    return batch_process('admin/reports/translations');
  }

  return $this->redirect('locale.translate_status');

Inside locale.routing.yml, you will notice that the path associated to the locale.translate_status route is /admin/reports/translations, the path passed to batch_process() in the code I am showing.
locale.translate_status:
  path: '/admin/reports/translations'
  defaults:
    _form: '\Drupal\locale\Form\TranslationStatusForm'
    _title: 'Available translation updates'
  requirements:
    _permission: 'translate interface'

Notice that, if you are calling batch_process(), you don't need to execute the redirect with the redirect() method of the controller. As you see in the code used from the Drupal core module, the call to $this->redirect() is necessary only if there isn't any batch to execute.
In your case, as you are adding the batch to execute in your controller method, the same method that calls batch_process(), checking the value returned from batch_get() is not necessary.


What exactly does "Enable Strict Checking of objc_msgSend Calls" mean?

Question: This is what I'm referring to:

From what I've read, an objc_msgSend is essentially what is happening at the c level when you send an Objective-C message, and this setting set to Yes ensures that the message being sent has the same number of arguments as the the receiver is expecting.
Is this correct? Also what are the advantages and disadvantages to setting this to Yes or No? Should I only set this to Yes in development and No in production?
Comment: Cocoapods has this enabled by default for each of its pods, so it seems. How can this be switched off by default?
Answer: You are essentially correct, yes.
Apple sets it to Yes by default because it helps to find errors faster.  The only reason to set it to No would be because you are compiling legacy code that hasn't been updated to compile cleanly with this option on.
"Enable Strict Checking of objc_msgSend Calls" is a compile time check, not run time, so there is no benefit to turning it off in production.
Answer: There's a presentation "What's new in LLVM" on Apple's website (text of the presentation is here).
It looks like the compiler will now (optionally) strictly check the types of calls to obj_msgSend. You will have use a correctly-typed function pointer in place of directly calling objc_msgSend.
Example given:
#include <objc/message.h>
void foo(void *object) {
  typedef void (*send_type)(void *, SEL, int);
  send_type func = (send_type)objc_msgSend;
  func(object, sel_getUid("foo:"), 5);
}

Comment: wasn't me! I was actually wondering where that presentation was because I saw the slides and there were a little useless without someone explaining them.
Comment: yes, I get that--the text of the presentation is transcribed on the second link. You should also be able to view the original presentation via the WWDC site.


UseDispatch() dentro de um useEffect() -> *missing dependency*

Question: ALERTA: React Hook useEffect has a missing dependency: 'dispatcher'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

import React, {useEffect} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import ACTION from './Action'

const App = () => {

  const dispatch = useDispatch();
  const REDUCER_USUARIOS = useSelector(state => state.ReducerUsuarios)

  //Estou usando como componentDidMount()
  useEffect(() => {
   dispatch(ACTION.CARREGAR())
  }, [])

  console.log(REDUCER_USUARIOS)

  return
TEST

}

OBS: Estou usando React(version:16.12) e React-Redux(version:7.1.3) com Hooks.
Answer: O alerta é dado pois a função dispatch não está no array de dependência do useEffect.
Para solucionar precisa deixar desta forma
 useEffect(() => {
    dispatch(ACTION.CARREGAR())
 }, [dispatch])

Comment: Valeu Vicenzo! era isso mesmo.


Index indefinida quando desloga

Question: Fiz um teste e coloquei uma forma de identificar quando o usuário está logado no site, e esse está funcionando numa boa. Mas quando eu me deslogo e vou na index, que é a página que pus o código, aparece o erro

Notice: Undefined index: nivel in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\site tcc\index.php on line 5

Queria saber um modo de tirar isso quando estiver deslogado, e só aparecer a mensagem que eu coloquei para os usuários que fizeram o login. Código que eu usei
<?php
session_start();
include "php/conexao.php";

if($_SESSION['nivel'] == "admin" ||  $_SESSION['nivel']== "usuario"){
echo "oi logado";
}
?>

Answer: Você pode utilizar o isset() para verificar se existe o index 'nivel' na sessão. Dessa forma ele não vai gerar um erro caso não exista.

if(isset($_SESSION['nivel'])){
  echo "oi logado";
}
?>

Comment: Obrigada, era isso mesmo!!
Comment: Que bom!! De nada!

Index indefinida quando desloga


Prove that every isometry on $\mathbb{R}^2$ is bijective

Question: Let $d(x,y)=\sqrt{(x_1-y_1)^2+(x_2-y_2)^2}$ for $x=(x_1,x_2), y=(y_1,y_2)$.
A isometry of $\mathbb{R^2}$ is an image $f:\mathbb{R^2}\to\mathbb{R^2}:d(x,y)=d(f(x),f(y))$. Show that every isometry is bijective. I don't know where to start, any hints ?
Comment: Showing that $f$ is injective is trivial. For surjectivity, see [this post](http://math.stackexchange.com/questions/36502/isometries-of-mathbbrn).
Comment: every isometry from $\mathbb R^2 \to \mathbb R^2$? Because in general ismometry is only injective.
Answer: Let $ABC$ be the triangle with vertices $(1,0)$, $(0,1)$, and $(0,0)$. Let $f$ be an isometry as defined in the post. Suppose $f$ takes $A$, $B$, and $C$ to $A'$, $B'$, and $C'$.
There is a combination $\phi$ of rotation and/or reflection and/or translation that takes $ABC$ to $A'B'C'$.  Then $\phi^{-1}\circ f$ is an isometry as defined in the post. Note that it leaves $A$, $B$, and $C$ fixed.
Given an unknown point $P=(x,y)$, if we know the distances from $P$ to $A$, $B$, and $C$, we know $x$ and $y$.  Since  $\phi^{-1}\circ f$ fixes $A$, $B$, and $C$, it is the identity. Thus $f=\phi$.
Rotations, reflections, and translations are surjective, and therefore $f$ is.
Comment: This is beautifully geometric.
Comment: There are many proofs, with many flavours. For pure geometry, the start should have been a *general* triangle, but I thought the one with the familiar corners would make the visualization easier
Comment: It took me some time to understand, but it was worth it :) Thanks for this enlightening post :)
Answer: You can show, that every isometry on a finite dimensional hilbertspace is affine linear. So with the fact, that every isometry is injective you get the bijection.
Comment: Generally affine, linear in case $f(0)=0$.
Comment: @JonasMeyer: apparently in some parts what you and I call "affine" are called "affine linear". For example: http://www2.stetson.edu/~mhale/linalg2/index.htm or even, gasp!, [nLab](http://ncatlab.org/nlab/show/affine+space).
Answer: If you assume $f(0) = 0$, in the $2$-dimensional case you can show surjectivity by observing that circles are mapped to themselves:
For any $x ∈ ℝ^2$ with $\lVert x \rVert = r$, since $d(f(x)),0) \overset{f(0) = 0}{=} d(x,0) = r$, you have $f(rS_1) \subseteq rS_1$.
Now you can show that an injective continuous map $f \colon S_1 → S_1$ is bijective:
Since $S_1$ is compact and $\operatorname{img}(f) \subseteq S_1$ is hausdorff, $f$ maps homeomorphically to $\operatorname{img}(f)$.
If $\operatorname{img}(f) ≠ S_1$, say $a \notin \operatorname{img} (f)$, then – as a connected space – it's homeo-morphic to an interval since $\operatorname{img}(f) \subseteq (S_1\setminus\{a\}) \underset{ae^{2πit}}{\cong} (0..1)$, which is a contradiction.
Answer: To prove it is injective, you want to show that if $f(x)=f(y)$, then $x=y$.
If $f(x)=f(y)$, then what is $d(f(x),f(y))$ ? What is $d(x,y)$ equal to ? What can you then say about $x$ and $y$ ?
Comment: Aaaah, I got. Thanks. $f(x)=f(y) \implies d(f(x),f(y))=0 \implies d(x,y)=0 \implies x=y$.
Comment: Yes that's it !
Comment: Any hint for showing it is surjective ?
Comment: as i told you every isometry is affine linear, if you have 2 times 2 matrix with rank 2, (because of the injective) you get the bijection
Comment: If someone has another proof, I am interested in that.
Comment: @user62705 with knowing that every isometry is affine linear  you easily show, that the absolute value of the  determinant of such a matrix is 1 and so it is a bijection.


Bad Request 400 - Usando API Fetch

Question: Estou com problemas ao acessar minha api usando POST method.
Esta é minha requisição:
function createTool(token, obj) {
  return fetch(`${url}/tools`, {
    method: 'POST',
    headers: {
      Authorization: token,
    },
    body: JSON.stringify(obj),
  })
    .then(async (response) => await response.json());
}

Esta é a resposta do meu back-end:
XHRPOSThttp://localhost:3000/tools
[HTTP/1.1 400 Bad Request 17ms]
    error   "Field 'title' doesn't have a default value"

Em meu console o Back-End retorna a execução corretamente. Porém, o objeto de inserção está vazio.
Executing (default): INSERT INTO `tools` (`id`) VALUES (DEFAULT);

Onde estou cometendo o erro ao passar o valores?
Comment: essa exception está vindo do próprio sql, sua tabela 'tools' tem o campo 'title' non nullable, está tentando inserir nulo e ela está avisando que não tem um valor default pra preencher
Comment: Todas as vezes que eu tive esse problema de chegar no back o objeto vazio, foi que o objeto que o back está preparado pra receber não está igual o que o front está enviando. Tipo, às vezes o front envia um campo cnpj em string, e o back recebe em int. Ou vice versa. Reveja seu objeto toos e as tipagens deles, em relação ao objeto que o back recebe e as tipagens.
int, tem que receber int, string com string, e assim sucessivamente.
Comment: Me parece que não é possível reproduzir o problema somente com essas informações, qual o banco de dados utilizado? Qual seu schema? Como o back-end trata a requisição? Talvez editar sua pergunta com essas informações te ajude com a ter uma resposta, veja mais em [mcve]
Answer: Consegui resolver especificando o tipo do arquivo do recurso em meu header.
A requisição ficou assim:
function createTool(token, tool) {
  return fetch(`${url}/tools`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',u
      Authorization: token,
    },
    body: JSON.stringify(tool),
  })
    .then(async (response) => await response.json());
}

Agradeço pelas dicas no comentários.

Bad Request 400 - Usando API Fetch


Having issues with isDragging attribute in dnd

Question: I use typescript for my project. I am trying to make some css effect (color change while dragging) while dragging a column. But I am getting errors while using isDragging attribute. Could any help me sort it out?
The error is: Property 'isDragging' does not exist on type 'DetailedHTMLProps
I know I am attempting to add the attribute isDragging to div. That is not a supported attribute for HTMLElement. That is why it gives such an error.
My question is how can I make it workable for my code.
Answer: You could use data attributes instead.
For example it could become:
<code>...
<div ... data-dragging={snapshot.isDragging}>
   ...
</div>
...
</code>
and then match it with CSS:
<code>[data-dragging="true"] {
  /* your styles */
}
</code>

Super simple example: https://stackblitz.com/edit/react-dpfmdi?file=src/App.js (click the paragraph)


Formatting getDate() in JavaScript

Question: I have been playing around with this JavaScript to get the right format on my date output, but with no luck. I need this code to show as Month Day, Year. As of now it's showing dd/mm/yy.
Below is the script I'm using.

Comment: See [MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Methods) for reference on all `Date` object methods.
Answer: Here is a modification of another post here on Stack Overflow. I think this will do what you want.
var tD = new Date();
var monthNames = [ "January", "February", "March", "April", "May", "June",
   "July", "August", "September", "October", "November", "December" ];
var datestr = monthNames[tD.getMonth()] + " " + tD.getDate()  + ", " + tD.getFullYear();
document.write("<input type='hidden' name='date' value='"+datestr+"'>");

Comment: @Robin Because that post doesn't do exactly what the OP wanted. I wanted to be more helpful by giving him exactly the code he should use, and because link-only posts are discouraged even if there just links to other posts. See http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers.
Comment: Why not just link to the post? :)
Comment: freaking awesome this worked perfectly. thats why you guys are the experts.
Answer: I don't really get it. Is this, what you're looking for?

Formatting getDate() in JavaScript


React-Native "undefined is not a function" error when sending a post request from client

Question: Server side code is working properly as I have tested it with thunderclient/postman, and have received the correct response from the external api (fyi, the external api is an api managed by the Department of Veterans Affairs). I have scoured my client side code but cannot locate the issue. The issue is that every time I send the post request from my client, I get the error "undefined is not a function". Here is my client side code (the relevant parts anyway - fyi, personal data included is dummy data provided by the DVA for dev purposes and is not confidential)... "
import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, ScrollView } from 'react-native';

const axios = require('axios');
import PhoneInput from 'react-native-phone-input';

export default function  FormScreen({ navigation }) {

  const [firstName, setFirstName] = useState('Alfredo');
  const [middleName, setMiddleName] = useState('M');
  const [lastName, setLastName] = useState('Armstrong');
  const [gender, setGender] = useState('M');
  const [birthDate, setBirthDate] = useState('1993-06-08');
  const [zipCode, setZipCode] = useState('78664');
  const [birthPlaceCity, setBirthPlaceCity] = useState('Johnson City');
  const [homePhoneNumber, setHomePhoneNumber] = useState('555-555-5555');

  const [streetAddressLine1, setStreetAddressLine1] = useState('17020 Tortoise St')
  const [city, setCity] = useState('Round Rock')
  const [state, setState] = useState('TX')
  const [country, setCountry] = useState('USA')
  const [mothersMaidenName, setMothersMaidenName] = useState('Smith')
  const [birthPlaceState, setBirthPlaceState] = useState('MA')
  const [birthPlaceCountry, setbirthPlaceCountry] = useState('USA')

  const handleSubmit = async () => {
    const formData = {
      firstName,
      lastName,
      birthDate,
      middleName,
      gender,
      streetAddressLine1,
      city,
      zipCode,
      state,
      country,
      homePhoneNumber,
      mothersMaidenName,
      birthPlaceCity,
      birthPlaceState,
      birthPlaceCountry
    };

  const postURL = 'http://10.0.0.130:3500/VetVERIFICATION/VerificationPayload'

   try {
    const response = await axios.post(postURL, formData);
    console.log('API Response:', response.data);
   } catch (error) {
    console.error('API Error:', error);
    console.log(formData)
   }

  };

  return (
    <(some code)>
    <View>
        <TouchableOpacity onPress={handleSubmit} style={styles.button}>
            <Text style={styles.buttonText}>Submit</Text>
        </TouchableOpacity>
    </View>
    <View style={styles.introContainer}>
        <Text style={styles.introText}>If you are having trouble verifying your
            Veteran status here, please visit your VA.gov account to change or confirm
            the data on file. MILVETCOM does not store any of the data you provide in this form.
        </Text>
    </View>
    <(some closing tags)/>
  );
 };

Again, every time I press the 'Submit' button, the handleSubmit function is called. But it ALWAYS returns an error response "undefined is not a function", regardless of the fact that server-side testing returns the correct response.
I have tried

checking the format of my formData const and it works (I console.logged that info, copied it, and pasted it in postman/thunderclient and it worked just fine from the backend.
checked my postURL to ensure it was correct. It is. And, again, this same url works when tested from the server-side
Asked ChatGPT about every question I could think of and in every possible way. By the way, is AI so good that it can actually become annoyed with a person?
Answer: Change

const axios = require('axios');

to:

import axios from 'axios'
Comment: YES! That fixed it. Obviously. I knew it was going to be something embarrassing like that but thank you. Sometimes when we check our code our own eyes see what they want. A second set of eyes is a huge help.


What is the amount of certainty in this yes/no test?

Question: A child must learn a poem by heart. The poem has 200 lines. To test the child, the teacher asks the child to complete ten lines of the poem given the first half of the sentence. If the child gets, say, seven lines correct, the teacher assumes that the child knows 140 lines of the poem correctly.
What is the uncertainty in the teacher's guess of the child's knowledge?
In general, given $n$ things to learn, which may be either right or wrong, what uncertainty is associated with a test which tests $m$ of them?
Comment: I don't see this as learning n things and testing m, since the m lines are consecutive -- and poetry is learned consecutively. I see it as chunking the poem into n/m chunks. You pick one chunk at random. If I were the teacher, I would have more confidence if I started the child near the end of the poem, rather than the beginning.
Comment: Where does it say that the lines tested are consecutive?
Comment: Is this homework? If so, it should have the homework tag.
Answer: This question is formally similar to another one posted recently.
Let $\hat{n}$ denote the number of lines the student actually knows, and let $\theta = \hat{n}/n$ denote the true underlying fraction of the total poem that the student has memorized. Let $\hat{m}$ be the number of questions the student answers correctly when tested on $m$ lines of the poem.  The challenge is to estimate $\theta$ and to provide a measure of the uncertainty in this estimate, as a function of $\hat{m}$ and $m$.
Assuming that the teacher chooses lines from the poem at random, and doesn't ask the student about the same line twice, the experimental procedure here involves random sampling without replacement. However, assuming that $m << n$, one may simplify by treating the situation as one of sampling with replacement, and still get approximately correct results.  (To be more statistically careful, the teacher could allow for repeated tests of the same line.)
Assuming the teacher's selection of lines are truly random, the line-tests may be treated as a sequence of independent, identically distributed Bernoulli trials. For a given success rate $\theta$, the student's total score $\hat{m}$ has a [binomial distribution][2] with probability mass function

$f(k \mid \theta) = \Pr[\hat{m} = k \mid \theta] = {m \choose k}\, \theta^k (1-\theta)^{m-k}$

where $k \in \{0,1, \ldots, m\}$. A probability distribution over $\theta$ can be derived using Bayes' Theorem:

$f(\theta \mid k) = f(k \mid \theta)\cdot f(\theta) \, / \, \sum_j f(j \mid \theta)$

where $j = 0, 1, \ldots, n$.
Here $f(\theta)$ represents the test administrator's prior beliefs about the likely values of $\theta$, before performing your first test. Based on the set-up, it seems as if there should be no prior information used, and so one should represent beliefs with a uniform distribution: $f(\theta)=1$.
Using Bayes' Theorem together with the formula for the binomial distribution, one may compute the posterior distribution $f(\theta \mid k=\hat{m})$ of $\theta$. This will be a Beta distribution with paramaters that depend on $\hat{m}$ and $m$. One may express the uncertainty in the estimate of $\theta$ in terms of the cumulative mass function of the Beta distribution.