Show $x-1$ is irreducible in $\mathbb{Z}_8[x]$

Question: How can I show that the polynomial $x-1$ is irreducible in $\mathbb{Z}_8[x]$?
$\mathbb{Z}_8[x]$ is not an integral domain so we cannot use degree considerations. I have tried reducing the problem mod 2 to conclude a factorization of $x-1$ must be of form $(1+a_1x+a_2x^2+...+a_mx^m)(1+b_1x+b_2x^2+...+b_nx^n)$ where $a_i,b_i$ are even, except $b_1$ is odd. I also tried using induction on the degrees $m,n$ but to no avail.
Any help is appreciated!
EDIT: Upon trial and error I have discovered $(2x^2-x-1)(4x^2-2x+1)=x-1$ in $\mathbb{Z}_8[x]$, however this does not disprove anything because we do not know if the 2 polynomials on the left are units or not...
Comment: Indeed, $4x^2-2x+1$ is a unit in $\Bbb Z_8[x]$: its reciprocal is $2x+1$. (Note that $\frac1{1+2x}=1-2x+4x^2-8x^3+16x^4\cdots=1-2x+4x^2$ in $\Bbb Z_8[x]$.)
Comment: It had occurred to me that I have never showed x-1 to be non-unit, but that is easy: let f be its inverse, the leading term of f times the leading term of x-1 must be a term with coefficient 0, but that means the leading term of f has zero coefficient, contradiction. I'm putting this down for other's reference.
Answer: Aha, together we have the necessary pieces! You've remarked (by looking modulo $2$) that any factorization of $x-1$ in $\Bbb Z_8[x]$ must look like
$$
x-1 = (1-x+2f(x))(1+2g(x)).
$$
However, $1+2g(x)$ is a unit, since its reciprocal is $1-2g(x)+4g(x)^2$. Therefore $x-1$ is indeed irreducible in $\Bbb Z_8[x]$.
Comment: Nice answer, +1. Indeed, in general, the units of $R[X]$ are polynomials $a_{0} + a_{1}X+\cdots a_{n}X^{n}$ such that $a_{0}$ is a unit, and $a_{1}, \ldots, a_{n}$ are nilpotent. (Here, $a_{0} = 1$, and every coefficient of $2g(x)$ is nilpotent, since $2$ is nilpotent.)
Comment: That's a very neat trick! Thanks a lot!
Answer: First of all I have to admit that I don't know what's an irreducible polynomial over a non-integral domain.
But if I understand well the OP wants to show that $X-1$ can't be written as a product of two non-invertible polynomials (of degree at least one).
Suppose the contrary, and write $X-1=fg$ with $\deg f\ge1$, $\deg g\ge1$.
If we work over a ring $R$ having only one prime ideal $\mathfrak p$ (as it is $\mathbb Z/8\mathbb Z$), then we arrive to a contradiction immediately: in $R/\mathfrak p$ we have $X-\overline 1=\overline f\overline g$ hence $\deg\overline f=0$ and $\deg\overline g=1$ (or vice versa). Then all coefficients of $f$, excepting $f_0$, belong to $\mathfrak p$, so they are nilpotent. But obviously $f_0$ is invertible, so $f$ is invertible.
Remark. We showed that $X-1$ is "irreducible" over any commutative ring having only one prime ideal (in particular for $\mathbb Z/p^n\mathbb Z$ with $p$ prime, $n\ge1$). One can't generalize this to commutative rings with at least two prime ideals: in $(\mathbb Z/6\mathbb Z)[X]$ we can write $X-1=(3X-1)(2X+1)$.
Comment: Note that this is essentially the same proof as in my answer together with Alex Wertheim's comment. This is not a derogatory statement!—just a way of helping the OP assimilate the various viewpoints on this topic.
Comment: @GregMartin I've thought I did a little more.


Synchronous delay of javascript or a setTimeout solution for command interpreter

Question: I've created a simple interpreter for kids, which allows them to run programs and control an object in a grid. The whole thing is working fine, so at the end I started to work on the "looks and feel". What I would like to do is to execute each command after a time delay (so that the movement is visible) and allow the screen to "repaint" after each step.
From how I understand setTimeout, this will not help me, as it runs assynchronous (I do not want to execute code further). I even tried a little work-around (e.g. running loop until global variable is true -> and setting the variable to true in setTimeout function. That did not do the trick either (setTimout function fired only after browser told me the script probably stopped working, although the timeout was just 500ms).
So I am stuck - many answers here say that setTimeout can do everything and no "sleep" is needed. But in my case, I do not know...
Here is what I have (greatly simplified):

                <td id="cellX2Y3" align="center"

                X

(Notice the "X", which is our object to move around the grid).
Let's say our "program" is a string of commands "up right up" -> so when executed, the X moves to coordinates X1Y2, X2Y2, X2Y3.
Once user runs the program a function processCommandString(str) is fired, which looks like this:
processCommandString(str) {
    var aProgram = [];
    aProgram = str.split(" ");

    for (iP = 0; iP < aProgram.length; iP++) {
        cmdReturn = executeElementaryCommand(aProgram[iP]);
        switch(cmdReturn) {
            case 0:
                //all is ok, increase counters, etc., proceed with next command
                break;
            case 1:
                //non critical error in program (meaning user program, not mine)
                break;
            case 2:
                //critical error -> throw exception and stop
                break;
            case 10:
                // [IF like statement] -> evaluate condition and proceed accordingly
                break;
            case 20:
                // [LOOP like statement] -> ...
                break;
            case 90:
                // custom command
                break;
        //Please note that cases 10, 20, and 90 may call the processCommandString recursively
        } //end switch
    } //end for
}

Then we have a function processElementaryCommand(cmd).
function executeElementaryCommand(cmd_param) {
    var rtrn;
    switch (cmd) {
        case eCMDs[0]:  //MOVE
            //some stuff
            rtrn = objectX.step();
            break;

        case eCMDs[1]:  //TURN
            rtrn = objectX.turn(direction);
            break;

        //case ...  (continues for all elementary commands that are in eCMDs array
        //objectX is an object that actually updates the position of the "X" in the grid:
        //What it does: (1) sets $("cellXaYb").innerHTML="" -> a, b are current (old) coordinates; (2) sets $("cellXcYd").innerHTML="X" -> c, d being new coordinates

        default:
            //check here for custom commands
            rtrn = 99;
            break;
    }   //switch end
    return rtrn;
}

Now I would like to have the pause somewhere... Anywhere :) It can be in the objectX code, it can be in processElementaryCommand, or in processCommandString. But any solution I tried lead either to endless loop, or the table not being updated as the program proceeds (it was only updated once the X was on X2Y3 position).
Comment: The correct answer is still `setTimeout()`.
Comment: If you need to block a thread out of curiosity try this `var pauseTimeout = 1500; var startDate = new Date(); while (new Date() -  startDate < pauseTimeout) { }`, don't use it in production, change logic of your app to be async and use setTimeout.
Answer: As pointed out by @Pointy, setTimeout is still your answer. I can suggest a small guideline to your approach. You should consider having a current state object which stores the current state of the command as in what has been processed and what remains to be. This can be a global. Then you need to alter your functions in such a way that once a UI action is taken, the state object should be updated and the subsequent part of the processing should be done in another callable function that will be the argument to the setTimeout function.
It is important to note that this argument function perform only one more UI update and then again call setTimeout with the further processing function.
Comment: @Pointy - I admit your answer is correct, but as such it did not provide any help. But thanks anyway.
Comment: @Igor Malyk -> I already tried that. The problem with that solution is that while the pause works and is taking place, the UI never gets updated. So you end up seeing the "X" in the final position only.
Comment: -> Thank you for your leads. I am not a programmer and this is my first program in javascript, so bear with me. I had to read your answer about 20 times, but finally I got it :)  I have created a jsfiddle for testing (only commands UP, RIGHT work and there is a hardcoded LOOP command to simulate loop code block). So original code (without delays) is here [Fiddle][1]  An updated fiddle with delays is here [Fiddle][2]   _Don't mind the effectiveness as I need the concept I will optimize later_   [1]: https://jsfiddle.net/BrandonSk/2cLghb2j/1/  [2]: https://jsfiddle.net/BrandonSk/fxd2kmzd/
Comment: **However** the code with delays works only for basic commands UP and RIGHT. The simulated block of commands (e.g. in a loop) does not work. I am currently working on the solution, but I'd like to ask for hints, how to tackle recursion. Create new and new objects (but then they will run parallel, which I do not want), or somehow save a state of current object and run subroutine in it? Thanks.
Comment: @BrandonSk, please refer the fiddle at [link](https://jsfiddle.net/sujitkm/ygspdcys/). I have made the LOOP also work. So , a command like "RIGHT LOOP RIGHT" etc will work. Hope this helps
Comment: thank you! This is a nice demonstration of difference between amateur and a pro :) I started working on a rather complex "current state" object, which had arrays as properties to do recursion. A lot of code and rather messy. Now look at your brilliant solution of around 10 lines achieving the same :) Thanks again. I still need to rewrite my former code, but I am sure it will work now. One last question: In the "exec" method you have this line "this.parent && this.parent.update();". While I know what it will do, I do not quite understand how it works. Could you explain please?
Comment: That is same as `if(this.parent) this.parent.update();`
Comment: Basically the execution thread comes here when a sequence of commands are processed. Consider if the command were RIGHT LOOP RIGHT, and when it had entered the `runSubRoutine()` and  after executing the last UP (3rd UP), you want to again start `update()` on the command after LOOP. This needs that the parent object's `update()` should get called. The state of the parent is currently pointing to the last RIGHT (of the original command after executing LOOP). Which allows the parent to continue processing from there.
Comment: The `this.parent &&` prevents the `parent.update()` to get called where there is no parent as in the case of the base command sequence.


Trying to allow a normal user to run a command which requires inputting root password

Question: I have this tool which allows users to manage printers in the linux environment.
I need to allow a user to run this tool without giving him the root password.
The permissions on the tool are:
-rwxrwxrwx 1 root root       78 Dec  4  2008 system-config-printer

Comment: The permissions on the tool are wrong. Group others should absolutely not have write permission to a tool like this in any case, and most especially if the tool has a setuid permission set; that is an instant root-level hole.
Answer: The sudo command is very configurable, and can be used to grant specific users permission to run specific commands. Use visudo to edit /etc/sudoers, and enter a line like the following:
bob ALL = (root) NOPASSWD: /usr/sbin/system-config-printer

