After what number N, would we know X is prime if X is not divisible by any integer 2 to N?

Question: So I'm making a program where I input a number, and it determines whether that number is prime or not. The method determining whether it is prime or not is determining if it is divisible by 2, it knows it is not prime. If it isn't, it tests if it is divisible by 3... and so on until it tests if it is divisible by X-1 which if it isn't, it then concludes that the number is prime. The problem with this method is that it is extremely slow. I soon realized that I could save time by setting N as half of X or 1/3 or 1/4 or 1/5... of x because, throughout the process, we would have tested 1-5..., and since it can only be divided by whole numbers, if N is set to anything higher than 1/5... of X, the second factor that multiplies with N to make X, can only go down to other numbers that the program already tested for.
So my problem is this: I want to optimize my program so that it tests the least amount of possible factors before determining whether X is prime. I need to minimize N so that knowing that X is not divisible by 2 through N, we can determe that X is prime.
Comment: The Javascript factoriser at http://www.se16.info/js/factor.htm does this, stopping at $\sqrt{X}$ when finding the last prime
Comment: @Henry But that takes away the fun of getting to make it yourself.
Answer: If $X$ is not prime, then it has a prime divisor less than or equal to its square root.  To check if $X$ is prime, try to divide by all primes up to $\sqrt{X}$.  There's no need to check for division by $4$ or $6$ or any other composite number, because if say $6$ divides the number, so does $2$ and $3$ and you've already checked those.


Generating an absolute node URL from its node id

Question: I think the question is self explanatory. I got a node ID and I need to create its absolute URL somehow. I can do this but (I think) this won't work every where in the site:
Node Title

Please correct me if I am wrong.
Is there a function that I can give the node id and returns me back the absolute path of it?
Answer: Drupal 8
$nid = 5;
// Or $nid = $node->id();
$node_title = 'Node Title'
// Or $node->getTitle();

Create absolute URL:
// Will output http://example.com/path-to-my-node
$options = ['absolute' => TRUE];
$url_object = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ url_object }}.
// In PHP (outside a render array) use $url_object->toString().

Create absolute link object (and inner span):
// Will output Node Title
$options = ['absolute' => TRUE, 'attributes' => ['class' => 'this-class']];
$node_title = \Drupal\Core\Render\Markup::create('' . $node_title . '');
$link_object = \Drupal\Core\Link::createFromRoute($node_title, 'entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ link_object }}.
// In PHP (outside a render array) use $link_object->toString().

Answer: Yes, the url() function:
$url = url("node/$nid");

Comment: It partially worked. I have written exactly what you wrote, but in my address bar it doesn't show the node id. I get this `?q=node/`
Comment: Ohh sorry! My bad. I mis calculated something. I fixed this. Thanks a lot :)
Answer: In Drupal 8 you can use toLink function if you already load the node to generate an absolute link.
$event = \Drupal::entityTypeManager()->getStorage('node')->load($event_id);
if (!$event)
  return false;

// add ->toString() or other if needed
$abs_link = $event->toLink(NULL, 'canonical', ['absolute' => true]);

For example.
This solution use same principle that previous answers but its seems to me more practical if you need other info from this node or if the node is already loaded.
Answer: Yes, the l() function:
$link = l("Node Title", $nid);
print $link;

Above code, prints the following output:

Node Title

If you want to get absolute URL as you stated in your question:
$link = l('Node Title', $nid, array('absolute' => TRUE));

which will generate the link like:

Node Title
Comment: Good answer BUT to be honest it doesn't really answers question as asked. Would be good if you could add some info why op actually wants to use something else than he wrote.
Answer: Drupal 7
You can get path alias using drupal_get_path_alias()
it will return:

An aliased path if one was found, or the original path if no alias was found.

This function will give you pretty path if it is created by admin or by pathauto module. After that you can use path alias to build absolute url.
There are many ways to do that, you can use url() or l() or you can even use dirtier approach and concatenate global $base_url to path alias which will give you just absolute url as a string and print it in whatever template you want.
using drupal_get_path_alias:
$path_alias = drupal_get_path_alias("node/{node_id}", $language_code);

Drupal 8
There are not above functions in Drupal 8 but you can do same using path.alias service.
e.g.
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);

More
Please check this link for more information on both versions
Comment: In d8, this will not generate an absolute url.
Answer: Drupal 9
$entity->toUrl('canonical', ['absolute' => TRUE])->toString();

Comment: The OP only has the `nid`, so it would be good to include the step for loading of the entity to this answer.
Answer: Drupal 9
Best practice is the AliasManager service: path_alias.manager
$alias = \Drupal::service('path_alias.manager')->getAliasByPath('/node/' . $nid);


Postback cause browser confirmation before refreshing (F5)

Question: When I do a postback, why the browser always ask me a confirmation before refreshing ? (F5 / CTRL + F5)
My code is really simple (I use a master page) :
.aspx
...
<asp:button runat="server" ClientIDMode="static" type="button" id="btnlogin"
                  OnClientClick="return veriflogin();" class="btn btn-primary" Text="Valider"
                  onclick="btnlogin_Click"></asp:button>

<asp:Label ID="ok" runat="server" Visible="false" Text="allright"></asp:Label>
...

.cs
protected void btnlogin_Click(object sender, EventArgs e)
{
    ok.Visible = true;
}

The confirmation (IE):

