How to generate iframe from Drupal 7 view (custom blog) with security token?

Question: I have a Drupal 7 site with a custom blog created with custom content types and a combination of views. I need to be able to export this blog as an iframe with a "long security token" to be used on a Salesforce site. I have read about several modules that can generate iframes, but I'm not sure how to go about the security side of things. Any suggestions? I've looked into the Entity Iframe project, and this seems to do what I want for individual nodes, but I'm not sure how to do this for the whole view/page.
A more involved alternative can be found here Drupal Iframe Widgets but this doesn't deal with the security side of things.
So, my questions remains: what's the best/easiest way to export a view to another site with a security token?
Answer: If you add ?entity_iframe to the url it will trigger the iframe theme. Entity iframe resize has examples of how to do cross domain communications (assuming sub-domains) securely and with less complexity then the provider / consumer handshake via the PostMessage capability built into browsers (http://caniuse.com/#search=postmessage)
Comment: Hi thanks for your answer, sorry I've taken so long to respond I've been laid up for a while. What about if I need the cross-domain security in a non-subdomain context? will that still work?
Comment: Yes I think so. I have not tried to do that myself but you can test if it works
Comment: So, the ?entity_iframe works, but I can't get it to load on another domain with just the embed code. Not sure where I'd have to implement the security token...also there doesn't seem to be an entity iframe resize module page.
Comment: Ok I'm sorry but I don't think that I can help you more than I have because I have not tried to do what you want before :-(
Comment: Appreciate the help so far, it's pointed the right way
Answer: Pretty sure there are many ways to accomplish this, however seems to me the easiest method would be creating a custom module.
This simple module would be responsible for creating a dedicated path for your view, and checking the security token for determining the access to it.
secret_blog.module

/**
 * Implements hook_menu().
 */
function secret_blog_menu() {
  $items = array();

  $items['secret_blog/%'] = array(
    'title' => 'My Secret Blog',
    'type' => MENU_CALLBACK,
    'page callback' => 'secret_blog_page',
    'access callback' => 'secret_blog_access',
    'access arguments' => array(1),
  );

  return $items;
}

/**
 * Page callback.
 */
function secret_blog_page() {
  $view = views_get_view('MACHINE_NAME_OF_YOUR_VIEW');
  $display_id = 'default';
  $args = array();
  $content = $view->execute_display($display_id, $args);

  $build['content'] = array(
    'secret_blog_view' => array('#markup' => $content),
  );

  return $build;
}

/**
 * Access callback.
 */
function secret_blog_access($access_token = '') {
  if ($access_token == 'LONG_SECURITY_TOKEN') {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

For this example let's assume your website is served at http://example.com and the blog view would be accessible at http://example.com/secret_blog/LONG_SECURITY_TOKEN
Now, you can provide that URL to Salesforce (or any 3rd party service) for embedding into it.
I suppose you would also need to use a different layout than the site default; you should create the necessary HTML and/or PAGE templates suiting to your needs. To find out proper template names enable theme debugging in settings.php file (this feature is available as of Drupal 7.33).

$conf['theme_debug'] = TRUE;

The suggested template names would be something like these:

html--secret-blog--LONG_SECURITY_TOKEN.tpl.php
page--secret-blog--LONG_SECURITY_TOKEN.tpl.php
Comment: Sorry it's taken me so long to check on this. Quick question about your solution: will the page callbacks allow content to be displayed that should be for logged in users only?
Comment: If you want to check against both conditions; you should update the statement like this:

`if (user_is_logged_in() && ($access_token == 'LONG_SECURITY_TOKEN'))`
Comment: I'm hoping to avoid users all together and just allow that single context to stay logged in so the authenticated users on the other site will have a seamless experience. As I'm just exposing a single view, I don't think there are huge security implications to expose it to anonymous views on a single path and iframe that, but I want to avoid the bad practice of sending credentials through the URL and my security requirement. My research suggests that maybe using oauth here would work, but I haven't seen a good example of how to actually set it all up for newbies...


Use of post hoc tests following model selection based on AIC

Question: I am working on a dataset of vegetation characteristics recorded over three seasons in two different areas used by buffalo.
I have run generalised linear mixed models to determine whether vegetation biomass changes seasonally in different areas used by individual buffalo. I have run every possible combination of model and used AIC to identify the one with the best fit, which includes a fixed effect of season.
Within the best-fitting model, I would like to know which seasons differ from each other, and for this I used a post-hoc Tukey test from the multcomp package to compare pairs of seasons, and identified season pairs that differed significantly based on p-values.
I have been told that using the AIC model selection and the post-hoc tests based on p-values is mixing two types of analysis methods and is therefore not viable. Is this correct?
I have searched the literature and cannot find any statistical papers that refer to this specific question, but I have found some research papers that have used this method. Can anyone direct me to relevant publications that can help me with this?
If indeed I cannot mix the two methods, does anyone have a suggestion for another way to look at differences between factor levels of a fixed effect?
Edit
Thank you for the response, but I just want to make sure that the question I am asking is clear. I got this response from a different forum, which may help to clarify the question that I am asking:
"This might depend on how you ran the model comparisons. If you had Season as e.g. a dummy-coded variable or something like that, and put all levels of it in as one step of the model (or e.g. just did it the R way, putting 'Season' in as its own predictor), then indeed model comparison doesn't tell you which levels of Season are different from each other, and therefore you still need some kind of post-hoc tests (or at least just inspecting the model coefficients, but indeed these should likely be corrected for multiple comparisons) to see which levels are different from which."
I am trying to make sure that I am interpreting answers correctly, but for that to happen I have to be sure that my question is clear as well.
Many thanks for all the responses
Emily
Comment: It may help to read my answer here: [Algorithms for automatic model selection](http://stats.stackexchange.com/a/20856/7290).
Answer: If you choose your model based on the actual observations (using aic, stepwise-regression etc.), your inferential statistics will be invalid for all the reasons gung has described here. Don't do it.

If indeed I cannot mix the two methods, does anyone have a suggestion
  for another way to look at differences between factor levels of a
  fixed effect?

Specify your model in advance, before observing any data.
Of course, you can conduct a pilot study and try different models on pilot data. This is completely valid. However, you cannot do valid inferential statistics on this dataset. Instead, specify your model based on your pilot data, and then collect independent new data on which you can perform inferential statistics with the prespecified model.
(Theoretically, you could possibly also account for your model selection in running inferential statistics on the same dataset you also selected your model for. However, I don't know how I would go about this, since this would in turn depend heavily on the specific dataset in question.)
Comment: Reasonable ways to account for the model selection that could be combined with AIC based criteria include to use model averaging or bootstrapping the model selection process (and averaging across the outcomes across the different bootstrap samples) and a number of other approaches. Of course there's other approaches that are not AIC based e.g. LASSO etc.


Allowing ajax link clicks to propagate

Question: A click event on a link with the use-ajax class on it does not seem to propagate up the DOM. Is this true? If so, is there a setting that will allow it to propagate?
Not being a JS whizz, I'm struggling to see where the call is made (preventDefault? return false?) that blocks the propagation. I've had a look at misc/ajax.js and there is a setting element_settings.prevent that looks like it might be relevant, but I haven't found any documentation on this.
Answer: It's in Drupal.ajax.prototype.eventResponse, round about line 265:
// For radio/checkbox, allow the default event. On IE, this means letting
// it actually check the box.
if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  return true;
}
else {
  return false;
}

It's hard-coded, but this is JS - you can just monkey-patch Drupal.ajax.prototype.eventResponse and get it to do whatever you like :)
Comment: Brilliant, thanks. Do you happen to know why "return false" is used instead of "preventDefault"? Seems to me that preventDefault would do what is intended and no more
Comment: Returning `false` is equivalent to running `event.preventDefault()` _and_ `event.stopPropagation()`. If I had to guess, I'd say that's why they've done it - just for brevity
Comment: Sorry, you're asking why the use of `stopPropagation()` at all, aren't you...'fraid I don't know that one. Might be an oversight, might be intentional

Allowing ajax link clicks to propagate


NativeScript Background Service JavaScript

Question: I've been trying to get Background Services working with NativeScript. I've tried to get a basic example following this tutorial.
https://ozymandiasthegreat.medium.com/android-continuous-background-services-with-nativescript-a0840fc1eceb
But to make it work with javascript. However the issues I am finding are that there are newer modules and it seems to be tricky in a JS environment.
Is there any hints to getting a basic background service just to ping a console log every second (for now, and i can then implement the geolocation part)
Answer: Starting with version 11, Android began to disable the background service. "Battery saver"!
Starting from version 11+, it is forbidden to start services from the background service!
Navicescript uses api worker to implement services and background service. But this will be a service that the OS can stop to save battery.
How to bypass it?
In AndroidManifest.xml add uses-permission
SET_ALARM, SCHEDULE_EXACT_ALARM, REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, RECEIVE_BOOT_COMPLETED
Receiver in android 11+ Can't start the service
Comment: that's interesting, will have to look into this


Does being well approximated by a polynomial characterize higher differentiability?

Question: Suppose $f:\mathbb R\to \mathbb R$ admits a polynomial $\sum_{k=0}^n\lambda_k(x-a)^k$ of degree $\leq n$ satisfying $f(x)-\sum_{k=0}^n\lambda_k(x-a)^k\in \mathrm o(|x-a|^n)$ as $x\to a$. Then dividing by powers of $(x-a)$ shows
$$\begin{aligned}\lambda_0 & =\lim_{x\to a}fx, \\ \lambda_1 & =\lim_{x\to a}\tfrac{fx-\lambda_0}{x-a}, \\ \lambda _2 & =\lim_{x\to a}\tfrac{fx-fa-\lambda_1(x-a)}{(x-a)^2}=\lim_{x\to a}\tfrac{\tfrac{fx-fa}{x-a}-\lambda_1}{x-a}, \\  & \vdots \\ \lambda_n & = \lim_{x\to a}\tfrac{fx-\sum_{k=0}^{n-1}\lambda_k(x-a)^k}{(x-a)^n}. \end{aligned}$$
Thus the asymptotic condition determines the polynomial, so it is unique when it exists. If $f$ is furthermore continuous at $x=a$ then $\lambda_0=fa$ whence $\lambda_1=f^\prime(a)$.

If $f$ is $n$-times differentiable at $x=a$ then Peano's form of Taylor's theorem tells us $R^n_af\in \mathrm o(|x-a|^n)$ as $x\to a$. Here $R^n_af(x)=f(x)-j^n_af(x)$ and $$j^n_af(x)=\sum_{k=0}^n\tfrac 1{k!}f^{(k)}(a)(x-a)^k$$ is the $n^\text{th}$ order Taylor series of $f$ about $x=a$.
By uniqueness we therefore have $\lambda_k=\tfrac 1{k!}f^{(k)}(a)$. For instance taking $k=0,1,2$ gives $$\tfrac 12f^{(2)}(a)=\lambda _2  =\lim_{x\to a}\tfrac{fx-fa-f^\prime(a)(x-a)}{(x-a)^2}=\lim_{x\to a}\tfrac{\tfrac{fx-fa}{x-a}-f^\prime(a)}{x-a}.$$

I am interested in the converse: are continuous maps which are well approximated by a polynomial of degree $\leq n$ necessarily $n$-times differentiable?
Question. Suppose $f$ is continuous and admits a polynomial $\sum_{k=0}^n\lambda_k(x-a)^k$ of degree $\leq n$ satisfying $f(x)-\sum_{k=0}^n\lambda_k(x-a)^k\in \mathrm o(|x-a|^n)$ as $x\to a$. Does it follow that $f$ is $n$-times differentiable at $x=a$, with $\lambda_k=\tfrac 1{k!}f^{(k)}(a)$?
Already for $k=2$ this amounts to the assertion$$\tfrac 12f^{(2)}(a)=\lambda _2  =\lim_{x\to a}\tfrac{fx-fa-f^\prime(a)(x-a)}{(x-a)^2}=\lim_{x\to a}\tfrac{\tfrac{fx-fa}{x-a}-f^\prime(a)}{x-a}.$$ This is not obvious at all to me.
Answer: The idea is that you cannot reclaim any information about  any neighborhood of $a$. So basically, $f$ may not even be differentiable at any neighborhood of $a$, so definitely it cannot be twice-differentiable. Consider the following example:
$$f(x)=W(x)\cdot e^{-\frac1{x^2}}  $$
Where $W$ is the Weierstrass function. $W$ is known to be non-differentiable at any point. However, $W$ is bounded, and so
$$ f(x)=o(x^n),\quad \forall n\in\mathbb N$$
just as $e^{-\frac{1}{x^2}}$ is. So, $f$ is differentiable at $0$ but
it is non differentiable at any other point. Therefore, we cannot even ask the question whether it is twice differentiable at $0$.


Merge Sort stops before displaying the sorted array

Question: I was trying to code Merge Sort using the algorithm, given in my textbook.
I did exactly as shown but the program stops after MergeSort function is called.
This is an image of the output when I executed it.
It is printing the unsorted array fine but omits everything after function call in line 16.
Please Help!!
<code>#include <iostream>

using namespace std;

int a[10] = {23,13,41,27,55,83,12,65,11,20};
int b[10];
void MergeSort(int,int);
void Merge(int,int,int);

int main(){
    int len = sizeof(a)/sizeof(a[0]);
    cout<<"array beffore sorting:";
    for(int i = 0; i<len; i++){
        cout<<a[i]<<" ";
    }
    MergeSort(0,9);
    for(int i=0; i<10000000; i++);
    cout<<"After Sorting:";
    for(int i = 0; i<len; i++){
        cout<<a[i]<<" ";
    }

}
void MergeSort(int l, int h){
    if(l<h){
        int mid = (l+h)/2;

        MergeSort(l,mid);
        MergeSort(mid,h);
        Merge(l,mid,h);
    }

}

void Merge(int low, int mid, int high){
    int h = low;
    int i = low;
    int j = mid + 1;

    while(h<=mid && j<=high){
        if(a[h]<a[j]){
            b[i] = a[h];
            h++;

        }
        else{
            b[i] = a[j];
            j++;
        }
        i++;
    }
    if(h>mid){
        for(int k= j; k<=high; k++){
            b[i] = a[k];
            i++;
        }
    }
    else{
        for(int k= h; k<=mid; k++){
            b[i] = a[k];
            i++;
        }
    }
    for(int k= low; k<=high; k++){
            a[k] = b[k];
    }

}
</code>
Comment: think about what happens in `MergeSort` if `l` is `0` and `h` is `1`
Comment: my bad, i missed that logic bad!! Thanks !!!
Comment: Are you on an embedded system using `for(int i=0; i<10000000; i++);` loop for a delay loop? That would certainly cause a "stop" before displaying the output. You may want to at least add comments to indicate what unusual looking parts of your code do.
Comment: yea that was not necessary apparently the problem was in the MergeSort() function.
Answer: I made an error int the logic of MergeSort function got the answer!!
<code>#include <iostream>

using namespace std;

int a[10] = {23,13,41,27,55,83,12,65,11,20};
int b[10];
void MergeSort(int,int);
void Merge(int,int,int);

int main(){
    int len = sizeof(a)/sizeof(a[0]);
    cout<<"array beffore sorting:";
    for(int i = 0; i<len; i++){
        cout<<a[i]<<" ";
    }
    MergeSort(0,9);
    cout<<"After Sorting:";
    for(int i = 0; i<len; i++){
        cout<<a[i]<<" ";
    }

}
void MergeSort(int l, int h){
    if(l<h){
        int mid = (l+h)/2;

        MergeSort(l,mid);
        MergeSort(mid+1,h);
        Merge(l,mid,h);
    }
}

void Merge(int low, int mid, int high){
    int h = low;
    int i = low;
    int j = mid + 1;

    while(h<=mid && j<=high){
        if(a[h]<a[j]){
            b[i] = a[h];
            h++;

        }
        else{
            b[i] = a[j];
            j++;
        }
        i++;
    }
    if(h>mid){
        for(int k= j; k<=high; k++){
            b[i] = a[k];
            i++;
        }
    }
    else{
        for(int k= h; k<=mid; k++){
            b[i] = a[k];
            i++;
        }
    }
    for(int k= low; k<=high; k++){
            a[k] = b[k];
    }

}
</code>


Do I need to clone a webform?

Question: I have created a webform a few days back. Now I want to re-use the webform which I created earlier with other results, so to save my time and energy I just want to clone that webform and reuse for a different purpose.
Note: previous webform has some result. However I do not want to have this result in the exported webform, I only need the form.
Comment: Do you want to add result too in the exported webform?
Comment: No @vishal i only need the form
Comment: Then check the solution provided by me
Answer: Use Webform Share(https://www.drupal.org/project/webform_share) module to export & import
Example usage 1: Prepopulated webforms

Create a webform with the required components.
Export the webform
Edit the webform content type and paste in the content from the export (under Publishing options)
Use the standard node add content links and each new content item created should be prepopulated with the exported webform.
Comment: Great module, lots of time saved :)
Comment: I am trying to use node clone but the 'clone' operation won't show up for any of my 'webform' content types.
Comment: Note that Webform Share doesn't export or import the node body or properties, only the webform-specific data.
Answer: Node clone  module is another option for webform

The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.
Answer: You can use Node Clone for cloning webforms or any nodes. It provides a simple interface to clone webform or nodes on node page itself.
If you want to export the submission data also then you can use webform import module.
Answer: If you need the webform configuration of the webform node you can use https://www.drupal.org/project/webform_template

Copy webform configuration from one node to another
This is an add-on
  module for Webform that allows you to select webform enabled content
  types as "source" and/or "destination" types. On node edit/creation of
  the so called "destination" types, you have to option to apply (=
  copy) the webform settings (including all webform fields) from nodes
  of the "source" type.

Im note sure about the submissions.

Do I need to clone a webform?


RDP Copy&Paste Error: Windows cannot find '%1!ls!'

Question: After working for years on mRemoteNG, and copying and pasting from servers I use all the time, I suddenly started getting the following error on a particular Windows 2003 server:
<code>Windows cannot find '%1!ls!'
</code>
Copying and pasting from the exact same server works with regular RDP (mstsc.exe). Everything seems to be set up fine in both, including clipboard and drive sharing.
Reading numerous online forums did not give the right direction, but the solution was fairly simple (see answer).
Answer: The solution was unbelievably simple: enabling Smart Card sharing did the trick and copying&pasting works again.
I am still trying to figure out why—on other almost identical Windows 2003 servers, Smart Card sharing is still disabled and copying and pasting still works.
Comment: Thank you! This worked for me using the Remote Desktop Manager from Devolutions. I had to enable the "Smart Card Sharing" under the Local Resources Tab of the Connection's parameters.
Comment: Am using RDM from Devolutions as well and needed to disable Clipboard sharing in `Local resources`. Smart card-related options didn't change a thing and clipboard makes somewhat sense as that has changed over the years in Windows.
Answer: The other thing you need to be cognizant of is if your RDP program has the "Connect to Console" checked. Then uncheck it.. or add the check to the "Smart Drive" shared resource.
Answer: I just had a similar issue with a Colleague. While we use mRemoteNG in our environment, he was using only the built in rdp client, mstsc.exe.
We found that for this particular server he had enabled the local C: drive to be shared from the Local Resources -> More button.
In our environment SMBv1 is blocked, and since the server is 2003 (and hence only has SMBv1) there must be some kind of volume check going on via terminal server that results in the error. Once the C: drive was no longer shared, the right-click -> copy function worked again.


Função Screenshot no android

Question: Estou colocando a função de screenshot no calendário, porém a foto não está saindo como deveria.

Mas usando a função nativa do android sai correto

Segue trecho do código:
View v1 = getActivity().findViewById(R.id.ScrollcalendarView);

            v1.setDrawingCacheEnabled(true);

            ScrollView z = (ScrollView) getActivity().findViewById(R.id.ScrollcalendarView);
            int totalHeight = z.getChildAt(0).getHeight();
            int totalWidth = z.getChildAt(0).getWidth();
            v1.layout(0, 0, totalWidth, totalHeight);

            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or OOM
            e.printStackTrace();
        }
    }

Alguém tem ideia do que pode ser?
Answer: Resolvido!
Alterei a linha:
new float[]{0, 0.5f, 0.5f, 0}, Shader.TileMode.REPEAT);

Para:
new float[]{0.5f, 0.5f, 0.5f, 0.5f}, Shader.TileMode.REPEAT);

Ficando assim:
private static Drawable generateSemiCircleDrawable(final int color1, final int color2) {

        ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
        drawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
            @Override
            public Shader resize(int width, int height) {
                return new LinearGradient(0, 0, width, height,
                        new int[]{color1, color1, color2, color2},
                        new float[]{0.5f, 0.5f, 0.5f, 0.5f}, Shader.TileMode.REPEAT);
            }
        });
        return drawable;
    }