The user bob would then run sudo /usr/sbin/system-config-printer in order to run the tool.
Answer: That is a great way to achieve that goal and i will use it myself next time.
I used another method though:
i've edited /etc/group and added the user in the end of the sys line:
sys:x:3:root,bin,adm,itaig
anyways, thanks for your solution.
Itai
Answer: You could set the owner and group of the executable as root, and then do chmod u+s and chmod g+s on it
Edit: Wikipedia


Inner product of fraction of matrices

Question: I wonder if $$\left\langle x\left|AB^{-1}\right |x\right\rangle = \frac{\left<x|A|x\right>}{\left<x|B|x\right>}$$ in general. If not, under what condition are they equal?
Comment: How do you define $\frac{A}{B}$ (assuming $B$ is invertible)?
Comment: $\frac AB$ is not unique: $AB^{-1}$ may not equal $B^{-1}A$.
Comment: @Clement C I would say $AB^{-1}$.
Comment: Then, why not $B^{-1}A$? That seems quite arbitrary for the LHS, and the RHS does not entail such choice to be made...
Comment: @Clement C i would say maybe limited to the case where $AB^{-1} = B^{-1}A$ and wonder if the equality holds in this case.
Comment: So, first restriction: $A,B^{-1}$ commute.
Comment: @Clement C yes....
Comment: You would also need $|x \rangle$ to be a unit vector
Comment: @Omnomnomnom thank you for the answer. But in my case the norm of $\left|x\right>$ need not be one. I see that your answer does not assume this also.
Comment: Multiply $x$ by $r$. The left hand side is multiplied by $r^2$, the right hand side is multiplied by $r^0$. This strongly suggests the formula is unreasonable. It would be better to divide the l.h.s. by $\langle x|x\rangle$.
Answer: They are not equal.  They will be equal, however, if $A$ and $B$ commute and $x$ is a unit vector.
Here's a fact you may be interested in: if $B$ is positive semidefinite,
$$
\frac{\left<x|A|x\right>}{\left<x|B|x\right>} =
\frac{\left<x|A|x\right>}{\left<B^{1/2} x|B^{1/2} x\right>} =
\frac{\left<B^{-1/2}y|A|B^{-1/2}y\right>}{\left<y|y\right>} =
\frac{\left<y|B^{-1/2}AB^{-1/2}|y\right>}{\left<y|y\right>}
$$

Inner product of fraction of matrices


Error: aspnet_wp.exe (PID: 332) stopped unexpectedly.,

Question: I am getting 3errors . this is the event log
Type: Error Event: 1089
User: N/A
Computer: HOME-590392F5B5
1) aspnet_wp.exe  (PID: 332) stopped unexpectedly.
2) Failed to execute the request because the ASP.NET process identity does not have read permissions to the global assembly cache. Error: 0x80131902
3) Failed to initialize the AppDomain:/LM/W3SVC/1/ROOT
Exception: System.Configuration.ConfigurationErrorsException
Message: Exception of type 'System.Configuration.ConfigurationErrorsException' was thrown.
StackTrace:    at System.Web.Configuration.ErrorRuntimeConfig.ErrorConfigRecord.System.Configuration.Internal.IInternalConfigRecord.GetLkgSection(String configKey)
   at System.Web.Configuration.RuntimeConfigLKG.GetSectionObject(String sectionName)
   at System.Web.Configuration.RuntimeConfig.GetSection(String sectionName, Type type, ResultsIndex index)
   at System.Web.Configuration.RuntimeConfig.get_HostingEnvironment()
   at System.Web.Hosting.HostingEnvironment.StartMonitoringForIdleTimeout()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters)
   at System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironmentAndReportErrors(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters
I see many posts about this on the internet but only the error..
Any help is greatly appreciated
Thanks
SC
Comment: What version of iis are you using ?
Answer: Based on your 3 error messages,  it appears the account that you are running your application pool under has not been granted sufficient access.
What account are your running your application pool under?  Also which version of IIS are you running on?   The details change based on the answer to the above two


Permission issues with Custom Content Entity exposed to REST API

Question: I hope it's not a duplicate entry.
I've recently created my Custom Content Entity within a Custom module and I'm currently having trouble with permissions. (Please see permissions below)

The permissions work perfectly when using the add/edit/delete Drupal forms. It throws a 403 if the current user has not the permission, which is great because everything is normal here.
But when I expose the Custom Content Entity via RESTui module : GET, POST, UPDATE. (please see screenshot below). Anonymous users don't get 403 and are able to create, edit.

Are the permissions defined under mymodule.permissions.yml only for Drupal entity form ?
How do we define REST permissions for a Custom Content Entity ?
Thank you very much for your help
Comment: How are you testing the petition? I see that you are using a cookie as a authentication mode and I think that your code is correct and is your testing that is wrong.

As you supposed, to alter/view a entity using REST you need the same permissions defined to do it using the entity form.
Comment: I have a little jQuery AJAX snippet to do my tests. I'm also using my browser in incognito mode with cookies cleared. First, I do a request to "/rest/session/token'" to get CSRF token. and I use jQuery AJAX to either POST or PATCH, with CSRF token in header.
Answer: Actually, this was a false positive error.. I did some testing with my REST Client in Chrome (please see screenshot at the end of the paragraph) and permissions are correctly working.
The issue was related to my XHR request which was (for some reasons) keeping a valid CSRF token and because of this I appeared to be identified as admin. And of course as admin ID 1, I was granted full access on CRUD..
Sorry and thanks for your time guys!
Comment: I supposed that the issue was something related with this (for this reason I ask you about the way to do the test) :)


apply condition to pages created by user roles

Question: if(isset($node) && $node->type == 'page') {
}

In the above code, I need add one more condition, so that it get applied on those pages which was created by users having user role "EDITOR" Please help.
Answer: if(isset($node) && $node->type == 'page') {
  if($node->uid) {
    $node_author = user_load($node->uid);
    if(is_object($node_author)) {
      if(in_array("editor",$node_author->roles)) {
        // This is the condition to match the current node author belongs to editor role.
      }
    }
  }
}

Comment: downvote with a reason would have helped me either


expansion of integrand and resulting integral

Question: I was watching a math tutorial on youtube and saw the following. I was wondering if I can get some advice on the difference between the two workings.
Why does the one on the left become fractions of (1/3, 1/2 & 1/4), while the one on the right only has a fraction for (1/5)?
Apologies for my course english, I thought I inserted the print screen with the pink arrows to make it clearer. =)

Appreciate any advice. Thanks in advance!
Answer: One formula computes the mean $E(X)$ and the other the $Var(X) = E(X^2)$. That is, the formulae being integrated are different, so you should expect the evaluation of the integrals to be different.
$\displaystyle E(X) = \int_1^3 x(1-x)(x-3) dx = \int_1^3 x(3 + 4x - x^2) dx = \int_1^3 (3x + 4x^2 -x^3) dx$
$\displaystyle Var(X) = \int_1^3 x^2(1-x)(x - 3) dx = \int_1^3 (3x^2 + 4x^3 - x^4) dx.$
Notice that in the first case, we are integrating a third-degree polynomial, and in the second case, we are integrating a fourth-degree polynomial.

Recall: For all nonnegative integers $n$ ,$$ \int_a^b x^n \, dx = \left[\frac{1}{n+1}x^{n+1}\right]_a^b=
\frac{1}{n+1}b^{n+1} - \frac{1}{n+1}a^{n+1}$$