Can I avoid this confirmation ?
Comment: When you refresh that page, you execute the Postback again. This message warns about potential problems with that. See also [Post/Redirect/Get](http://en.wikipedia.org/wiki/Post/Redirect/Get)
Comment: the browser does that automatically, it's normal behavior
Comment: You can't avoid this confirmation because its managed by your browser itself. Like Jonesy said its normal behavior.
Answer: Postback occurs (as name suggests) using POST HTTP verb.  POST by definition is not idempotent, and thus repeating the same request is not necessarily safe.  In other words, repeating POST may result in different end result than doing it once.  Hence the browser warns you that in order to retrieve the page again, it has to repeat POST operation which may have unintended consequences.
For example, in RESTful applications, POST implies "create" (as in CRUD, akin to SQL's INSERT) a resource.  Executing POST twice means two instances of the resource will be created rather than one.  Compare it with GET which is a read operation, and reading the same resource more than once does not affect the state of the resource(s), and is thus considered safe (because GET is idempotent)
Comment: So can I make my button click to use GET method to avoid this ?
Comment: @VincP. buttons that calls back to the server are per definition postbacks. You should probably rethink how you want to authenticate the user.
Comment: @VincP. IIRC (been awhile), ASP.NET WebForms uses one single form and any action that causes callback to server must submit the form (so all the form state is passed in with the request) and the form is `POST`. If instead of rendering the form back, you can do `.Redirect` (which browser follows up on with a `GET`), then this should remove that warning (but there are implications since viewstate is lost).  But I hope others can lend a better suggestion as it's been a long while ago since I did WebForms.
Comment: Ty, I agree, postback = post. I forgot that. Now it is clear. Ty for the suggestion. But I was wondering if I could do something, but it look like I can't ! (With this method)
Comment: @VincP. This is a login form, right?  After user is authenticated, how do you transfer user to the next page?  Can you transition via `.Redirect`?  If so, this may do it for you.
Comment: Yes, I will probably do that. But I wanted to understand why the browser ask a confirmation. It will be useful to understand how it works. TY
Answer: No, you can't avoid the confirmation.
If your last action on a site was a POST, most browsers will ask for a confirmation on whether you want to refresh the site with the same POST again. That's intended behavior.
POST requests are intended to modify state in one way or another. That's why your browser warns you. GET requests should not modify state, and are therefore considered "safe" to resubmit.


How to send Shipping Cost to paypal from cart

Question: I'm trying to send the Shipping amount of the cart to paypal. Paypal is not receiving the amount of  an entire cart, but it will work if I do the shipping on each item in the cart. Has anyone successfully sent the shipping amount of an entire cart to paypal and not foreach line item?
Here is what I've tried:
<code>    @Html.Hidden("cmd", "_cart")
    @Html.Hidden("upload", "1")
    @Html.Hidden("business", ConfigurationManager.AppSettings["BusinessAccountKey"])

    @Html.Hidden("first_name", Model.UserShippingInfo.FirstName)
    @Html.Hidden("last_name", Model.UserShippingInfo.LastName)
    @Html.Hidden("address1", Model.UserShippingInfo.Address)
    @Html.Hidden("city", Model.UserShippingInfo.City)
    @Html.Hidden("state", Model.UserShippingInfo.State)
    @Html.Hidden("zip", Model.UserShippingInfo.Zip)
    @Html.Hidden("shipping", @shippingCost.ToString("N2"))
    @Html.Hidden("amount", @totalCost.ToString("N2"))

    @foreach (CartLine item in Model.Cart.Lines)
    {

        @Html.Hidden("item_name_" + itemCount, item.Product.Name)
        @Html.Hidden("item_number_" + itemCount, item.Product.ProductID)
        @Html.Hidden("amount_" + itemCount, item.Product.Price.ToString("N2"))
        @Html.Hidden("quantity_" + itemCount, item.Quantity)
@*      @Html.Hidden("shipping_" + count, item.Product.Price.ToString())
        @Html.Hidden("handling_" + count, 0)*@

        itemCount++;
    }
</code>
Answer: I found a solution. If I use the 'handling_cart' variable it works.
<code>@Html.Hidden("handling_cart", @shippingCost.ToString("N2"))
</code>
is this the correct way to approach it for a cart?


What's the difference between outlier analysis and clustering?

Question: What's the difference between outlier analysis and clustering?
When clustering is done isn't that outliers (if exist) are also found?
Answer: No, clustering creates a pre-defined number of clusters $k$, so all "outliers" will end up in in one of these "common" clusters. If you increase $k$ you may eventually be able to form some clusters, which are far off from the other clusters, and hence find some "outliers", however there is no guarantee for this. Also if you have only a small amount of "outliers" then the algorithm probably won't cluster these in their own clusters but rather join them in some other bigger cluster.
Probably the best option would be hierarchical clustering with single linkage, as this would create a hierarchical structure based on distance, from where you could find some very distant branches based on plots, but still this is not what it was intended for.
Comment: Not all clustering methods require the number of clusters to be predetermined.
Comment: @whuber Are you referring to methods where you select the number of clusters based on some criterion?
Comment: Yes--and that would include methods to identify an arbitrary number of outliers.


Using entity form display modes

Question: I have created a custom form display mode my_mode for nodes and wish to display node form using this mode instead of default one at a custom page. How can I do it?
$this->entityFormBuilder()->getForm() accepts an operation as a parameter, but not form mode.
Answer: Form modes and form operations are a bit strange. You also need to define a form operation through hook_entity_type_alter() to be able to use a custom form mode.
Which makes the UI to create form modes pretty useless, but ssshh, don't tell anyone :)
For an example, see views_ui_entity_type_build(): $entity_type->setFormClass($operation, $class_name)
Comment: Where did you read it? Is there any documentation with details how it should be done?
Comment: I didn't read it, I know it as I participated in the relevant issues. Updated the answer with references to an example.
Comment: http://lobsterr.me/post/how-render-programatically-custom-entity-form-mode-drupal provides a comprehensive explanation how it can be done.
Answer: Indeed it is quite strange I find to have both operation and form display, but you do not especially need to have a form operation to use your display. You have to use hook_entity_type_alter though...
Here is the way for example to load the "super" form mode (if exists and is activated) :
/**
 * Implements hook_entity_form_display_alter().
 */
function my_module_entity_form_display_alter(&$form_display, $context) {

  // Load the right entity form display.
  $id = $context['entity_type'] . '.' . $context['bundle'] . '.super';
  $storage = \Drupal::entityManager()->getStorage('entity_form_display');
  $change_display = $storage->load($id);

  // If form mode is activated, replace the given one with ours.
  if ($change_display) {
    $form_display = $change_display;
  }
}

Using entity form display modes


Programmatically displaying a view into a colorbox

Question: Love the module. My use case is to take programatically take the result of a view and load it into a colorbox. I can use views_get_view or views_embed_view to get a result array or a large html string. But how can I pass that to the colorbox?
Any help is greatly appreciated.
https://drupal.org/node/1991948
Comment: Welcome to stack exchange.
Comment: Any tips on how to Set the Image Format To Colorbox? @Sam152
Answer: Put your view into a div with a wrapper that is hidden (ie, display:none;). Then you can use the following javascript:
$.colorbox({
    'inline' : true,
    'href' : $('.views-view-my-view'),
});

You must replace the 'href' attribute with the appropriate jQuery collection representing your view. Other customisations to the way your colorbox appears can be found here.
If you need some advice on placing a view on your page, here is a clean implementation:
function MODULE_preprocess_page(&$vars) {
  $vars['page']['bottom']['my_view'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'my-view-container',
    ),
    'children' => array(
      '#markup' => views_embed_view(...),
    ),
  );
}

In this case your selector for colorbox would be #my-view-container .view


graphical lasso with known precision matrix structure

Question: I wonder if there is a way to estimate the precision matrix when certain elements are restricted to be zero?
Suppose data are from $N(\mu,\Omega)$, where $\Omega=V^{-1}$, i.e. the precision matrix. Suppose we know that $\Omega_{i,j}=0$, $i\neq j\in\{1,2,\dots,p\}$, where $p$ is number of variables. Note, sample size $n$ may be less than $p$.
How do we estimate $\Omega$ when we restrict $\Omega_{i,j}$'s to be zero? Can this be done in R?
I understand that this post has a similar discussion. However, it penalizes $\Omega_{i,j}$ but not set it to be zero.
Comment: As I understand, you question concerns sparse inverse covariance matrix estimation where the sparsity structure is known. There is a wealth of literature on this problem recast as structure learning of a Gaussian graphical model, but I couldn't find very much on how to encode a *known* sparsity structure, probably because it is arguably an easier problem. The following is a related question, but I can't vouch for the references: https://stats.stackexchange.com/questions/34502/estimating-a-sparse-inverse-covariance-matrix-with-known-sparsity
Comment: The source in my view that addresses your problem directly are the following 2019 Wald Lecture slides given by Trevor Hastie here: https://web.stanford.edu/~hastie/TALKS/wald_III.pdf. See slide 11 onwards *"Solving for $\Theta$ when zero structure is known"*. In that case it looks like you just use constrained optimisation methods and some modification of co-ordinate descent.
Answer: Would "pathway graphical lasso" be suitable for your case?
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4497513/


If a toy car moves down a ramp, would the speed be constant?

Question: When it moves down a declining ramp, would the speed of the toy car be constant? If not, what would the distance/time graph look like? (distance as in the distance the car moved)
Comment: Depends. What's the angle of the ramp? Incline or decline? Starting velocity? Height of the ramp? This question needs a lot more details
Comment: If the speed were constant (no acceleration at all), this means that if it were stationary, it would remain stationary.  This isn't the case though, so there must be a nonzero acceleration.  This agrees with everyday intuition (imagine going down a hill on a bicycle without peddling).
Comment: Assuming, of course, that the ramp is a decline (I think it is, given "moving down a ramp").
Comment: Sorry. I added decline to clarify the situation.
Comment: This is not a mathematical cuestión, as far as I can tell.
Answer: No. A car going down a slope experiences an acceleration of $g \cos{\theta}$, where $g$ is the strength of the near-constant gravitational field on Earth and $\theta$ is the angle of the slope. By integration the car must have a speed of $gt \cos{\theta}$. By integration once more (assuming the car starts with no velocity and at the top of the ramp) the car must be displaced by $\frac{1}{2} gt^2 \cos{\theta}$.
The graph of distance versus time would look like a parabola.
Comment: The acceleration is constant. The magnitude of the velocity, however, does increase over time, and it increases linearly.
Comment: Eh... In layman's terms? So it accelerates quicker and quicker right?
Comment: If the ramp is a decline, it accelerates because of gravity. You might have heard of it
Comment: distance versus time - What do you mean by distance?
Comment: The amount of meters/feet the car travels down the ramp.
Comment: Why would it be a parabola???
Comment: Because $\frac{1}{2}(g \cos{\theta}) t^2$ is the graph of a parabola. How did I get this function? By taking the integral twice.

https://en.wikipedia.org/wiki/Integral
Answer: If the car starts at rest, but is moving by the end of the ramp, then its speed was not constant.


Correlating web request latency with temporal density

Question: I'm trying to analyze a series of request on our web server. I have the latency of each request with the associated timestamp that the request was made.
What I suspect is that higher latencies occur when requests are clustered in time, but I'm not sure about what the timescale even is. It could be requests made within a 5s, 1s, or even 1ms window.
I put together a rudimentary python script to use a sliding window to calculate the request density and compare that with the current latency but even as I tweaked the window size between a few milliseconds and several seconds I couldn't see any obvious correlation.
Crucially, I think the problem is that I don't know what the time period of the latency/request density is, and therefore how big to make my window.
Am I barking up the wrong tree? Or does my method sound roughly correct, suggesting there is no correlation?
Some people have asked for sample data, so I've uploaded some here
Comment: To get useful answers you have to provide example data, otherwise you are just getting confirmation of your own analysis
Comment: The method seems fine to me, but hopefully someone can come along with experience in this domain and provide a more authoritative answer.
Comment: Your method sounds OK to me, though as above sample data would help. At some point you have to trust your data, and if you have tried your analysis with a variety of time windows you might genuinely have a null result.  You might also consider recording, for each request at the time it was made, how many other requests were still outstanding as an alternative measure of request density. That gets around the time-window-sizing issue somewhat.
Comment: Thanks for your inputs - I've uploaded sample data above
Comment: Dave the sample data needs to be regenerated eg 16.607601s,1.47E+09
Comment: @seanv507 Yeah sorry this data is annoying to use in excel thanks to the string formatting. I've been using python to scrape it though and I can work around it there
Answer: Your methodology sounds OK, but it is entirely possible that no matter the size of your window, you may still find that there is no signal produced by the higher amount of requests. Some backgound:
Web servers often rely on a pool of backend available process threads that run very far under the surface of the application (to the point of not 100% transparent in logs). Often, web servers are so efficient and well-tuned that they rarely max their out under normal circumstances. This is a good thing - running a server with sub-optimal resources would be like driving your car on empty and only ever refueling to get to the next gas station! And as such, it's likely that you'll never be able to find any really strong evidence to prove a point by parsing your logs in this way...
What may be more effective is to use a service like Locust to load-test your app and then gather statistics this way. Loadtest is another available on NPM. These kinds of applications can help you find the numerical limits of your application in a sandboxed environment, which can be really nice for finding out where your run out of gas, keeping with the car analogy.
Comment: Thanks Derek. In our particular case the problem is (was) that we were trying to do run some pretty complex algorithms in the space of a web request. The heavy number crunching and potential for GIL-hogging/swapping (Python) I believe were to blame for overlapping requests becoming very slow. Have solved it since by moving this into a micro-service and using a more performant language.


Check leverage phenomenon on ARCH-GARCH models in R

Question: I estimated an ARCH(10) and a GARCH(1,1) models on R. I have to verify the presence of leverage phenomenon, graphically or descriptive evidence. Leverage effect: volatility reacts asymmetrically to the changes in prices (i.e. usually in stock returns the volatility increases more after bad news than after good news).
How can I test it?
Comment: If you give us the definition of the phenomenon (i.e. what is meant by leverage), it will be easier to suggest a formal or informal test for evaluating it.
Comment: Leverage effect: volatility reacts asymmetrically to the changes in prices (i.e. usually in stock returns the volatility increases more after bad news than after good news).
Comment: I do not remember if vanilla ARCH and GARCH models are capable of accounting for leverage. There are models like GJR-GARCH that are more suitable for that. One idea for now: collect all the instances of bad news and the volatilities of the following periods; do the same with the good news. Compare the distribution of the former volatilities with that of the latter volatilities. The differences in the distributions can be informative of the leverage effect (you would look for difference in location of the distributions).
Answer: I do not remember if vanilla ARCH and GARCH models are capable of accounting for leverage. At least directly they are not (there is no parameter tied specifically to leverage), but there are models like GJR-GARCH that are more suitable for that.
An idea: collect all the instances of bad news and the volatilities of the following periods; do the same with the good news. Compare the distribution of the former volatilities with that of the latter volatilities. The differences in the distributions can be informative of the leverage effect (you would look for difference in location of the distributions). Use a formal test, e.g. something like a $t$-test or rather a version that is robust to nonnormality of volatilities, to test whether the means of the two distributions are equal. One problem will be that volatilites are not observed, just estimated, so the observations are noisy proxies for the real volatilities, and you cannot take the test results at their face value.
Another idea: use a GJR-GARCH model and see (test) if the leverage parameter is estimated at zero.
Comment: thank you very much
Comment: @RobertoRosina, you are welcome!


How to interpret the DHARMa quantile residual plot?

Question: We calculated a GLMM based on the beta distribution:
model_dur_red <- glmmTMB(tr_prop ~ treat + handler * day + corner * day  + (1|subject), data = data_red, family = beta_family(link = "logit"))

The dependent variable is a proportion of time spent receiving one of two treatments (treat) in a test of a fixed duration. All fixed effects are categorical with two levels, and we had 12 subjects. This is a reduced model; the full model also contained treat * day, but the interaction was not significant. We simulated the residuals:
simulationOutput <- simulateResiduals(fittedModel = model_dur_red)

and when I ran
plot(simulationOutput),
I get these graphs:

Here it was suggested to add a quadratic effect to a model that produces a somewhat similar graph, but that does not work for our model, as it contains only categorical predictors. Is the deviation (most likely) a problem and is there anything we can do about it?
I also tried plotting the residuals against treat, the predictor of interest, but that didn't work.
Answer: Disclaimer: I'm the DHARMa developer. Regarding your question: there are two levels on which to answer this:

First of all, note that the evidence for a misfit is relatively weak. None if the tests to the left are significance, and also the quantile regression in the middle is n.s.. Just the upper quantile regression is significant, I would guess barely given the n.s. of the lower. While the quantile regressions are meant to help, they may optically exaggerate the strength of the signal with a low number of data points. Make the same plot with quantreg = F, and ask yourself if you see a strong pattern in there. I would suggest that it is relatively likely that wiggle you see in your residual pattern could also arise by chance, given the low number of data points.

Thus, given the low evidence, I wouldn't bend over backwards to get the pattern away, but you should consider if you missed something in your model specification. It could be interactions for the fixed effects but you can also consider (in glmmTMB) the dispformula to model dispersion - a dispersion dependency could create the same pattern.

When you do this, note that playing around too much and in particular making inclusion of fixed effects dependent on significance inflates type I error (p-hacking), so my advice would not to remove predictors just because they are n.s.
Comment: Thank you, your answer has been very helpful.


Feeds unlock tab

Question: I had one of my feeds freeze up and I can't unlock it. I did some searching and found a function for adding an unlock tab form this page:
http://drupalcontrib.org/api/drupal/contributions!feeds!feeds.pages.inc/function/feeds_unlock_tab_form/7
<?php
function feeds_unlock_tab_form($form, &$form_state, $importer_id, $node = NULL) {
  if (empty($node)) {
    $source = feeds_source($importer_id);
    $form['#redirect'] = 'import/' . $source->id;
  }
  else {
    $importer_id = feeds_get_importer_id($node->type);
    $source = feeds_source($importer_id, $node->nid);
    $form['#redirect'] = 'node/' . $source->feed_nid;
  }
  // Form cannot pass on source object.
 $form['#importer_id'] = $source->id;
 $form['#feed_nid'] = $source->feed_nid;
 $form['source_status'] = array(
   '#type' => 'fieldset',
   '#title' => t('Status'),
   '#tree' => TRUE,
   '#value' => feeds_source_status($source),
 );
 $form = confirm_form($form, t('Unlock this importer?'), $form['#redirect'], '', t('Delete'), t('Cancel'), 'confirm feeds update');
 if ($source->progressImporting() == FEEDS_BATCH_COMPLETE && $source->progressClearing() == FEEDS_BATCH_COMPLETE) {
   $form['source_locked'] = array(
     '#type' => 'markup',
     '#title' => t('Not Locked'),
     '#tree' => TRUE,
     '#markup' => t('This importer is not locked, therefore it cannot be unlocked.'),
   );
   $form['actions']['submit']['#disabled'] = TRUE;
   $form['actions']['submit']['#value'] = t('Unlock (disabled)');
 }
 else {
   $form['actions']['submit']['#value'] = t('Unlock');
 }
 return $form;
} ?>

File
contributions/feeds/feeds.pages.inc, line 202
    Menu callbacks, form callbacks and helpers.
So I know it goes in the feeds.pages.inc but not sure how to implement this. Can someone please point me in the right direction, thanks!
Comment: Well, nothing seemed to work so I cloned the original import and then deleted it. This seems to work.
Answer: You don't implement that function, it is already implemented by the feeds module.
feeds_menu() adds a menu item that calls that function.
It uses a custom access control function feeds_access(), which gives access to certain feeds actions based on your website's permission settings.
So if you don't have access to unlock a feed then it is likely that you need to give your role permissions to unlock the feed or else have the "administer feeds" permission or be user 1.
Answer: The easiest way to do this is to execute the following query for the importer that's "stuck", using PHPMyAdmin for example:
UPDATE feeds_source SET state='b:0;', fetcher_result='b:0;';

That's it.
Answer: Feeds get locked because of an incomplete import. To unlock, that import needs to be either canceled or completed. If you're not seeing those options, you don't have the proper permissions.

Feeds unlock tab


Calculating distance between two PointField (s) - Why is my result incorrect?

Question: I am trying to calculate the distance between two locations in miles however the result that I am getting is incorrect.
The reason I think its incorrect is because I put locations (latitude and longitude) on this website  and I get the distance in miles as 0.055. Here are the details from my code
PointField A : (-122.1772784, 47.7001663)
PointField B : (-122.1761632, 47.700408)
Distance : 0.001141091551967795

However, according to the website, the distance should be
Distance: 0.055 miles

Here is how I am calculating the distance.
This is my model
class modelEmp(models.Model):
       user                = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
       location            = models.PointField(srid=4326,max_length=40, blank=True, null=True)
       objects             = GeoManager()

and this is how I calculate the distance
 result = modelEmpInstance.location.distance(PointFieldBLocation)
   where result = 0.001141091551967795

Any suggestions on what I might be doing wrong here and why my result is different from the website?
Comment: Where are the variables `modelEmpInstance` and `PointFieldBLocation` coming from? (Side note - your code will be much more readable to others if you use [PEP8 conventions](https://www.python.org/dev/peps/pep-0008/?) - using camelcase for variables is frowned apon).
Comment: The answer is right - just in degrees! I don't know enough about GeoDjango to give an answer, but to get a result in metres from PostGIS you either need an SRID in metres, use geography rather than geometry type, or use st_distance_sphere. As your distances are quite small your most accurate option might be to use a local projection.
Comment: Possible duplicate of [How to calculate distance between two PointField?](https://stackoverflow.com/questions/36020805/how-to-calculate-distance-between-two-pointfield)
Comment: FWIW I just entered your points in Google Earth and measured direct distance between as 282 feet or 0.0534091 miles
Comment: so that means the other website is correct and for some reason my calculations in code are wrong
Answer: Your calculation is not wrong but the result is in the EPSG:4326's units, which are degrees. In order to calculate the distance in the wanted unit, we need to do the following:

Transform the points into an EPSG with meter units.

If you don't care much about the accuracy of the calculations, you can use the         EPSG:3857 (but the result will be 0.08104046068988752mi).
If you do care about the accuracy of your calculation though, you need to find an EPSG with meter units that are appropriate for your location. Since your points are located around the Seattle area, the appropriate EPSG is 32148.

Create a Distance object with the distance calculation in meters
Finally, convert it to miles:
from django.contrib.gis.measure import Distance

result = Distance(
    m = modelEmpInstance.location.transform(
        32148, clone=True
    ).distance(PointFieldBLocation.transform(32148, clone=True)
)
print(
    'Raw calculation: {}\nRounded calculation: {}'
    .format(result.mi, round(result.mi, 2)
)

This will print:
Raw calculation: 0.0546237743898667
Rounded calculation: 0.055

Comment: I am going to give this a try later today and mark it
Comment: Thanks for clearing this up. I am new to this. Is there a service out there that would tell me what the EPSG is based on longitude latitude ?  or is there a standard EPSG I can use ?
Comment: I don't know of a site that you can add a point and get the appropriate EPSGs for that place. What you can do though is search where your point is on the map and then google something like "Seattle EPSG". From there I trust http://www.spatialreference.org and http://www.epsg.io.
Comment: I have been reading a bit about EPSG. But I had a question. You mentioned that my initial result was correct but was in degrees. Is there a way to convert it into a unit of length ? I am not looking for a super accurate result but something +-15 miles would be great
Comment: @MistyD There is not a standard way of doing that. If you don't care about accuracy, you can use the `EPSG:3857`.
Comment: Ok thanks if I use EPSG:3857 will I need to change the SRID of the model as well ?
Comment: @MistyD You can keep your model's EPSG as it is and only transform it at the time of the calculation.
Comment: did you mean keep the SRID as it is and use the EPSG:3857 during calculation ?
Comment: @MistyD Yes. (EPSG is the authority that produces reference systems and SRID is the corresponding code. So EPSG:4326 is produced from EPSG and has the SRID of 4326.)
Comment: @MistyD No problem :)
Comment: So I have been trying this out for a while now and I am getting the error 'Point' object has no attribute 'tranform' . Any suggestions ? Am I missing something here ?
Comment: Suspect "tranform" is a typo and should be "transform". Also, possibly "format" and not "fromat".
Comment: @MistyD That is correct and that is also the reason why one should not just copy paste directly from StackOverflow :D
Comment: Nope I am using transform. Seems like I need to do this instead ```employerLocation = GEOSGeometry(loggedInEmployer.location).tranform(32148, clone=True)```
Comment: Seems like there is no transform method in the location. I am currently experimenting with ```GEOSGeometry(loggedInEmployer.location).tranform(32148, clone=True)```
Comment: @MistyD There is definitely a `transform` method on a `model.PointField`.
Comment: Let me confirm this - I dont know why its failing in my code
Comment: @MistyD Don't mention it :D


How to backup an MSSQL Database from another host using osql?

Question: We have been performing our sql database using osql as follows:
osql -s IP-9873743\SQLEXPRESS -E -Q "BACKUP DATABASE DBNAME TO
Disk ='e:\sysbkup\sqlbackup\DBNAME.bak' WITH NOFORMAT,
INIT, NAME = N' DBNAME-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10"

We want to do the same from another host but when we add the -H for host option on the command we get "The login failed".  With MS SQL Server Management Studio, we are able to login to the other server fine with Windows Authentication since my machine and the other host are using the same usernames with same password.
When I run the backup statement from the MGMT Studio console the backup is saved to the disk of the other host, instead of transferring the backup to the client machine. Any ideas how I will be able to backup an MSSQL database from another host different than the mssql engine itself?
Answer: You should be specifying the server name in the -s parameter, not -H, though this will still backup to the server the SQL service is running on.
In my experience SQL Server is fussy about operating on network drives, but you could try specifying a UNC path (\\<server>\<share>\<backup_file>) to the place you want the backup to go to on the network. I believe that the user the SQL Server instance is running as will need write access to the destination machine, I don't think it will use your account despite logging in via Windows integrated security, so you will need to arrange that first.
Comment: Thanks David. I tried both with -H and with -s.  When I did the backup using ms mgmt studio the backup was done in the host c drive instead of the client host c drive.
Comment: The path you specify is _always_ relative to the server SQL is running on, not the client that asks it to run a backup. That is why you need to use a UNC path, though for that to work you need to ensure the user the service runs as has write access to that location.
Comment: Don't forget that it's an upper case S, and if you're using the SQL 2005 client tools then switch to SQLCMD.exe instead.  If the remote SQL Server service account is not a domain acocunt or network service then using a UNC will not be possible.

osql/sqlcmd -E -S server\instance -Q "backup database db to disk = '\\otherhost\share\db.bak' with init, stats=10"


Create Own Hardware To Locate Phones with GPSR receivers

Question: I understand that phones use GPS receivers to communicate with gps satellites. I was wondering if it would be possible for me to create a piece of hardware to mimic a satellite signal to locate a phone?
Answer: the phone does not communicate with the satellite, the gps receiver in the phone receives the signal from the gps satellite.  it is a one way thing.  And sure if you can generate the right signals the phone may see them but, the phone does not talk back to the gps satellite, it uses the phone network to communicate out which is a whole other thing
Comment: if you want to find a phone, the phone has to know where it is (gps or triangulation between towers, or other signals it can detect and choose between the strongest).  And then the phone needs software that you can communicate with.  And that software cant have protections to prevent you from communicating with it, and THEN you can write some software on some machine on the net that communicates.  If you want to take over a signal you would be looking at cdma or gsm or lte or other, not gps.  and still software is involved
Comment: did you mean GPSR or GPS in the title? and if GPSR which of the expansions of those letters did you intend?


how to copy particular text inside pre tag using selenium python

Question: Need to copy the text given inside the
 tag using selenium python

    "test test1 test2"

Please guide me to copy those test2 inside
 tag
Answer: Try maybe like
preTextEl = driver.find_element_by_xpath("//div[@id='response_headers']/pre")
print preTextEl.text

Or using CssSelector:
preTextEl = driver.find_element_by_css_selector("div[id='response_headers'] pre")
print preTextEl.text


Como identificar algarismos numericos em numeros dentro de uma lista?

Question: preciso de uma ajuda. Estou preso em um exercício onde alem de várias orientações, pede para que eu remova todos os números dentro de uma lista que terminem com 7 (17, 27, 37, etc)
Como eu faria isso? (python)
Comment: o que você tentou fazer?
Comment: Tentou usar o operador % (resto da divisão)?
Comment: tentei usar outro for para percorrer cada algarismo de cada item, mas não consegui. É uma com  números de 1 a 100. Tentei usar a lógica de verificar se o segundo algarismo do número termina em '7' (como se fosse o indice de um string). Mas não deu kk.

(utilizei o % para remover os múltiplos de 7, uma das coisas que o exercício pede)
Answer: Você pode utilizar compreensão de listas para resolver o seu problema:
lista = list(range(100))
lista = [x for x in lista if x % 10 != 7]

Na segunda linha de código estamos dizendo que queremos todos os elementos da lista desde que o elemento dividido por 10 tenha resto diferente de 7.
Answer: Uma possibilidade é utilizar a função built-in filter(função , iterável ) que cria um iterador a partir dos elementos de iterável para os quais a função filtro, passada no primeiro parâmetro, retorne true. O iterável pode ser uma sequência, um contêiner que suporta iteração ou um iterador.
Como filtro passe uma expressão lambda que nada mais é uma função anonima:
lambda x: x % 10 != 7

Essa expressão lambda devolve a referência para uma função anonima contendo um único parâmetro,x, tal que se a unidade de x não for 7 retorna verdadeiro, caso contrário retorna false.
Código:
No caso criei uma lista hipotética chamada lista cujo os elementos são os números naturais de 0 até 99.
Depois apliquei o filtro, a cima descrito, de forma que seja feita apenas uma única iteração pelos elementos de lista.
#Cria uma lista com os naturais de 0 até 99 para teste.
lista = list(range(100))

#Filtra os elementos da lista cujo a unidade seja 7
resultado = list(filter(lambda x: x % 10 != 7, lista))

print(resultado)  #imprime o resultado

Teste o código no Repl.it
Saída:
[0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24,
 5, 26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48,
49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71,
72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 94,
95, 96, 98, 99]

Relacionado:

Lista de Funções Built-in do Python
Typos de Dados Python
Notação Big-O

Pesquisas relacionadas aqui no site

[python] filter
[python]lambda
Big-o
Answer: Tente:
for i in range((len(lista)-1),-1,-1):
  if (lista[i] % 10) == 7:
    del(lista[i])

Comment: Para listas pequenas não faz diferença, mas em operações com lista grades essa estratégia não é muito performática. Remover itens individualmente pode ser uma [operação custosa](https://wiki.python.org/moin/TimeComplexity), compare a [complexidade de tempo](https://pt.wikipedia.org/wiki/Complexidade_de_tempo) entre apensar um item ao final da lista(`Append[1]`) e remover um item qualquer(`Delete Item`).
Comment: Caso o primeiro elemento da lista seja `7` ou terminado em `7` ele não sera removido da lista com o laço acima. Uma solução seria passar `-1` como stop do `range`, ficaria assim: `for i in range(len((lista[i]-1), -1, -1).`
Comment: Funcionou perfeitamente! obrigado!

tentei antes:

 for i in range(0, len(lista)):
    if(lista[i] % 10) == 7:
        del(lista[i])

Mas deu IndexError: list index out of range. Sabe me dizer o que porque? (aprendendo python ainda)
Comment: Começando a varredura pelo início da lista: `range(len(lista))` Acontece que conforme os números vão sendo excluídos o tamanho da lista diminui. Por isso em algum momento o range acabaria alcançando um número acima do de elementos da lista, o que causaria esse erro. Fazendo o contrário e varrendo a lista a partir de seu final: `range((len(lista)-1), 0, -1)`, o número vai diminuindo juntamente com o passo do iterador "-1".
Comment: Obrigado, vou editar ali :)


Prevent drupal from adding a favicon from default directory in custom theme

Question: I want Drupal to look for a favicon in a specific directory dynamically. This is mainly because I'm using the domain access module and I'd like the favicon based off the subdomain that is being used. For example if the url is
example.url.com

I want drupal to look for the favicon in
sites/all/themes/mytheme/example/favicon.ico

If the subdomain is example2 I want it to look for the favicon here
sites/all/themes/mytheme/examples2/favicon.ico

I think I have a handle of how to grab the url and base the location on that but right after I have added the favicon, drupal adds it's own. For example I see this in the header
<link rel="shortcut icon" href="sites/all/themes/mytheme/examples2/favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="http://example.url.com/misc/favicon.ico" type="image/vnd.microsoft.icon">

I've accomplished adding my own favicon but it doesn't matter since it is added before anything else. I'm currently using preprocess_html to do this
function mytheme_preprocess_html(&$variables) {
    $favicon = 'sites/all/themes/mytheme/example/favicon.ico';
    $type = 'image/x-icon';
    drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}

(It does not yet have the logic to grab the url) I'm assuming that it is at the top based on the term preprocess. Is there a way to give it weight? Or is there another function I should be using?
Answer: I found a solution. in Appearance>Mytheme>Settings, there is an option to uncheck shortcut settings.
After unchecking that option the link provided in mytheme_preprocess_html was able to display the favicon unopposed.


Centre of a group with a faithful irreducible representation is cyclic

Question: The following is taken from section 3.1 of $\textit{Représentations linéaires des groupes finis}$ by J.-P. Serre:

Exercise 2) Let $\rho$ be an irreducible representation of $G$ of degree $n$ and character $\chi$; let $C$ be the centre of $G$ ($\textit{i.e.}$ the set of $s \in G$ such that $st=ts$ for all $t \in G$.), and let $c$ be the order of $C$.
c) Show that if $\rho$ is faithful ($\textit{i.e.}$ $\rho_s \neq 1$ for $s \neq 1$), then $C$ is cyclic.

Now if we let $G=C_2\times C_3 = \{\sigma,\tau \mid \sigma^2=\tau^3=e, \sigma\tau=\tau\sigma \}$, we can define the following irreducible representation $\rho:G \to \mathbb{C}^{\times}$:
\begin{equation}
\rho(\sigma)=-1, \qquad \rho(\tau) = \omega
\end{equation}
where $\omega \in \mathbb{C}^{\times}$ is a primitive third root of unity.
$\rho$ is a faithful irreducible representation and $G$, being Abelian, coincides with its own centre. Hence its centre is not cyclic.
Why is this not a counterexample?
Answer: $G$ is a cyclic group. By the Chinese Remainder Theorem, if $m$ and $n$ are  relatively prime, $C_m \times C_n \cong C_{mn}$.


Cannot convert from 'method group' to 'System.Action' error

Question: I have created the following function:
public void DelegatedCall(Action<Object> delegatedMethod)

And defined the following method
public void foo1(String str) { }

However, when I try to call DelegateCall with foo1:
DelegatedCall(foo1);

...I get the following compiler error:

Argument 1: cannot convert from 'method group' to 'System.Action<object>'

What is the reason for this error and how can I correct it? Unfortunately, casting foo1 to Action is not an option.
Comment: Related: [What is a method group in C#?](http://stackoverflow.com/q/886822/1497596)
Answer: DelegatedCall expects a delegate that takes any object as an argument. But your function foo1 that you are passing to DelegatedCall can only cope with a string argument. So, the conversion isn't type-safe and thus is not possible.
Input parameters are contra-variant, but your code needs covariance. (See Difference between Covariance & Contra-variance.)
You can make DelegatedCall generic:
DelegatedCall<T>(Action<T> action)

...or have it take any delegate:
DelegatedCall(Delegate action)

But then implementing it is ugly and requires reflection. It also doesn't verify that the function has only one parameter at compile-time.
Comment: Are you aware of any way i can create such a code? I want DelegateCall to have the ability to receive a function which receives any one parameter of any type (String, bool, List...)
Comment: Can you recommend on any reading material how to use reflection to implement the second option?
Answer: Variance doesn't work that way around; you would need
DelegatedCall(obj => foo1((string)obj));

As even in 4.0 it won't believe that every object is a string.
Note that if it was foo1(object) and Action<string> (i.e. the other way around) it probably would work (in 4.0), since every string is an object.
Comment: The other way round works even prior to 4.0. When converting from a method group variance was available even in earlier versions.
Comment: Ok is there anyway i can make this work then: I want DelegateCall to have the ability to receive a function which receives any one parameter of any type (String, bool, List...). Any help would be appreciated


How can I find the range of the function $f(x) = 2^{x} + 2^{-x}$?

Question: How can I analytically determine the range of the function for $f(x) = 2^{x} + 2^{-x}$?
If I have an ordinary linear equation, I proceed as follows:
$$f(x) = x + 2 \Rightarrow y = x + 2 \Rightarrow  y - 2 = x$$
then the range of the function is $\mathbb{R}$, but I don't see what to do here
I speak about this range.
Comment: Welcome to MSE! Try to apply the AM-GM inequality.
Comment: The application of the AM-GM inequality results into:
\begin{align*}
f(x) = 2^{x} + 2^{-x} \geq 2\sqrt{2^{x}2^{-x}} = 2
\end{align*}

Hence the range of $f$ is the interval $[2,+\infty)$.
Comment: The function is symmetric, and although I can't prove that it is rising if $x>0$ without using derivatives, yiu can see that this is true meaning the minimum is at $x=0$
Comment: Isn't there another way? We haven't formally taken derivatives yet, so I wanted to try another way, if possible...
Comment: @ÁtilaCorreia Thank you i didn know that.
Comment: For fun, $2^x+2^{-x}=2\cosh(\ln(2)x)$
Comment: @Martin88 you are welcome! I am glad I could help.
Answer: Well, if $f: x\longmapsto 2^{x}+2^{-x}$, then ${\rm Dom}(f)=\mathbb{R}$.  The Arithmetic mean-geometric mean (AM-GM) inequality says that for non-negative real values we have $$\frac{u+v}{2}\geqslant \sqrt{uv}$$ with equality if and only if $u=v$. Hence, using AM-GM for $u(x)=2^{x}>0$ and $v(x)=2^{-x}=1/2^{x}>0$ we have
$$f(x)=2^{x}+\frac{1}{2^{x}}=u(x)+v(x)\geqslant 2\sqrt{u(x)v(x)}=2\sqrt{2^{x}\frac{1}{2^{x}}}=2\sqrt{1}=2$$
Therefore, the ${\rm Im}(f)=[2,+\infty[$.
N.B: This is simply a little more elaborate than Átila Correia's comment (which is a answer).
Answer: Let me I would like to say that the solution method applied based on the AM-GM inequality alone does not seem rigorous enough. Because,
$f(x):=2^x+2^{-x}≥2$ doesn't imply the range (image) of the function $f(x)$ should be $[2,+\infty)$. For instance, you can consider the following function:
$$g(x):=\frac {x^2+1}{x^2+2}+\frac {x^2+2}{x^2+1}$$
Applying the AM-GM inequality you have:
$$\frac {x^2+1}{x^2+2}+\frac {x^2+2}{x^2+1}≥2$$
Observe that, this doesn't tell us $\operatorname {Im}(g)$ is $(2,+\infty)$.
Because, the range (image) of the function $g(x)$ is exactly
$$\operatorname{Im}(g)=\left(2,\frac 52\right].$$

The possible rigorous way can be considered as follows:
$$
\begin{align}&y(x):=2^x+\frac 1{2^x},\; y>0\\
\implies &2^x=\frac 12\left(y±\sqrt {y^2-4}\right)\\
\implies &x=\log_2\left(\frac {\sqrt {y^2}±\sqrt {y^2-4}}{2}\right)\wedge y≥2\end{align}
$$
This implies that: $\forall y≥2$ there exist $x\in\mathbb R$ such that, $y=2^x+2^{-x}$ holds. This means, the image of the $f(x)$ is exactly $[2,+\infty)$.


Combining Multiple Laravel Livewire "updated" Lifecycle Hooks Into a Single Function

Question: I need to update the price on the page when a user changes the value of either the width, height and/or length. The code below works, but it seems it could be cleaner instead of having three separate updated lifecycle hooks with duplicate code. When the view is mounted, I set the default values of width, height and length and calculate the price.
show.php
...
class Show extends Component
{
    public $product;
    public $sku;
    public $name;
    public $description;
    public $width;
    public $height;
    public $length;
    public $price;

    public function mount(Product $product){
        $this->product = $product;
        $this->sku = $product->sku;
        $this->name = $product->name;
        $this->description = $product->description;

        $this->width = 4;
        $this->height = 4;
        $this->length = 10;
        $this->price = (((($this->width + $this->height + $this->height)*12)/144)*25)*$this->length;
    }

    public function updatedWidth() {
        $width = $this->width;
        $height = $this->height;
        $length = $this->length;
        $this->price = (((($width + $height + $height)*12)/144)*25)*$length;
    }

    public function updatedHeight() {
        $width = $this->width;
        $height = $this->height;
        $length = $this->length;
        $this->price = (((($width + $height + $height)*12)/144)*25)*$length;
    }

    public function updatedLength() {
        $width = $this->width;
        $height = $this->height;
        $length = $this->length;
        $this->price = (((($width + $height + $height)*12)/144)*25)*$length;
    }

    public function render()
    {
        return view('livewire.shop.show')->layout('layouts.frontend');
    }
}

show.blade.php

{{$product->name}}

Product information

${{number_format($price, 2, '.')}}

Description

                {{$product->description}}

    <form wire:submit.prevent="createOrderItem" method="POST" class="mt-6">

Size

                    Outer Width:
                    <select wire:model="width" id="width" name="width" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                        <option value="3">3"</option>
                        <option value="4">4"</option>
                        <option value="5">5"</option>
                    </select>

                    Outer Height:
                    <select wire:model="height" id="height" name="height" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                        <option value="3">3"</option>
                        <option value="4">4"</option>
                        <option value="5">5"</option>
                    </select>

                    Length:
                    <select wire:model="length" id="length" name="length" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                        <option value="10">10'</option>
                        <option value="11">11'</option>
                        <option value="12">12'</option>
                    </select>

Answer: Since you are doing the same calculation multiple times, it would make sense to extract that into its own method. Then, you can use the "global" updated() lifecycle-hook and conditionally set the price based on which fields were updated.
class Show extends Component
{
    public $product;
    public $sku;
    public $name;
    public $description;
    public $width;
    public $height;
    public $length;
    public $price;

    public function mount(Product $product)
    {
        $this->product = $product;
        $this->sku = $product->sku;
        $this->name = $product->name;
        $this->description = $product->description;

        $this->width = 4;
        $this->height = 4;
        $this->length = 10;
        $this->price = $this->calculatePrice();
    }

    /**
     * Calculates the price based on height, width and length
     * @return int $calculatedPrice
     */
    private function calculatePrice()
    {
        return (((($this->width + (2 * $this->height)) * 12) / 144) * 25) * $this->length;
    }

    /**
     * Life-cycle hook that will fire on each updated value from the view
     * @param string $field The fieldname that is updated
     */
    public function updated($field)
    {
        if (in_array($field, ['width', 'height', 'length'])) {
            $this->price = $this->calculatePrice();
        }
    }

    public function render()
    {
        return view('livewire.shop.show')
                ->layout('layouts.frontend');
    }
}


Smooth circular data - Matlab

Question: I am currently doing some image segmentation on a bone qCT picture, see for instance images below.

I am trying to find the different borders in the picture for instance the outer border separating the bone to the noisy background. In this analysis I am getting a list of points (vec(1,:) containing x values and vex(2,:) containing the y values) in random order.
To get them into order I am using using a block of code which effectively takes the first point vec(1,1),vec(1,2) and then finds the closest point among the rest of the points in the vector. And then repeats.
Now my problem is that I want to smooth the data but how do I do that as the points lie in a circular formation? (I do have the Curve Fitting Toolbox)
Comment: For circular curves, you can fit a polynom `x(t)` and another for `y(t)` where `t` ranges over all your data points.
Comment: can you upload an example of `vec` and the ordering of the points you get from your procedure?
Comment: You can find an example of one of my vectors here: http://imada.sdu.dk/~nmatt11/files/  It is the one called O.mat and it contains a vector O.
Answer: Not exactly a smoothing procedure, but a way to simplify your data would be to compute the boundary of the convex hull of the data.
<code>K = convhull(O(1,:), O(2,:));
plot(O(1,K), O(2,K));
</code>
You could also consider using alpha shapes if you want more control.

Smooth circular data - Matlab


Sets and Sequences

Question: My question is basically: true or false? I'm told this is false, but don't understand why.

Set: A set is an unordered group of related elements which are
distinct.
Sequence: A sequence is a list of related elements which
occur in a particular order.
Comment: "Related" is debatable, and sets are not ordered.
Comment: @randall typeo on ordered, was supposed to be unordered.
Comment: What is your question exactly? Your two statements about "Set" and "Sequences" are neither true or false because  "Set" is an undefined primitive concept similar to point and line in Euclidean geometry, and "Sequence" is not precise enough to be a definition.
Answer: A set doesn't have a specified order.  The two element set $\{1,2\}$ is the same as $\{2,1\}$.
A sequence is a list of values. You can think of a finite sequence of length $n$ as a function on the set $\{1,2,\ldots,n\}$.  An infinite sequence is a function on the set of natural numbers $\mathbb{N}$.
Answer: The definition of a set is a somewhat complicated discussion as evident by Russel's paradox.The definition by Cantor (as taken from wikipedia) is "A set is a gathering together into a whole of definite, distinct objects of our perception or of our thought—which are called elements of the set." .The formality about what is a set can be explored through the axioms proposed by Ernst Zermelo and Abraham Fraenkel.
A sequence can be defined to be a function $f:\mathbb{N}\rightarrow A$ where $A$ is a set.

Sets and Sequences


GoLang Level3 embedded struct initialisation

Question: I am new to Golang development. I was trying to initialize a struct which has a level 3 embedded struct. I can create till 2 levels, but when I try with level 3, it gives me this compile time error.
missing type in composite literal
Here is the trial code
available. Please help/suggest an excellent way to achieve the same.
In main.go, unable to initialise a2 variable.
package main

import (
    "structpackage"
    cfmt "basic/utils"
    "fmt"

)

type p StrPackage
type n NestedStruct

type Address struct {
    Name         string
    city         string
    Pincode      int
    StrPackage   p // embedded struct
    NestedStruct n // nested struct embedded in Address struct
}

func main() {

    // Declaring and initializing a struct using a struct literal
    a1 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, StrPackage: p{14, "Software engineer"}} // embedded struct implementation

    /** * embedded struct implementation Start  **/

    a2 := Address{Name: "Akshay", city: "Dehradun", Pincode: 3623572, NestedStruct: n{Designation: "Software engineer", S: {Age: 12, Occuption: "sfdsf"}}} // Naming fields while initializing a struct

    fmt.Println("Address2: ", a2)
}

structpackage.go
package structpackage

type StrPackage struct {
    Age       int
    Occuption string
}

type NestedStruct struct {
    Designation string
    S           StrPackage
}

Answer: Notice that an object of type Strpackage needs to be constructed on the fly and assigned to NestedStruct.S
a2 := Address{
         Name: "Akshay",
         city: "Dehradun",
         Pincode: 3623572,
         NestedStruct: n{
            Designation: "Software engineer",
            S: structpackage.StrPackage{
                  Age: 12, Occuption:
                  "sfdsf"
            }
         }
     }


Is it possible to reference a different column in the same table?

Question: If a blog has a 'categories' table such as the following:
CREATE TABLE categories
(
  id INTEGER PRIMARY KEY AUTO_INCREMENT,
  parent_id INTEGER NOT NULL,
  name VARCHAR(30) NOT NULL,
  description TEXT,
  count INTEGER NOT NULL DEFAULT 0
);

And if the parent_id field is intended to refer to the 'id' field of the categories table, then how could I add a constraint that would ensure that values inserted into parent_id references the id field?
I simply want to make sure that only category id values that exist can be used as a parent of a newly inserted category.
Answer: Yes, you can reference a column in the same table.
But that column should be nullable otherwise you can't insert the first record.
CREATE TABLE categories
(
  id INTEGER PRIMARY KEY AUTO_INCREMENT,
  parent_id INTEGER NULL,
  name VARCHAR(30) NOT NULL,
  description TEXT,
  count INTEGER NOT NULL DEFAULT 0,
  FOREIGN KEY (parent_id) REFERENCES categories(id)
);

Note that after the REFERENCES keyword the table name is not optional, so you must specify it even if you are referencing a column in the same table. From the documentation:

reference_definition:
    REFERENCES tbl_name (index_col_name,...)
      [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
      [ON DELETE reference_option]
      [ON UPDATE reference_option]

See it working online: sqlfiddle
Comment: So does that mean I should do something like: parent_id INTEGER REFERENCES (id) ?
Comment: @JimJohnson: You need to specify the table name.
Answer: Just use a normal foreign key:
ALTER TABLE categories ADD CONSTRAINT FK_categories_Parent_ID
REFERENCES categories (ID)

However Parent_ID should be nullable as you'll never be able to insert a record
Comment: @JimJohnson: Do you have a row 0 in your table? If not, your foreign key constraint will fail if you try to add a row with parent_id = 0. But you can use NULL instead.
Comment: I never knew that foreign keys could also be columns in the same table >.<
Comment: Could I default parent_id to 0 by any chance?
Comment: @Mark Byers I'll just use NULL instead :D
Answer: You can use below link. It has how you can do it Oracle database.
http://www.adp-gmbh.ch/ora/data_samples/hierarchic_yahoo.html
Thanks


Fazer Split da string que está entre duas \

Question: Estou tentando fazer o split por \ da string abaixo, queria pegar apenas Yorktown, mas não estou conseguindo.
\Locations\North America\US Mid-Hudson Valley\Yorktown\Yorktown Heights\

Meu código está assim:
String[] locationCategory1 = row.getCell(0).getStringCellValue().split("/[\\.]/");
             String locationCategory1splited = locationCategory1[4];

Answer: Algumas linguagens exigem que uma regex esteja entre delimitadores, sendo a / o mais comum. Mas não é o caso do Java, você não precisa colocar as barras no início e fim. Ao colocá-las, o split tentará procurar pelo próprio caractere /.
Outro detalhe é que [\\.] na verdade corresponde ao caractere ., então sua regex está buscando por uma barra, seguida de ponto, seguida de outra barra.
Se a ideia é separar por \, basta colocar este caractere. Um detalhe chato é que ele é usado em regex para fazer o escape de meta caracteres e para que ele seja interpretado como o próprio caractere \, você precisa escrevê-lo como \\.
Só que em uma string do Java, "\\" resulta em apenas um \, então a regex tem que ser escrita como \\\\ (isso se transforma na regex \\, que corresponde ao caractere \). Assim:
String s = "\\Locations\\North America\\US Mid-Hudson Valley\\Yorktown\\Yorktown Heights\\";
System.out.println(s.split("\\\\")[4]);

A saída do código acima é "Yorktown".
Comment: hkotsubo rei das regex
Comment: Muito obrigada! Funcionou!!


RAA Proof using conditionals

Question: I am having trouble trying to prove the following using RAA.
$(G∙P)→K,$
$E→Z,$
$~P→~Z,$
$G→(E \lor L),$
$\text{___________}$
$\therefore (G∙~L) →K$
I have already proved it using the conditional proof method, and was trying to prove it using RAA to show that it could be done with both.
Comment: Assume the negation of the conclusion...
Comment: @MauroALLEGRANZA I am familiar with the procedure of doing an RAA proof. I assumed the negation of the conclusion and have, unsuccessfully, used other equivalence rules to try and reach a contradiction. I was more asking for help in doing the problem, since I am clearly not seeing the correct path.
Comment: The negation of the conclusion is $(G \land \lnot L) \land \lnot K$ from which we have $\lnot K$ and $G \land \lnot L$. Thus, in order to produce a contradiction, we may try to derive $K$.
Comment: From $G \land \lnot L$ we have $G$ and from 4th premise: $E \lor L$. With $\lnot L$ we get $E$ and from 2nd premise $Z$. With it and 3rd premise we get $P$. Now we have both $G$ and $P$ and we can finally use 1st premise.
Comment: @Mauro ALLEGRANZA Thank you for your insight. I was trying to do it only negating K and was unsuccessful in my attempts.
Answer: Since you can prove it by conditional proof, of course you may prove it by reduction to absurdity.
When you assume the negation, then you may obviously derive a contradiction using the conditional proof.
$$\def\fitch#1#2{\quad\begin{array}{|l}#1\\\hline#2\end{array}}
\\\fitch{(G\cdot P)\to K\\E\to Z\\\neg P\to\neg Z\\G\to(E\vee L)}{\fitch{\neg((G\cdot\neg L)\to K)}{\left.{\raise{2ex}{\fitch{G\cdot\neg L}{~\vdots\\K}\\(G\cdot \neg L)\to K}}\right\}\\\bot}\\\neg\neg((G\cdot \neg L)\to K)\\\hspace{-4ex}\therefore\hspace{2ex}(G\cdot\neg L)\to K}$$
This is why reduction to absurdity should only be attempted as a last resort -- if a direct proof is possible, then a RAA proof will contain redundancy.
Comment: I agree. The point of the question was that things can be done many different ways and to show how a conclusion can be derived using different methods of proof solving. Thank you for your response!

RAA Proof using conditionals


Completar próximo campo sem usuario ter que dar TAB

Question: Ao clicar no botão ao lado de UF o usuário abre uma tabela com os estados do Brasil, e a partir da escolha do Estado os outros campos são completados, até ai tudo bem eu consegui fazer, porém tenho que clicar dentro do input e depois em outro lugar ou dar TAB, para completar os campos, tem alguma forma de eu adaptar minha função para que complete o campo imediatamente, sem precisar dar TAB ou qualquer coisa do tipo ? Para facilitar a vida do usuário
index.php

        UF:
        <input type="text" class="form-control estado" name="estado">

            <button class="btn btn-secondary" style="margin-top:25px;" type="button" data-toggle="modal" data-target="#Modal">...</button>

        Estado:
        <input type="text" class="form-control" name="nome_estado">

        Alíquota Base do ICMS:
        <input type="text" class="form-control" name="aliq_base_icms">

        Alíquota do ICMS:
        <input type="text" class="form-control"  name="aliq_icms">

function_est.php
<?php

include_once("conn.php");

function retorna($estado, $conn){

    $result = "SELECT * FROM estados WHERE estado = '$estado' ";

    $resultado = mysqli_query($conn, $result);

    // DECLARA A VARIAVEL
    $valores = array();

    if($resultado){

        $row = mysqli_fetch_assoc($resultado);
        $valores['nome_estado'] = $row['nome_estado'];
        $valores['aliq_base_icms'] = $row['aliq_base_icms'];
        $valores['aliq_icms'] = $row['aliq_icms'];
        $valores['icms_subst_sn'] = $row['icms_subst_sn'];
        $valores['insc_est_subst'] = $row['insc_est_subst'];
        $valores['aliq_icms_subst'] = $row['aliq_icms_subst'];

    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));
    }

        return json_encode($valores);

}

if(isset($_GET['estado'])){
        echo retorna($_GET['estado'], $conn);
}
?>

Comment: Qual é o código que você usa para o modal inserir o valor selecionado no input?
Comment: vou colocar abaixo do código html, mas ele captura os dados vindos do modal normalmente
Answer: Você está utilizando a função através do event handler onblur (ou apenas blur no jquery). Ou seja, será executado sempre que o campo perder o estado de foco (onfocus).
Nesse caso, altere a sua função javascript para utilizar algua evento como o onchange:

$('select').on('change', function() {
    alert( this.value );
})

<select>
    <option value="">-- selecione --</option>
    <option value="Valor 1">Valor 1</option>
    <option value="Valor 2">Valor 2</option>
</select>

Update
Houve um detalhe que me passou despercebido. Esse detalhe é a forma que o seu código insere o valor selecionado no modal para o input. Infelizmente, o evento onchange somente é disparado (triggered) quando ocorre uma interação via usuário. O seu input está tendo uma interação via código. Através do seguinte trecho:
$('.estado').val(value);

Dessa forma, você tem duas opções, mover o código de update para dentro do código JavaScript ou realizar trigger do evento de forma manual. Eu acho a segunda opção mais simples.
Basta que, aonde você insere o valor, insira também a chamada do evento change:
$('.estado').val(value).change();

Comment: Não funcionou, do mesmo jeito tenho de dar TAB
Comment: @VictorT. dizer que não funcionou é muito abrangente. Por favor, atualize seu código com as novas implementações para podermos verificar o ocorrido.
Comment: Desculpe, não quis dizer isso e tirar seu mérito, porém eu coloco SP ou seleciono na tabela dentro do modal e mesmo assim para a função ser chamada tenho de ou dar tab ou clicar fora do campo input UF
Comment: @VictorT. sem problemas, apenas preciso saber como você implementou, pois, o código acima deveria funcionar sem problemas.
Comment: editei o script dentro do index
Comment: @VictorT. código atualizado, deve resolver seu problema.
Comment: Muito obrigado cara me ajudou bastante, se eu quiser também fazer um evento que a medida que o usuário digite diretamente no campo input sem clicar no modal e completar, também consigo ?
Comment: Sim, apenas pode ser possível que tenha que adequar qual o melhor evento a ser disparado. _onchange_ será disparado sempre que houver qualquer alteração (adicionou uma letra, é disparado).
Answer: Adiciona um listener no document que irá verificar o valor no input estado quando houver cliques na página (quando você escolher uma opção na modal). Caso haja alterações no referido input, a função é chamada:
$(document).ready(function(){
    var estado_form = $('input[name=estado]'); // armazeno o elemento numa variável
    var estado_val = estado_form.val(); // pego o valor original
    $(document).on("click", function(){
        if(estado_val != estado_form.val() && estado_form.val() != ""){ // verifico se o valor é diferente e não pode estar vazio
            estado_val = estado_form.val(); // atribuo valor atual

            var $nome_estado = $("input[name='nome_estado']");
            var $aliq_base_icms = $("input[name='aliq_base_icms']");
            var $aliq_icms = $("input[name='aliq_icms']");
            var $icms_subst_sn = $("input[name='icms_subst_sn']");
            var $insc_est_subst = $("input[name='insc_est_subst']");
            var $aliq_icms_subst = $("input[name='aliq_icms_subst']");

            $.getJSON('function_est.php',{
                    estado: estado_form.val()
            },function( json ){
                $nome_estado.val ( json.nome_estado );
                $aliq_base_icms.val ( json.aliq_base_icms );
                $aliq_icms.val ( json.aliq_icms );
                $icms_subst_sn.val ( json.icms_subst_sn );
                $insc_est_subst.val ( json.insc_est_subst );
                $aliq_icms_subst.val ( json.aliq_icms_subst );
            });
        }
    });
});

Comment: Não estava chamando a função, adicionei var na segunda e terceira linha e agora chama a função logo que recebe os dados no campo UF, porém retorna valores nulos
Comment: @VictorT. Blz, vou analisar aqui.
Comment: @VictorT. O problema está no `$( this ).val()`. Mude para `estado_form.val()`
Comment: Obrigado, agora deu o resultado esperado


lex & yacc multiple definition error

Question: I want to make code scanner and parser but I don't know why this error happens just by looking at the error log. The scanner takes the sample code and divides it into tokens, then returns what each of the tokens in the code is doing.The parser receives the values returned from the scanner and parses the code according to the rules.
It checks validity of grammar of sample code.
and finally this my error
lex.yy.o: In function main:
lex.yy.c:(.text+0x1d2a): multiple definition of main
y.tab.o:y.tab.c:(.text+0x861): first defined here
collect2: error: ld returned 1 exit status

Answer: You have defined main in both your files, but C only allows a single definition of main in a program, which is what the linker error is telling you.
The main in your scanner file has an invalid prototype (C hasn't allowed function definitions without a return type for almost 20 years) and also calls yylex only once, which is not going to do much. So it seems pretty well pointless. If you want to debug your scanner without using the parser,byou can link the scanner with -lfl; that library includes a definition of main which repeatedly calls yylex until end of file is signalled.
Instead of scattering printf calls through your scanner, you can just build a debugging version of the scanner using the --debug flag when you generate the scanner. That will print out a trace of all scanner actions.

lex & yacc multiple definition error


Imposing conditions on orders of cyclic group to create a group homomorphism

Question: I am trying to solve:

Let $G,H$ be cyclic groups, generated by elements $x,y$. Determine the condition on the orders $m,n$ of $x$ and $y$ so that the map sending $x^i \rightsquigarrow y^i$ is a group homomorphism.

Here is my attempt.

We require that the map $\varphi: \underset{x^i}{G} \underset{\longmapsto}{\to} \underset{y^j}{H}$ is well-defined. That is, if $x^i = x^j$ for $i,j \in \mathbb{Z}$, then $y^i = y^j$. That is, if $i \equiv j \text{ (mod $m$)}$, then $i \equiv j \text{ (mod $n$)}$, i.e., if $i - j = \alpha m$ for some $\alpha \in \mathbb{Z}$, then $i - j = \beta n$ for some $\beta \in \mathbb{Z}$. As $i,j$ are arbitrary and any integer can be written in the form $i - j$, this means that for all $z \in \mathbb{Z}$, $m \mid z$ implies that $n \mid z$, which is true provided that $n \mid m$. To show that this condition is sufficient, let $m = nk$ for some $k \in \mathbb{Z}$ and suppose that $x^i = x^j$ for some $i,j \in \mathbb{Z}$. Then we have
\begin{align*}
i - j = \gamma m = \gamma (nk) = n(\gamma k)
\end{align*}
for some $m \in \mathbb{Z}$, so $i \equiv j \text{ (mod $n$)}$, so $y^i = y^j$, hence $f(x^i) = f(x^j)$, so $\varphi$ is well-defined. I claim that $\varphi$ is then a homomorphism. Indeed, for any $i,j \in \mathbb{Z}$, we have
\begin{align*}
\varphi\left(x^i x^j\right) = \varphi\left(x^{i+j}\right) = y^{i+j} = y^i y^j = \varphi\left(x^i\right) \varphi\left(x^j\right),
\end{align*}
as desired.

Is the logic correct? The only thing I am still not completely certain about is the pairing of $i-j$ with some arbitrary integer $z$, but there is surely at least a surjective mapping from differences of integers with the integers themselves, so I believe the logic is valid.
Comment: Indeed, $z=z-0$.
Answer: I believe you have the right condition there:  $n\mid m $.
That's because the order of $\varphi  (x) =y $ is $n $; but it must also divide $m $, since $(\varphi  (x))^m=\varphi  (x^m)=\varphi  (e)=e $.
On the other hand,  well-definedness doesn't seem to be much of an issue (anymore)  because the homomorphism property will ensure it.
So, the condition is necessary and sufficient.


Prove that if ${x_1, x_2, x_3}$ are roots of ${x^3 + px + q = 0}$ then ${x_1^3+x_2^3 + x_3^3 = 3x_1x_2x_3}$

Question: How to prove that ${x_1^3+x_2^3 + x_3^3 = 3x_1x_2x_3}$ holds in case ${x_1, x_2, x_3}$ are roots of the polynomial?
I've tried the following approach:
If $x_1$, $x_2$ and $x_3$ are roots then
$$(x-x_1)(x-x_2)(x-x_3) = x^3+px+q = 0$$
Now find the coefficient near the powers of $x$:
$$
x^3 - (x_1 + x_2 + x_3)x^2 + (x_1x_2 + x_1x_3 + x_2x_3)x - x_1x_2x_3 = x^3+px+q
$$
That means that I can write a system of equations:
$$
\begin{cases}
-(x_1 + x_2 + x_3) = 0 \\
x_1x_2 + x_1x_3 + x_2x_3 =  p \\
- x_1x_2x_3 = q
\end{cases}
$$
At this point I got stuck. I've tried to raise $x_1 + x_2 + x_3$ to 3 power and expand the terms, but that didn't give me any insights. It feels like I have to play with the system of equations in some way but not sure what exact.
Comment: If you ever need to go further, I recommend that you study [Newton's identities](https://en.wikipedia.org/wiki/Newton%27s_identities). They settle this question also. But, as shown by the answers below, you don't need their full power to reach the sum of cubes.
Answer: $x_1^3 + x_2^3 + x_3^3 - 3x_1x_2x_3 = (x_1 + x_2 + x_3)(x_1^2 + x_2^2 + x_3^2-x_1x_2 - x_2x_3-x_1x_3)$
Now, here $-(x_1 + x_2 + x_3) =$ Coefficient of $x^2$/ Coefficient of $x^3  =0  $
So, $x_1^3 + x_2^3 + x_3^3 = 3x_1x_2x_3$
Answer: Rewrite $x_1,x_2,x_3$ with $a,b,c$. From first Vieta formula we have $$a+b+c=0$$
so $a+b=-c$ and so on...
Now $$a^3+b^3+c^3= (a+b)(a^2-ab+b^2)+c^3 = c(\underbrace{-a^2+ab-b^2+c^2}_I)$$
Since
$$I = -a^2+ab-b^2+c^2 = a(b-a)+(c-b)(c+b) = $$ $$a(b-a)-a(c-b) = a(2b-a-c)=a(2b+b)=3ab$$
Answer: Hint: $\,x_1^3+px_1+q=0 \iff x_1^3=-px_1-q\,$, then adding the three relations together:
$$\require{cancel}
x_1^3+x_2^3+x_3^3=\cancel{-p(x_1+x_2+x_3)}-3q=\cdots
$$
Comment: Great solution +1
Comment: @ChristianF Thanks. One advantage of this approach is that it easily extends to equations $\,x^{\color{red}{n}}+px+q=0\,$, where $\,\sum_i x_i^n = (-1)^{n+1}n \prod_i x_i\,$.
Comment: @dxiv I understand this method is one of the basic ones used all over the places, but is there some source where I can read about such methods. Jyrki Lahtonen has mentioned Newton's Identities above, is it something that comes from there?
Comment: @RomanKapitonov My shortcut takes advantage of the particular form of the given polynomial. In general, the [elementary symmetric polynomials](https://en.wikipedia.org/wiki/Elementary_symmetric_polynomial), [Vieta's relations](https://en.wikipedia.org/wiki/Vieta%27s_formulas) and [Newton's identities](https://en.wikipedia.org/wiki/Newton%27s_identities) should get you through.
Comment: @dxiv Thank you for your guidance
Answer: If $ x_1,x_2,x_3 $ are roots of $ x^3+p x+q=0 $ then $ x_1+x_2+x_3 = 0 $
If $ x_1+x_2+x_3 = 0 $ then $ x_3 = -(x_1+x_2) $ and
$ x_1^3+x_2^3+x_3^3 = x_1^3+x_2^3+(-1)^3(x_1+x_2)^3 = -3(x_1^2x_2+x_1x_2^2) = -3x_1x_2(x_1+x_2) = -3x_1x_2(-x_3) = 3x_1x_2x_3 $
Answer: Every symmetric polynomial can be expressed in terms of the elementary symmetric polynomials, in this case $s_1=x_1+x_2+x_3$, $s_2=x_1x_2+x_2x_3+x_3x_1$ and $s_3=x_1x_2x_3$. Since $x_1^3+x_2^3+x^3$ is homogeneous, we can find $a$, $b$ and $c$ such that
$$
x_1^3+x_2^3+x_3^3=as_1^3+bs_1s_2+cs_3
$$

For $x_1=1$, $x_2=0$, $x_3=0$: $1=a$
For $x_1=1$, $x_2=1$, $x_3=0$: $2=8a+2b$
For $x_1=1$, $x_2=1$, $x_3=1$: $3=27a+9b+c$

Therefore $a=1$, $b=-3$, $c=3$ and finally
$$
x_1^3+x_2^3+x_3^3=(x_1+x_2+x_3)^3-3(x_1+x_2+x_3)(x_1x_2+x_2x_3+x_3x_1)+3x_1x_2x_3
$$
This is a general result.
In your case, by Viète's formulas
$$
x_1+x_2+x_3=0,\qquad
$$
so in the end
$$
x_1^3+x_2^3+x_3^3=3x_1x_2x_3
$$


ROCAUC = average sensitivity across all thresholds according to IEEE TPAMI, yet my calculations show otherwise

Question: Carrington et al (2023) make the claim that area under the receiver-operator characteristic curve is equal to the average sensitivity across all thresholds, and similarly for specificity (section 3), citing a book by Zhou, McClish, and Obuchowski (2002).

Two other less commonly known interpretations of the AUC are that AUC equals average sensitivity across all thresholds, and AUC equals average specificity across all thresholds.

I had never heard this and wrote a simulation to check it out. The results are about the same if the sample size N is increased to at least a million and the number of repetitions R to at least ten-thousand.
library(pROC)
set.seed(2024)
N <- 1000
R <- 1000
aucs <- senss <- specs <- rep(NA, R)
for (i in 1:R){

  # Simulate some data
  #
  p <- rbeta(N, 1, 1)
  y <- rbinom(N, 1, p)

  # Calculate the ROC curve
  #
  my_roc <- pROC::roc(y, p)

  # Save the area under the ROC curve
  #
  aucs[i] <- my_roc$auc

  # Save the mean sensitivity and mean specificity values
  #
  senss[i] <- mean(my_roc$sensitivities)
  specs[i] <- mean(my_roc$specificities)
}

# Are all three equal?
#
summary(aucs - senss)
summary(aucs - specs)
summary(senss - specs)

The summary calls show that the AUC always differs (rather considerably) from both the average sensitivity and the average specificity. Further, the average sensitivity and average specificity are not even equal.
It appears that the claim in the article is, then, incorrect. Is there something weird about how pROC does the calculations? Is there some narrower sense in which the claim would be correct? (Did I just write code with a bug?)
REFERENCES
Carrington, André M., et al. "Deep ROC analysis and AUC as balanced average accuracy, for improved classifier selection, audit and explanation." IEEE Transactions on Pattern Analysis and Machine Intelligence 45.1 (2022): 329-341.
X.-H. Zhou, D. K. McClish, and N. A. Obuchowski, "Statistical
Methods in Diagnostic Medicine." Hoboken, NJ, USA: Wiley, 2002.
Answer: This is decidedly not my area of expertise so I'll refrain from interpreting anything, and I apologize if I only say trivial things. Since the ROC curve is given plotting sensitivity against specificity at various threshold values, the area under the curve is the average of both sensitivity and specificity (over all values of the other) in the sense that the integral of a function is just the "average" of that function.
Moreover, the computed my_roc$specificities and my_roc$sensitivities are not evenly spaced so if you want to compute the average of the specificity over all sensitivities in your simulation, you will need to weigh each specificity by "how large" the band of sensitivities that specificity corresponds to is. For example, in the below picture (at N = 100 for visual clairity), the sensitivity computed in the red circle is given for a large band of specificity compared to the black circle, but mean(my_roc$specificities) discards that.
Once we take this into account, everything seems to work out alright. The following code gives all three bottom differences as basically equal, as expected: this weighted average is identical to a Riemann sum, e.g.
senss[i] <- weighted.mean(my_roc$sensitivities[1:N],
                            diff(my_roc$specificities))

and
  senss[i] <- sum(my_roc$sensitivities[1:N] * diff(my_roc$specificities))

are exactly the same. So I think the issue is how one interprets/computes the phrase "average across all thresholds."
library(pROC)
set.seed(2024)
N <- 1000
R <- 1000
aucs <- senss <- specs <- rep(NA, R)
for (i in 1:R){
  # Simulate some data
  p <- rbeta(N, 1, 1)
  y <- rbinom(N, 1, p)

  # Calculate the ROC curve
  my_roc <- pROC::roc(y, p)

  # Save the area under the ROC curve
  #
  aucs[i] <- my_roc$auc

  # Save the mean sensitivity and mean specificity values
  senss[i] <- weighted.mean(my_roc$sensitivities[1:N],
                            diff(my_roc$specificities))
  specs[i] <- weighted.mean(my_roc$specificities[1:N],
                            diff(my_roc$sensitivities))
}

# Are all three equal?
#
summary(aucs - senss)
summary(aucs - specs)
summary(senss - specs)

}

# Are all three equal?
#
summary(aucs - senss)
summary(aucs - specs)
summary(senss - specs)

I get the following results.
> summary(aucs - senss)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
      0       0       0       0       0       0
> summary(aucs - specs)
      Min.    1st Qu.     Median       Mean    3rd Qu.       Max.
-1.354e-14 -1.665e-15  3.331e-16  4.714e-16  2.776e-15  1.432e-14
> summary(senss - specs)
      Min.    1st Qu.     Median       Mean    3rd Qu.       Max.
-1.354e-14 -1.665e-15  3.331e-16  4.714e-16  2.776e-15  1.432e-14


Impedir que animação repita ao mudar a orientação do dispositivo

Question: Estou trabalhando em uma tela que contém uma animação que é repetida toda vez que a tela é girada. Procurei mas não achei nenhuma informação precisa do que preciso fazer para que a animação não se repita ao mudar a orientação do dispositivo.
Esse é o código da Activity em questão:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class Login extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ImageView imgLogo = (ImageView) findViewById(R.id.imageView1);
        final LinearLayout LoginBox = (LinearLayout) findViewById(R.id.LoginBox);

        LoginBox.setVisibility(View.GONE);

        Animation animTranslate = AnimationUtils.loadAnimation(Login.this,
                R.anim.anim_logo);
        animTranslate.setFillAfter(true);
        animTranslate.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                LoginBox.setVisibility(View.VISIBLE);
                Animation animFade = AnimationUtils.loadAnimation(Login.this,
                        R.anim.anim_login);
                LoginBox.startAnimation(animFade);

            }
        });
        imgLogo.startAnimation(animTranslate);
    }
}