E depois de pronto ficou assim.
Answer: Problema resolvido! em parte.
Estava usando:
view.setBackgroundDrawable(generateCircleDrawable(color));

e mudei para:
view.setSelectionDrawable(generateCircleDrawable(color));

Mas quando de trata de duas cores exemplo:
view.setSelectionDrawable(generateSemiCircleDrawable(color1, color2));

Só aparece a uma cor como pode ser visto no post.
https://github.com/prolificinteractive/material-calendarview/issues/263
O estranho é que só acontece com o código no App, usando o screenshot nativo funciona bem.
Ainda aguardo sugestões

Função Screenshot no android


Perl executable crashes even though file is not missing

Question: I get the following error:
Can't load '...\AppData\Local\Temp\par-6e72616f\cache-20221205133501\5743946b.xs.dll' for module GD:
   load_file:
      The specified module could not be found at <embedded>/DynaLoader.pm line 193.
      at <embedded>/PAR/Heavy.pm line 140.

(Line breaks added for readability.)
Here is the file t2.pl:
use GD;

Here is the command to convert it to an exe (I use a batch file that timestamps it):
pp -T 20221205133501 -o t2_20221205133501.exe t2.pl

On my laptop, the exe works, but on a barebones Citrix environment it fails.
My environment:

Strawberry Perl v5.32.1 built for MSWin32-x86-multi-thread-64int
GD v2.73