If you need more help with how to integrate polynomials, the link will take you to PlanetMath, where you'll find a tutorial to refresh your memory.
For a video tutorial: see Khan Academy's video, which discusses integration of polynomials. The Khan Academy's website also provides interactive tutorials so you can practice with actual problems, and brush-up on your math skills (here's a link to help you review Calculus, e.g.).
Comment: Thanks for the speedy reply @amWhy. Really appreciate it. I've not done integration for a long time and have lost touch with it. Appreciate your kind advice please.
Answer: It's just simplified. On the right side you have
$$\frac{3}{4}=\int_1^3 4x^3-x^4-3x^2 = \frac{3}{4}\left[\frac{4x^4}{4}-\frac{x^5}{5}-\frac{3x^3}{3}\right]_1^3=\frac{3}{4}\left[{x^4}-\frac{x^5}{5}-{x^3}\right]_1^3$$


How do I add a new field to a YAML file in python?

Question: I have a YAML file with content:
---
  'Croatia':
    population: 4600000
    capital: Zagreb
  'Italy':
    population: 60000000
    capital: Rome

How do I want to add a new field:
---
  'Croatia':
    population: 4600000
    capital: Zagreb
    continent: Europe
  'Italy':
    population: 60000000
    capital: Rome
    continent: Europe

How do I add the field "continent" with value Europe to every State?
Comment: What have you tried so far?
Comment: Possible duplicate of [Editing Yaml File by Python](https://stackoverflow.com/questions/29518833/editing-yaml-file-by-python)
Comment: Your second example missed a colon after `'Croatia'`, making it invalid YAML. There is also no mention of fields in the YAML specification. A mapping has keys and values.
Answer: Load it, update the field as usual in a dictionary and dump again.
data = yaml.load(...)
data['Croatia']['continent'] = 'Europe'
yaml.dump(data, ...)

Comment: There is absolutely no reason to use the unsafe `load()` instead of `safe_load()`. You should also indicate that doing this drops the (superfluous) quotes around `'Croatia'`, doesn't have the indentation that the OP requested, nor does it have the start of document marker.
Answer: If you want to preserve your original YAML layout and quoting, then you cannot generally do that with pyyaml without a lot of effort.
With ruamel.yaml (disclaimer: I am the author of that package) this is much simpler, but you still need to do something for the top-level indentation by two spaces (using the transform parameter):
import sys
import ruamel.yaml

yaml_str = """\
---
  'Croatia':
    population: 4600000
    capital: Zagreb
"""

def indent_data(s):
    return s.replace('\n', '\n  ')

yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
yaml.preserve_quotes = True
yaml.explicit_start = True
data = yaml.load(yaml_str)
data['Croatia']['continent'] = 'Europe'
yaml.dump(data, sys.stdout, transform=indent_data)

gives:
---
  'Croatia':
    population: 4600000
    capital: Zagreb
    continent: Europe

Any comments in the original document would be preserved in the output, but EOL comments might shift because of the extra indentation.
Comment: @Becks Yes you can, by passing the result of `open(your_file_name.yaml)`  instead of `yaml_str` to `yaml.load()`. Using the `yaml_str` in just to have a single source testable example.


How to escape pipeline char in Windows shell?

Question: I need to specify a regular expression that includes | character to findstr command:
processtext.exe | findstr /R "Hello|Bye"

How do I escape it? \| does not work. Quotes fix issue with pipelining but the regex does not match although separate searches for "Hello" and "Bye" do. I'm interested in a solution for legacy shell, not powershell.
Comment: [FINDSTR support for regular expressions is limited and non-standard](http://ss64.com/nt/findstr.html). FINDSTR does not support alternation with the `|` pipe character...
Comment: Have you tried encapsulating it in quotation marks? What does your entire script look like?
Comment: Are you sure findstr supports pipe syntax (this|that matching)? Not seeing anything in the documentation.
Answer: If someone is still interested just replace the pipe with a space, like in findstr /R "Hello Bye".
Answer: I've found a solution for my purposes of running powershell commands from cmd.exe as follows:
C:\GitLab-Runner>powershell get-service *gitlab* ^| ft

to get following output
Status   Name               DisplayName
------   ----               -----------
Stopped  gitlab-runner      gitlab-runner

Comment: This doesn't even remotely address the question.
Comment: The point is that using `^|` worked for my command to escape the pipe character correctly. At least, it is a chance that the `^` char works for your requirement, too.
If not, this answer might at least be helpful for other persons searching for a solution in combination with other commands (like `powershell`).
Comment: For your reference, you might want to take a look at https://stackoverflow.com/questions/1200235/how-to-pass-a-quoted-pipe-character-to-cmd-exe which provides some solutions for similar challenge


Variable gets "Undefined" in JQUERY Function

Question: i am new to webdevelopment and atm i am trying to build a function which handels all different buttons on my Page (to call php code by post).
It works fine without the switch/case (or if/else) but as soon as i try to dynamically "load" parameters for Post action it does not work properly anymore. It actually works, when i press the button a 2nd time which looks very strange to me :-). The problem is that button_id suddenly shows as "undefined"
Could you give me a little advice please?
$(document).ready(function() {

$(".btn").click(function()
{
    button_id = $(this).attr("id");
    switch ($(this).attr("id"))
    {
        case "ZXY" :
           php_func_name =  "ABC"
           php_id = "DEF"
           break;

        case "XYZ" :
           php_func_name = "HIJ"
           php_id = "KLM"
           break;
    }

    $('#' + button_id).click(function() {
        $.post("php_functions.php", {
            method: php_func_name,
            id: php_id
        }, function(data) {
      $("#test").html(data);
      alert (data);
        });
    });

});
});

Comment: Where did you get the "undefined" value for button_id ?   By the way, consider changing this line:  `button_id = $(this).attr("id");`  to  `var button_id = $(this).attr("id");` .  Without the **var** , it adds button_id to the global `window` object so you are actually setting `window.button_id` . It's usually not what you want and can lead to bugs.  Consider adding another line after it, to define these vars also:  `var php_func_name, php_id;` . So these variables also remain local and don't get added to `window`.
Answer: The problem is that you are changing the function for the button.click. As you do not know your HTML code, I would store the php_func_name and php_id data into data- attributes in the button:
<button id="ZXY" class="btn" data-funcname="ABC" data-id="DEF"></button>
<button id="XYZ" class="btn" data-funcname="HIJ" data-id="KLM"></button>

$(document).ready(function() {
    $('.btn').click(function() {
        $.post("php_functions.php", {
            method: $(this).data('funcname'),
            id: $(this).data('id')
        }, function(data) {
            $("#test").html(data);
            alert (data);
        });
    });
}


How does $3(5^{k+1} + 4 \cdot 5^{k+1} - 1) / 4$ lead to $3(5^{k+2} - 1) / 4$?

Question: I am struggling with following from an example, which I hope someone can explain for me.

How does the first expression lead to the second?
  $$3(5^{k+1} + 4 \cdot 5^{k+1} - 1) / 4 \quad\to\qquad3(5^{k+2} - 1) / 4$$
Comment: Hint: $x+4x=5x$
Comment: $5^{k+1} + 4 \cdot 5^{k+1}=(1+4)5^{k+1} =5 \cdot 5^{k+1}=5^{k+2}$.
Answer: It's because $5^{k+1}+4\cdot5^{k+1}=(1+4)\cdot5^{k+1}=5\cdot5^{k+1}=5^{k+2}.$


É possível criar um site com HTML e C# sem ASP.NET?

Question: É possível criar um site somente com HTML e C#, sem ASP.NET? Em linhas gerais, como?
Comment: Isso é apenas curiosidade ou há outra motivação? De repente você tem a intenção de criar um site em C# sem ASP.NET para poder hospedar em servidores Linux ao invés de Windows....se fosse esse o caso, aí poderíamos mencionar outras soluções...apenas fiquei curioso com sua pergunta.
Comment: @Alisson Era só curiosidde mesmo!
Comment: @isaque de uma vista de olhos na [NancyFx](https://github.com/NancyFx/nancy). E uma forma de construir o site sem utilizar, nem depender no ASP.NET (MVC).
Comment: @Omni blz, vou olhar
Answer: Sim, HTML é padrão. CSS também é quase obrigatório na prática. JS provavelmente será usado. Tudo isto no lado do cliente.
No lado do servidor pode usar virtualmente qualquer linguagem. C# é uma delas, e das mais viáveis. É uma das 3 linguagens mais usadas em toda web.
Não precisa usar ASP.NET clássico, mas é provável que queira usar alguma outra tecnologia próxima disto. Pode usar outras tecnologias que não o ASP.NET, pode pegar estas tecnologias que são open source e modificar para atender suas necessidades. Um exemplo é o Nancy citado pelo Omni.
Se quiser pode reinventar a roda, mas mesmo eu que gosto disto para ter mais controle provavelmente não o faria.
Detalhar como fazer é muito amplo, mas as duas formas principais é usar a API do servidor web, provavelmente IIS ou Apache, mandando mensagens para ele do que deseja fornecer e receber mensagens dele de requisições ou usar CGI, aí basicamente é escrever no console e configurar para o servidor capturar isto. Cada servidor pode ter dua própria forma de comunicar com a aplicação servidora.
Precisa achar um bom motivo para fazer isto. Se for performance acho que tem outros meios melhores de alcançar o objetivo. Se for não ter que aprender uma tecnologia, provavelmente não compensa o esforço que terá que fazer na mão.
Note que é possível evitar o WebForms que é obsoleto e considerado ruim por muitos, ou mesmo evitar o MVC que é um pouco pesado, melhorou no ASP.NET Core, mas ainda é um canhão para matar passarinho em muitos casos. Tem problemas que não precisa de modelos e controladores. E é verdade que nos casos mais simples, a última coisa que vai querer fazer é comunicar com o servidor HTTP na mão. Para isto existe o Razor Pages.
É bom lembrar que o ASP.NET Core possui servidor HTTP próprio, que pode ser usado em muitas situações, mas não em todas. E agora conta até com proxy reverso.
Tem perguntas no site com mais detalhes.
Coloquei no GitHub para referência futura.
Comment: Boa explicação. Se pararmos para pensar, já que o próprio ASP.NET foi desenvolvido em C#, nada nos impediria de criar uma biblioteca concorrente para desenvolvimento de aplicações web, mas como mencionado, isso seria reinventar a roda, correto?
Comment: @Alisson correto. Pode inclusive mexer no código existente já que ele é totalmente livre, livre no sentido de livre mesmo, não no sentido de GPL que não é livre de verdade.


Interactions and Regressors Conditional on Other Regressors

Question: Short version: I am trying to build a model in which some binary regressors (whether or not a specific medical procedure took place) are conditional on other regressors (whether or not a specific medical procedure was clinically indicated for a given person), and I'm not sure of the best way to go about it. The regressand is the difference in total medical expenditures between a base year (when the medical procedures do or do not occur) and a later year, to see the impact of those procedures on subsequent costs with the ultimate goal of building a predictive model. My instinct is to include, for each rule, both binary regressors in the model individually along with an interaction, but I'm not certain how sound that is or if it's enough to capture the relationship between the "procedure applies" indicator and the "procedure was done" indicator. So:

Is that a sound approach?
If (1), are there any major pitfalls I should be aware of?
If not (1), what other approaches might be suitable instead?

Additional details: I'm working on a project attempting to relate certain medical "best practices" in a base year to medical expenditures in following years. I have a list of best practices (from a vendor) as well as whether or not they applied to specific participants and were followed with a particular in a given year. Not all of the best practice rules apply to all members, and I need my model to reflect a difference between a rule not applying to a participant versus a rule applying and the procedure not taking place. Some rules apply to nearly everyone, while others apply to as few as seven participants. The conditions I am working with are chronic and so are assumed to have some (fairly) regular, nonzero cost from year to year.
I have around 60 rules to consider for inclusion. Because every rule would be represented by three terms in my planned model, the model itself will be pretty big and I am concerned about overfitting. I've thought a little bit about variable selection but haven't settled on an approach yet and may try including every rule.
I appreciate any advice, and am eager to review any referenced material related to my situation. I have not had much luck finding anything addressing a strongly similar situation, but what I can find seems to suggest that my intended approach is acceptable.
Answer: To 1. and some of 2. but not 3.:
You don't need to model with an interaction. Binary predictors for indicated and happened are enough.
An interaction would allow you to model a separate effect for all the combinations of indicated and happened. Since having the procedure without being indicated the procedure is not possible (i.e. indicated = 0; happened = 1), you can achieve all the necessary freedom with main effects. If B_* indicates the coefficient for *:
indicated  happened                          effect
        0         0                             B_0
        1         0               B_0 + B_indicated
        1         1  B_0 + B_happened + B_indicated

Every group can be given a unique prediction and the model is adequately specified. Using an interaction will lead to undefined coefficients in a standard linear model. Excluding the interaction means fewer coefficients for the same amount of freedom.
If you regularise then you will get slightly different results by using an interaction, but only because the model can use two coefficients to affect the same group and cheat the regularisation penalty (depending on its nature). So again, no interaction is better.
Given the nature of your problem it's definitely worth trying a regularized model. Including every rule in an L1 and tuning $\lambda$ by cross-validation is a standard approach.
Comment: If it is true that happened => indicated, (happened =1 => indicated =1) then happened*indicated = happened.


Memcached error in fuelPHPH, error code 47

Question: I have problem with memcached in fuelphp.
i installed memcached and set everything as it should be and when i run my app i get following error.
Fuel\Core\FuelException [ Error ]: Memcached returned error code "47" on write. Check your configuration.
I know that configuration file in fuelphp is correct because it works on other computers, so that is not the issue. Something is wrong with my memcached.
Answer: 47 means MEMCACHED_SERVER_TEMPORARILY_DISABLED, and you get it when your memcached connection goes into a tcp timeout or passes it's retry limit. It's generated by libmemcached, and is outside your control.
So you need to figure out why your memcached server became (temporarily) inaccessable.
Comment: ln -sfv /usr/local/opt/memcached/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist
Comment: @NikolaTasic Could you please mark the answer as "solved"? It would make "valuable" answer easier to notice. Thanks
Answer: We have encountered the same problem and carried out a decision that problem is with our php-memcached module but not with FuelPHP at all. This error is not permanent for us and appears only at one server out of four.
Is this error permanent for your configuration?
Comment: ln -sfv /usr/local/opt/memcached/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist

that solved the problem


For a small production environment is it better to use only masters k8s or some mini k8s solutions?

Question: I have a scenario of a small air-gap production environment with only three Linux servers (CentOS or RHEL).
I want to deploy a small k8s cluster on them.
I have two approaches for now:

Installing a pure k8s cluster with only master nodes and untainting them from NoSchedule to run all pods on them.
Installing a mini cluster solution using k3s, k0s, or microk8s and configuring all nodes as master and workers

If I use the first approach (I know it's a bad practice) is it the correct way to run pods on masters?
If I want to use the second one who is the best and easiest to install in different air-gap environments and maintain them? (I used k8s and okd 3 in production but not them)
Lastly, what do you think is the best approach from those two, or are there better ones for my scenario?
Thanks in advance for the help
Answer: The big detail that's going to affect what's right for production is how much information security matters to you.
Kubernetes lets you have mechanisms (ResourceQuota, LimitRange, Pod security admission, pod priority, …) that protect apps in one namespace from being affected by another namespace.
If you already know how to set these up - or you know that you'll have to learn them - then putting the apps onto control plane nodes of a "regular" Kubernetes cluster can be a good fit.
That focus on infosec is going to make it important that you take appropriate hardening measures, and these are easier to do when the Kubernetes cluster you're configuring starts off like vanilla upstream Kubernetes.
You might even want to set up gVisor to provide additional restrictions on what the application containers can do. If that's a story that's important for your context, have a look at the CKS syllabus to learn about other topics to consider.
If information security isn't a big focus, and perhaps you're keen to get something up and running soon, I think k3s would be a better fit. k3s does more for you out of the box, and makes it easier to run a replicated control plane with good availability.


TypeError: unorderable types: int() > list()

Question: # Import Packages
import random

# Global Variables
perf_num = 500
species = [20]
temp_num = 0
length = 0
s = 0

# Main Program
for num in range(100):
    r1 = int(random.random()*10)
    r2 = int(random.random()*10)
    species.append(r1)
    length = len(species)
    while s < length:
        print(s)
        if species[s-1] > species[s]:
            temp_num = species[s-1] - r1
            species[s-1] = temp_num
        else:
            temp_num = species[s] - r1
            species[s] = temp_num
        if s-1 < 5:
            species[s-1] = []
        s += 1

    print(species)

Please don't explain in very complicated coding language as I just started learning Python from youtube. I tried making my own program and continue to get this error.
Answer: In the following line:
species[s-1] = []

you're assigning an empty list to a list of numbers, which results in something like:
20 [20, 2] 2

Then when you try to compare a number and a list:
if species[s-1] > species[s]:

you'll get that error:
TypeError: unorderable types: int() > list()

Comment: Actually, the error happens on the line `if species[s-1] > species[s]:`. This is only in python 3, the error doesn't happen in python 2 (all types can be compared in python 2), so you get a different error at the subtraction operation.
Comment: The error in python2 is a _different_ one: `TypeError: unsupported operand type(s) for -: 'list' and 'int'`
Comment: @Random832 hmmm... I'll check it out when I get back home. Thanks!
Comment: @Random832 Thx, I think your right but do you have any idea how could ffix this error or do what i want to do in a different way? Plz answer ASAP. rly need to get this done for a school project
Comment: @alfasin Any idea how I could still do what i want to do without getting this error?
Comment: @user3927678 if you would only describe what is it that you're trying to do there... Assuming we'll read the code and understand what you wanted to do is most of the times a real long shot ;)
Comment: @alfasin Ya sorry the program is supposed simulate evolution so every cycle of the while loop, the numbers duplicate into (hypothetically) more species. And bigger numbers (species) eat smaller numbers causing their number to become smaller. In that line, "species[s-1] = []" I am trying to remove a number which is too small to survive from the list. So if i don't use that How else do I remove something from the list?
Comment: @Vansh03 instead try: `del species[s-1]`
Comment: @alfasin NOw I'm getting the Error IndexError: "list index out of range"
Comment: @alfasin in the line "if species[s-1] > species[s]:"
Comment: Start with `s = length - 1` and go down `while s > -1:` decrement s: `s -= 1`


How to find correlation if we have continuous and categorical variables present in my dataset as features and target is again binary

Question: I am working on classification problem where I have categorical and continuous features however the target is binary.

What is the best way to check correlation with respect to target variable.
Also I want to eliminate some features which are highly correlated.

I have generated a correlation heatmap for continuous features and for categorical features I am thinking to perform a chi square test .
Is this a right approach? Do I have to apply two different methods for continuous and  categorical features?
Comment: Related: [Correlations with unordered categorical variables](https://stats.stackexchange.com/q/108007/7290).
Answer: For correlations between continuous and categorical variables see Correlations between continuous and categorical (nominal) variables and Correlations with unordered categorical variables.
But your main question seems to be about classification into two classes, since the target is binary. It is in most cases better to see this as a risk estimation problem, and that can be modeled via logistic regression, see Choosing between logistic and discriminant,   Why isn't Logistic Regression called Logistic Classification?,   When is logistic regression suitable?
And finally, you want to eliminate features. Doing that by bivariate correlation/association is seldom a good idea. See How to reduce predictors the right way for a logistic regression model.


$q \equiv 2 (\mod 3)$ be a prime , then does there exist non-zero integers $a,b,c$ such that $a^2+ab+b^2=qc^2$ ?

Question: Let $q$ be a prime such that $q \equiv 2 (\mod 3)$ , then is it true that $a^2+ab+b^2=qc^2$ has no solution in non-zero integers $a,b,c$ ?
Answer: With the prime $q\equiv2\pmod3$ the only way $a^2+ab+b^2$ can be divisible by $q$ is for both $a$ and $b$ to be divisible by $q$. This is seen as follows. Assume contrariwise that $q\nmid b$. Then in the field $\Bbb{F}_q$ $b$ is invertible. Dividing the congruence $a^2+ab+b^2\equiv 0\pmod q$ by $b^2$ then implies that $x=a/b\in\Bbb{F}_q$ is a solution of the equation
$$
x^2+x+1=0.
$$
Clearly $x\neq1$, because $a=b$ is impossible. But
$x^3-1=(x-1)(x^2+x+1)=0$ then implies that $x$ is of multiplicative order $3$.
But the multiplicative group of the field $\Bbb{F}_q$ is of order $q-1$ and, by Lagrange's theorem, cannot have an element of order three.
This settles your question as follows. Clearly $q\mid qc^2$, so $a^2+ab+b^2$ must be divisible by $q$. But then both $q\mid a$ and $q\mid b$ by what we just saw, so the L.H.S. is divisible by $q^2$. Therefore $q^2\mid qc^2$ meaning that $q\mid c$ also. But we can cancel the square of any common factor of $a,b,c$ from your equation. So assuming that this was done at the beginning we have arrrived at a contradiction.
Comment: There are several closely related threads such as [this](http://math.stackexchange.com/q/1101612/11619). Any duplicates?


Do we need to worry about outliers when using rank-based tests?

Question: Apologies if this is a very basic question.
If we have data that are not normally distributed (e.g. skewed, Shapiro-Wilk test is significant) and we resort to rank-based methods (e.g. Wilcoxon Signed Rank test), then do we need to be concerned with outliers?
Imagine, for example, we plot the data using a boxplot and a minority of data points are marked as outliers. Should we transform those points? Or remove them? It seems to me that many textbooks talk about dealing with outliers, but only because they exert a major influence on the parameters such as mean and standard deviation. However, when we use a rank-based test they will already be 'transformed' to be the next value in the rank, and would therefore not exert a major influence on the test. I have not seen this stated explicitly in a statistics book so far, so I thought I would ask the question here.
Do we need to worry about outliers when using rank-based tests?
Comment: Statistically rank-based tests are robust against outlier. But an outlier is an outlier, on the operational level the analyst should still examine that case. So, I'd say we still need to "partially" worry about outliers.
Comment: It's fine even if the question might be very basic. As long as the question is unasked on this site, even basic questions are good questions
Answer: @Hotaka's answer is quite correct. Ranking makes transformation unnecessary; it is itself a transformation that ignores exact values except in so far as they lead to differences in rank. In fact, a little thought, or some example calculations, will show that the results after ranking logarithms or square roots or any other monotonic transformation are exactly the same as those after ranking the original data.
But more can be said. The either-or thinking

Either my data are normally distributed, and I can use standard or classical procedures.
Or I need to resort to rank-based tests.

is a little stark, and (it may be suggested) over-simplified. Although it's hard to suggest exactly what you should be doing without some sight of your data and your precise goals, there are other perspectives:

Many users of statistics look at marginal (univariate) distributions and assess whether they are close to normality, but that may not even be relevant. For example, marginal normality is not required for regression-type procedures.
For many procedures, it's how the means behave, not how the data behave, that is more important and closer to the main assumptions.
Even (say) a significant result at conventional levels for a Shapiro-Wilk test is equivocal in terms of guiding later analysis. It just says "your distribution is detectably different from a normal distribution". That itself does not imply that the degree of non-normality you have makes whatever you have in mind invalid or absurd. It may just mean: go carefully, as underlying assumptions are not exactly satisfied. (In practice, they never are exactly satisfied, any way.) The habit to cultivate is that of thinking that all P-values are approximations. (Even when assumptions about distributions are not being made, assumptions about sampling or independence or error-free measurement are usually implicit.)
Although many texts and courses imply otherwise, non-parametric statistics is something of a glorious dead end: there are a bundle of sometimes useful tests, but in practice you give up on most of the useful modelling that is central to modern statistics.
Outliers are mentioned here, and they always deserve close attention. They should never be omitted just because they are inconvenient or appear to be the reason why assumptions are not satisfied. Sometimes analysis on a transformed scale is the best way forward. Sometimes a few mild outliers are not as problematic as less experienced users of statistics fear. With small samples, data will often look ragged or lumpy, even if the generating process is quite well-behaved; with large samples, a single outlier need not dominate the rest of the data.
There is always the option of doing both kinds of tests, e.g. Student's t and Mann-Whitney-Wilcoxon. They don't ask exactly the same question, but it is often easy to see if they point in the same direction. That is, if a t test and the other test both give clear signals that two groups are different, you have some reassurance that your conclusion is well supported (and some defence against the sceptic who distrusts one or other procedure given a whiff of non-normality). If the two tests give very different answers, this in itself is useful evidence that you need to think very carefully about how best to analyse data. (Perhaps that massive outlier really does determine which way the answer comes out.)

With experience, users of statistics are often more informal than texts or courses imply they should be. If you talked through an analysis with them, you would often find that they make quick judgements such as "Sure, the box plots show some mild outliers, but with data like this analysis of variance should work fine" or "With skew that marked, a logarithmic scale is the only sensible choice". I don't think you will often find them choosing techniques based on whether a Shapiro-Wilk test is or is not significant at $P < 0.05$. Saying something like that may not help less experienced users much, but it seems truer than the idea that statistics offers exact recipes that must always be followed.
Comment: I quite like the idea of (5), doing both parametric and non-parametric tests. But I've rarely seen an article (at least in psychology) that says "here are the results of various alternative statistical tests." They just choose one method and report that, which can be problematic, because they can just choose the method that gives them a significant result, as highlighted in the psych science article here: http://bit.ly/15uTFlT
Comment: Your thoughtful comments deserve very detailed discussion. My experience confirms that people in many fields are very concerned to show that there's a single  correct analysis of a given data set, which is what they did.
Comment: Thank you for your detailed answer. Regarding choice of method, I can believe most users of statistics are fairly exploratory during the first look at their data. But when they write an article, they need to justify which method they chose. I guess this partly depends on the field and whether we are more interested in modelling lots of data or testing a hypothesis. For the latter, a Shapiro-Wilk, how ever under-powered, must look better than reporting skewness without a test, and then going on to conduct a non-parametric test.
Comment: Of course, the alternative of reporting multiple methods will almost certainly lead to some ambiguity, i.e. some methods being significant and others not. How many would you need to conclude you've got an effect? 4 out of 5 significant? What about 3 out of 5?
Answer: No. When the data are ranked, an outlier will simply be recognized as a case that is ranked one above (or below) the next less extreme case. Regardless of whether there is .01 or 5 standard deviations between the most and second most extreme value, that degree of difference is thrown away when data are ranked.
In fact, one of the many reasons why someone might use a rank-based (or nonparametric) test is because of outliers.
Comment: And the excellent efficiency of nonparametric and semiparametric methods is a reason not to pre-test for normality (besides the inadequate power of the normality test).
Comment: I'm at a loss as to whether to accept this great concise answer or the thought-provoking detailed one from @NickCox. I will wait a couple of days to see which ends up with the most votes!


Javascript crypto SJCL GCM not decrypting what I encrypted

Question: I'm currently experimenting with SJCL but I'm having trouble with encryption/decryption. With the lack of good examples I came up with what you see below but it's not working. Can anybody point out what I'm doing wrong? Thanks in advance.

Results in:
encrypted: 5Z2QQ9s6gfORlr6qLvlwjO/J+/TbfSbOs79c4w==
decrypted: AAAAAAAAAAAAAAAA

Answer: I think your problem is sjcl.codec.bytes.toBits(plaintext). If you run that by itself, you get [0,0,0]. I think you want sjcl.codec.utf8String.toBits(plaintext) instead.
You would use bytes.toBits if you have an actual byte (octet) array (like [255, 34, 12, 16]), but in this case you're using a string so it needs to be converted differently.
Also, I've had problems with using strings for IVs, you may want to run it through the same conversion as the key before passing it in (base64.toBits(iv)).
Comment: i need help with task ready to pay for it can u tell email or skype


Value de button nao esta aparecendo

Question:
ja testei no chrome e no firefox mas nada e nem a ide esta acusando acusando erro
Comment: Niko se fosse input daria certo para button a syntaxe é assim `Tecle Enter`
Answer: Erro de sintaxe.
O correto seria:

<button>tecle enter</button>
ou

<input type="button" value="tecle enter"/>

Value de button nao esta aparecendo


Question regarding supports of random variables and their transformations

Question: Disclaimer: I preface by saying, I am currently reading "Hogg, McKean, and Craig, introduction to mathematical statistics", hence, kindly forgive me if I get some definition/concept wrong here, as all of these are stitched together by me from various random sources. The book does not talk about any of this.
Some preliminary definitions: Let $X$ be a random variable $X: \Omega \to \mathbb{R}$, and let $P_X$ be a probability $P_X:\mathcal{B_0} \to [0,1]$, where $\mathcal{B_0}$ is the Borel Sigma algebra, defined on $X$. Here ($\Omega$, $\Sigma(\Omega)$,$P$) form a probability space, and ($\mathbb{R}$,$\mathcal{B_0}$,$P_X$), where $P_X$ is the induced probability, also form a probability space. Let $Y=g(x)$ be a measurable function $g:\text{Range(X)}\to \mathbb{R}$, and let $P_Y:\mathcal{B_0} \to [0,1]$ be "induced" by $P_X$. That is, $P_Y(\text{some set in }\mathcal{B_0}):=P_X(g^{-1}(\text{some set in }\mathcal{B_0}))$. The associated sigma algebra for $\text{range}(X)$ I shall take to be $\mathcal{B_0}$. I hope till here, things are properly defined (?).
Now I define my "support" $R_X$ of the random variable $X:\Omega \to \mathbb{R}$ to be the smallest closed subset of $\mathbb{R}$ such that $P_X(R_X)=1$. Or equivalently, $R_X:=\{x\in\mathbb{R} :\forall \ \varepsilon>0, P_X(V_{\varepsilon}(x))>0 \}$. In a similar vein, for $Y$, $R_Y$ would be the smallest closed subset of $\mathbb{R}$ such that $P_Y(R_Y)=P_X(g^{-1}(R_Y))=1$, or again, equivalently, $R_Y=\{y\in\mathbb{R} :\forall \ \delta>0, P_Y(V_{\delta}(y))=P_X(g^{-1}(V_{\delta}(y)))>0 \}$.
Note: When the probability density function $\text{pdf}_X(x)$ exists, another equivalent definition would be $R_X:=\text{closure}(\{x\in\mathbb{R}:\text{pdf}_X(x)>0 \})$
My question is should it be that $R_X \subseteq g^{-1}(R_Y)$?
I was able to show this fact for the case of finite ranged Random variables, but not the general case, based on the definitions above. If I further assume that the probability density function exists (both for $X$ and $Y$), and moreover, $y=g(x)$ is one-one and continuous (hence, monotone) on the support $R_X$ of $X$, then I can quite easily show that $R_X = g^{-1}(R_Y)$. But in any other case, I wasn't able to show my claim. Kindly provide some insights on the range of applicability of the above assertion, and (if it is true at all in the general case) provide a proof (or a counter example?) for the general case.
I would also be satisfied with a proof (or a disproof, or a counter example) in the case where the probability density function exists for both $X$ and $Y$ (referred to as "absolutely continuous" in my book)
Answer: The question can be reframed as follows.

Let $\mu$ be a measure a probability measure on $(\mathbb{R},\mathscr{B}(\mathbb{R}))$ with $F=\operatorname{supp}(\mu)$, and let $g$ be a measurable function on $(\mathbb{R},\mathscr{B}(\mathbb{R}))$. Let $H=\operatorname{supp}(\mu\circ g^{-1})$, where $\nu=\mu\circ g^{-1}$ is the measure defined by $\nu(A)=\mu(g^{-1}(A))$. What is the order inclusion relation between the sets $F$ and $g^{-1}(H)$?

Notice that  $\mu(\mathbb{R}\setminus F)=0$ for open sets are countable union of open balls and each open ball contained in the complement of the support of $\mu$ has measure zero.
Similarly, if   $H=\operatorname{supp}(\nu)$, then $\nu(H)=1$ and
$$1=\nu(H)=\mu(g^{-1}(H))=\mu(g^{-1}(H)\cap F)+\mu(g^{-1}(H)\setminus F)=\mu(g^{-1}(H)\cap F)$$
Thus $g^{-1}(H)= F$ $\mu$-a.s.

Examples

Consider the a measure $\mu$ on $(\mathbb{R},\mathscr{B}(\mathbb{R}))$ with density $\mathbb{1}_{(0,1)}$ w.r.t to Lebesgue's measure. This is the uniform distribution in (0,1). Clearly $F=\operatorname{supp}(\mu)=[0,1]$. Consider the fractional part function $g(x)=x-\lfloor x\rfloor$. It is clear that $H:=\operatorname{supp}(\mu\circ g^{-1})=[0,1]$. Observe that $g^{-1}([0,1])=\mathbb{R}$ and thus $g^{-1}(H)\supset F$; however, $f^{-1}(H)=F$ $\mu$-a.s.

As in example (2), consider now the function $h(x)=1-\mathbb{1}_{\mathbb{Q}}(x)$ which takes values $0$ and $1$. Notice that the measure $\mu\circ h^{-1}$ is the singular measure $\delta_1$, that is $\mu(h^{-1}(A))=\mathbb{1}_A(1)$. Of course, $H=\operatorname{supp}(\delta_1)=\{1\}$ and  $h^{-1}(H)=\mathbb{R}\setminus\mathbb{Q}$. In this case, $h^{-1}(H)\not\supset F$; yet, $h^{-1}(H)=F$ $\mu$-a.s.


How can I Inject Behavior into Entity Framework Object Constructors?

Question: If I have an entity EntityA, which is an Entity Framework object, how would I go about injecting different behavior at time of creation?
These particular entities need to utilize a different strategy for some calculations. I would like to use DI to supply the correct strategy when the object is created. Is there any way to intercept?
Added:
i thinking on the two patterns below (just pseudo to get the point across).
        public partial class Entity
    {
          public Entity(ICalculationStrategy strategy)
          {
              _calcStrategy = strategy;
          }
    }

public partial class Entity
        {
              public Entity(ICalculationFactory factory)
              {
                  _calcStrategy = factory.ProvideCalculator(this);
              }
        }

Comment: Those two patterns are not significantly different. It still doesn't show what factors determine the strategy to be used by this particular instance.
Comment: That's the tricky part. The way it is done now is they use an Entity attribute(name) which matches the class name to dynamically create the correct calculator instance (Activator). I am not sure if I am thinking about this incorrectly at this point.
Answer: Can you pass in the strategy at the time the calculation is performed?
myEntity.Calculate(myStrategy);

How about invert the relationship between the strategy and the entity?
myStrategy.Calculate(myEntity);

Or, DI the strategy using property injection?
Comment: Completely inverting the relationship is something I have considered. I am starting to lean that direction the more I think about it. In my case there is actually more than one step/strategy involved in the overall process. A DDD Service object might be the way to go here. It could manage the generation of each strategy and overall workflow, which is identical for all entities.

The only thing that bothers me is that the entities themselves are tied to a specific strategy. I am not sure if there will be any reuse. Each strategy has a specific dataset/parameters it requires. Any ideas? :)
Comment: By paramaters I mean constants really. All strategies don't use the same constants, but there is overlap there.
Answer: EntityObjects don't have any constructor defined in their generated code, so you can just add one in a partial class:
public partial class MyEntity
{
    public MyEntity()
    {
         // Whatever logic to determine your strategy
    }
}

How you would go about doing your calculations differently, depends on what exactly you're trying to do. If you want to pass extra parameters to the constructor somehow, I don't think you can, so you'll have to work around that.
Also, have you looked at inheritance in Entity Framework? Based on the value of some column / property, you can have it use a different subclass, which can have different implementations of various business logic, through the use of partial classes with abstract and/or virtual methods and properties.
Of course, you could change the behavior after the object is instantiated, but I get the feeling that isn't what you want? Could you access the factory in a static way? Either as a static class, method or property?
MyFactory.Current = new MyFactory(parameters);

public partial class MyEntity
{
    public MyEntity()
    {
        _calcStrategy = MyFactory.Current.ProvideCalculator(this);
    }
}

Comment: I need something more than a default no params constructor. Essentially I want to inject a strategy at construction time or a factory so the Entity can request the proper strategy. Maybe I'll broaden the scope and explain what I am trying to do. The strategy direction doesn't feel correct.
Comment: Just wanted to add that inheritance doesn't work in this case as every entity will have a slightly different strategy logic.


Group of order 42 cyclic

Question: As a follow-up from this question:
Groups of order 42
I realize that this would probably mean that $G$ is cyclic, could someone walk me through the logic behind this?
Answer: The question is:

If $G$ is a group of order $42$ and we have a surjective homomorphism $\varphi: G \to C_{21}$, must $G$ be cyclic?

We have seen that $\ker\varphi\subseteq Z(G)$. This implies that $G/Z(G)$ is isomorphic to a subgroup of $C_{21}$ and so is cyclic.
It is well known that

If $G/Z(G)$ is cyclic, then $G$ is abelian.

Therefore, $G$ is abelian. Since $42=2\cdot3\cdot7$ is a product of distinct primes, $G$ must be cyclic.
(Indeed, there are elements $g_p \in G$ of order $p$ for $p=2,3,7$. Then $g_2g_3$ has order $6$ and $g_2g_3g_7$ has order $42$.)
Comment: And [I thought](http://math.stackexchange.com/questions/999247/if-g-zg-is-cyclic-then-g-is-abelian-what-is-the-point) that well-known fact was rather silly...
Comment: Is it always so that if product of the order of a abelian group is composed of distinct primes then it must ne cyclic?
Comment: @KprimeX, yes, it is. The proof is as in the last sentence.
Comment: Is there any other way to show that it is abelian?
Comment: I also presume that C21 is <21> right?
Comment: @user92821, I know no other way to prove that $G$ is abelian. $C_{21}$ is the cyclic group of order $21$.

Group of order 42 cyclic


Shouldn't the product rule cause infinite chain rules?

Question: This question is about understanding the implications of the chain rule, and I will use the area of a triangle to demonstrate:
$$A=\frac{B\cdot H}{2}$$
Let's say that it is growing (both the base and the height and thus the area too) and we want to find the rate of change of one of its components. So we differentiate everything with respect to time:
$$A'=\frac{1}{2} (BH)'$$
I know that I should use that product rule for $(BH)'$, but I was curious about using the power rule. Consider that $(BH) = (BH)^1$, so by the power rule we have $(BH)' = 1$, and then by the chain rule we multiply by $(BH)'$ again:
$$A'=\frac{1}{2} \cdot 1\cdot(BH)'$$
Obviously that doesn't help. BUT, it made me think: whenever we differentiate something, the chain rule will always trigger, right? It just happens that depending on the differentiation method you use, it may be pointless like just now. So let's use the product rule now:
$$A'=\frac{1}{2} \cdot 1\cdot(B'H + H'B)$$
I used the product rule to differentiate $BH$. But, by the chain rule, should I not be multiplying by the derivative of $(BH)$? In other words:
$$A'=\frac{1}{2} \cdot 1\cdot(B'H + H'B)\cdot (BH)'$$
And if I keep going with the product rules, I would have
$$A'=\frac{1}{2} \cdot 1\cdot(B'H + H'B)\cdot (B'H + H'B) \cdot (B'H + H'B) \cdot (B'H + H'B) \cdot ...$$
Because of the chain rule!
Again, this is based on my understanding that the chain rule happens whenever we differentiate, and the product rule is a form of differentiation. This example is clearly wrong, but I don't know why is that the case.
What is wrong with my interpretation of the chain rule?
Answer: The paradox is explained by noticing that you're using the notation $(BH)'$ to mean two different things.
First, we're assuming (I suppose) that $B$ and $H$ are functions of another variable, such as time $t$; and then the first $(BH)'$ means $\frac d{dt}(BH)$.
After you apply the chain rule, writing $A' = \frac1\cdot1\cdot(B'H+H'B)\cdot(BH)'$, the context in which that calculation makes sense is if $(BH)'$ is interpreted as $\frac d{d(BH)}(BH)$. And that expression simply equals $1$. (You're implicitly writing $BH = f(g(B,H))$ where $g(B,H)=BH$ and $f(BH)=BH$, that is, $f(x)=x$, whose derivative is $f'(x)=1$.)


Store: TypeError: Cannot read properties of undefined (reading 'ids') at selectIds

Question: What is causing the issue in the title. I am basically getting a typeError when I try to retrieve data in a feature store module.
Answer: The issue was that I configurated wrongly the reducers in the StoreModule.forRoot inside the app.module.ts (I had multiple reducers so it should be declared in an object)


Qual método que posso usar para fazer um layout de ticket?

Question: Estou em um projeto de estacionamento do qual é necessário a utilização de ticket gerado através de um aparelho bluetooth.
 minha dúvida é como posso fazer esse layout? quais parametros e métodos que posso utilizar?
Answer: Este Layout te agrada?

É de uma biblioteca chamada TicketView. Ela funciona apartir da API 15 para cima. Você só tem de adicionar no seu gradle:
dependencies {
    implementation 'com.vipulasri:ticketview:1.0.4'
}

E utilizar no seu Layout XML:
<com.vipulasri.ticketview.TicketView
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:layout_marginTop="60dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:id="@+id/ticketView"
        app:orientation="vertical"
        app:scallopRadius="10dp"
        app:showBorder="false"
        app:scallopPositionPercent="50"
        app:showDivider="true"
        app:dividerType="dash"
        app:ticketElevation="14dp"/>

A app na imagem acima tem código aberto e pode ser encontrado aqui.
Comment: valeu mesmo cara,agradecido!!


Would tipped pass be a 2 or 3 pointer?

Question: I was playing in a basketball league that follows NCAA rules. A scenario happened where we players and referees did not know the exact answer and cannot find a specific rule explanation online.
My teammate threw an oop pass from beyond the 3 point line to me. I went to jump to catch it but was below the hoop. The defender jumped with me and tipped it in; I had no contact with the ball.
Would it be considered a 3 pointer since I did not touch it and the pass came beyond the 3 point line, or would it be ruled a 2 since it was a pass and the defender accidentally tipped it in?
Answer: I don't think the fact that the pass originated from beyond the 3-point line matters much here.  The pass couldn't have been on target as a 3-point try or the opponent would have been called for goaltending.
So it's just someone making an own goal, which is always worth 2 points.  That falls under the NCAA rules Rule 5, Section 1, Article 4a

a. When a player scores a field goal in the opponent's basket, it shall count two points for the opponent regardless of the location on the playing court from where it was released. Such a field goal shall not be credited to a player in the scorebook but shall be indicated with a footnote.

Would tipped pass be a 2 or 3 pointer?


Is a differentiable function $g(x)$ a strictly increasing function iff $g'(x)>0$?

Question: Yes, I think a differentiable function $g(x)$ is a strictly increasing function if and only if $g'(x)>0$, but I am not sure why.
Is there a theorem for it?
I informally know that if $g(x)$ is differentiable and $g'(x)>0$, then the $g(x)$ is strictly increasing. And if $g(x)$ is differentiable and $g'(x)<0$, then the $g(x)$ is strictly decreasing.
Answer: No. The function $g: \mathbb{R} \to \mathbb{R}$, $g(x) = x^3$ is strictly increasing and satisfies $g'(0) = 0$.
If a function $g$ is (not necessarily strictly) increasing and differentiable, then $g'(x) \ge 0$ for all $x$. This is a direct consequence of the definition of the derivative.
Comment: Can we adjust the claim, perhaps in the following way: If $g$ is strictly increasing and differentiable everwhere, does it then follow that $g'(x)>0$ in all points except for countably many $x$ where $g'(x) = 0$?

By the way +1.
Comment: I don't think you require MVT to prove that "$g$ is (strictly) increasing and differentiable $\Rightarrow g'(x) \geq 0$". Just the definition of derivative suffices. MVT is required (but not necessarily so) to prove the implication in the other direction.
Comment: @Eff We can adjust the claim in the following way: If $g$ is differentiable, then the set $\{x \mid g'(x) = 0\}$ has empty interior. I'm not sure whether your version holds aswell. I don't see an obvious solution, so it might be an interesting question to ask.
Comment: @ParamanandSingh You're right, I've adjusted my answer. Thanks.
Answer: Here's a strictly increasing $C^1$ function on $\mathbb {R}$ whose derivative $=0$ on an uncountable set: Let $K$ denote the Cantor set. For $x\in \mathbb R,$ set $g(x) = d(x,K).$ Then $g$ is continuous on $\mathbb {R}, g = 0$ on $K,$ and $g>0$ on $\mathbb {R}\setminus K.$
Set $G(x) = \int_0^xg.$ Then $G'=g$ everywhere by the FTC, which implies $G' = 0$ on $K,$ an uncountable set. To see that $G$ is strictly increasing, recall that $\mathbb {R}\setminus K$ is dense in $\mathbb {R}.$  Thus if $x<y,$ $g$ will be positive somewhere in between, hence positive on an interval of positive length contained in $(x,y),$ hence $G(y)-G(x) = \int_x^yg >0.$
Comment: @Dominik Not much difference. You can replace the distance with a smooth bump function in the definition.
Comment: A nice example! What if we demand $g$ to be twice differentiable or even smooth?
Comment: Heh, thanks for answering my subquestion, +1.


Multiple MX Records handling

Question: I have an app hosted in AWS, my mail service is not on AWS, I'm using a hosting in hostgator due to pricing since I need 500+ simple mail accounts.
My DNS points to my email service and it works correctly.
The part I'm lost in is that I'm trying to receive emails in a specific address so that my app can process it. Is there a way so that some addresses are sent to a secondary MX record, or if the address is not found in the first will it go look at the second? Or the second priority MX record is only if the first in offline?
Answer: MX records are used according to priority value in the records.
The record with the lowest priority is used first, then the higher ones until one responds. If there are multiple records with the same priority, one is randomly selected (this is how you generally do load balancing if you have multiple mail servers accepting incoming connections).
The MX records only dictates which mail servers are responsible for a specific domain, it doesn't deal with individual recipients. So a sending server will only use secondary records if the primary server doesn't respond to its connection attempts, not if the primary server rejects the message.
What you're trying to achieve is only doable at the DNS level if you use a subdomain for messages destined for your application. That way you can have the MX records for example.com point to your mail servers and the MX records for app.example.com to point towards your application.
If you need to use the same domain for both, you'll need to configure your mail server to forward e-mail messages to your application. This can usually be done a couple of different ways depending on the mail server/hosting provider.
Comment: An alternative to forwarding messages from your mailserver :  rather than receiving your messages directly you let the app poll a mailbox that resides on your actual mailserver (or get a helper application to that for you; fetchmail is common linux tool for that)  That has some side benefits as well  since you automatically will get the anti spam and anti virus security you already have on your existing mail server
Comment: so, i did manage to make the config, if i use a dns checker to check on the MX subdomian i get the correct amazon smtp server, but if i send a mail from gmal to that subdomain i get DNS Error: 69557 DNS type 'mx' lookup of app.binestarpatrimonial.com responded with code NXDOMAIN Domain name not found: app.binestarpatrimonial.com
Comment: It's probably due to DNS propagation, it can take a couple of days for DNS changes to propagate. I can't find binestarpatrimonial.com at least, is this the real domain or a fictions one?
Comment: that was a typo, its bienestarpatrimonial.com, and the subdomain is app.bienestarpatrimonial.com, still get the same error with no typo, mxtool checker gives me the actual dns, so apparently its propagated
Comment: It seems to be propagated alright: https://dnschecker.org/#MX/app.bienestarpatrimonial.com
Comment: thats what's weird, sending a mail to it gives as if it isnt
Comment: Might be that Google has cached an NXDOMAIN somewhere or something, I'd give it a couple hours and try again.
Comment: Thx, it worked now
Answer: MX records cannot solve this, multiple records (with possibly different priorities) can be used for redundancy, but the service is expected to be the same (accept the same addresses).
What you can do is either have the address that your application processes at a different domain (eg firstname.lastname@example.com if the regular addresses are @example.com) or set up some forwarding solution with the other mail service (eg forward email@example.com to wherever you can deliver mail for the application).

Multiple MX Records handling


Create a JSP element with JavaScript

Question: I need to create a jsp form with javascript. The problem is to assign the data path.
Imagine $form.work = "Hello Work";
If I create the form with html:

    Work:<input value=${form.work}></input>

The input will show the work value (Hello Work). But I need to create this div form with js, something like:
var oDiv = document.createElement('div');
oDiv.setAttributte('id', 'workForm');
var oInput= document.createElement('input');
oDiv.appendChild(oInput)
...

I tryed to add an attribute to the input like:
oInput.addAttributte('value', '${form.work}')

But it shows: ${form.work} not Hello Work
Can someone help me?
Thanks!
Comment: Check this
[Reading a JSP variable from JavaScript](https://stackoverflow.com/questions/4803906/reading-a-jsp-variable-from-javascript)
Answer: Try this,
var work = "<%=form.work%>";

or
var work = "${form.work}"
alert(work);

If the window/ System alert had provided what you need, then you can setAttribute("value", work) to the hidden field or the JSP element you needed.
Answer: You're close, you must use template literals (backticks) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
oInput.setAttribute('value', `${form.work}`)

Comment: I tryed but i got a undefined message

Create a JSP element with JavaScript


Is there any way to complete an array with values of clicked rows, after a jQuery DataTable is loaded by submitting a form?

Question: Hi guys I have a problem when I'm using jQuery datatable. After Datatable is loaded by submitting  an ID to the server, and then server response with the data that I render then into DataTable. In that DataTable I want to make multiple row selection and the values that I want to push into array are for example all the values of first column. My code below is everything that I have created now.
The HTML Code:
<form name="search_form_order" id="search_form_order" novalidate="">
<input type="text" name='login_id' id="login_id" class='form-control'>
<button type="submit" name="search" id="search">Search</button>
</form>

Login ID
Order ID
Comment
Actions

Login ID
Order ID
Comment
Actions

jQuery Code:
  //This is the part where user submit the id parameter
$('#search_form_order').on('submit', function(event) {
event.preventDefault();
var id = $('#login_id').val();
$('#orders_table').DataTable().destroy();
loadOrdersTable(id);
});

//This is the function
function loadOrdersTable (id) {

table=$('#orders_table').DataTable({
responsive: true,
processing: true,
serverSide: false,
lengthMenu: [[100, -1], [100, "All"]],
"ajax": {
url: "/list_orders.php",
type:"POST",
dataSrc: "",
data: {login_id:id}
},
columns: [
{data: 'login_id', name: 'login_id'},
{data: 'order_id', name: 'order_id'},
{data: 'comment', name: 'comment'},
{data: 'actions', name: 'actions'}
]
});
}

Until here everything works perfectly, but when I want to select the the order_id-s of each row, the below jQuery code do not work:
 var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
});
console.log(dataArr);

This I'm using because I want to populate this array, to make bulk edit or bulk delete of all selected rows. On console it is displayed only this '[]', as output since onlcick event do not get the value from table rows.
Thank you!
Answer: your mistake is that you have your console.log outside of the event handler. That means that it's executed when the page is loaded and thus the array is empty.
If you move that inside your event handler (1 before) you'll se that everytime you click, the ID is pushed to the array and then shown at console.
Here is a working snippet:
PD: Note that everytime you click on one row the ID will be added to the array causing possible duplications, meanwhile the toggle will.. toggle, probably causing unexpected behaviours. You should need to add extra logic to avoid that

 var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
console.log(dataArr);
});

Login ID
Order ID
Comment
Actions

  login_id
  order_id
  comment
  actions

Login ID
Order ID
Comment
Actions

Comment: As you can see even the declaration of the dataArr  is outsite of the event handler, so it means that my interest is after I populate this array, I want to use it on another event, such as Edit All Selected or Delete All selected.
Comment: Thats will work. But keep in mind that when you use "console.log" the data logged is the value of the variable when it was logged. If you modify that variable, the log won't be updated. That is why you should print everytime the value is updated.
Comment: var dataArr = [];
$('#orders_table tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
var id= $(this).find('td').eq(1).text();
dataArr.push(id);
console.log(dataArr);
});


Significance of correlation with only 11 datapoints

Question: I am currently working on my thesis and calculating some simple correlation coefficients. I only have 11 datapoints available, but I would like to assess the statistial significance of my results. The asymptotic p-values are not significant at the 10% level.
Because of the small sample, I additionally computed bootstrapped confidence intervals, which are, to my surprise, different from zero at the 10% level. My question: Can I claim statistical significance of my results according to my bootstrapped confidence intervals? Or is this not valid because of the small sample?
Cheers and many thanks in advance!
Chris
Answer: As long as you did the bootstrapping correctly, yes, I think you can.
Of course, there might be other reasons why correlation is not a good measure, but the bootstrapping should get around the small sample size. (see e.g. the Anscombe quartet)
With only 11 points, you might be able to do a permutation test instead of bootstrapping.
Comment: With "correct" I suppose you mean pairwise bootstrap, which jointly draws from the two variables.
Comment: I just wanted to be careful not to give more approval than I can; bootstrapping is complex. There's no code or details in the post, so ... I prefaced my remarks with that qualifier.


Apk incresed in size after adding FFmpegMediaMetadataRetriever

Question: I added the dependency (com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.3)  to my application ( build.gradle ) in my Android Studio, The apk jumped from 2 MB to 16 MB .I just used the sample code nothing more ,is there a way to have a less size than this?
<code>        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
        mmr.setDataSource("http://testsite.com/test/upload/Twale_FLO.mp3");
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
        long duration =Long.parseLong(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
        duration=duration/1000;
        long minute=duration/(60);
        long second=duration-(minute*60);
        mmr.release();
        your_text_view.setText(minute+":"+second);
</code>
Answer: FFmpegMediaMetadataRetriever uses native code. This means the library includes prebuilt binaries for each support Android architecture. If you'd like to reduce your APK size you'll need to use the prebuilt libraries found on the FFmpegMediaMetadataRetriever project page and build an APK each supported architecture manually.
Answer: The only way to decrease Apk size after including FFmpegMediaMetadataRetriever is the support ABI spits.
FFmpegMediaMetadataRetriever uses native code that is different for every CPU used. If you don't slit, all native codes will be merged inside your APK: a total of 25Mb or more!
So by adding these lines to your build.gradle, you will enable APK splitting:
<code>lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "armeabi-v7a", "mips", "arm64-v8a", "x86_64", "armeabi"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk true
        }
    }
</code>
So, after apk build (or generate signed APK), your build would have 6 apks, one for each cpu. Upload them all to google play so your user would only download the necessary files. A armeabi-v7a APK will only be around 6Mb!
Comment: What do you mean by upload them all on play store ? so each apk will have different download page ? and information ? or we can upload on same project page multiple apk's ?


no arguments that correspond to the mandatory formal parameter item1 have been specified

Question: I've this object:
public class RankingAll
{
   public Tuple<List<Ranking>, List<RankingLegend>> Ranking { get; set; }
}

I've declared this:
RankingAll rankingAll = new RankingAll();
rankingAll.Ranking = new Tuple<List<Ranking>, List<RankingLegend>>();

but I get a compiler error on the last line

no arguments that correspond to the mandatory formal parameter item1 have been specified

what's wrong?
Answer: Tuples are immutable, so cannot be changed after construction. You can't set Item1 or Item2 after this point, so the only way to get values into it are at construction. This is enforced by a constructor signature that requires the values.
You need to supply values to the constructor, or use the handy helper method:
Tuple.Create(new List<Ranking>(), new List<RankingLegend>())

Given that a Tuple is immutable, placing mutable structures within it is, IMO, somewhat questionable.
Answer: Your tuple requires two items (A List and a List) to be passed into the constructor. You can't construct a tuple without the members of the tuple being provided.
Comment: I just need to create the tuple
Comment: You can't just create a tuple without items in the tuple (passed into the constructor)


scheduleAtFixedRate slow / late

Question: I'm using a ScheduledExecutorService to provide an update to a database every hour with the scheduleAtFixedRate method.  The problem is that it gradually gets later - in long service I've been logging it and it's about a second a day.
I made a small class just to examine this aspect - seems to work fine when nothing is happening on the PC ( running WinXP ) but if things are going on it rapidly gets later.  18:00:00.5 last night was its first log and this morning was 09:00:00.5 then 10:00:05.9, 11:00:26.8, 12:00:45.3, 13:01:07.8...
I can attach the code although my example isn't the smallest.
Anyone else experienced this?  Any ideas why this isn't working properly?
I can think of lots of ways around it but I'd really like to know why it doesn't work as advertised!
Thanks, Mike
Answer: This is normal AFAIK. With scheduleAtFixedRate, If any execution of this task takes longer than its period, then subsequent executions may start late. That being said, I'd recommend scheduleWithFixedDelay. This will ensure that tasks are carried out at the specified delay interval.
Comment: No, the duration of each execution should not matter, according to the JavaDoc: `In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).`
Comment: @Thomas, Can you provide a link?
Comment: @Moonbean I just figured I got the wrong class - `Timer` instead of `ScheduledExecutorService`. However, the JavaDoc you linked states your answer the other way round: `scheduleAtFixedRate` should start exactly at `initial_delay + n * rate` whereas `scheduleWithFixedDelay` would take the duration of the task into account: `...with the given delay between the termination of one execution and the commencement of the next` (scheduleWithFixedDelay)
Comment: @Thomas, Did you read my answer? If any execution of this task takes longer than its period, then subsequent executions may start late. So, a fixed interval is not always possible with `scheduleAtFixedRate`. With `scheduleWithFixedDelay`, subsequent tasks will always still start at the specified interval, regardless of task execution time.
Comment: You're right, that's what `scheduleAtFixedRate` would do, sorry for misreading. However, I'd still rather use that instead of `scheduleWithFixedDelay`, since the OP wants execution to be as close to the full hour as possible. Additionally, I'd doubt the update would take exactly one hour and a few seconds but that should be verified - @Michael please tell us :)
Comment: "If any execution of this task takes longer than its period, then subsequent executions may start late" - my task does not take longer than an hour - in my test class it takes about 50 ms to write a 5 MB file ;-)  As pointed out above, the JavaDoc says "executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on" i.e. with a period of 3600000 ms you'd expect it to kick off every hour, even if occasionally it is kicked off track because Windows is busy doing something else.
Comment: Well this is interesting... since 2 o'clock that afternoon ( just after I first posted! ) the process was kicked off early!  It went from 13:01:07.8 to 13:59:59 and is now about 1.5 s early e.g. the last log was 08:59:58.6.  I haven't looked at the source for this class - does anyone know it and if so is this expected behaviour to try to average out the start point?  Another factor is that there was a lot of activity on the test PC yesterday and yet the start time was steadfastly constant.