Lendo um pouco sobre o ciclo de vida de uma Activity, vi que a mesma é reinciada toda vez que o dispositivo é girado. A dúvida que ficou é: qual código preciso implementar para que a animação não seja repetida?
Answer: Sempre que a orientação é alterada a sua Activity é recriada: o método onCreateé chamado.
Uma forma simples de você verificar se a sua Activity foi recriada é verificar se o Bundle passado ao método onCreate é nulo ou não.
Quando a Activity é criada pela primeira vez savedInstanceState é nulo.
Se você quer que a animação seja apenas executada no arranque da aplicação coloque a instrução startAnimation dentro de um if:
if(savedInstanceState == null){
    imgLogo.startAnimation(animTranslate);
}

Se você quiser saber mais sobre como utilizar o Bundle passado ao método onCreate siga este Link
Comment: muito obrigado!
Comment: estava testando aqui e percebi que, ao verificar se o Bundle savedInstanceState é nulo, o layout é redefinido para o estado antes da animação (é como se a animação não tivesse sido executada). Saberia me dizer por que isso ocorre?
Comment: Isso ocorre porque a *Activity* é recriada ou seja é como ela nunca tivesse existido. No entanto o Android usa o *Bundle* passado ao método `onCreate` para guardar parte do estado que a *Activity* tinha antes de ser recriada. Você também pode usar esse *Bundle* para guardar o que achar necessário para que, quando a *Activity* for recriada, seja possível colocá-la num estado igual ao anterior, antes da recriação. Daí a razão do link que eu adicionei à resposta.