I know the file is simple, but that one line is enough to cause the crash.
The file it complains about exists and is located where it is looking.
I have looked and is looks like I need to add -m GD, or -l xxx to make it work. I tried adding all the dll files I could find for GD, but failed.
I have a corporate environment so I can't really use anything that depends on external programs not in Windows 10. pp_simple depends on wxpar which I do not have. I have used:
objdump -x C:\Strawberry\perl\vendor\lib\auto\GD\GD.xs.dll | find "DLL"

which got me a list of DLLs, and I did try using them with -l.
Comment: Note that the module in question might not be the .xs.dll, but a DLL used by it.
Comment: You can use process explorer on the machine where you pack the program. It runs without installation under standard user privileges. https://stackoverflow.com/a/53353869/10667839
Answer: From Re: Par with strawberry-Perl

There are likely missing DLLs that need to be added to the pp call
using the --link option.
Finding these manually can be a pain, so have a look at pp_autolink or
pp_simple (the former is mine, but adapted from the latter).

https://github.com/shawnlaffan/perl-pp-autolink
https://www.perlmonks.org/?node_id=1148802


At what points is the function discontinuous

Question: I am stuck on this math problem in my precalc class. If you have time, could you please explain how to do this to me? Thank you!
Answer: Intuitively, a function is discontinuous at points where you have to lift your pencil from the page when you draw it's graph. Of course, it's also not continuous where it isn't even defined (like at a vertical asymptote). Try applying that to your function!
Comment: Sweet, I guess I was over thinking it then :P That seems fairly simple. Thank you guys!
Comment: This answer is correct, but I would like to point out that disturbingly, shockingly, many texts would call $-1$ a point of discontinuity here.
Comment: So the points at which it is discontinuous would be 2 and -1?
Comment: I don't really see a problem with that, and in my response I tried to guide Alan to include -1 in his answer. This is precalc, not rigorous analysis.
Comment: Sorry, I have to disagree with @ZachEffman's second comment. If you define a function to be discontinuous where it isn't defined, then $\sqrt x$ will have to discontinuous for all negative numbers. More fully, for a function to be discontinuous at $a$, it must be defined at $a$ and not continuous there. And continuity will not even be considered at points of nondefinition.
Comment: That's certainly true, but at the precalculus level pretty much everybody treats vertical asymptotes as points of discontinuity. I agree with you on what the true definition of discontinuous should be.


Is it necessary to dispose variables in finally block in static methods?

Question: This example below I found while looking answer to another quiestion.
Here that guy disposes response in finally block.
Is it really necessary? Is it a GC's work in this case?
public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
    {
        try
        {
            if (response.IsSuccessStatusCode)
                return;
            var content = await response.Content.ReadAsStringAsync();
            throw new SimpleHttpResponseException(response.StatusCode, content);
        }
        finally
        {
            response.Content?.Dispose();
        }
    }