scheduleAtFixedRate slow / late


Logistic Regression: the logic of testing for all threshold probabilities in an ROC Plot?

Question: In Logistic Regression, what's the logic of testing for all threshold probabilities in an ROC Plot?
I thought that in logistic regression, we're concerned with the 0.5 probability threshold, and if something is greater, we mark the outcome as 1, and if less, we mark the outcome as 0.
So why test all the possible threshold probabilities? Why not just test the case for the one we're concerned with?
Comment: You might find [this](http://stats.stackexchange.com/questions/25389/obtaining-predicted-values-y-1-or-0-from-a-logistic-regression-model-fit/25398#25398) helpful.
Comment: You have to vary the cutoff to generate the ROC-AUC.  And when you vary the cutoff, it's not simply 0.5.
Comment: I am no expert, but the key point IMO is that logistic regression is really solving a certain [MLE](http://stats.stackexchange.com/tags/maximum-likelihood/info) problem for the [conditional probabilities of the classes](http://stats.stackexchange.com/a/29326/127790). As a byproduct it gives a "soft classification". But for the "hard classification" (i.e. 0 or 1) problem, [different loss functions are possible](http://stats.stackexchange.com/a/173234/127790). In this "machine learning" context, the threshold to go from "soft to hard" is treated as an additional free parameter.
Comment: @GeoMatt22 Thank you, that was indeed pertinent. Usually when doing Logistic Regression, I don't actually specify the threshold (e.g. in R). So how does the threshold get chosen? And what is it usually? (I thought it was 0.5 always.)
Answer: The cutoff is ultimately something you have to choose using domain knowledge as well as the costs of getting it wrong. You also might have a case where your decision space isn't the same as the event you're trying to predict. For instance, if you predict the probability of a person having a given disease is < 1%, don't do anything, if it's < 50% observe regularly and carefully watching for more signs, and if it's > 50% perform another, possibly more invasive test.
Of course, that's just an example, but the idea is that what you do with the probabilities is up to you. There is no cutoff chosen by the logistic regression and it doesn't even have to correspond to "declare this instance a 0 or a 1". And even if it does, if the cost of calling a 1 a 0 is ten times that of calling a 0 a 1, you would be better off calling 1's even if you thought there were only a 20% (or lower chance) of it being 1. This idea comes up in what is called "cost sensitive learning".
Also, since logistic regression is just giving you the log-odds ratio (or equivalently the probability) if you're just looking for a measure of how well it does on a problem, you might not even care what label an individual class gets. You could look at loss functions based only on the predicted conditional class probabilities, like log loss or a Brier score. The AUC curve is a tool to look at the tradeoff of sensitivity and specificity if you were to set the cutoff at different points. As that other answer says, if you want to optimize for getting the most true positives subject to an upper bound on false negatives you'd do one thing, whereas if you wanted as few false negatives as possible with a lower limit on the number of true positives you'd do another.
At the end of the day, there's no rule, and it comes down to your understanding of the problem and reasons for using the method.
Edit:
As @GeoMatt22 wisely suggested, the "other answer" I'm referring to that he originally mentioned is: Obtaining predicted values (Y=1 or 0) from a logistic regression model fit
Comment: You are absolutely correct, sir. And I have added it
Answer: If you haven't got an explicit loss function, you can also think about it this way.
Where the ROC plot is flat, decreasing the cutoff reduces the false positives without increasing the false negatives much. Where the ROC plot is steep, increasing the cutoff reduces the false negatives without increasing the false positives much.
So there is a sweet spot wherever there is a "shoulder", i.e. a local extremum in the second differential.
You have to smooth it first, or think about the span over which you estimate the slope, because when you zoom in on a ROC curve it is all steps.


Add button disappears for subgrid when using addOnLoad

Question: When I'm using the addOnLoad function in Dynamics CRM for my subgrid(incidents) the add button disappears. My addOnLoad event works perfectly and when I click on the delete button for a row in the subgrid the add button appears again.

Obviously there is a event that can be triggered? Since the add button appears when I'm clicking on the delete button. I don't have this problem on other subgrids with relationships to other entities than incidents.
var grid = Xrm.Page.getControl("issues");

if (grid == null) {
    setTimeout(function () { AddEventToGridRefresh(); }, 5000);
    return;
}

grid.addOnLoad(refreshNumberOfIncidents);

--
window.refreshNumberOfIncidents = function () {

Api.getIncidents(globals.getAccountId(), function (result) {

    if (result.success) {

        arrayLength = result.data.value.length;

        Xrm.Page.getControl("WebResource_Interaction").getObject().contentWindow.document.getElementById("incidents").innerHTML = arrayLength;
    }

});

Comment: Please include the code samples into the question.
Comment: @ArunVinoth Found a solution, I had to delay the refresh like this  setTimeout(function () { Xrm.Page.data.refresh(); }, 1000);
Comment: Updated with code sample
Comment: See if you have any ribbon customizations? More context:https://stackoverflow.com/q/45603397/7920473
Comment: @ArunVinoth Don't have any ribbon customizations, grid.refresh() or Xrm.Page.data.save() won't do it for me either.
Comment: show us the code of refreshNumberOfIncidents
Comment: @ArunVinoth Here you go
Comment: this should work. probably you have to debug it or try catch.. not sure if this assignment to iframe control break the crm form load flow.. :( any errors you see in browser console?
Comment: @ArunVinoth Getting lots of these messages "Refused to set unsafe global.ashx?ver=359582084:4020 Refused to set unsafe header "Content-Length". But I get them without the "addOnLoad" as well.
Answer: Solved it by delaying a refresh after the addOnLoad call
setTimeout(function () { Xrm.Page.data.refresh(); }, 1000);


Probability integration notation: integrating with respect to X over a set involving $Y$

Question: Let $A$ be the set $Y^{-1}(B)$, where $Y$ and $X$ are independent random variables, defined on a common background space with probability function $P$. We wish to calculate $$\int_{A} X \ dP$$
Now the notes I am reading do something I don't quite understand: $$\int_A X \ dP = \int_{(Y \in A)} \ X \ dP = \int 1(Y \in A) \ X \ dP = \int 1_{A}(y) \cdot x \ d(X,Y)(P)(x,y)$$
Why did $A$ become $(Y \in A)$? What is $1(Y \in A)$? What happened in the final equality?
Comment: Should have been $(Y\in B)$ instead of $(Y\in A)$.
Answer: HINT
$$
1(Y \in A) = \begin{cases} 1, & Y \in A \\ 0, & Y \not \in A \end{cases}
$$
and
$$
1_A(y) = \begin{cases} 1, & y \in A \\ 0, & y \not \in A \end{cases}
$$
Both are indicator functions.
Answer: Formally, $1_{Y\in A}=1_A\circ Y$. This responses your first ask.
Then, you have
$\int_\Omega 1_{Y\in A}(\omega)X(\omega)dP(\omega)=\int_\Omega (1_A\circ Y)(\omega)X(\omega)dP(\omega)$
But the last is precisely $E[(1_A\circ Y)X]$, which can be calculated as $\int x 1_A(y)f_{X,Y}(x,y)d\lambda(x)\otimes\lambda(y)$, which is the final term of your equality.
Comment: OP didn't mention the existence of a joint density.
Comment: This does not address the typo in the text, which is probably the main cause of the OP's doubts.


Is melodic analysis a thing?

Question: I know that harmonic analysis can be done like this:
i iv V i
Is there a similar standard for melodic analysis? Is melodic analysis a thing?
Thanks, Nathan.
Answer: Yes. There is a whole discipline for it: http://jan.ucc.nau.edu/krr2/mel_anal.html
One looks a range, key, ornaments, type of tone connections, essential and non-essential tones, rhythm, harmonic implications, etc.
Comment: Thanks! They mostly teach harmonic analysis in music theory classes, but I'd never heard of melodic analysis.

Is melodic analysis a thing?