PCA captures full dataset info with half of the features

Question: I have a dataset with 13 features and run PCA on it. I can see PCA with 7 principal components can explain variance 100% and reconstruction error is 0. When may this happen? I was thinking maybe these 6 useless features are just scaled version of other 7 features thus giving no information, but correlation matrix shows at most .3 score. Any idea why this may happen?
Answer: If I understand your PCA model, you started with 13 prospective variables.  And, your PCA model used only 7 of those 13 variables that it recombined in a certain number of Principal Component functions.  And, this PCA model using just 7 of the 13 prospective variables performs really well.
You observe that the correlations between the Xs are very low at = < 0.3.  This suggests that there are no multicollinearity between those Xs variables.  Given that, your complex PCA model may add no value over a more transparent OLS regression model.  I suspect that if you run such an OLS regression with the mentioned 7 selected variables, it will perform as well as the PCA model
If your 7 X variables have strong correlations with Y, and not with each other; It is very likely you will generate a model with a high R Square (explaining much of the variance of Y)regardless if it is a PCA or an OLS regression.  The fact that 6 of the 13 variables are superfluous is a very common occurrence with such models.
However, near perfect model performance usually triggers caution.  Make sure that your model is not overfit.  Your model may fit the data.  But, is it predictive?  Does it do well in hold out out-of-sample testing, testing on new data, or cross validation.
Also, are your Y and Xs variables properly transformed?  If you have time series data, you should make sure that such variables are fully detrended to render them stationary.  Otherwise, it is very easy to get what looks like perfect models that are truly meaningless and non-predictive.  Clive Granger has covered those situations with papers on spurious regressions.
Comment: I think what you stated makes sense, multicolliniarity. correlation doesn't show this.
Comment: .3 correlation is not with label y. It is among these 13 features. I am trying to understand how we can recover fully removing 6 features and only retaining 7 components. I don't have labels for the dataset.