Comment: I don't like very much disposing an object passed as a parameter... it is something a little... I don't know... Not beautiful... Not bad bad, but not good good.
Comment: But the code is correct... If possible/not too much difficult, you should always `Dispose()` `IDisposable` objects... It helps the GC... and you don't have any guarantee the GC will ever run. If there is no memory pressure, the GC could not run for a long time.
Comment: @xanatos - The GC **never** ever calls `.Dispose()`. You must explicitly do it.
Answer: The whole point of using IDisposable is to clean up unmanaged resources that the GC can't clean up on its own.  So no, you can't just let the GC clean it up because, by definition, it can't.
Comment: A correctly implemented `IDisposable` pattern has a finalizer if it manages unmanaged resources, so even if `Dispose()` isn't called, at the next GC run everything fill be fixed. Incorrect `IDisposable` patterns are by definition incorrect, so they could even not free everything :-) So the only use of `Dispose()` is to guarantee a deterministic and timely freeing of the unmanaged resources.
Comment: @xanatos finalizers *might* clean up the resource.  There are a number of circumstances in which they won't run at all.  They are, by design, unreliable.  For resources that need to be reliably cleaned up, you need to be manually disposing of them.  There are also plenty of disposable resources that *don't* have finalizers.  It is incorrect to assume that every single disposable resource must have implemented a finalizer, just as it's incorrect to assume that that finalizer must run.  It is not "incorrect" for a disposable resource to not implement a finalizer.
Comment: The question though becomes, at least in this case, because the method doesn't *own* the `HttpResponseMessage`, should the method be calling `Dispose` on it (or its contents). If the owner then calls the `Dispose` this will cause an exception. I tried looking for the source, but I would assume disposing the `HttpResponseMessage` calls `Dispose` on its `Content` property, would this not cause hard-to-trace issues later?
Comment: @RonBeyer WIthout knowing the intent of the method, and the context of its use, that's rather hard to comment on.  It seems that this method is created with the intent of cleaning up the object when it's done.  Whether that actually makes sense for this particular operation is something that we don't really have enough information to comment on.
Comment: @RonBeyer Both `HttpResponseMessage` and `HttpContent` are correctly (where correctly means "as suggested by Microsoft on MSDN) done and can accept multiple `Dispose()` without any problem
Comment: Maybe the `Dispose` was the wrong choice of an example, but if something somewhere else assumes that the `HttpResponseMessage` is not disposed and tries to access the `Content` property, it will except as trying to access a disposed object. I agree with Servy though, the context here is not enough to draw a conclusion from the example.


Domain Access: Edit admin/domain/content/ display settings, filters etc

Question: I am using Drupal Commerce and Domain Access module and I wonder where I could be able to edit how page admin/domain/content is displayed. I would expect to find a View page which is utilised by this module to show content and to allow to add filters and fields.
I have got a multi-domain site with thousands of products and I need to filter content by manufacturer or other field and to assign all products with desirable keywoord to selected domains.
Am I missing anything? I have not found any corresponding View.
Thank you for an answer
Answer: Domain Access does not provide a view like you want.
You could try the Admin Views module which overrides the standard content admin page with a view.
Also, Domain Views module which integrates domain access with views.
Comment: I think this https://www.drupal.org/project/domain_vbo is exactly what I needed. Adding an action of setting domain affiliation to views bulk operation.
Comment: Thank you for your answer. Maybe it would suffice if there is a possibility to widen filter criteria form - beside Status, Type and Language I just want to add one or two more, to filter content by another field. I am not really good at programming, but I guess it could be accomplished somehow by editing domain_content.admin.inc like editing number of items to display?
Comment: You could write your own module which does the same as the the domain admin interfaces, than add your own customizations. Editing the files of the domain access module is probably not the ways to go as updating the module would override your edits.
Answer: The Domain Access module for Drupal is for sorting and displaying content and themes/styles depending on the added system aware domains, which have to be covered, and only works with proper virtual host settings on server for incoming calls. It can achieve to give the visitor the feeling to be on two different places or at near but slidely different places. It is made for the cases where you definitely need a shared backend and content or design pool for two different domains but should not be considered for any case. It isn't as easy as it reads on the module project page. It needs further understanding how paths work in Drupal universe and can get broken on bigger updates. And you will have a hard time to teach a views view to be filtered different depending on incoming domain, even with Domain Views Module at hand.
I sadly can not confirm to use the other recommendation Admin Views modules because it is too limited in its approach and its not true that views doesn't support overriding admin pages. It works very well and is mostly one of my first steps in a new Drupal installation. It even works great with the different tabs on the admin pages (like admin/content with the files or comments tab) and there are enough tutorials around explaining the path settings to setup and how it works. I hope I make noone upset here, but I think it is not true to say, that you need Admin View module for overriding admin pages like admin/content etc. Maybe there was a time when it was hard to achieve this with views allone, but in the meantime views has a lot of options to make it work and even with more options than Admin Views module provides out of the box and stucks there on its limits.


Dynamically size images for mobile first design (omega theme)

Question: I've built my first site using an omega subtheme and I'm really liking it. The mobile first design dynamically changes the width of the page to follow the width of the browser.
With my column arrangement with a wide browser, my content area is 780px wide. So, the header images I use on my blog posts are up to 780px wide. If the user's browser is more narrow, then the css will shrink the content area to the following sizes:
wide: 780px
normal: 620px
narrow: 460px
mobile: 720px and smaller (in this arrangement the sidebars are removed to give the content more room.
The smaller the browser gets, the smaller the content area gets. When it is below 720px, then it follows pixel for pixel, so if I make my browser only 480px wide, then that's how wide the content area will be.
PROBLEM:
The header image on my Article nodes is up to 780px wide so that it fills the content area in the widest browser size. However, when the content area shrinks to 620px, the image doesn't get smaller which means that it overlaps the side bar.
The image below shows how the layout would work in the "wide" arrangement.

The next one shows how the header image is overlapping the sidebar in the "normal" arrangement:

I tried to solve the problem by setting the css width of my header image to be 100% of its container element. That did successfully restrict the width of the image, but when drupal generates the html for that image it always includes explicit width and height tags. This causes the image to become distorted because the width is shrinking to match 100% of the parent container but the height isn't changing along with it, so it ends up looking like this:

Is there a way to prevent drupal from including the explicit height attributes? Or is there some other drupal solution?
I know that I could set up some javascript to strip those attributes off, but that seems really hackish.
Any suggestions or solutions?
Answer: More of a CSS than Drupal question, but the standard solution is
img {
  max-width: 100%;
  height: auto;
}

You might get some funny results with images inside table columns that don't have an explicit or minimum width set, but those just have to be handled on a case-by-case basis.
Answer: I would add this in a comment to Clive's answer, but I don't have enough reputation to post a comment, so I'll add this here. Not only is the standard CSS solution correct, but be sure also to read Ethan Marcotte (who was one of the first prominent authors to write about responsive design) writing about fluid images at: http://unstoppablerobotninja.com/entry/fluid-images/
There's important information there as to making fluid images a bit more cross-browser compatible, especially for older versions of IE that don't understand max-width.
Cheers!


my reducer functinos calls sometimes once, sometimes twice and i dont understand what is the problem.. :(

Question: my reducer functinos calls sometimes once, sometimes twice and i dont understand what is the problem.. :(
My nodejs server sometimes gets 2 requests and sometimes one request but I only tell the app to send one request as soon as a button is pressed.
i know i have a bad erorr handling, just tried to use context and reducer..
import AuthContext from "./AuthContext";
import React, { useCallback, useEffect, useReducer } from "react";
import axios from 'axios'

function AuthContextProvider(props) {

    const AuthManager = useCallback((state, action) => {
        if(action.type === "signup") {
            axios.post("http://localhost:3001/users/signup", {...action.payload}).then(res => res.data).then(data => {
                console.log(data);
                return {
                    login: true
                }
            })
        } else if(action.type === "login") {
            axios.post("http://localhost:3001/users/login", {...action.payload}).then(res => res.data).then(data => {
                console.log(data);
                return {
                    login: true,
                    user: data.user
                }
            })
        }

    }, [])

    const [state, dispatch] = useReducer(AuthManager, {
        login: false,
    })

    const authObject = {
        login: false,
        signupHandler: (account) => dispatch({type: 'signup',  payload: {...account}}),
        loginHandler: (account) => dispatch({type: 'login',  payload: {...account}}),

    }

    return <AuthContext.Provider value={authObject}>{props.children}</AuthContext.Provider>
}

export default AuthContextProvider

Answer: Where are you calling these actions?
Also, why don't you take your reducer outside your component instead of using useCallback hook?
e.g:
Comment: Please don't post images of code.


dotnet publish with absolute path do not respect output

Question: Repro
On windows with git bash:
I created some asp net core web app with razor pages. Now I would like to publish it to directory.
dotnet publish -o C:\temp\myApp

Temp directory exists, wheras MyApp not exists yet.
Problem
dotnet publish to ..\currentProjectDirectory\tempmyApp
Why its happens? I have also tried to run git bash with admin permissions, but it has not helped.
Answer: You use git bash. It means you should use linux-style path:
dotnet publish -o /c/temp/myApp


UISlider and continuous property

Question: I am changing a value with UISlider and  this value is the number of my PDF pages , so when users sliding they can navigate through the pages , because of tiles rendering I need set continuous property to NO, also I need a live page counter that uses with the same slider, so the property should be YES :, how can I set the property yes or no for specific codes with the same slider ?
this part , the property should be  NO
navSlider.continuous = NO;
     pageInt = CGPDFDocumentGetNumberOfPages(pdfscroll.pdf);
     prgress = (int)(navSlider.value + 0.5);
    navSlider.maximumValue = pageInt;
    navSlider.minimumValue = 1;
    [bookController moveToPage:prgress];

and here yes :
navSlider.continuous = YES;
    NSString *numberOfPage = [NSString stringWithFormat:@"%d of %d",prgress,pageInt];
    pageCounter.text = numberOfPage;

Comment: @KaHole  I modified the question
Answer: You clearly do need to know about every slider change, so it must be continuous.  However, you should not call [bookController moveToPage:prgress]; after every single slider movement.  The solution is to update the page number for every slider movement, but only call [bookController moveToPage:prgress]; when the slider is released.

UISlider and continuous property


Como associar/abrir arquivos mp3 na pasta raw?

Question: Eu estou com probremas com musicas, sempre que adiciono alguma musica e vou executar algum código da erro, sempre que clico na musica na pasta raw aparece um texto , em tutoriais que eu vi a pessoa clica na música e toca ela vou mostrar fotos,
Answer: Isso acontece porque ao copiar o arquivo para a pasta raw você associou-a como texto ou algo do género.
De qualquer forma o AndroidStudio não possui um player de música interno.
O que deve fazer é, na janela de associação, escolher a opção "Open matching files in associated application"
Isso irá abrir a aplicação registada no Windows para abrir arquivos com a extensão mp3.

A associação de arquivos pode ser gerida em File -> Settings ; Editor/File Types


Quickest way of moving a large number of files?

Question: I've got to move around 320,000 files, 80,000 folders (only 100 Gb) of data. Some files are > 1GB but most are < 1kB.
I've had a look at Fastest method of copying files but I'm not sure how useful any of these will be, my problem is not about pure transfer rate speeds but really about how quickly Windows can deal with the IO of 320,000 files.
Do you think I will see speed benefits using either xcopy, robocopy, teracopy or fastcopy?
It took us long (12 hours+) to copy them once (using robocopy), and I hate to have to do that again. What can I do to speed it up?
The stuff is on a USB 2.0 External Drive.
Answer: Something like robocopy will be your best bet.  USB drives can't handle a whole lot of IO to begin with.
I've pushed millions of small files to and from USB drives using robocopy.  It takes time, but it gets the job done.
Answer: As mrdenny said, Robocopy would be best, partly because of its robustness. The best advise I can offer, provided you're sure about the cleanliness of the files to be moved, is to make sure the antivirus software is disabled while they are being moved. You really don't want the overhead of having all those files being scanned.
Answer: Obviously there is a quicker way than all mentioned here. Quicker, but less flexible :-) If you have put the files on a separate partition, you can copy the entire partition to the target disk.
I'm not familiar with any free Windows tool for the job (tool with VSS support would be perfect), but for sure you can boot off Ghost CD, or Partition Magic CD, or boot a Linux standalone CD. In linux you just dd the partition, or ntfsclone if this happens to be an NTFS partition.
Answer: You will almost certainly experience better overall performance for the transfer sequence if you first pack up the source files into a single archive (tar, or compressed into zip, etc), then transfer the archive over the network, and then unpack the archive at the destination.
Please don't forget that when you're transferring the archive over the network, you will be better off using ftp (or another file-oriented transfer protocol) than a simple SMB file copy.
Using a process like the above, I've routinely transfer application directories of about 60GB (with about 50,000-75,000 files) between multiple, geographically-separated, datacenters (US, Europe, Asia).   The difference between transferring one file at a time, and transferring a compressed archive over FTP is 10-40 times faster.
Rsync can be your friend here too (as it can in many other file transfer scenarios).
If you are open to commercial options, a UDP-based binary streaming solution that can push bits over multiple UDP streams might be of value to you.  Take a look at http://www.filecatalyst.com/
Answer: If I were you I would change the external Harddrive to a Firewire, the speed transfer is alot faster than USB2.
I think that maybe packing the files into a single "tar", and then transfering the files would save a bit of time. Cause it reduces the I/O times, since your only copying 1 giant file over, compared to thousands of files, it also consumes less resources I believe (during the copy phase). Or you can pipe the tar stream straight to your USB drive.
Comment: Yes, I know the single tar approach will definitely yield results, but wasn't sure if building the single file would take a significant amount of time.
Comment: Firewire's good but eSATA can be faster too.
Answer: I found the most efficient way to copy large numbers of files was to stream them in to ISO files first and then copy the ISOs instead. This way the disk isn't concerned by issuing the thousands of commands required to copy files.
Of course this depends on your directory structure. I was fortunate enough to have a new directory created at 4.7GB intervals so it made creating a VBScript to automate the process a lot easier.
Comment: @JohnGardeniers Lewis is betting that the time it takes to copy small files across the network have a much greater overhead than the time it takes to put them into an ISO and then transfer that file. It really depends on your particular environment, but as unintuitive as it sounds, it can be faster to transfer one consolidated instead of thousands of tiny files.
Comment: I don't follow your logic. To create the ISO all those files need to be read and written into the ISO. Then the ISO is read to extract the files and finally write them to the destination. How is that more efficient than reading and writing them once?
Comment: any sample code in VBSCript, C#, or another script language ?
Answer: Another option would be to use Bittorrent using a built-in tracker or DHT turned on. The client would group all the files together in blocks (use 2MB or bigger if available). On the receiving end, you will receive files in big block chunks as they get written to the hard drive. This helps to consolidate your small files into 2MB chunks and you get better transfer rates and


how can i use a a vue component inside knockout

Question: I have a large page with a lot of knockout code and I want to use a Vue.js component for a small part of it.
I did try using controlsDescendantBindings on a tag around the component and it seems to work somewhat (I tried doing

 and nothing shows) but Vue isn't working.
I think part of the problem is that it is inside a knockout with context.
I'm new to Vue and trying to switch over from knockout slowly, so if anyone can give me some insight into this I would really appreciate it.
(for reference, I'm using Vue through the CDN.)
Answer: so the problem was that the block of code that the Vue component was in was being rendered conditionally by knockout. so what I did was append the component after that part of the DOM was rendered.


Start activity in a Fragment

Question: I've decided to add more tablet-friendly UI to my app by creating a dual-pane layout using the new fragments API. But the problem is that lots of screens in my app are Activity subclasses. Manually converting them all to fragments is not an option because:
- There are nearly 50 activities.
- I'd like my app to be compatible with all versions of Android starting at 1.6
- And I'd like it to be as small as possible so using a compatibility library is not an option as it is too huge
Although I've found some questions whose answers are saying that it is impossible, I've done it almost successfully. Here is code of my custom Fragment:
public static class ActivityFragment extends Fragment{
    Intent intent;
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(intent==null){
            Bundle a=getArguments();
            intent=a.getParcelable("intent");
        }
        LocalActivityManager am=((ActivityGroup)getActivity()).getLocalActivityManager();
        Window wnd=am.startActivity("intent"+intent.hashCode(), intent);
        if(view==null){
            view=wnd.getDecorView();
            view.setLayoutParams(new FrameLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
        }
        return view;
    }

    public void onDestroy(){
        super.onDestroy();
        if(!((TabletMainActivity)getActivity()).tabs.containsValue(this)){
            ((ActivityGroup)getActivity()).getLocalActivityManager().destroyActivity("intent"+intent.hashCode(), true);
        }
    }
}

In order to work it must be used only in ActivityGroup.
Only problem is that in some activities with a ListView method onItemClick() does not get called after the activity is resumed, i.e. I click an item, another activity starts on top of current, but when I go back, items are no longer clickable.
Comment: You can't use fragments without the compatibility library and that adds only ~110kb to your apk.
Comment: That means you have to create ActivityFragments of Activities in addition for all parts that shall be used as Fragments - that increases your apk size as well and I don't see the benefit over using the support library.
Comment: I use them directly and enable only on Honeycomb.
Comment: No, as you can see from the code, I'm creating them dynamically passing an Intent as an argument.
Comment: You can't use a class that `extends Fragment` on a device that does not know what a Fragment is. Once you try to load that class into memory you get a ClassNotFoundException. The part where the intent is evaluated is way after that.
Comment: Yes I know, I use this code only on devices that support fragments natively, on others I start activities in full screen
Comment: Ok, I see what you are trying. I've seen it work but Idk what it is that causes your behavior. But it sounds like you may need to do focus management and event forwarding from your fragment to the activity window. E.g. TabHost does those sort of things (and the fragment api probably too). See [TabHost sourcecode](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/widget/TabHost.java#TabHost)
Answer: I've finally found a solution by comparing all ListView's fields' values before and after onResume. And solution to this problem is to call the notifyDataSetInvalidated() method on the list adapter.

Start activity in a Fragment


JQPlot not rendering with labels

Question: I am rendering some script to create a graph using jqplot, and the script on the page ends up like this:

This renders a blank graph - no line. However, the Y axis shows the totals, but the x axis is blank.
However, if I render it with JUST the value - it works:
    $.jqplot('chartdiv', [[38.25,-11.70,5930.15,4139.13,207.92,-103.53,635.81,559.16,253.53,183.53,183.53,183.53,54.62,67.62,67.62,47.62,-32.38,-32.38,-32.38,-82.33,364.07,254.45,186.95,114.05,57.05,53.36,50.51,30.51,30.51,-86.43,5922.89,5720.82,5468.87,4742.57,896.11,680.69,425.07,323.07,228.42,113.42,-20.82,-20.82,-20.82,-47.82,-47.82,-47.82,-47.82,-59.30,1004.02,767.00,663.15,302.16,231.66,223.16,12.60,-27.40,-27.40,-27.40,-27.40,-27.40,-27.40,-39.60,803.29,6709.11,4968.20,1381.55,296.86,285.61,161.77,47.80,70.90,56.30]],
{
    title: 'Your financial control',
    axes: { yaxis: { renderer: $.jqplot.LogAxisRenderer } },
    series: [{
        lineWidth: 1,
        color: '#5FAB78',
        showMarker: false
    }]
});

I'm trying to follow the example provided on their page - but it seems as soon as I add the labels to the data - it doesn't work. Can you spy an issue?
http://www.jqplot.com/tests/rotated-tick-labels.php
Answer: You need to specify xaxis date renderer
xaxis: {
          renderer: $.jqplot.DateAxisRenderer
        }

Your date format also needs to be changed if you use default renderer.
as shown in example, date format is mm/dd/yyyy and the one in your code its dd/mm/yyyy -
Change the input date format, it should come up fine -
['11/13/2013', 38.25],['11/14/2013', -11.70],....
There might be some util in jqplot itself to accept the other date format.
Edit - Here is the option to accept other date format -
http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html
you will need to set tickOptions.formatString = '%Y-%m-%d'

JQPlot not rendering with labels


How to set locale for errors.po?

Question: How to set a locale in Phoenix, to get to use priv/gettext/{lang}/LC_MESSAGES/errors.po?
As a test, I built the locale file with mix gettext.merge priv/gettext --locale ja, and translated some words in it.
It works if I explicitly call put_locale/2 in web/views/error_helpers.ex and <%= translate_error(message) %> in a template file, but it's a bit ugly, in a point of DRY.
def translate_error(msg) do
   Gettext.put_locale(LoginStudy.Gettext, "ja")
   Gettext.dgettext(LoginStudy.Gettext, "errors", msg)
end

Is there any better way to set the default locale? I specified the default_locale in config/config.ex, but it doesn't work.
config :login_study, LoginStudy.Endpoint, default_locale: "ja",

Best Regards,
Answer: Great questions @hykw! Since Gettext support in Phoenix is new, documentation is just now starting to show up.
A good starting point is this excellent blog post by Rebecca Skinner: http://sevenseacat.net/2015/12/20/i18n-in-phoenix-apps.html
For example, if you want to set the locale to japanese only for some of your web requests, you can define a plug, as she did with MyApp.Locale, and run it at the beginning of your request lifecycle. I just don't advise to store the locale in the session but keep it rather as part of the URL or some other parameter.
However, if you want the locale to always be japanese, you can write in your config file:
config :my_app, MyApp.Gettext, default_locale: "ja"

You can find more information about this on the Gettext docs:  http://hexdocs.pm/gettext/Gettext.html
Comment: José, thank you for the url and config!  It works perfectly!

How to set locale for errors.po?


How to configure 'qsub' to use a scheduling system like LSF or SGE?

Question: There are several scheduling system (workload management system). Like SGE(Sun Grid Engine), LSF, PBS. Usually on a workstation, using 'qsub' command can put a job in a queue, then the scheduling system will take over from there. I got some questions:

Is 'qsub' a Unix command?
How does qsub associate with a scheduling system? What does the system admin have to configure?
Which scheduling system is more popular?
Answer: <code>* Is 'qsub' a Unix command?

    qsub is the binary used to submit jobs in SUN GRID ENGINE. Just like bsub in LSF

* How does qsub associate with a scheduling system? What does the system admin have to configure?

    qsub associate 100% with the scheduling system. The system admin can configure from nothing "basic installation" to server resource, policies, esub, elims to define the rules on job launching.

* Which scheduling system is more popular?

    Depends. When we tried SGE couple of years ago it had issues taking more than 10K jobs but now SGE improved a log. At that point we had to opt for Platform LSF, which is a paid scheduling system but works great for large clusters with good monitoring solutions.
</code>


Formulating a formula for$ P_n$

Question: The sequence is $P_2=\dfrac 34, P_3=\dfrac 23, P_4=\dfrac 58, P_5=\dfrac 35, P_6=\dfrac 7{12}, P_7=\dfrac 47$.
I'm having trouble putting this formula for $P_n$ on paper.
Answer: This may be the result of simplifying too much. Note that
$$P_2=\frac{3}{4},\quad P_3=\frac{4}{6},\quad P_4=\frac{5}{8},\quad P_5=\frac{6}{10}, \quad P_6=\frac{7}{12}, \quad P_7=\frac{8}{14}.$$
Remark: When we make calculations for small $n$ in order to get an idea of what might be going on, "simplifying too much" is a persistent issue. Even worse is the student habit of feeding expressions into a calculator: instead of a pattern, we get a jumble of digits.
Comment: I.e., $P_n = \frac{n + 1}{2 n}$. And I have the sneaky suspicion OP and @AndréNicolas share some background that we lack...
Comment: Wow, yes that's it. Can't believe I didn't see it
Answer: $\bf{hint}$ : if $n$ is odd the numerator increases by $1$ and the denominator increases by $2$
if $n$ is even, the numerator increases by $2$, and the denominator by multiples of $4$.
Then combine the two.
Answer: If $n$ is even, $$P_n=\frac{n+1}{2n}$$
If $n$ is odd, $$P_n=\frac{n-k}{n}$$ where $P_n$ is the $k$th odd number in the sequence.

Formulating a formula for$ P_n$


Square brackets breaking OAuth signature generation - how to encode them?

Question: I'm generating an OAuth signature using Ruby, for a site that uses OAuth.  It's been working fine up till now, till I've tried to add some params with square brackets.  Now I'm getting a "Signature doesn't match" error back.
My guess is that when Oauth generates the signature, it deals with the square brackets in a different way to how I deal with them when I generate my signature.
This is how I'm generating my OAuth sig (in Ruby):
<code>oauth_params = {
  "oauth_consumer_key" => options["key"], #oAuth Consumer Key
  "oauth_nonce" => MiscUtilities.generate_nonce, #oAuth Nonce - just a random numnber
  "oauth_signature_method" => "HMAC-SHA1", #oAuth Signature Method - don't need to change this
  "oauth_timestamp" => Time.now.to_i.to_s, #oAuth Timestamp, standard seconds since epoch.
  "oauth_version" => "1.0" #oAuth Version - don't need to change this
}
#add any other non-oauth params we've been given
params = oauth_params.merge(options["params"])

#sort and url encode the params
encoded_params = params.sort_by{|k,v| k.to_s}.collect { |k, v| CGI.escape("#{k.to_s}=#{v}") }.join('%26')
signature_base_string = "#{options["method"]}&#{CGI.escape(options["api_url"])}&#{encoded_params}"
signing_key = "#{options["secret"]}&"

#generate the signature and add it to params
digest = OpenSSL::Digest::Digest.new('sha1')
hmac = OpenSSL::HMAC.digest(digest, signing_key, signature_base_string)
params["oauth_signature"] = Base64.encode64(hmac).chomp
params
</code>
Like I say, this was working fine till I added square brackets to the mix.
Has anyone encountered this problem, or able to see what I might be doing wrong, above?
Comment: Can you clarify what you mean by "square brackets"? Are you talking about calling your options hash, as in `options["secret"]`? Also, is the trailing `&` at end of `signing_key` on purpose? And are your options for `method` and `api_url` supposed to be key/value pairs? (e.g. `method=#{option["method"]}&`)
Comment: Hi @JayDorsey.  For "square brackets" i meant a parameter like `student[id]=123` or `ids[]=4561&ids[]=678`.  I actually figured this out, I'm going to write it up into an answer later.  thanks
Answer: You should not be using CGI:Escape on a URL nor on the whole key value pair.  It should be used on the key, and separately on the value.  Then these two would be joined by an equal sign, and then these pairs would be added to the query string separated by &'s.
Speaking of which -- I see that you are joining with '%26' (encoded &).  This doesn't seem to follow the spec, unless perhaps your base values don't need encoding?  That would be equivalent to 'encoding' the values, and then encoding the whole string. And perhaps that's why the brackets caused an issue -- as soon as you added them to a value, that value then needed to be encoded.
<code> encoded_params = Map [params.map {|k, v| CGI.Escape(k), CGI.Escape(v)}]
                  .sort_by{|k,v| k.to_s}
                  .collect { |k, v| CGI.escape("#{k.to_s}=#{v}") }
                  .join('%26')
</code>
I'm not a ruby guy -- I just took an example from an answer on processing a hash and applied it here.  Please do what needs to be done to make this correct ruby code.  I also kept the rest of the code; while potentially confusing, it seems like it would do the job.
There is another potential issue -- According to the spec, the URI encoding that's done may be a little different than a normal URI encoding.  Spaces are %20 and not +, and everything but ALPHA, DIGIT, '_', '-', '.', and '~' Must be encoded, and those values must not be encoded.  So does that apply to CGI:Escape?  I don't have ruby installed, and my quick check on the spec lead me to a one line document.
edit: the algorithm above wouldn't work with things that need to be encoded, because the %'s from the things that are encoded would also be encoded.  It just needs a slight tweak to encode the entire value instead of joining with the encoded ampersands.
Comment: Thanks.  I ended up doing all the things you suggest above, I think, perhaps in a different way - see my answer below(above?).  The space did have to be encoded as a %20, which i handle specifically, and yes there's a set of characters that we don't want to encode.  It seems quite fiddly.
Comment: @Max, agreed that it seems fiddly -- probably because the spec talks in generalities, and then makes exceptions, instead of describing what is needed in a progressive fashion.
Comment: Yeah while I was reading that spec I kept thinking "There's got to be a cleaner way to describe this". That's v1 though, maybe v2 is nicer.
Answer: The trick is you have to convert the square brackets in the signature base string twice:

[ => %5B =>  %255B
] => %5D =>  %255D
Answer: I ended up doing this, which I don't think is particularly clean but does work.
<code>#New version following https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html
def oauth_signed_params(options)
  #defaults
  options["method"] ||= "POST"

  oauth_params = {
    "oauth_consumer_key" => options["key"], #oAuth Consumer Key
    "oauth_nonce" => generate_nonce, #oAuth Nonce - just a random number
    "oauth_signature_method" => "HMAC-SHA1", #oAuth Signature Method - don't need to change this
    "oauth_timestamp" => Time.now.to_i.to_s, #oAuth Timestamp, standard seconds since epoch.
    "oauth_version" => "1.0" #oAuth Version - don't need to change this
  }
  params = oauth_params.merge(options["params"])
  encoded_params = params.sort_by{|k,v| oauth_percent_encode(k.to_s)}.collect{|k, v| "#{oauth_percent_encode(k.to_s)}=#{oauth_percent_encode(v.to_s)}" }.join('&')

  signature_base_string = "#{options["method"]}&#{oauth_percent_encode(options["api_url"])}&#{oauth_percent_encode(encoded_params)}"
  signing_key = "#{options["secret"]}&"

  #generate the signature and add it to params
  digest = OpenSSL::Digest::Digest.new('sha1')
  hmac = OpenSSL::HMAC.digest(digest, signing_key, signature_base_string)
  params["oauth_signature"] = Base64.encode64(hmac).chomp
  params
end

#according to this twitter oauth doc, we actually only percent-encode a limited set of characters.
#Others are left as is. The ones in the regex below are NOT encoded.
#https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html
def oauth_percent_encode(string)
  string.gsub(/[^a-zA-Z0-9\-\.\_\~]/){|match| match == " " ? "%20" : CGI.escape(match)}
end
</code>


WKDownloadDelegate download fails with error -3000

Question: When using the new WKDownloadDelegate, I try to download a file, and the first time it downloads fine, but when I attempt to download the same file again, WKDownloadDelegate invokes this method:
func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?)

When I print this to the console:
download(_ download: <WKDownload: 0x7fc58fb2dfd0>, didFailWithError error: The operation couldn't be completed. (NSURLErrorDomain error -3000.), resumeData: nil

Problem is I can't find any information about this error (-3000), so any suggestions would be nice.
Here is the whole WKDownloadDelegate code
    public func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
    let tempDirectory = FileManager.default.temporaryDirectory
    let tempFolderName = UUID().uuidString
    let tempDirectoryPath = tempDirectory.appendingPathComponent(tempFolderName)
    try? FileManager.default.createDirectory(at: tempDirectoryPath, withIntermediateDirectories: false)
    let url = tempDirectory.appendingPathComponent(suggestedFilename)
    currentDownloadedPreviewItemUrl = url
    completionHandler(url)
}

public func downloadDidFinish(_ download: WKDownload) {
    guard let currentDownloadedPreviewItemUrl = currentDownloadedPreviewItemUrl else {
        print("Download finished but no URL found")
        return
    }

    DispatchQueue.main.async {
        let activityVC = UIActivityViewController(activityItems: [currentDownloadedPreviewItemUrl], applicationActivities: nil)
        activityVC.popoverPresentationController?.sourceView = self.view
        activityVC.popoverPresentationController?.sourceRect = self.view.frame
        activityVC.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
        self.present(activityVC, animated: true, completion: nil)
    }
}

public func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
    debugPrint("------------------")
    debugPrint("download(_ download: \(download), didFailWithError error: \(error.localizedDescription), resumeData: \(resumeData)")
    debugPrint("------------------")
}

Answer: I am clumsy, so I will post what was the problem for anyone that ever encounters error -3000 again. When working with WKDownloadDelegate and the method
func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void)

is invoked, when passing the URL to the completion handler, you MUST ENSURE that a file with the same name doesn't exist, or else it will later throw an error in downloadDidFail method.
So in my case I fixed the code in this method:
public func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
    let tempDirectory = FileManager.default.temporaryDirectory
    let tempFolderName = UUID().uuidString
    let tempDirectoryPath = tempDirectory.appendingPathComponent(tempFolderName)
    do {
        try FileManager.default.createDirectory(at: tempDirectoryPath, withIntermediateDirectories: false)
    } catch {
        debugPrint(error)
    }
    let url = tempDirectoryPath.appendingPathComponent(suggestedFilename)
    currentDownloadedPreviewItemUrl = url
    completionHandler(url)
}

Notice that line
let url = tempDirectoryPath.appendingPathComponent(suggestedFilename)

is using tempDirectoryPath instead of tempDirectory


conditional formatting of anki deck class style with javascript based on a hidden variable

Question: I have a basic anki deck configuration, I'd like to add colors for gender of a noun word in latin languages (Portuguese, to be specific):
Front:
man
Back:
homem
Example:

Gender:
m

<-- for contrast, I'll write example of another card -->
Front:
woman
Back:
mulher
Example:

Gender:
f

For better memorization, I force to type my answers:
{{Front}}

{{type:Back}}

so far so good.
Now, I created my styling:
.card-m {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #66d;
}

.card-f {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #f5426f;
}

.card {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
}

and my back Template card has the following format:

{{FrontSide}}

{{hint:Example}}

Here's my question:
I would like to have a javascript to read the value of Gender variable, and apply class= highlight the back of the card in either Blue, or Pink (for feminine or masculine respectively):

But the Gender variable seems to have no effect on the class that is being applied.
Any idea why?
Answer: It looks like some of the HTML and JS syntax was not correct. Also, the {{Gender}} card field can be directly inserted into a string.
I was able to make it work with these changes to your code.
Full Back Template:

    {{FrontSide}}

    {{hint:Example}}

Answer:
Also, the {{Gender}} card field can be directly inserted into a string.