How do I, from a column of time values, compare them with the current time and get the closest value after the current time?

Question: Say you have a list of time values in a column in a MySQL database.
Time
-----
10:15 AM
10:35 AM
10:55 AM

And say that right now is 10:27 AM. How would I get the 10:35 AM value specifically in a variable in PHP?
I know that I could get the current time with
$currenttime = time();

and then operate on the time values with
$some_time = strtotime($row['time']);

But how do I get the closest one into that $some_time variable?
Answer: You want the row with the minimum delta between the recorded time and the reference time where the recorded time is greater than the reference time.
SELECT * FROM SomeTable AS T
 WHERE T.Time = (SELECT MIN(T2.Time) FROM SomeTable AS T2
                  WHERE T2.Time > ?)

The '?' is a placeholder for your reference time.
Comment: what's sometable and time represent? can you mix your code with my $variable settings so i can understand what you mean a bit more?
Comment: @Dan: I presume your table has a name?  You didn't tell us what your table was called (a remarkably common failing in SQL-related questions), so I had to invent a name for it; I chose 'SomeTable' to indicate that it was the name of some table in your database.  I assume that the column name is 'Time'.  You could replace my question mark placeholder with your $currenttime variable if you want to; you'd have to worry about the relevant quoting conventions.  If you can use prepared statements with placeholders, it is simpler to pass the value at the point where you execute the query.
Comment: yeah sorry about not being specific, it's late here um so if i wanted to pass the $currenttime variable instead of the question mark would I just do . "$currentime" .) or?
Comment: also, this would only give the ONE closest value after the current time right? not an entire list?
Comment: @Dan: something along the lines of: `$sql = "SELECT * FROM SomeTable AS T1 WHERE T1.Time = (SELECT MIN(T2.Time) FROM SomeTable WHERE T2.Time > '$currenttime')";`, but you'll need to worry about the data types and formatting of the data in the column and the value in `$currenttime`.
Comment: It will give only one row if the times are unique; if there are N rows with the same time (and that time is the closest), you'll get the N rows.  You'll have to decide whether that can happen and what you want to do if you do get a collision on the time.  You also need to worry about whether there are date components to your time values, and how that affects things.  Etc.
Answer: You can get closest time from within your query using TIMESTAMPDIFF:
SELECT
  time, TIMESTAMPDIFF(MINUTE, time, NOW()) AS minutes