We can go one step further: the card field can be directly used as part of the HTML code. This gives us the following:

{{FrontSide}}

{{hint:Example}}

This way the class becomes card-X when {{Gender}} is X, and card when the field is empty - no JavaScript needed.
You can read up on the features used here: https://docs.ankiweb.net/templates/generation.html


What scale comprises D-E-F#-G-A-Bb-C?

Question: I composed a piece of music (more like a few renditions of a theme) that I sat down to transcribe, but it doesn't seem to fit into any scale! (I haven't looked at Japanese scales yet) Bear in mind that I am not entirely sure if I am representing the scale correctly or if it is a mode (I'm new to modes), but it is odd and unconventional nonetheless.
The scale is: D-E-F#-G-A-Bb-C-back to D, obviously. I also use C# a LOT, so I kind of consider it part of the scale, too.
Here is an image of the sheet. I transcribed it with no key signature, just note by note.

This is obviously not the whole thing. The rest goes: Cm-D-Gm-D-Gm-D-Cm-... there are some other things, and it has another version that replaces Gm with Bb to give it a more resolved, yet bittersweet ending (and a half-cadence for the finale. How could I not?).
But, as you can see, It seems quite irregular to the eyes of many non-professionals.
Comment: Seems to me like it's in D major, and that it goes (so far) to Gm. no problem so far.
Comment: How does the piece begin? how does it end? D-major or D minor? or G-minor?
Comment: To be totally nitpicky, the last measure should probably have a dotted quarter note instead of a quarter note tied to an eighth note. I don't know if you were imagining some accompaniment or anything that would justify that eighth not though.
Comment: @AlbrechtHügli. This piece starts and ends on D-major, although it can also feel conclusive with an Em ending. The exerpt is the beginning of the piece.
Comment: @awelotta don't worry, the phrase continues after the end of the pic. I love that kind of constructive-criticism though!
Comment: No Surprises by Radiohead starts with the same vamp (D / Gm), outlining the Bb on the Gm passage ^^ I approve the modal mixture answer!
Comment: if you run it up and add the E at both ends it's the lick from Carol of the bells. I'm looking for a name for it also. looks like break it down into two scales
Answer: I would not look at this as a single scale.
Based on the excerpt in the OP, consider it as D major, but with its IV chord (that is, the G chord) borrowed from D minor (including the C natural in the melody). That's a common borrow in tonal music. The technique is called "modal mixture".
Depending on where the piece goes, it could also be interpreted as being in G minor, with the D chord being the dominant chord. Ordinarily G minor would have an F natural as its seventh scale note, but in tonal music it is conventional to sharp the seventh scale tone, thus F#.

As an aside, returning to the D major interpretation, a section of the piece could be a "sunny" contrast to the portion given, by changing the Bbs to B naturals (and the Cs to C#s). It will sound as though the clouds have cleared.
Comment: modal mixture seems to me very convincing? Is this one of the Glareans Dodecachordon?
Answer:
it doesn't seem to fit into any scale!

I think you may be confusing being in a key versus in a scale.
You have the collection of tones G A B♭ C D _ F♯ G. The tone E is missing for a complete scale, assuming we are working with the gamut ABCDEFG. We can't really speak about a complete scale, but we can talk about the key and tonality.
In terms of key you want to find a plausible tonic/dominant pair. Find a leading tone, that needs to be a half step relations ship. There are two A B♭ and F♯ G. B♭ or G are the potential tonics. Is there a major chord or dominant seventh chord rooted a perfect fifth above either potential tonic, either a D major, D dominant seventh, F major, or F dominant seventh chord? Yes, you have a D major chord in the left hand and it keeps going to G minor. There is the dominant/tonic pair.
Does the melody confirm a key of G minor, does it fit dominant/tonic harmony? Yes, the melody outlines the D major chord and with it's continuation up to C it fully outlines D dominant seven. The other tones of the melody are G and B♭. The melody is clearly in G minor.
That's sort of the "theoretical" way to describe analyzing the key, but in reality it's perfect clear to the ear that it's G minor.
In terms of scale you can't really say what scale is used, for two reasons: you don't play an E - so you can't says whether it's harmonic minor or melodic minor, but more importantly the music is based more on chord tones than purely scalar ideas.
Below is the music with dominant chord tones highlighted pink, tonic tones green, and the stuff circled in red is just embellishment of chord tones...

Notice how you have about 85% chord tones and just a little bit of embellishing material? And the chord tone material coincides strongly with beats one on each bar.
I think you should consider things in terms of key and harmony rather than scale, at least for music like this example passage.
Answer: Looks like the piece is conceived in G-minor. This is only an excerpt. All the notes come from the minor mode (including the mutable sixth and seventh steps.)
Answer: It is melodic major scale (also known as aeolian dominant or mixolydian b6).
Melodic major scale has the first tetrachord (D E F# G in your case) from major scale (D major in your case) and the second one (A Bb C D) from aeolian minor scale (d minor). Or in another words the minor scale with raised 3rd note.
There is also harmonic major scale (D E F# G A Bb C# D), which is also your case.
You simply use D melodic and harmonic major scale. It is less common, but used (in jazz I think).
Answer: The intervals are w-w-h-w-h-w-w so it's not a Western mode based on the major scale.
I think it may be one of the melodic minor modes, specifically D mixolydian b6, if you consider D as the starting point.  It may also be one of the Carnatic scales in Indian music.  I am not considering the C# you mention as I do not even see that in the score.
Comment: If it really is a D mixo b6 then the melodic minor scale is G, which is a relative minor to Bb Major.  So from a Western point of view you might write the key as Bb maj and keep the accidentals in place to indicate a sharp 6 and 7 of G minor.  The Key would have Bb and Eb and your score would have E natural and F # throughout.
Comment: what would i write as the key signature?
Answer: Like other answers say this is the D major scale with a flattened 6th and  7th degree, because of the minor subdominant = Gm (G,A,Bb,C,D) - borrowed from the relative key dm.
(If there is an Eb in the succeeding bars it could also be a piece in Gm, and D would be the dominant. But we'd need more context to decide this definitely.)
Edit:
Yes! if we had more information, we might also guess that your song is in D-minor and in these bars there is an extension to the subdominant G-minor, of which the dominant chord is D.
But as you are asking what scale this could be
D major/G minor scale with borrowed Gm-subdominant
(Gm with the V7/i chord  D. In this case  it would be the scale of the melodic or harmonic G-minor scale DoReMiFa of D turns to MiFiSiLa-TiDoReMi of g-minor)

The scale is: D-E-F#-G-A-Bb-C-back to D, obviously. I also use C# a LOT, so I kind of consider it part of the scale, too.

These are the tones of the D7 chord, the secondary dominant of G-minor:
As you say the excerpt is the opening bars the first assumption D major with borrowed iv (minor subdominant) is the correct analysis.
But the answer to the question what scale is this remains the same:
The lower tetrachord is the D-major scale, the upper tetrachord belongs to the g-minor scale.
no matter whether  we are in D (I) and and gm (iv) or gm (i) and D (V7b6).
Answer: It sounds like Gm is the home chord, so I'd write it with a key signature of two flats.
Comment: what now, as he says it is in D?
Comment: @AlbrechtHügli My ear says that the written part of the song is in Gm, and OP says there are Cm chords coming after that. :) If it ends on D, then it either ends on a V chord, _or_ it has modulated, _or_ it's some modal mixture.
Comment: As far as we can see the posting  and as long we have only 2 chords it can be both: D or gm. My ear tells me both :). We should see the whole piece. But the scale isn't different.
(we need more information - like a mode and its hypo scale...https://viva.pressbooks.pub/openmusictheory/chapter/diatonic-modes/#:~:text=A%20scale%2C%20mode%2C%20or%20collection,note%20belongs%20to%20that%20collection.

What scale comprises D-E-F#-G-A-Bb-C?


How to display all the terms of a vocabulary with a list of the items associated to the term below in a view?

Question: In a view in D8, I want to achive something like :
<code>term 1
-item 1
-item2
term 2
-item 3
-item 4
term 3
- item 5
- item 6
</code>
Is it possible ? If yes, how ?
Comment: Found the solution here : https://drupal.stackexchange.com/questions/155116/views-page-list-of-all-content-grouped-by-taxonomy-term
Answer: It sounds like you are looking for a glossary view.  There are many tutorials on how to do this, ex: https://www.ostraining.com/blog/drupal/glossary/
... after rereading, you may actually be looking to create a view of all terms in that is grouped by parent id. There are different ways to do this. Take a look at:

Grouping Taxonomy terms by their parents
https://www.konordo.com/blog/show-taxonomy-terms-grouped-taxonomy-parent

These talk about D7, but the same should work in D8


How to display mysql records as preselected checkboxes?

Question: I have a table column called post_tags within a table called posts where assigned tags are stored separated by the @ symbol. I also have a table called tags where all tag names are stored. I would like to design my database in a more normalized way but for the purpose I am trying to achieve this is the easiest option.
Anyway, I want to display on the screen all the entries from the tags table as checkboxes, so I do:
    $query = mysql_query("SELECT * FROM tags ORDER BY name");

    while ($row = mysql_fetch_assoc($query)) {

        $tag = $row['name'];

        echo "<input type='checkbox' name='tags[]' value='$tag' />\n";

    }

Next I want to have the tags that are assigned to a particular post be preselected. For example, if I have a post with the following in it's post_tags column:

party@beaches@dolphins@

I want the "party", "beaches" and "dolphin" checkboxes to be checked by default (while the checkboxes for the other options are unchecked). How can this be done?
Comment: I'm not sure that you want to have a column like post_tags instead of using an intersection table. But if you really do you will just need to do more processing when pulling data out.
Answer: try the two results and the in_array() function.
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party@beaches@dolphins@";
$arr_tags = explode("@", $post_tags);

while ($row = mysql_fetch_assoc($query)) {
    $check = in_array($arr_tags, $row['name'])? 'checked="checked"' : "";
    echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
    echo "\n";
}
?>

UPDATE
Because of Jeff question on performance, I looked for faster solutions and using isset() is faster so this would do a faster lookup of the values. the array_flip() is 3 time less taxing than in_array():
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party@beaches@dolphins@";
$arr_tags = array_flip(explode("@", $post_tags));

while ($row = mysql_fetch_assoc($query)) {
    $check = isset($arr_tags[$row['name']])? 'checked="checked"' : "";
    echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
    echo "\n";
}
?>

Comment: What is the overhead of the in_array function? Is it scanning the whole array everytime?
Comment: I tested on my machine with medium size query results and it ran in .25 seconds
Comment: Your update looks great, when I looked more at the in_array it would scan the array each time through the loop so as the # of tags grows it would have problems but the flip and isset seems much better.
Answer: The first thing to do is see if there is any existing data. So run that query and put the result of that table cell into lets say $checkedstring if not then put your default string in.
<?php
$checkedstring = "party@beaches@dolphins@";
//Pull from DB if exsists and set $checkedstring to that value
///
$checkeditems =  explode ( "@" , $checkedstring);
$checked = array();
foreach($checkeditems as $item)
{
  $checked[$item]=true;
}

$query = mysql_query("SELECT * FROM tags ORDER BY name");

while ($row = mysql_fetch_assoc($query))
{
    $tag = $row['name'];
    $checkedstatus = '';
    if($checked[$tag])
    {
      $checkedstatus = "checked='checked'";
    }
    echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n";
}

?>


Is it true that a polynomial is reducible over a field only if the polynomial has a zero in the field?

Question: I am doing some practice problems for abstract algebra and have come across this idea in a couple places, but it seems fundamentally wrong. For example, in order to prove that $f(x) = x^2 + x + 1$ is irreducible over the field $\mathbb Z_2$ I came across an example where a person just plugged in $f(0) = 1$ and $f(1) = 1$ and stated that this was enough to prove it. But what about the polynomial $p(x)=21x^2 + 32x + 12=(7x+6)(3x+2)$ over the ring $\mathbb Z$? Though it's only zeros are $\frac{-6}{7}$ and $\frac{-2}{3}$, it is certainly reducible over $\mathbb Z$. I tried to solve the problem by showing that $\mathbb Z_2[x]\setminus A$, where the ideal $A=(x^2 + x +1)$, is a field, but am getting hung up on showing that every nonzero element has an inverse.
EDITED: My point about the sample polynomial talks about the ring Z, which I initially misidentified as a field, so it should be disregarded.
Thanks for all your help!
Comment: @DavidC.Ullrich Well, it's still true for cubics ...
Comment: Well, $\Bbb Z$ is not a field. It is true that a _quadratic_ polynomial over a field $K$ is reducible if and only if it has a root in $K$; this is very easy to prove (one direction is trivial and the other direction is immediate from the division algorithm). It's false for polynomials of higher degree; consider $K=\Bbb R$, $p=(x^2+1)^2$.
Comment: @HagenvonEitzen Hmm, $2+2>3$. Good point.
Comment: You should really correct what you said here. $\Bbb Z$ is not a field. Really.
Comment: @DavidC.Ullrich Thank you, it's been corrected
Answer: Assume you work over a field $K$.

Is it true  that a polynomial $P$ over $K$ having a root is reducible ?

False. Example $P(X):=X$ has $0$ for root but is irreducible.

Is it true that a polynomial $P$ of degree $>1$ over $K$ having a root is reducible ?

True. Let $r$ be the root of $P$ then $P(X)=(X-r)Q(X)$ with $deg(Q)=deg(P)-1>0$.

Is it true that a polynomial $P$ without roots is irreducible ?

False. Example : $K:=\mathbb{Q}$. Then $P(X)=(X^2-2)(X^2-3)$ is clearly reducible. However its roots in $\mathbb{R}$ are $\pm\sqrt{2}$ and $\pm\sqrt{3}$, none of them belongs to $\mathbb{Q}$. It follows that $P$ has no root in $\mathbb{Q}$.

Is it true that a polynomial $P$ of degree $\leq 3$ without roots is irreducible ?

True. If $P$ were reducible then we could find $Q$ and $R$ such that $P=QR$ and $deg(Q),deg(R)>0$. Since $deg(P)\leq 3$ then we necessarily have $deg(Q)=1$ or $deg(R)=1$. Since $Q$ or $R$ is of degree $1$, at least one of them has a root and so $P$ has a root too.
Answer: The argument works with polynomials of degree $2$ or $3$ over a field, but not higher.
The reason is that if a polynomial of such degree is reducible, it must have a factor of degree $1$, and in a field such a factor always has a root (in your example, the degree $1$ factors have no root in $\mathbb{Z}$, so you see why it is important that we have polynomials over a field). But as explained by David's comment it is not true for higher degree.
Comment: Thanks very much, this makes alot of sense.
Answer: Counterexample:
$$x^4+1=(x^2-\sqrt 2 x+1)(x^2+\sqrt 2 x+1).$$


Area of polygon on complex plane formed by complex roots of a polynomial

Question:
Compute the area of the polygon whose vertices are the solutions in the complex plane to the polynomial $x^7+x^6+x^5+x^4+x^3+x^2+x+1=0$.

What I did was find the complex numbers by factoring and then using Surveyor's formula. However, that required me to use synthetic or polynomial division. I was wondering if there was a way to find the numbers without directly using division or whether there's a geometric approach to this?
Comment: My bad. It should be surveyor's formula.
Comment: Since $x^7 + \cdots + 1 = \frac{x^8-1}{x-1}$, the roots are $e^{\frac{2\pi k i}{8}}$ for $k = 1,\ldots, 7$.
Comment: What's Surveyor's rule?
Answer: Simply note that the polynomial is $\frac{x^8-1}{x-1}$ has roots $\operatorname{cis}(2\pi k/8)$ for $k \in \{1, \ldots, 7\}$.
Thus the value is the area of the regular octagon minus the area of a triangle formed by two adjacent sides.
The area of an octagon (by splitting into triangles) with radius $1$ is $8 \cdot \frac{1}{2} \cdot \frac{\sqrt{2}}{2} = 2\sqrt{2}$.
The is a unit square inside an octagon. Removing the square reveals $4$ little triangles. Thus the area of one little triangle is $\frac{2\sqrt{2} - 1}{4} = \frac{\sqrt{2}}{2} - \frac{1}{4}$.
$$2\sqrt{2} - \left(\frac{\sqrt{2}}{2} - \frac{1}{4}\right) = \frac{3\sqrt{2}}{2} + \frac{1}{4}$$


What is an "uninformative prior"? Can we ever have one with truly no information?

Question: Inspired by a comment from this question:
What do we consider "uninformative" in a prior - and what information is still contained in a supposedly uninformative prior?
I generally see the prior in an analysis where it's either a frequentist-type analysis trying to borrow some nice parts from Bayesian analysis (be it some easier interpretation all the way to 'its the hot thing to do'), the specified prior is a uniform distribution across the bounds of the effect measure, centered on 0. But even that asserts a shape to the prior - it just happens to be flat.
Is there a better uninformative prior to use?
Comment: Maybe you'll enjoy a look on the so-called [Principle of Maximum Entropy](http://en.wikipedia.org/wiki/Principle_of_maximum_entropy). I don't feel like expanding that in a full answer – the Wikipedia article seems of good quality. I'm pretty confident some contributors will expand on it that much better than I would.
Answer: [Warning: as a card-carrying member of the Objective Bayes Section of ISBA, my views are not exactly representative of all Bayesian statisticians!, quite the opposite...]
In summary, there is no such thing as a prior with "truly no information".
Indeed, the concept of "uninformative" prior is sadly a misnomer. Any prior distribution contains some specification that is akin to some amount of information. Even (or especially) the uniform prior. For one thing, the uniform prior is only flat for one given parameterisation of the problem. If one changes to another parameterisation (even a bounded one), the Jacobian change of variable comes into the picture and the density and therefore the prior is no longer flat.
As pointed out by Elvis, maximum entropy is one approach advocated to select so-called "uninformative" priors. It however requires (a) some degree of information on some moments $h(\theta)$ of the prior distribution $\pi(\cdot)$ to specify the constraints$$\int_{\Theta} h(\theta)\,\text{d}\pi(\theta) = \mathfrak{h}_0$$ that lead to the MaxEnt prior
$$\pi^*(\theta)\propto \exp\{ \lambda^\text{T}h(\theta) \}$$
and (b) the preliminary choice of a reference measure $\text{d}\mu(\theta)$ [in continuous settings], a choice that brings the debate back to its initial stage! (In addition, the parametrisation of the constraints (i.e., the choice of $h$) impacts the shape of the resulting MaxEnt prior.)
José Bernardo has produced an original theory of reference priors where he chooses the prior in order to maximise the information brought by the data by maximising the Kullback distance between prior and posterior. In the simplest cases with no nuisance parameters, the solution is Jeffreys' prior. In more complex problems, (a) a choice of the parameters of interest (or even a ranking of their order of interest) must be made; (b) the computation of the prior is fairly involved and requires a sequence of embedded compact sets to avoid improperness issues. (See e.g. The Bayesian Choice for details.)
In an interesting twist, some researchers outside the Bayesian perspective have been developing procedures called confidence distributions that are probability distributions on the parameter space, constructed by inversion from frequency-based procedures without an explicit prior structure or even a dominating measure on this parameter space. They argue that this absence of well-defined prior is a plus, although the result definitely depends on the choice of the initialising frequency-based procedure
In short, there is no "best" (or even "better") choice for "the" "uninformative" prior. And I consider this is how things should be because the very nature of Bayesian analysis implies that the choice of the prior distribution matters. And that there is no comparison of priors: one cannot be "better" than another. (At least before observing the data: once it is observed, comparison of priors becomes model choice.) The conclusion of José Bernardo, Jim Berger, Dongchu Sun, and many other "objective" Bayesians is that there are roughly equivalent reference priors one can use when being unsure about one's prior information or seeking a benchmark Bayesian inference, some of those priors being partly supported by information theory arguments, others by non-Bayesian frequentist properties (like matching priors), and all resulting in rather similar inferences.
Comment: (+1) Your book? Oh damn. I *so* have 387 questions for you :)
Comment: (+1) For an objective (no less!), straightforward answer.
Comment: +1 Thank you for a good and well-informed overview of the issues.
Comment: An outstanding answer. Thank you. And yet another book to go on the wish list.
Comment: It's almost unfair. After all, he's Christian Robert! Just kidding. Great answer. And I'd love if @Xi'an could expand it in a post at his blog, specially about how parametrization is important to the topic of "uninformative" priors.
Comment: Re. uniform prior- Olle Haggstrom gives a very nice talk on this ("Notes From My Personal Crusade Against The Uniform Distribution").  The uniform distribution can say something utterly ludicrous, it is a modelling assumption, and definitely not the same as no information!
Comment: @gwr: if you read the reference prior literature, you will see that they consider the expected information, so it does not depend on the data.
Comment: **Correct:** The Fisher information is derived from the density behind the observations, thus uses a frequency property of the distribution. Most parameters are also defined in terms of (frequency) moments of this distribution. Whether this is "good" or "bad" remains a matter of opinion.
Comment: Regarding maximizing the information brought in by the data: Why should the prior be dependent upon the data or the likelihood for that?
Comment: Yes, I thought about that, but that amounts a bit to frequentism in itself from my preliminary understanding, doesn't it? Somehow MaxEnt seemed clearer from what I know which definitely is a kind of information that needs maximization... ;)
Answer: An appealing property of formal noninformative priors is the "frequentist-matching property" : it means that a posterior 95%-credibility interval is also (at least, approximately) a 95%-confidence interval in the frequentist sense.
This property holds for Bernardo's reference prior although the fundations of these noninformative priors are not oriented towards the achievement of a good frequentist-matching property,
If you use a "naive" ("flat") noninformative prior such as the uniform distribution or a Gaussian distribution with a huge variance then there is no guarantee that the frequentist-matching property holds.
Maybe Bernardo's reference prior could not be considered as the "best" choice of a noninformative prior but could be considered as the most successful one. Theoretically it overcomes many paradoxes of other candidates.
Comment: Why could it not be considered the "best"?
Answer: Jeffreys distributions also suffer from inconsistencies: the Jeffreys priors for a variable over $(-\infty,\infty)$ or over $(0,\infty)$ are improper, which is not the case for the Jeffreys prior of a probability parameter $p$: the measure $\text{d}p/\sqrt{p(1-p)}$ has a mass of $\pi$ over $(0,1)$.
Renyi has shown that a non-informative distribution must be associated with an improper integral. See instead Lhoste's distributions which avoid this difficulty and are invariant under changes of variables (e.g., for $p$, the measure is $\text{d}p/p(1-p)$).

References
E. LHOSTE : "Le calcul des probabilités appliqué à l'artillerie", Revue d'artillerie, tome 91, mai à août 1923
A. RENYI : "On a new axiomatic theory of probability" Acta Mathematica, Académie des Sciences hongroises, tome VI, fasc.3-4, 1955
M. DUMAS : "Lois de probabilité a priori de Lhoste", Sciences et techniques de l'armement, 56, 4ème fascicule, 1982, pp 687-715
Comment: As far as I remember, [Lhoste's invariance result](http://biomet.oxfordjournals.org/content/90/3/728.abstract) is restricted to the transforms $\log\sigma$ and $\log p/(1-p)$ for parameters on $(0,\infty)$ and $(0,1)$, respectively. Other transforms from $(0,\infty)$ and $(0,1)$ to $\mathbb{R}$ will result in different priors.
Comment: From my brief correspondence with Maurice Dumas in the early 1990's, I remember that he wrote a Note aux Comptes-Rendus de l'Académie des Sciences, where he uses the $\log()$ and $\text{logit}()$ transforms to derive "invariant" priors.
Answer: I agree with the excellent answer by Xi'an, pointing out that there is no single prior that is "uninformative" in the sense of carrying no information.  To expand on this topic, I wanted to point out that one alternative is to undertake Bayesian analysis within the imprecise probability framework (see esp. Walley 1991, Walley 2000).  Within this framework the prior belief is represented by a set of probability distributions, and this leads to a corresponding set of posterior distributions.  That might sound like it would not be very helpful, but it actually is quite amazing.  Even with a very broad set of prior distributions (where certain moments can range over all possible values) you often still get posterior convergence to a single posterior as $n \rightarrow \infty$.
This analytical framework has been axiomatised by Walley as its own special form of probabilistic analysis, but is essentially equivalent to robust Bayesian analysis using a set of priors, yielding a corresponding set of posteriors.  In many models it is possible to set an "uninformative" set of priors that allows some moments (e.g., the prior mean) to vary over the entire possible range of values, and this nonetheless produces valuable posterior results, where the posterior moments are bounded more tightly.  This form of analysis arguably has a better claim to being called "uninformative", at least with respect to moments that are able to vary over their entire allowable range.

A simple example - Bernoulli model: Suppose we observe data $X_1,...,X_n | \theta \sim \text{IID Bern}(\theta)$ where $\theta$ is the unknown parameter of interest.  Usually we would use a beta density as the prior (both the Jeffrey's prior and reference prior are of this form).  We can specify this form of prior density in terms of the prior mean $\mu$ and another parameter $\kappa > 1$ as:
$$\begin{equation} \begin{aligned}
\pi_0(\theta | \mu, \kappa) = \text{Beta}(\theta | \mu, \kappa) = \text{Beta} \Big( \theta \Big| \alpha = \mu (\kappa - 1), \beta = (1-\mu) (\kappa - 1) \Big).
\end{aligned} \end{equation}$$
(This form gives prior moments $\mathbb{E}(\theta) = \mu$ and $\mathbb{V}(\theta) = \mu(1-\mu) / \kappa$.)  Now, in an imprecise model we could set the prior to consist of the set of all these prior distributions over all possible expected values, but with the other parameter fixed to control the precision over the range of mean values.  For example, we might use the set of priors:
$$\mathscr{P}_0
\equiv \Big\{ \text{Beta}(\mu, \kappa) \Big| 0 \leqslant \mu \leqslant 1 \Big\}. \quad \quad \quad \quad \quad$$
Suppose we observe $s = \sum_{i=1}^n x_i$ positive indicators in the data.  Then, using the updating rule for the Bernoulli-beta model, the corresponding posterior set is:
$$\mathscr{P}_\mathbf{x} = \Big\{ \text{Beta}\Big( \tfrac{s + \mu(\kappa-1)}{n + \kappa -1}, n+\kappa \Big) \Big| 0 \leqslant \mu \leqslant 1 \Big\}.$$
The range of possible values for the posterior expectation is:
$$\frac{s}{n + \kappa-1} \leqslant \mathbb{E}(\theta | \mathbb{x}) \leqslant \frac{s + \kappa-1}{n + \kappa-1}.$$
What is important here is that even though we started with a model that was "uninformative" with respect to the expected value of the parameter (the prior expectation ranged over all possible values), we nonetheless end up with posterior inferences that are informative with respect to the posterior expectation of the parameter (they now range over a narrower set of values).  As $n \rightarrow \infty$ this range of values is squeezed down to a single point, which is the true value of $\theta$.
Comment: +1. Interesting. What is kappa in the last equation? Should it be kappa star?
Comment: I have edited to remove variation in $\kappa$ to give a simpler model.  It should be okay now.