ORDER BY
  minutes, time DESC

If you want to select just one tow with closest time:
SELECT
  time, TIMESTAMPDIFF(MINUTE, time, NOW()) AS minutes
ORDER BY
  minutes, time DESC
LIMIT 1

Answer: Try taking the absolute values of the differences between the current time and possible times. Whichever value is lowest is the closest. The only thing from there you would have to worry about is if a given time is equally close to two times which you can handle in whichever way you please (it seems most reasonable to me to simply round up at that point)
Regards,
Dennis M.
Comment: Absolute times will sometimes select a time before the current (or reference) time.  You need to ensure that the time is after the reference time, and then a simple minimum is sufficient.


Some maps of the land of mathematics?

Question: This question is motivated by a little anecdote. I was at home teaching some secondary school math to a relative. At some relax time, he glanced at a book I had over the table - it was some text about analytical number theory that I had recently bought, second hand- and I  explained him that that was an area of mathematics quite arcane to me, that I'd like to learn something about it in some future, but I had little hopes...
He looked puzzled for a moment, and then asked me: "But, wait a moment... You don't know all the mathematics?"
This happened months ago, and I'm still laughing. But also (and here comes the question) I'm still thinking about how to make some picture of this issue: the big extension of "the land of mathematics", in diverseness and ranges of depth - and the small regions that one has explored.
I was specifically looking for some kind of bidimensional (planar?) chart, perhaps with the most basic/known math kwowledge in the center, and with the main math areas as regions, placed according to its mutual relations or some kind of taxonomy.
(I guess this should go in community wiki)
Comment: The chart of interrelationships between mathematical subjects cannot be plotted as a planar graph, I suspect.
Comment: I seem to remember a graph which attempted to picture mathematical activity by area, with larger circles representing more activity. But I can't seem to locate it...
Comment: @Arturo: Perhaps you mean this: http://www.math.niu.edu/~rusin/known-math/index/mathmap.html
Comment: One thing that would be nice to do sometime is take all math papers in the arXiv, interpret the mathematical subject classifications as hex numbers, and produce a density plot of research interest over time. Unfortunately the arXiv doesn't like robots much so I don't see this happening anytime soon.
Comment: @PEV: Yes, that's the one I was thinking of. Thanks!
Comment: @PEV That link no longer works :(.  Can you please find and post a substitute?
Answer: The Princeton Companion of Mathematics is a good resource. The mathematical atlas is good as well. The size of the bubbles are directly proportional to the amount of research activity in each area. This MO post might be useful also (looking at real world applications of arxiv areas).
Comment: The Princeton Companion is a _great_ resource, but unless you consider its Table of Contents a map...
Comment: It seems Dave Rusin's Mathematical Atlas is no longer available, after moving around a bit on the Internet.  An archived version is [here](http://archive.is/www.math-atlas.org).or see the [Wayback Machine](https://web.archive.org/web/*/math-atlas.org).

Some maps of the land of mathematics?