Disable /Enable a multivalued paragraph field on Ajax calls

Question: I have 2 fields in a form. One select list and another entity reference field referring to a Paragraph type (multivalued).
The on-change event should trigger an ajax callback which will disable some of the fields in the paragraph type.
I managed to achieve this on ajax callback. Now, the problem is when I add more values to the paragraph the previous disabled field goes back to the default state.
Any suggestions /examples will be helpful. Below is my code.
Thanks.
    function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      //Ajax callback on change event
      if (isset($form['field_link_type'])) {
        $form['field_select_sample']['widget']['#ajax'] = array(
        'callback' => '_my_ajaxcallback',
        'event' => 'change',
       );
      }
     }

    function _my_ajaxcallback(array $form, FormStateInterface $form_state) {

      $response = new \Drupal\Core\Ajax\AjaxResponse();

      //disable field_htext of paragraph field
      $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

      return $response;
    }

Updated code -
In my callback -
    echo 'disabled - ' . $form_state->get('field_header_disabled');`
    $form_state->set('field_header_disabled', TRUE);`
    echo $form_state->get('field_header_disabled');
    return $response;

The output is something like - disabled - 1 on both first and second callbacks. On second callback I'm expecting the output to be something like disabled - 11
Comment: You'll have to make your changes more permanent. E.g. within your Ajax callback save a flag to `$form_state`, that the fields are disabled/enabled and in your `hook_form_alter()` read that flag from `$form_state` and set the field attributes accordingly.
Comment: Why do you expect a `disabled - 11`? - You echo the value only once...
Comment: The code is added in the callback function. So at first line it will output `disabled - ` .I am ok with that coz this is the first callback and the `field_header_disabled` is not yet set. On the next line I'm setting the `field_header_disabled` and again echoed as `1` . Till here I concur with you. Now, when I trigger the callback function for the second time it should give me `disabled - 1` in the first line and once again output `1` in the third line. So altogether it should output something as `disabled - 11`. Right?
Answer: Your issue arises, as the paragraphs widget(s) itself do a lot of Ajax calls and you disable the field(s) in your browser only. So your paragraph form will be reloaded and re-rendered without knowing that the field has been disabled before.
To have the field(s) disabled on consecutive reloads, you need to make your changes more permanent.
You could e.g., save a flag to the $form_state using the FormStateInterface::set() method:

FormStateInterface
  [...] it may be used to store information related to the processed data in the form, which will persist across page requests when the 'cache' or 'rebuild' flag is set.

This means, after you stored a custom flag in the $form_state and an ajax request to reload this form is made, it will be available within the $form_state of your hook_form_alter() implementation as well.
So all we have to do now, is checking for this flag in hook_form_alter() using the FormStateInterface::get() method and ensure the field will be disabled, if it has been set before.
A less abstract example:
/**
 * Callback for disabling field_htext.
 */
function _my_ajaxcallback(array $form, FormStateInterface $form_state) {
  $response = new \Drupal\Core\Ajax\AjaxResponse();

  // Disable field_htext of paragraph field.
  $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

  // Set a 'disabled' flag in form state.
  $form_state->set('field_htext_disabled', TRUE);

  return $response;
}

And in your form alter:
/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Better use the form ID here and check, if you are at
  // your form in question, or even use a more specific hook as
  // hook_form_BASE_ID_alter() or hook_form_FORM_ID_alter().

  // Check our custom disabled flag.
  if (
    !empty($form_state->get('field_htext_disabled'))
    && isset($form['field_htext'])
  ) {
    // Set the 'disabled' attribute.
    $form['field_htext']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
  }

  // Add ajax callback on change event.
  if (isset($form['field_link_type'])) {
    $form['field_select_sample']['widget']['#ajax'] = array(
    'callback' => '_my_ajaxcallback',
    'event' => 'change',
   );
  }
 }

Comment: ++ for the example code.
Comment: I tried setting the flag in callback. Unfortunately, the value showing as null on hook_form_alter().For debugging I tried to get the value inside the callback itself and tested by changing the select box multiple times. Still the value dont show. Posted the updated code on the question.
Comment: @wilNev: The value will be NULL on your first form alter. Even on your first callback it will be NULL, as the flag is set after form alter has been invoked and the disabled property will be set within the frontend only. In the third round however (e.g. a callback of the paragraphs widget), it should be TRUE. Also note, that the form alter hook may be invoked multiple times during a post back. And that printing values before you send a response to the browser may have unintended side effects. Consider using a proper debugger instead or as lightweight alternative, temporarily print to error log.
Comment: Not sure if I missed out on anything. For now, I went with the approach suggested [here](https://drupal.stackexchange.com/a/239358/45786)  .I will definitely have to check why the `$form_state` value is not accessible even after multiple callbacks.
Comment: You could additionally try to explicitly set rebuild in your callback. This will ensure `$form` and `$form_state` being cached. Caching should happen automatically, since there is an `#ajax` property, but maybe it's not... - Try adding `$form_state->setRebuild(TRUE);` to your callback.


Are these versions of the Taylor Theorem equivalent?

Question: In the wikipedia we have this version the Taylor's theorem:

Taylor's theorem (Wikipedia): Let $k\ge 1$ be an integer and let the function $f:\mathbb R \to \mathbb R$ be $k$ times
  differentiable at the point $a \in R$. Then there exists a function
  $h_k:\mathbb R \to \mathbb R$ such that
$f(x)=f(a)+f'(a)\cdot (x-a)+\frac{f''(a)}{2!}\cdot(x-a)^2\ldots+\frac{f^{(k)}(a)}{k!}\cdot (x-a)^k+h_k(x)(x-a)^k,$
where $\lim_{x\to a}h_k(x)=0$.

I'm reading a book which has this another formulation of basically the same theorem:

Infinitesimal Taylor Formula: Let $f:I\to \mathbb R$ be a n times derivable function at the point $a\in I$. Thus, if for every $h$ such
  that $a+h\in I$, then
$$f(a+h)=f(a)+f'(a)\cdot h+\frac{f''(a)}{2!}\cdot
 h^2\ldots+\frac{f^{(n)}(a)}{n!}\cdot h^n+r(h),$$
where $\lim_{h\to 0} \frac{r(h)}{h^n}=0$.

I think this book is wrong, because when we replace $x$ by $a+h$ in the Wikipedia article we should have $\lim_{h\to 0} \frac{r(a+h)}{h^n}=0$ instead of $\lim_{h\to 0} \frac{r(h)}{h^n}=0$.
Comment: Both are same and it's just a matter of notation.
Comment: No, both are the same. You have $r(h) = h_k(a+h)h^k$.
Answer: With the equality $h=x-a$,
$$r(h) = h_k(x) (x-a)^k$$
$$\frac{r(h)}{h^n} = h_k(x)$$
so the limit conditions are the same.
Answer: Of course you are right that replacing $x$ with $a+h$ in the first formula gives a final term of $h_k(a+h)h^k$, and we know the ratio of this quantity to $h^k$ must vanish as $a+h\to a$, i.e. as $h\to0$.
The second formula just views the quantity $h_k(a+h)h^k$ as a function of $h$, since $a$ is typically fixed. But it doesn't matter what you call the final term. You could simply call it $R$. Or you could call it "the difference between $f(x)$ and the $k$-th order approximation centered at $f(a)$." The substance of the claim is that, whatever you call it, its ratio to $(x-a)^k=h^k$ vanishes in the limit.


What's the use of transparent plastic double bass strings?

Question: I went to a rockabilly live the other day and I saw that  the double bassist used transparent plastic strings on his bass.
What's the purpose of that? Is there anything different from the normal steel ones?
Comment: You might want to look thru the range of strings offered by stores such as Shar and JohnsonString; many online stores will have a supporting page describing the reasons one might prefer metal, plastic, true gut, etc. strings.
Answer: It is likely an attempt to get closer to the sound of gut strings that were used on the double bass in times of yore (and now, although it's not so common). The slap style, and the back to basics approach of rockabilly would suggest this.
Answer: In addition to the gut string feel cited by Meaningful Username in her/his answer, another advantage of strings without a metal core is that they are less susceptible to changes in pitch resulting from climactic change, especially temperature. At least that is what this manufacturer claims. The Tremors are one of the bands who use their strings, and they look pretty rockabilly to me:


Run all commands as Administrator on Windows Server 2008 R2

Question: I'm having issues with permissions on Windows Server 2008 R2.
I'm used to (from Windows Server 2003) being able to open up a CMD prompt and type something like: `copy \some\file /y' and overwrite a file in the current directory.
The permissions on the directory/file allow modifying by 'Administrators', but I get Access is denied. unless I specifically run the cmd.exe 'as Administrator' which is unacceptable for how I need to manage my server. I need to be able to on-the-fly perform tasks without having to go and open a new cmd prompt, switch to the directory, retype the command, etc.
So how can I make it so my user who is a member of Administrators can by-default, run commands as an Administrator?
Answer: I would never recommend this, but here goes
On a stand-alone Windows Server 2008 R2, do the following:

Go to Control Panel
Choose User Accounts -> User Accounts
Click "Change User Account Control Settings"
Take the Slider down to the bottom where it says "Never Notify"
Press OK.
Press OK in your last UAC Prompt
Comment: +1 I would never recommend this.
Answer: It sounds like you're asking "how do I bypass UAC?" Well you can't bypass UAC. You can turn off UAC however.
From this relevant blog post by Margosis:

Having said all that, there is a Local Security Policy option to
  change the behavior of the elevation prompt for Administrators to
  "elevate without prompting". With this option selected, anything that
  requests elevation gets elevated without prompting the user. (The
  default setting is "prompt for consent"; the third option is "prompt
  for credentials". Note that "elevate without prompting" is available
  only for members of the Administrators group. The options for standard
  users are "prompt for credentials" and "automatically deny elevation
  requests".) While "elevate without prompting" may be useful in
  well-constrained, secure environments for automated testing and
  possibly for initial system setup, having this option selected
  otherwise is very risky and strongly discouraged. (Note also that
  Vista's Home SKUs do not include the policy editor.)
Answer: I always have this issue on a new Win 2008R2 server.  The problem is in the Start Menu properties. (I always forget this.)
Right Click  and choose Properties.  On the Start Menu tab select . In the context menu find "Enable context menus and dragging and dropping" and check the box.  Then
Now when you right click a program in the start menu you will get the pop-up with the options like "Run as administrator", "Pin to Taskbar", etc.
Now you just have to remember to start your PowerShell or cmd window with Run as Administrator.


juju on local server + wrapping my own application server custom built wtih charm

Question: I'm interested in juju before starting with it i would like to ask a few questions.

Can juju be only be used with ubuntu? is it possible to use it with CentOS?
I have my own application server which i wrote, can i wrap it in a charm and deploy it on my local juju cloud? (I do not publish ofcourse my charm to the openstack because its a propriety server code, if yes can someone direct me maybe to a link of how i can achieve such a thing?) my server is built with java.
Is ubuntu server + full capabilities of juju always be free of charge?
Which technologies would you recommend me to write my app server installer (i'm going to go for continuous deployment on my own cloud rolled, perhaps with juju).
Answer: Find inline answers along with.

Juju is primarily supported for Ubuntu but code is open so one can easily get it working on another distribution.
https://askubuntu.com/questions/65359/how-do-i-configure-juju-for-local-usage  This might help.
Yes
You can write charms in any programming language you are comfortable with. http://juju.ubuntu.com has all the details you need.


RabbitMQ access refused when publishing message - how to give user permission for specific queue?

Question: I've setup a very basic queue, 'test_queue', on a fresh installation of RabbitMQ, and created a basic non-admin user, 'user' (which I have given the same virtual host access as admin account).
When I send in a test message on the command line via:
rabbitmqadmin publish exchange=amq.default routing_key=test_queue payload="hello, world" -u admin -p {admin password}

It works just fine. But when I try and use the basic user:
rabbitmqadmin publish exchange=amq.default routing_key=test_queue payload="hello, world" -u user -p {user password}

I get the following error:

*** Access refused: /api/exchanges/%2F/amq.default/publish

I've searched for how to add permission for a specific user to publish to a message queue but can't find the solution through the noise.
Answer: I had a similar problem and resolved it by adding the permission through RabbitMQ Admin UI (Admin->Users->Some User->Set Permission):

You can enable the Admin UI as a plugin through CLI:
rabbitmq-plugins enable rabbitmq_management

To access it you will also need to create some login credentials.
More details: https://www.rabbitmq.com/management.html#getting-started
Answer: I searched Google with site:rabbitmq.com permission and this document is the first hit: https://www.rabbitmq.com/access-control.html
At the end of the "How Permissions Work" section, you are directed to the rabbitmqctl man page
Within that page, you will find the documentation for the set_permissions command. That is what you need to use.
If you would like to open a pull request to improve the documentation to make finding this solution easier, we would welcome it here! Thanks.


How to bind a Map object containing Pojos to a yaml file?

Question: In a spring-boot/ spring-cloud application, I would like to bind a Map object to my application.yml but I've got a "Elements ... where lef unbound error".
In my class called Ebox, I would like to bind a map called infosTenants, indentified by a string and containing values of type InfosTenant.
Below my application.yml (without the getters / setters of each classes or subclasses)
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {

    private Ebox ebox = new Ebox();

    public ApplicationProperties() {
    }

    // getters/setters ...

    public static class Ebox {
        private String authUrl;
        private Map<String, InfosTenant> infosTenants = new HashMap<>();

        public Ebox() {
        }

        public class InfosTenant{

            private String clientId="";
            private String clientSecret="";

            public InfosTenant() {
            }
            // getters/setters ...

        }
    }
}

In my application.yml, I defined one tenant in my tenants map, indentified by the key tenant1.
application:
    ebox:
        auth-url: https://oauth-server/api/oauth/token
        infos-tenants:
            tenant1:
                client-id: myclient
                client-secret: secret

But all values under infos-tenants were left unbound.
Does somebody have an idea ?
Thanks
Comment: Do you have getter and setter for infosTenants?
Comment: Yes I have gérées and setters for infosTenanrs
Comment: Well `clientId` and `client-id` are different names. Use `clientId` in the YAML instead or somehow tell Spring to map the name correctly (I am not familiar with Spring YAML handling).
Comment: @flyx Spring maps automatically camelCase variables to yml. Upper-case letters are converted to lower-case letters prefixed by -
Answer: I found my error, inner classes should be static, I forgot the static before class InfosTenant.
public static class InfosTenant{

        private String clientId="";
        private String clientSecret="";

        public InfosTenant() {
        }
        // getters/setters ...

    }


Permutations and Combinations- which one to use?

Question: The probability that Ali will answer any one question out of the 10 questions correctly, is 0.6. Each correct answer is worth 4 points.
find in how many ways can Ali receive a grade of 28 out of 40?
I am not sure whether to use permutation formula or the combination formula or something else entirely??? please help.
Comment: Are we assuming that he cannot get partial credit and there are no penalties for wrong answers?
Comment: Yes, we are assuming he's taking the AMC 8, but just the first 10 problems :D
Answer: This problem is equivalent to saying:
"How many ways are there to get 7 problems out of 10?"
I'm unsure of why you would mention the probability of getting a problem right, as it doesn't contribute to the question.
The reworded problem would be: $${10\choose 7} = \frac{10!}{7!3!} = \frac{10\cdot 9\cdot 8}{3\cdot 2} = \boxed{120}$$
So to answer your question, it would be combination, not permutation, as you only need to choose 7 options without rearranging them. Getting #1 right then #2 right is the exact same as getting #2 right then getting #1 right.
Comment: I suspect that the stated problem may be a part of a progression, whereby the student must eventually calculate the probability of scoring 28 out of 40.
Comment: Probably. Too bothered to do that though :D


Get term value from user field and set that value to new field

Question: How to get term from user field and set that to the field in node?
When user is creating node I need to get term and set it to the node field.
I have field_term_reference in user fields and in node I have field_book_reference field. I need to get term from field_term_reference and set that term to the field_book_reference.
Both fields has autocomplete widget.
Here is my current non-working code:
function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
$term = field_get_items($user, $account, 'field_term_reference');

$node->field_book_reference[$node->language][0]['value'] = $node->$term;

}

SOLVED Here is working code:
function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
// Get field from user
$term = field_get_items('user', $user, 'field_term_reference');

$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

}

Answer: $node->$term definitely isn't what you want. Taxonomy references are stored by tid, so
$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

should work


error message not appearing, validate array

Question: Please help me showing my error message, array message not appears in table
$validation_file = $this->validate([
            'requirements' => 'required|array',
            'requirements.*' => 'required|array',
            'requirements.*.file' => 'required|mimes:pdf,jpg,png,jpeg|max:20000|array',
            'input.*.input' => 'required|array',
            'requirements.*.file.input' => 'required|array',

        ]);

Blade
<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $requirements->id }}">
<input type='file' wire:model="requirement.{{ $requirements->id }}.file" class="form-control" accept=".pdf">
@error('requirements.{{ $key }}.file')

{{ $message }}

@enderror

<input type="hidden" name="req_id[{{ $key }}]" wire:model="req_id.{{ $key }}.id" value="{{ $input->id }}">
<input type='text' wire:model.defer="input.{{ $input->id }}.input" class="form-control">
@error('input.{{ $key }}.input')

{{ $message }}

@enderror

Comment: Your front has related div with codes to show errors?
Comment: Is that your entire blade ile?
Answer: Your wire:model has a spelling error:
wire:model="requirement.{{ $requirements->id }}.file"
It should be (notice the missing s):
wire:model="requirements.{{ $requirements->id }}.file"
Comment: Sorry Bro Not Working
Comment: @Bilhaq2612 So, you've changed the `wire:model`, then uploaded a file, and inside your component triggered [validation](https://laravel-livewire.com/docs/2.x/input-validation)?


Getting a 403 error when trying to access web site

Question: Apache/2.4.18 (Ubuntu)
Ubuntu 16.04

Here's my 000-default.conf file:
<VirtualHost *:80>
   ServerAdmin firstname.lastname@example.com
   ServerName myserver.net
   DocumentRoot /home/utils/rails/public
   <Directory /home/utils/rails/public>
      AllowOverride all
      Options -MultiViews
      Require all granted
   </Directory>
   LogLevel warn
   ErrorLog ${APACHE_LOG_DIR}/myserver.net_error.log
   CustomLog ${APACHE_LOG_DIR}/myserver.net_access.log combined
</VirtualHost>

File settings for the /home/utils/rails/public directory are set to 0755
I am getting:
Forbidden

You don't have permission to access / on this server.

This is the first time I run into this. Any ideas?
Comment: *"Forbidden. You don't have permission to access / on this server."* - That looks like the error you will see as a site visitor. As a server administrator the next step would be to take a look at the (error) log file on the server, typically you get a more useful error message there... - Frequently the problem is a missing Index file  (i.e. you don't have an index.html or you want to use index.php and have not defined it with the [`DirectoryIndex`](https://httpd.apache.org/docs/current/mod/mod_dir.html#directoryindex) directive) or the permissions at a higher level directory are incorrect.
Comment: Don't edit your solution into the question. Instead, post it as an answer and accept it.
Answer:
he fixed Directory / in the answer already *
Your own solution is the worst advice possible. Directory directive represents the directory of the filesystem. What actually solved your issue is setting "AllowOverride none" in which probable a rogue .htaccess file was changing your permissions at first.

Set directory in your virtualhost to your documentroot and if you are the admin, don't use .htaccess, since as you can see, if you don't perfectly know what you are doing it will lead you to confusion and mistakes, so the real answer is, set directory to the documentroot and set allowoverride none, control the access within the virtualhost, all in one place for easy checking.
<VirtualHost *:80>
   ServerAdmin email@example.com
   ServerName myserver.net
    DocumentRoot "/home/utils/rails/public"
    <Directory "/home/utils/rails/public">
        AllowOverride None
        Require all granted
   </Directory>
   LogLevel warn
   ErrorLog ${APACHE_LOG_DIR}/myserver.net_error.log
   CustomLog ${APACHE_LOG_DIR}/myserver.net_access.log combined
</VirtualHost>

If you wonder where <Directory /> belongs, it belongs in server config (or global config, outside of virtualhost) and should be set to Require all denied. Otherwise you are actually giving access to everyone to your whole filesystem.
I also removed your IfModule for mod_negotation since to disable multiviews is the same as not having it so an Ifmodule mod_negotiation to disable multiviews makes little sense.
Comment: This is a clean install. There were no .htaccess files around.
Comment: @EastsideDeveloper if that's really true the first example would have worked for you from the start. I don't mean you are lying, but there was something else not in that example changing the behaviour in the config you showed. AllowOverride all is the only thing that points to that in that example.
Comment: No. This is a clean install. Spun an new instance on ubuntu 16.04 from AWS, created the utils user/home directory, installed mysql server/client I deleted the instance and restarted one more time. The same results. The only thing that's different, is "Require all granted"
Comment: I tested AlloweOverride both ways (None and All), and it makes no difference.
Comment: @EastsideDeveloper Require all granted was already specified in the first example!
Answer: The following solved the problem:
<VirtualHost *:80>
   ServerAdmin email@example.com
   ServerName myserver.net
    DocumentRoot "/home/utils/rails/public"
    <Directory "/home/utils/rails/public">
        <IfModule mod_negotiation.c>
            Options -MultiViews
        </IfModule>
        AllowOverride None
        Require all granted
   </Directory>
   LogLevel warn
   ErrorLog ${APACHE_LOG_DIR}/myserver.net_error.log
   CustomLog ${APACHE_LOG_DIR}/myserver.net_access.log combined
</VirtualHost>

The key is:
Require all granted

This is used since Apache 2.4. The other directives are not key to the access issue, but I have them to disallow .htaccess directives (ALlowOverride) and deal with Multiviews
Setting permissions to 0755 works and did not need to be changed
*Fixed typo where the directory path did not copy


Proxy problems with Drupal 7.20

Question: I have an installation of Drupal 7.20. I've entered the proxy settings in the default.settings.php but it's still unable to check on updates. A simple test with a dummy page which executes
<code>http://updates.drupal.org/release-history/drupal/7.x?version=7.20')); ?>
</code>
Results in the following error message

object(stdClass)#62 (2) { ["code"]=> int(-110) ["error"]=> string(20) "Connection timed out" }

Which leads me to believe the proxy settings are not being detected
Answer: As far as I'm aware, changing default.settings.php won't do anything. This file is only there to be copied into settings.php when the site is first installed - so if you change it after settings.php has been created it will do nothing at all.
You might try this module for proxy settings (though don't believe it when it claims to have a working version for D8)

Proxy problems with Drupal 7.20


How do I use confirm_form()?

Question: I have a custom block made in the edit-mode of a node, and I would like to have it linked to a confirmation screen. So I figured out that I'll use confirm_form(). After a few days, I'm not able to get this function working.
Is there anyone who can tell me what I do wrong or what I'm supposed to do?
This is the switch statement that defines my actions when hitting the button.
case ACTION_FICHE_OFFLINE :
    if ($form_state['buttons']['5']['#value'] == ACTION_FICHE_ONLINE) {
      $form_state['values']['status'] = '1';
        drupal_set_message('FICHE ONLINE', 'warning', FALSE);
    }
    else {
      confirm_offline($form, 'Are you sure?', 'dashboard', t('This action cannot be undone'), 'Confirm', 'Cancel', 'fiche_offline');
      $form_state['values']['status'] = '0';
      drupal_set_message('FICHE OFFLINE', 'warning', FALSE);
}
    break;

The formal parameters for confirm_offline() are the following ones:

$form
$question
$path
$description = NULL
$yes
$no = NULL
$name = 'confirm'

What code should I use in confirm_offline()?
Answer: confirm_form() is a form builder; as such it should be called from a menu callback or another form builder function. From the code you shown, I take you are calling it from a form submission handler, and that is not how you should use that function.
As example of code that shows a confirmation form, you can look at system_modules(), the form builder associated with the "admin/modules" path. The function contains the following code.
  // If the modules form was submitted, then system_modules_submit() runs first
  // and if there are unfilled required modules, then $form_state['storage'] is
  // filled, triggering a rebuild. In this case we need to display a
  // confirmation form.
  if (!empty($form_state['storage'])) {
    return system_modules_confirm_form($visible_files, $form_state['storage']);
  }

The form submission handler for the "admin/modules" path, system_modules_submit(), then contains the following code.
  // Redirects to confirmation form if more modules need to be enabled.
  if ((!empty($more_required) || !empty($missing_modules)) && !isset($form_state['values']['confirm'])) {
    $form_state['storage'] = array(
      'more_required' => $more_required,
      'modules' => $modules,
      'missing_modules' => $missing_modules,
    );
    $form_state['rebuild'] = TRUE;
    return;
  }

Settings $form_state['rebuild'] to TRUE tells Drupal to call again the form builder which (basing on the value of $form_state['storage']) shows the confirmation form, rather than the form listing all the modules found for the Drupal site.
Comment: Thanks for the extra background information! I'll take a look at it!
Answer: You need a form, which shows your text and buttons, and you need an URL go call this form.

Define your path by implementing hook_menu(). If you are new to Drupal, you should find the D6 menu system handbook helpful.
Define a form with help of the Drupal FAPI. This FAPI tutorial guides you step-by-step.

You'll find working code examples for both steps in the Example Module.
Once this is working, you can call your URL with drupal_goto().
Comment: Yes I know, but how can I configure the path and the confirmation page?
Comment: What exactly is your problem with the path? From the parameters of confirm_offline I take that you want to show a form which gives the user the chance to say "yes" or "no", right? Did you implement the form and the path in hook_menu? If yes, please show your code.
Comment: Hm, I'm rather new into Drupal and I didn't implement the path (which path by the way).
Comment: @BetaRide isn't drupal_goto() redundant when using confirm_form()? I think [`#action`](http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#action) takes you to the default path, while the [`$path`](http://api.drupal.org/api/drupal/modules!system!system.module/function/confirm_form/6) parameter takes you to the canceled action path. I have not used this helper function before, so anyone please correct me if I am wrong.

How do I use confirm_form()?


Optimizing COUNT(DISTINCT) SQL query

Question: I have two tables A, B:
A contains two columns and has a relatively small amount of rows compared to B (thousands):
id, build_id (string)

B contains three columns and has a large amount of rows (hundreds of thousands):
 id, build_id (string), task_id (string)

There may be many tasks for a given build. I would like to obtain a table containing all builds and the latest task id for each build and the number of tasks for that build. The query I have is below:
SELECT
    A.build_id,
    MAX(B.id) as latest_task_id,
    COUNT(DISTINCT B.task_id) AS task_count
FROM
    A
LEFT OUTER JOIN
    B ON B.build_id = A.build_id
GROUP BY
    A.build_id

Is there any way to optimize this? There are already indexes on build_id and task_id.
UPDATE: This is on postgres 9.6+
Comment: Tag your question with the database you are really using.  I removed the incompatible database tags.
Comment: which postgres version? this matters as you can optimise on 9.6+
Comment: MySQL and postgresql are two different products with different sql implementations. Which one do you use? Also, why do you need to optimise the query? Is it slow? If yes, how slow it is? What's roughly the number of affected records?
Comment: Please [edit] your question and add the execution plan generated using `explain (analyze, verbose, format text)`. [**Formatted text**](http://dba.stackexchange.com/help/formatting) please, [no screen shots](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557)
Comment: is B.task_id unique in either table? (if so, creating a unique index might help)
Comment: task_id only exists in table B and it is not unique.
Answer: Try aggregating before the join:
SELECT A.build_id,
       MAX(B.id) as latest_task_id,
       COUNT(B.task_id) AS task_count
FROM A LEFT OUTER JOIN
     (SELECT B.build_id, B.task_id, MAX(B.id) as id
      FROM B
      GROUP BY B.build_id, B.task_id
     ) B
     ON B.build_id = A.build_id
GROUP BY A.build_id;

Sometimes, the algorithms for overall aggregation are more efficient than for COUNT(DISTINCT).
You can also try an index on B(build_id, task_id, id) for this query.
Comment: This query speeds it up a bit, thanks!. The covering index however didn't help.

Optimizing COUNT(DISTINCT) SQL query


change containerColor from a list

Question: I have previously asked a question regarding lists in Flutter. I got good help but new problems arose within the same list. Since this new probelm is of other character then the initial question I made this new question.
I have a list (the code below is simplified from my working-code to make my problem clearer) of blue colored containers.
When the user types in 5 and press the 'submit'-button the color of the first container should change to green (if not 5 the button should turn red).
The second time the user press the 'submit'-button the second container should change color. And so on...
The problem I'm facing is that I can't get my increment to the list to work.
      import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'listing 4',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  int sum = 5;
  String userAnswer;
  String correction = "";
  var _controller = new TextEditingController();
  int _counter = 1;

  List<Color> colors = [Colors.blue, Colors.blue, Colors.blue];

  submitPressed(int index) {
    if (userAnswer == sum.toString()) {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.green;
      });
    } else {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.red;
      });
    }
  }

  Widget myTextField() {
    return Container(
      width: 50.0,
      child: TextField(
        controller: _controller,
        textAlign: TextAlign.center,
        autofocus: true,
        keyboardType: TextInputType.number,
        onChanged: (val) {
          userAnswer = val;
        },
      ),
    );
  }

  Widget myListBuilder() {
    return Container(
      height: 50.0,
      width: 300.0,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 3,
          itemBuilder: buildContainer,
        ),
      ),
    );
  }

  Widget buildContainer(BuildContext context, int index) {
    return Container(
        child: Padding(
      padding: const EdgeInsets.only(top: 10.0),
      child: Container(
        height: 20.0,
        width: 15.0,
        decoration: BoxDecoration(
            color: colors[index], //this is the important line
            borderRadius: BorderRadius.all(Radius.circular(8.0))),
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Listing 4'),
      ),
      body: Container(
        child: Center(
           child: Column(
            children: <Widget>[
              Padding(
               padding: EdgeInsets.only(top: 10.0),
               child: Text('Correct answer is 5',
                    style: TextStyle(fontSize: 20.0)),
              ),
              myTextField(),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  setState(() {
                    submitPressed(0);  //This will naturally only give index 0
                  });
                },
              ),
              myListBuilder(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  buildContainer(context, 0),
                  buildContainer(context, 1),
                  buildContainer(context, 2)
                ],
              ),
              RaisedButton(
                child: Text('Next'),
                onPressed: () {
                  _counter++;
                  _controller.clear();
                  myTextField();
                },
              ),
              Text('This should be container no: $_counter'),
            ],
          ),
        ),
      ),
    );
  }
}

Comment: I can't see where you are using ```myListBuilder```, did you forget to post the code ? Also when you change to ```red``` you forgot to ```setState```.
Comment: Working on fixing that (thanks  for pointing it out). Still the incrementer won't work :-/
Comment: Code is uppdated and you can see both myListBuilder and buildContainer. The reason for that is only for clearity in this question.
Answer: I can't figure out why you have this
submitPressed(0);

This code works:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'listing 4',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  int sum = 5;
  String userAnswer;
  String correction = "";
  var _controller = new TextEditingController();
  int _counter = 0;

  List<Color> colors = [Colors.blue, Colors.blue, Colors.blue];

  submitPressed(int index) {
    if (userAnswer == sum.toString()) {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.green;
      });
    } else {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.red;
      });
    }
  }

  Widget myTextField() {
    return Container(
      width: 50.0,
      child: TextField(
        controller: _controller,
        textAlign: TextAlign.center,
        autofocus: true,
        keyboardType: TextInputType.number,
        onChanged: (val) {
          userAnswer = val;
        },
      ),
    );
  }

  Widget myListBuilder() {
    return Container(
      height: 50.0,
      width: 300.0,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 3,
          itemBuilder: buildContainer,
        ),
      ),
    );
  }

  Widget buildContainer(BuildContext context, int index) {
    return Container(
        child: Padding(
          padding: const EdgeInsets.only(top: 10.0),
          child: Container(
            height: 20.0,
            width: 15.0,
            decoration: BoxDecoration(
                color: colors[index], //this is the important line
                borderRadius: BorderRadius.all(Radius.circular(8.0))),
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Listing 4'),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: Text('Correct answer is 5',
                    style: TextStyle(fontSize: 20.0)),
              ),
              myTextField(),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  setState(() {
                    submitPressed(_counter);
                  });
                },
              ),
              myListBuilder(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  buildContainer(context, 0),
                  buildContainer(context, 1),
                  buildContainer(context, 2)
                ],
              ),
              RaisedButton(
                child: Text('Next'),
                onPressed: () {
                  setState(() {
                    _counter++;
                  });
                  _controller.clear();
                  myTextField();
                },
              ),
              Text('This should be container no: ${_counter +1}'),
            ],
          ),
        ),
      ),
    );
  }
}

I changed the _counter to act like an index and use it as the parameter of the method submitPressed.
I also put the increment in a setState, or you saw the new number only after hitting the Submit button.
Comment: I can't thank you enough :D Sometimes when I do some trial and error testing, I add stuff that I forget to remove in the "beta"code. The increment were sloppy and just to prove what I was trying to do. But I will use it to navigate to next screen after a certain amount of questions. Thank you again! This means I can proceed with my work :)
Comment: No problem! ^_^
When I put debug stuff in the code (I do this too!), I personally prefer adding `// TODO`, so I can easily track them down with my IDE tools when I want them to be removed.
Comment: Good idea. I will implement that :)

change containerColor from a list


IOS: Can I use ABAddressBook to store contact information outside the iPhones Contacts?

Question: I'm wanting to store some contact information and allow the user to call/email the person instead of just looking up the info.  I don't want the contacts stored in the user's Address Book in their contacts though.  I want to keep it within the app only.  Can I use ABAddressBook for this or do I need to create my own classes to accomplish this?
Answer: I'll address both your questions:

Can I use ABAddressBook for this?

You cannot use ABAddressBook to store a separate contacts database. Here's an excerpt from the ABAddressBook Class Reference:

The ABAddressBook class provides a programming interface to the Address Book—a centralized database used by multiple applications to store contact and other personal information about people.

The database referred to here is a pre-specified database; there is no method or class to create a new one, as the whole Address Book framework provides access to a single database accessible to the user through the Contacts application.

Do I need to create my own classes to accomplish this?

You would need to create a custom class for this. If you plan on supporting users with many, many contacts (in the thousands/high hundreds range), you probably would use an SQLite database. If you plan on supporting users with few contacts, you should probably use a .plist.
Usually, Objective-C programmers use the C library for SQLite directly, but now there is a great wrapper that you can find here called FMDB.
For info on the syntax and basics of SQLite, see the SQLite Language Guide.
Lastly, here are a couple books on SQLite and database programming for iOS:

(Apress) Using SQLite
(Wrox) Professional iPhone and iPad Database Application Programming

Hope this helps!
Comment: @daveomcd FMDB is a wrapper around SQLite, while Core Data is a completely different way of persisting data. So yeah, they're completely different things.
Comment: Sure did! Cleared some things up thanks! Quick question however... why do you recommend FMDB over Core Data... or are they separate things? Thanks!


PostgreSQL JSON building an array without null values

Question: The following query
SELECT jsonb_build_array(jsonb_build_object('use', 'Home'),
        CASE WHEN 1 = 2 THEN jsonb_build_object('use', 'Work')
        END)

produces
[{"use":"Home"},null]

When I actually want
[{"use":"Home"}]

How do I go about doing this? json_strip_nulls() does not work for me.
Comment: `json_strip_nulls()` does not remove all nulls by design, it removes all object fields having null as value
Comment: For how to do this in an aggregation, see [Postgresql LEFT JOIN json_agg() ignore/remove NULL](https://stackoverflow.com/q/24155190/1048572). For building an object instead of an array, see [Postgres json_object. Add json field only if value is not null](https://stackoverflow.com/q/48538275/1048572)
Answer: Creating a custom function seems to be the simplest way.
create or replace function jsonb_build_array_without_nulls(variadic anyarray)
returns jsonb language sql immutable as $$
    select jsonb_agg(elem)
    from unnest($1) as elem
    where elem is not null
$$;

select
    jsonb_build_array_without_nulls(
        jsonb_build_object('use', 'home'),
        case when 1 = 2 then jsonb_build_object('use', 'work') end
    )

 jsonb_build_array_without_nulls
---------------------------------
 [{"use": "home"}]
(1 row)

Answer: By using a PostgreSQL array like that:
SELECT array_to_json(array_remove(ARRAY[jsonb_build_object('use', 'Home'),
        CASE WHEN 1 = 2 THEN jsonb_build_object('use', 'Work') END], null))

which does produce:
[{"use": "Home"}]

while, to be sure:
SELECT array_to_json(array_remove(ARRAY[jsonb_build_object('use', 'Home'),
        CASE WHEN 1 = 2 THEN jsonb_build_object('use', 'Work') END,
        jsonb_build_object('real_use', 'NotHome')], null))

does produce:
[{"use": "Home"},{"real_use": "NotHome"}]

Answer: Postgres 16 did introduce JSON constructor functions like json_array.

If ABSENT ON NULL is specified, NULL values are ignored

So you can use
SELECT json_array(
    json_object('use': 'Home'),
    (CASE WHEN 1 = 2 THEN json_object('use': 'Work') END),
    ABSENT ON NULL
)

For JSONB, there is no jsonb_array function but rather you use
json_array(… ABSENT ON NULL RETURNING jsonb)

Answer: I'm assuming this query is generaetd dynamically, somehow. If you're in control of the SQL generation, you can also use ARRAY_AGG(...) FILTER(...) instead, which, depending on your real world query, might be more convenient than using all the different array conversion functions suggested by Patrick.
SELECT (
  SELECT json_agg(v) FILTER (WHERE v IS NOT NULL)
  FROM (
    VALUES
      (jsonb_build_object('use', 'Home')),
      (CASE WHEN 1 = 2 THEN jsonb_build_object('use', 'Work') END)
  ) t (v)
)

Or also:
SELECT (
  SELECT json_agg(v)
  FROM (
    VALUES
      (jsonb_build_object('use', 'Home')),
      (CASE WHEN 1 = 2 THEN jsonb_build_object('use', 'Work') END)
  ) t (v)
  WHERE v IS NOT NULL
)

Answer: One other way that this can be handled is the following:
SELECT jsonb_build_array(
  jsonb_build_object('use', 'Home'),
  CASE
    WHEN 1 = 2 THEN jsonb_build_object('use', 'Work')
    ELSE '"null"'
  END
) - 'null'

(Unfortunately it's not really possible to do much with null by itself in postgres -- or most other DBs)
In the case above, '"null"' could be replaced with just about any unique string that would not be mistaken for live data in the array. I would not use numbers since - 0 would actually try to remove the first item from the array, rather than a number within the array. But you could probably use '"0"' and remove using something like - '0' if you wanted.
For those not using CASE, a COALESCE could be used to convert nulls into the desired string (alas, no NVL, IFNULL or ISNULL in postgres, but at least COALESCE is portable)


elements in list not staying together on resize

Question: I posted this a little earlier but deleted it because I was able to figure a little of it out. Im having an issue when resizing a screen with this todo list project im working on. Im using a bit of javascript that creates a list item every entry. The person types in a todo task and then a check box and remove icon is added. My issue is that on smaller screens, the checkbox and remove icon is jumping up a layer when a long named task is given. Im using bootstrap 4 to hold it all in place on my html side. My image should help clarify what I'm talking about. I think the javascript may be the issue.
Here is the list when on a medium screen. Looks correct with the checkbox/trash icon being to the right of the item.

Here is the issue when the screen gets smaller. The checkbox/trash icon goes up a line as the text breaks down. How can I make it stay on the first line as the text? Ive tried setting the "li" element to width="90%;" with the checkbox/remove icon taking up the remaining 10. It looks worse then. I'm really not sure. Ill attach the relevant code.

function show() {
 var todos = get_todos();

 var html = '
';
 for(var i=0; i < todos.length; i++) {
     html += '<input class="checkBox" type="checkbox">
' + todos[i] + '
' + '<button class="remove" id="' + i  + '"></button>
';
 };
 html += '
';

 document.getElementById('todos').innerHTML = html;

 var buttons = document.getElementsByClassName('remove');
 for (var i=0; i < buttons.length; i++) {
     buttons[i].addEventListener('click', remove);
 };
}
   body, html { /*makes the background image stretch the whole screen*/
 height:100%;
}
 body {
 background-image:url('campingBackground.jpg');
 background-repeat:no-repeat;
 background-attachment:fixed;
 background-position:center;
 background-size:cover;
}
 .checkBox {
 margin-right:10px;
 height:18px;
 width:18px;
}
 .checkBox:hover {
 background-color:#C0C0C0;
}
   .remove { /*Trash can button*/
 color:white;
 font-size:24px;
 border:0;
 padding:0;
 background-color:transparent;
}
 .remove:hover {
 color:#C0C0C0;
}
 ul {
 text-align:right; /*This pushes the checkbox/trash can right while the
 in the js file floats the todo text left*/
 list-style-type:none;
 padding-left:0px; /*Makes up for not having the bullet point spacing on smaller screens*/
 font-size:24px;
 color:white;
 font-weight:600;
}
 li {
 text-align:left;
}

To-Do List

      <input type="text" class="form-control" id="task">

     <button id="add" style="border-radius:50%; font-size:35px; width:65px;" class="btn btn-danger">+</button>

Comment: Can you tell what the screen size does the problem start with?
Comment: it brakes down to two lines @ 767px. That is probably just because that is the length of my longer task "finishing packing before going to airport at 8:15". If I had a task that was twice as long, it would break at an earlier point and if I had one smaller, it would break later.@Dmitry S.
Answer: First, having an ul list with items like span as child nodes is not correct, according to the HTML Specification for a list (ul) element:

The ul element represents a list of items, where the order of the items is not important — that is, where changing the order would not materially change the meaning of the document.
The items of the list are the li element child nodes of the ul element.

The problem is given because according to the name of the todo item, there is no space for the todo to fit.
I recommend this changes to your code as a possible solution:

var todos = [
  'Lorem ipsun dolor sit amet',
  'Answer a question related to JavaScript on StackOverflow',
  'Another todo',
  'A really long long todo to show this code working for todo with long long long names'
];

var html = '
';
for(var i=0; i < todos.length; i++) {
    html += '
' +
          '' + todos[i] + '' +
          '<input class="checkBox" type="checkbox">' +
          '<button class="remove" id="' + i  + '">' +
          '' +
          '</button>' +
      '
';
};

html += '
';

document.write(html);
/* https://www.w3schools.com/howto/howto_css_clearfix.asp */
.todo-item::after {
  content: "";
  clear: both;
  display: table;
}

.todo-item {
  text-align: right;
}

.todo-item .todo-label {
  display: block;
  float: left;
  max-width: 80%; /*  you can increase the size */
  text-align: left;
  /* you can use this props if you don't wan another line */
  /* white-space: nowrap; */
  /* text-overflow: ellipsis; */
  /* overflow: hidden; */

}
Comment: So this is really helpful but there is one thing I left out that I now see isnt quite working right. I have this line of css that doesnt work when things are shifted around. ` input:checked + li {
 text-decoration:line-through;
 max-width:90%;
}
`Basically what this does is put a line through the list item when its corresponding checkbox is checked. This is helpful for people that want to acknowledge that they did something on their list but dont want to delete it so they can still reference that they did it. Im trying to see if I can get it working again. I think its the order.


Generating Pythagorean triples where the legs are Hypotenuses of other Pythagorean triples

Question: I know how to generate regular Pythagorean Triples given two positive integers P and Q such that
$$a=2*p*q$$ $$b=p^2-q^2$$ $$c=p^2+q^2$$ where $p>q$, but I want to find scenarios where $a$ and $b$ can also be written in the format $p^2+q^2$.  Specifically, I am looking for a generalized way of finding all situations where the hypotenuses of the first two triples form the legs of the third triple.
$$$$
I want to be able to generate a formula for finding these special triples.
So far, I have been able to find four cases where this holds true by using the brute force method.

$P_1$
$Q_1$
$A_1=2P_1Q_1$
$B_1=P_1^2-Q_1^2$
$C_1=A_3$

10
2
40
96
104

16
4
128
240
272

15
9
270
144
306

21
3
126
432
450

$P_2$
$Q_2$
$A_2=2P_2Q_2$
$B_2=P_2^2-Q_2^2$
$C_2=B_3$

12
3
72
135
153

12
9
216
63
225

12
8
192
80
208

20
12
480
256
544

$P_3$
$Q_3$
$A_3=2P_3Q_3=C_1$
$B_3=P_3^2-Q_3^2=C_2$
$C_3=C_1^2+C_2^2$

13
4
104
153
185

17
8
272
225
353

17
9
306
208
370

25
9
450
544
706

As you can see, the third chart shows Pythagorean triples with legs that are also hypotenuses of the previous charts.  For example, the right triangle with sides (104, 153,185) corresponds to the right triangles with (40,96,104) and (72,135,153).  The P and Q vales show $P_1^2+Q_1^2=2P_3Q_3$ ($10^2+2^2=2*13*4=104$), and $P_2^2+Q_2^2=P_3^2-Q_3^2$ ($12^2+3^2=13^2-4^2=153$).
I gathered this information using the highly inefficient and laborious method of inputting a table of P and Q values into Google sheets up to P and Q being less than or equal to 25.  Then, I searched the data by using vlookup and countif functions, after sorting it a bit.
$$$$
I think there must be a way of simplifying this process, but it eludes me.  How can I (in a much less time consuming way) generate these special Pythagorean triples where each side of the triangle is a hypotenuse of another Pythagorean triple?
Edit: While the Euclidean formula for Pythagorean triples relies on the value of $p$ and $q$ to generate legs $a$ and $b$ with hypotenuse $c$, I am looking for a generalized way of finding the special "triple triples" for lack of a better term given integer inputs $(input_1...input_k)$ that I can input into functions
$$f_A(input_1...input_k)=A$$
$$f_B(input_1...input_k)=B$$
$$f_C(input_1...input_k)=C$$
Where A and B are hypotenuses of other Pythagorean triples, and (A,B,C) forms a Pythagorean triple in and of itself.
Comment: I guess looking at your table, you really do want solve the Pythagorean triple problem. But be aware that your nested squared equation is something different. Also note that the $P_i, Q_i$ in your table do not play the roles of $p_i, q_i$ in your description of the problem. Instead it is the $A_i, B_i$ that correspond to $p_i, q_i$. This inconsistent labelling makes it confusing to work out what you are doing.
Comment: What is your ultimate goal? You can write a program to generate millions of these. Anyway see [sum of two squares](https://en.wikipedia.org/wiki/Sum_of_two_squares_theorem) for the information you need.
Comment: The positive integers being the sum of at most two squares can easily be classified, but when a positive integer is the sum of two positive squares is a bit more complicated. At least you can check the necessary condition to find out whether $a,b$ can be the sum of two squares at all. One additional fact you can use is that one of $a,b$ must be divisible by $3$ and therefore divisible by $9$.
Comment: Ultimately, I am looking for a method of generating the sides of the special Pythagorean triple, given certain input variables.  I want it to function in a similar way to Euclid's formula for regular Pythagorean triples (input P and Q to yield A,B, and C) but I'm not sure if I would need more than 2 inputs, or if this approach is even viable.
Comment: If you want "three Pythagorean triples where the hypotenuses of the first two form the legs of the third", then you need $$p_1^2 + q_1^2 = h_1^2 \\p_2^2 + q_2^2 = h_2^2\\h_1^2 + h_2^2 = h_3^2$$ Combining gives $$p_1^2 + q_1^2 + p_2^2 + q_2^2= h_3^2$$ without any nested squaring. But that equation itself does not require the $p_i, q_i$ to be parts of Pythagorean triples, It is unclear to me if you are interested in solving the Pythagorean triple problem described, or your nested-squares problem, but the two are not the same.
Comment: @Joseph Gatts Have any of the comments or my answers been useful. I just updated one answer. Feedback would be helpful.
Comment: @Joseph Gatts Note how, in my update, any pair of natural numbers
$\space (n,k)=(p,q)\space$ can yield a "candidate".
Comment: @Joseph Gatts My updated answer shows how to find the following with little work.
$$
(28,96,100),\space (21,72,75)\longrightarrow (75,100,125)\\
(28,96,100),\space (2205,1176,2499)\longrightarrow(2499,100,2501)\\
$$

$$
(75,100,125),\space (180,240,300)\longrightarrow (125,300,325)\\
(75,100,125),\space (84,288,300)\longrightarrow (125,300,325)
$$
Answer: With Euclid's formula
$\quad A=m^2=n^2\quad B=2mn\quad C=m^+n^2\quad a$
primitive Pythagorean triple with side-$A\,$ equal to the hypotenuse of any other triple can be generated using $\quad m=\dfrac{C+1}{2},\,n=\dfrac{C-1}{2}.\quad$
For example, with $\,(5,12,13),\,$
$C=13\longrightarrow m=7,\,n=6\longrightarrow
F(7,6)=(13,84,85).$


ASPNET Core - Erro 500 ao fazer post em um método que retorna uma Partialview com só um objeto

Question: Eu tenho um método na minha controller chamado de ListagemTarefasEmDesenvolvimento() que me retorna uma PartialView. Porém, quando eu chamo esse método via ajax, o servidor me retorna um erro de estatus 500.
Abaixo tem a minha controller:
[HttpPost]
        public IActionResult ListagemTarefasEmDesenvolvimento()
        {
            var idUser = Int32.Parse(User.FindFirst("IdUsuario")?.Value);

            var obj = _tarefaContext.getTarefaEmDesenvolvimentoByIdUsuario(idUser).Result;

            var retorno = PartialView("_Em", obj);
            return retorno;
        }

O método getTarefaEmDesenvolvimentoByIdUsuario(), retorna somente um objeto. (não retorna lista).
Esse é a minha PartialView
    @model RKMES.Models.Tarefa

Em Desenvolvimento

                    @Model.Nome

                    Atividade: @Model.Atividade.Nome

                    Tempo previsto: @Model.HorasPrevisto

Algumas curiosidades:

Se eu fizer o método getTarefaEmDesenvolvimentoByIdUsuario() retornar
uma lista de objetos, e eu fizer um ajuste na view, tudo funciona
normalmente.

Pelo que vi em uns dos métodos construtores de PartialView(), ele
espera um objeto como segundo parâmetro, então em teoria, o que eu
fiz deve funcionar normalmente, mas eu recebo erro
500.

Alguem sabe me dizer onde estou errando?
Comment: Faça o debug e veja qual é o erro 500... só essa informação não é o suficiente.
Answer: O erro ocorre por falta de validação de algum dos argumentos.
Considere que se o erro é 500 o defeito não está na chamada desse endpoint.
A família de erros 500 referem-se à erros do lado do desenvolvedor, como por exemplo a falta de validação de nulo ocasionando um ArgumentNullException. O que o seu código realmente deveria fazer quando User.FindFirst("IdUsuario")?.Value retornar nulo?
Apenas como medida de teste, sugiro adicionar um tratamento de erro retornando a mensagem do erro interno. Isso facilitará seu diagnóstico.
[HttpPost]
public IActionResult ListagemTarefasEmDesenvolvimento()
{
    try
    {
        var idUser = Int32.Parse(User.FindFirst("IdUsuario")?.Value);
        var obj = _tarefaContext.getTarefaEmDesenvolvimentoByIdUsuario(idUser).Result;
        var retorno = PartialView("_Em", obj);

        return retorno;
    }
    catch (Exception ex)
    {
        var retorno = Content(ex.Message);
        retorno.StatusCode = 500;
        return retorno;
    }
}

Na sequência faça uma chamada para esse endpoint através do Swagger ou Postman para ver a mensagem do erro.


From Developer to Web Developer to Web Designer

Question: Is it possible for a fairly experienced Java Developer to transition to being a Web Developer and then to Web Designer. I guess what I'm asking is - assume you have (Java) developer of above average aptitute - is it possible for that developer to acquire web development skills that will enable him/her to develop small business websites without the need to hire outside skills.
If so, where does one start on the path to becoming a Web Developer/Designer?
Skills required?
Tools used?
Comment: @leftbrainlogic: Photoshop or Gimp (Photoshop *is* better, but I'm using Gimp on Linux), CSS, HTML, Servlet, JSP, Selenium, Firefox's firebug... You're good to go :)   Note that as a Java developer you have a *huge* advantage over "simpler" Web designers: you can write real Java apps using GWT that shall convert them automatically to Javascript (think GMail: it's written in Java...).
Answer: Most web designers that I've met do not have a background in development at all. They possess a combination of aesthetic talent and an understanding of the HCI/usability side of website design.
They have some knowledge of what is possible of the development side or what the costs would be, but they usually don't do it themselves. A lot of studios have both designers and developers.
I personally believe that programming skills and design skills are not something that one can acquire, one has to have an aptitude and natural talent for each. It is possible to learn, but one wouldn't be as effective in it as a "natural". I freely admit, for example, that I do not have the aesthetic talent for good website design. Heck, my wife would argue that I don't have the aesthetic talent to dress myself nicely :) But if you have it, why not?
Beyond that, I would say that every developer should probably learn some of the state-of-the-art knowledge on ui or website design, or at least read a usability book. Jakob Nielsen writes some very good books on that topic.
A transition from non-web development to web development is generally easier, though you may have to learn a bunch of new APIs and possibly languages. For instance, I'm rusty on JSP and J2EE, and haven't learned any of the frameworks for the past 5-10 years.
Answer: Yes. It is certainly possible, I assume you have been developing most Desktop Application and native Software using Java and so would advise to take up some JSP and Servlets knowledge to dive into web development.

Books for Web Application
Development
JSPs and Servlet - Head First Series is good book to start.
Don't Make me thing good book on understanding UI stuffs, which is important for Web Designers.

Try to browse through web-development tags as you will find very useful suggestions there.
Answer: While I think that it's definitely possible to transition from a Java Developer to a Web Developer, Web Design requires IMO a very different set of skills (including artistic sense) that some people don't have and might never be able to get.
Comment: Downvoting without any explanation is so lovely... And I really wonder why this answer is worth a downvote.
Answer: It is possible and as far as just moving to Web Developer, it isn't that difficult.  Pick up Head First Servlets & JSP and give it a read to get up to speed on the stateless Request Response model and how things are done in the Java world.  The use of Jquery and other javascript frameworks has really made the javascript aspect much easier.  You don't have to learn as many browser specific tricks.
As far as web designer, Pascal is right on. That moves more into the artistic/graphic design world that is harder to do if you don't have that kind of design aesthetic.  But like most things, the best way to do it, is just to start doing it.  Create some small database driven sites on your own and get your feet wet.
Answer: I think in Web development or any other development platform ,main programming skills are still valid. Only you have to learn new platform and new tools. Bu Web design, User experience
is an other science and you should spend time to learn and practice.
And with passion and practicing it, I think you can be succesful on Web design or any other subject.
Answer: You can learn a lot just by being around and working with designers. The more I work around designers the more I pick up subtle tricks and ways to look and and view a design. I think my design skills are much improved and I can improve my 'designs' by applying what I've noticed but I still don't think I have a natural vision for design.
Answer: It surely is possible, but don't overestimate yourself, Web Designer is a totally other profession than developer. I doubt you can be a specialist in everything, and hiring a designer allows you to concentrate and be proficient on your skill set and allows you to have time to develop your business (which in turn will pay for outsourcing to a designer).


Safe Updates no PHPMyAdmin

Question: No MySQL Workbench tem uma função muito útil chamada: "Safe Updates", que impede Updates em uma coluna sem WHERE, por exemplo.
No PHPMyAdmin, existe esta função? Não consegui encontrar.
Answer: Você tem algumas opções:

remover do usuario que acessa o PHPMyAdmin a permissao de DELETE e UPDATE e criar uma stored procedure para essa operaçoes (que exige entre seus parametros, o conteudo da clausula WHERE)
você pode criar triggers que dao ROLLBACK no upda te se o numero de linhas atualizadas for igual ao numero de linhas da tabela (pode dar errado se outros usuarios inserirem registros em paralelo)
você pode customizar o codigo do PHP MyAdmin (que é aberto) para que ele valide o conteudo dos formularios de query e impeça o usuario de submeter UPDATEs e DELETEs sem where, claro que, pra fazer isso, você precisa conhecer o codigo do PHPMyAdmin e precisa ser capaz de incluir tal alteração sem dar pau no restante das funcionalidades
Comment: Ótimo, Marcelo Bezerra! Muito obrigado!

Safe Updates no PHPMyAdmin


HTML checkbox without label tick not displaying

Question: I'm trying to build a checkbox without a label tag with CSS.
input[type='checkbox']:after{
    line-height: 1.5em;
    content: '';
    display: inline-block;
    width: 18px;
    height: 18px;
    margin-top: -4px;
    margin-left: -4px;
    border: 1px solid rgb(192,192,192);
    border-radius: 0.25em;
    background: #fff;
}

input[type='checkbox']:checked:after {
width: 15px;
    height: 15px;
    border: 2px solid black;
}

Tick is not appearing after clicking the checkbox. What is the missing thing here?
Fiddle
Comment: The original checkbox is behind your :after, and therefor not visible.
Comment: to your checked:after css rule add property: background: none;  It is because :after has 15px by height and width overlay.
Comment: @Arturas After adding  background: none; tick mark is visible but original checkbox is appearing, I'm trying to have a big tick relative to box
Comment: checkout my answer @pupil
Answer: For check inside checkbox you can put content: '✔'; inside input[type='checkbox']:checked:after
Here is simple solution

input[type='checkbox']:after {
    line-height: 1.5em;
    content: '';
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 1px solid rgb(192,192,192);
    border-radius: 0.25em;
    background: #fff;
    margin-top: -4px;
    margin-left: -4px;
}

input[type='checkbox']:checked:after {
    content: '✔';
    text-align: center;
    width: 15px;
    height: 15px;
    border: 2px solid black;
}
<input type="checkbox"/>

here my jsfiddle you can checkout Here

Different Way
for that you need to add Fontawesome CDN to use icon to your project
https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css

after that just add in ur css under input[type='checkbox']:checked:after{}
input[type='checkbox']:checked:after {
    /* content: '✔'; */
    content: '\f00c';
    text-align: center;
    width: 15px;
    height: 15px;
    border: 2px solid black;
   font-family: 'FontAwesome';
}

also you can find here fontawesome Cheatsheet for Code

input[type='checkbox']:after {
    line-height: 1.5em;
    content: '';
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 1px solid rgb(192,192,192);
    border-radius: 0.25em;
    background: #fff;
    margin-top: -4px;
    margin-left: -4px;
}

input[type='checkbox']:checked:after {
    /* content: '✔'; */
    content: '\f00c';
    text-align: center;
    width: 15px;
    height: 15px;
    border: 2px solid black;
   font-family: 'FontAwesome';
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<input type="checkbox"/>

checkout fiddle Here
Comment: How do I have a same styled tick like original checkbox tick
Comment: you want original check on it..?
Comment: Yes that's what I'm looking for
Answer: Try this code, with html entity for a tick symbol
input[type='checkbox']:checked:after {
width: 15px;
    height: 15px;
    border: 2px solid black;
    content: '\2713';
    font-size: 22px;
    line-height: 15px;
}

Comment: This makes sense. But how to add a similar tick relative to original checkbox tick but in a bigger size
Comment: You can increase tick symbol with font-size property.


Calculating F-statistic, why is SS used instead of just $r^2$?

Question: The calculations and question are for a simple regression (one independent and one dependent variable).
SSres = SSy * (1 - $r^2$)
SSreg = SSy * $r^2$
F = (SSreg / DFreg)/(SSres / DFres)
So, I've figured out that the value of SSy does not matter for what F-value we get, and that's a good thing since otherwise the F-value is in part contingent upon the scale of our measure. So, in actuality, am I correct to assume that we could in fact simply replace SSres and SSreg with $r^2$ and $(1 - r^2)$ and ignore the in-between calculations of SSres and SSreg? Or is this due to that the F-statistic in this case comes from a simple regression, as opposed to multiple regression?
Answer: If the degrees-of-freedom are taken as fixed, the F-statistic and the coefficient of determination are related as one-to-one functions:
$$F = \frac{MS_{Reg}}{MS_{Res}} = \frac{df_{Res}}{df_{Reg}} \cdot \frac{SS_{Reg}}{SS_{Res}} = \frac{df_{Res}}{df_{Reg}} \cdot \frac{R^2}{1-R^2}.$$
If you have already calculated the coefficient of determination then you can use this to obtain the F-statistic via the above formula.  From this equation we see that these two measures of goodness-of-fit are monotonicly related (a higher coefficient of determination goes with a higher F-statistic).
Incidentally, this means that a goodness-of-fit test could just as legitimately be conducted directly on the coefficient of determination instead of the F-statistic.  The latter is generally used becuase it has a simpler distribution, but they are both increasing monotonic functions of one another, so either statistic gives a proper ordinal measure of the evidence against the null hypothesis in a goodness-of-fit test.
Answer: We could replace SSres and SSreg with $r^2$ and $(1 - r^2)$. For multiple regression, you can replace SSres and SSreg with $R^2$ and $(1 - R^2)$, where $R^2$ is (unadjusted) R square.
Comment: Is there a particular reason why SS is used in almost every single formula for F that I come across in textbooks? (Mostly undergraduate textbooks but also a couple of graduate/general textbooks for social sciences.)
Comment: Two methods give you the exact results (maybe round off difference). I have no clear idea why people use SS, instead of $r^2$ or $R^2$. My guess is: (1) in the process of computing, RRs come first, if you do not need r or R, you can get F from SS directly (it is very important in non-computer time) (2) It is easy to understand the segment of SS. (SS(total) = SS(model) + SS(left)).


If the sum of the digits of $n$ are divisible by 9, then $n$ is divisible by 9; help understanding part of a proof

Question:
Let $n$ be a positive integer such that $n<1000$. If the sum of the digits of $n$ is divisible by 9, then $n$ is divisible by 9.

I got up to here:
$$100a + 10b + c = n$$
$$a+b+c = 9k,\quad  k \in\mathbb{Z}$$
I didn't know what to do after this, so I consulted the solution
The next step is:
$$100a+10b+c = n = 9k +99a+9b = 9(k +11a+b)$$
I don't get how you can add $99a + 9b$ randomly, can someone please explain this for me?
Comment: The statement is true for any positive integer $n$, but from what you've written, are you assuming that $n$ is a three-digit number?
Comment: Updated accordingly.
Answer: We are not adding it "randomly", we add it to both sides of the equation
$$a+b+c=9k$$
to produce$$\begin{align*}
(a+b+c)+99a+9b&=(9k)+99a+9b\\\\
100a+10b+c&=9k+99a+9b\\\\
n&=9k+99a+9b\\\\
n&=9(k+11a+b)
\end{align*}$$
The statement is true for any positive integer $n$, not just $n<1000$. The best way to prove that is through modular arithmetic.
Comment: This does not explain why it is added though, please explain the need to add 99a + 9b what is the reason for this?
Comment: And how do you know adding 99a + 9b will make 9k equal n?
Comment: To get $n$ on one side of the equation, and a quantity we know will be divisible by 9 on the other.
Comment: Remember that you **defined** $a$, $b$, and $c$ so that
$$n=100a+10b+c$$
Comment: To be honest, I am still lost, but this seems like a better answer than the other good answer, so I gave you a checkmark
Comment: You don't have to do that if you don't want to; there's no rush to accept an answer. Now, do you agree that we started out in this problem letting $a$, $b$, and $c$ be the hundreds, tens, and ones digit of $n$ respectively, so that
$$n=100a+10b+c\quad ?$$
And do you also understand why
$$(a+b+c)+(99a+9b)=100a+10b+c\quad ?$$
Comment: No I don't understand the second step
Comment: Addition is commutative; in other words, for any $x$ and $y$, we can rearrange them when we're adding:
$$x+y=y+x$$
Using this fact multiple times to rearrange the terms,
$$a+b+c+99a+9b=a+99a+b+9b+c$$
Now use that $$a+99a=100a,\qquad b+9b=10b.$$
Comment: Oh now I finally get it! Thanks so much. Here have an Oreo cookie as a reward!
Comment: Haha thanks :-)
Answer: I don't know why they are thinking about three digits.  I would say let $n=10a+b$, where $b \lt 10$ (intuitively, $b$ is the ones digit and $a$ is all the rest).  Then $n \pmod 9 \equiv 10a+b = (10-1)a +a +b \equiv a+b \pmod 9$ shows we can "strip off" all the lowest digits and add them up.
Comment: Unfortunately, I still do not understand the need to strip off all the lowest digits. Can you rephrase the answer please (as a comment)
Comment: @AndrewMurray:  An example is that the remainder on dividing $123$ by $9$ is the same as dividing $12+3=15$ by $9$ because the difference is $120-12=12(10-1)=108$ which is divisible by $9$.
Answer: Simple way to see it: Take the number $N = \sum_{0 \le k \le n} d_k 10^k$ where the $d_k$ are the digits, modulo 9 you have:
$$
N = \sum_{0 \le k \le n} d_k 10^k
  \equiv \sum_{0 \le k \le n} d_k \pmod{9}
$$
since $10 \equiv 1 \pmod{9}$, and so $10^k \equiv 1 \pmod{9}$ for all $k$.


Como criar assinatura em asp.net com pagseguro

Question: Olá já pesquisei por todos os lados e não achei como integrar uma assinatura dentro do meu sistema em asp.net mvc com o pagseguro. Usei esse código e meu retorno não está dando certo quando adiciono esse preapproval !
<code> //**********************Inicio do procedimento para gerar uma compra pela API do pagseguro
                    DateTime now = new DateTime();
                    var payment = new PaymentRequest();

                    payment.Items.Add(new Item("0001", "Notebook Prata", 1, 2430.00m));
                    payment.Items.Add(new Item("0002", "Mochila", 1, 150.99m));

                    payment.Sender = new Sender("José Comprador","email@example.com",new Phone("11","56273440"));

                    payment.PreApproval = new PreApproval
                    {
                        Charge = Charge.Auto,
                        Name = "Seguro contra roubo do Notebook",
                        AmountPerPayment = 100.00m,
                        MaxAmountPerPeriod = 100.00m,
                        Details = string.Format("test"),
                        Period = Period.Monthly,
                        DayOfMonth = now.Day,
                        InitialDate = now,
                        FinalDate = now.AddMonths(6),
                        MaxTotalAmount = 600.00m,
                        MaxPaymentsPerPeriod = 1,

                    };

                    payment.Currency = Currency.Brl;

                    SenderDocument senderCPF = new SenderDocument(Documents.GetDocumentByType("CPF"), "12345678909");
                    payment.Sender.Documents.Add(senderCPF);
                    AccountCredentials credentials = new AccountCredentials("email@example.com","ABC1234DEF");

                    Uri paymentRedirectUri = payment.Register(credentials);

                    return Redirect(paymentRedirectUri.AbsoluteUri);

                    //**************************************************************************
</code>
Já olhei o método do @CiganoMorissonMendez que ajudo bastante porem é meu primeiro projeto e não tenho nenhum conceito sobre o assunto.
Answer: Resolvi o problema de assinatura sem necessitar items:
Usei e o Pré-aprovado que está no exemplo da pasta dotnet->source->example->preapproval->createPreapproval
Nisso tive que alterar PreapprovalSerializer.cs  por causa de um problema de data que foi gerado
Como explicado pelo Margatho adicionei o dateRead
<code>namespace Uol.PagSeguro.XmlParse <- NameSpace
internal static class PreApprovalSerializer <- Classe
internal static void Read(XmlReader reader, PreApprovalRequestResponse preApprovalResponse) <- Método

switch (reader.Name)
                    {
                        case PreApprovalSerializer.Date: <- Ini
                            DateTime dateRead;
                            DateTime.TryParse(reader.ReadElementContentAsString(), out dateRead);
                            preApprovalResponse.RegistrationDate = dateRead;
                            break; <- fim
                        case PreApprovalSerializer.Code:
                            preApprovalResponse.Code = reader.ReadElementContentAsString();
                            break;
                        case PreApprovalSerializer.Status:
                            preApprovalResponse.Status = reader.ReadElementContentAsString();
                            break;
                        default:
                            XMLParserUtils.SkipElement(reader);
                            break;
                    }
</code>
Sendo assim foi criado uma assinatura sem produto ! Mas não teria achado esse resultado sem ter entendido a conversa anterior.


Limitar o valor de TextBox tendo em conta a soma dos seus valores

Question: Eu tenho a seguinte tabela em que estão incluidos 3 textbox's correspondentes a percentagens, o que prentendo é que quando o utilizador insere os valores nas 2 primeiras TextBox's , o 3º valor apareça com o valor que sobra da subtração de 100 com a soma das outras duas textBox's. Por exemplo , se for escrito na 1º textb's o valor de 50 , e na 2º o valor de 25, terá de aparecer no 3º automaticamente  o valor de 25. Pode ser em Javascript ou Jquery.

           Peso das Nota

        <form>Testes: <input type="text" name="nome" id="mySelect11">
                  Exame:  <input type="text" name="nome" id="mySelect12">
                  Trabalhos:  <input type="text" name="nome" id="mySelect13">

Answer:

$("#mySelect12").on("blur",function(){
  var valor1 = parseFloat($("#mySelect11").val());
  var calc = 100 - (parseFloat($(this).val()) + valor1);
  $("#mySelect13").val(calc);
});

        Peso das Nota

    <form>

        Testes:
        <input type="text" name="nome" id="mySelect11">

        Exame:
        <input type="text" name="nome" id="mySelect12">

        Trabalhos:
        <input type="text" name="nome" id="mySelect13">


How to handle measurement inaccuracy? [improved]

Question: This is based on my old question but the question was too confusing. I've tried to make it clearer this time.
This is the kind of data we're dealing with:
<code>Group A

+--------+----------+----------+----------+------------------+
| Object | Prior #1 | Prior #2 | Prior #3 | Post-Measurement |
+--------+----------+----------+----------+------------------+
|   LUMN |       22 |       22 |       23 |               24 |
+--------+----------+----------+----------+------------------+
|   BQX9 |      112 |      108 |      115 |              115 |
+--------+----------+----------+----------+------------------+
|   LST1 |       33 |       30 |       32 |               35 |
+--------+----------+----------+----------+------------------+
|   FWWD |      291 |      288 |      287 |              293 |
+--------+----------+----------+----------+------------------+
|   LBQ0 |      173 |      277 |      165 |              270 |
+--------+----------+----------+----------+------------------+
</code>
Object is the identifier of the Object we're measuring and Prior #n are
the measurements that are done prior to treating the object. The Post-measurement is a single measurement we can do after having treated the object
in some fashion. We can not measure the same object twice after it was treated.
Since the physical property doesn't change between prior measurements all the variance in the measured values is measurement uncertainty. The measurement uncertainty is different for each object meaning the accuracy of our measurement depends on the specific object we're measuring. We don't know the exact value a prior measurement should measure but we know that it doesn't change during measurements because it's a physical property that doesn't just change randomly. The post measurement is of course also affected by uncertainty. In reality we have hundreds of objects.
How do we establish a useful overall (over every object, not per object) metric for

Did our treatment do anything and how much did it?

We could of course just compute the averages over the prior measurement and then do calculate the difference between the averages and the post-measurements but that's not convincing enough for us because our average could be 105 and a post-measurement of 107 would indicate a change of two but we know from prior measurements that we've also measured a 108 and thus the 107 is probably not a significant change at all.
We could of course assume a per-object normal distribution and then do significance testing to see whether the post-measurement is a significant change with p=0.95 and then repeat this for every object but how do we summarize this to an overall metric?
I think we're kinda looking for the average amount of change between pre- and post-treatment with 95% confidence as in "We can be 95% confident that our treatment makes a difference on average of at least +3lm"
Answer: Let $Y_{ij}$ be $j$-th measurement on subject $i$ , $X_{ij}$ = 1 for Post-treatment, = 0 for prior treatment. Fit a model
$$Y_{ij}=\beta_0 +\beta_1X{ij} + \gamma_i +\epsilon_{ij}$$
where $\gamma_i$ is object specific random intercept following normal distribution with mean 0 and variance $\sigma_e^2$, and $\epsilon_{ij}$ is error term following the normal distribution with mean 0 and variance $\sigma^2$.
$\beta_0$ is the mean of prior measurement. $\beta_1$ is change due to the treatment (or difference between post and prior measurements. So if $\beta_1 \ne 0$, it means treatment has effect of measurement. The random intercept $\gamma_i$ is used to incorporate the correlation between measurement from the subject.
Maybe you should add the Object as covariates into the model. But I do not know what Object means in your study.


Quando posso usar o .NET Framework 4.x e .NET Core no Windows, Linux e MacOS?

Question: Aplicação utilizando NET Framework 4.x pode ser executada em Windows, Linux e MacOS?
E aplicação utilizando .NET Core pode ser executada em Windows, Linux e MacOS?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer:
Aplicação utilizando NET Framework 4.x pode ser executada em Windows, Linux e MacOS?

Não, só Windows, e ele pode ser considerado obsoleto.

E aplicação utilizando .NET Core pode ser executada em Windows, Linux e MacOS?

Depende de como for feita e o que utiliza, pode. Não pode usar nada específico de um dos OSs citados (tem muita coisa que só roda no Windows), a não ser que saiba como fazer para rodar diferente em cada um, tem que fazer pensando para rodar nos 3, se é o que deseja. Veja O que é o .NET Core?.


Using Java lambda expression

Question: These are JavaScript:
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
function area(radius)
    {
        return Math.PI * radius * radius;
    };

How can I do the same thing in Java using the Lambda Expression? So far, what i understand is something like this:
(int fahrenheit) -> (5/9) * (fahrenheit-32);

But it shows error(illegal start type), i guess it's not correct.
Comment: Step 1: Open IDE.  Step 2: Write code.  Step 3: PROFIT!  (Read our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) and [edit] your question if you want a better answer.)
Answer: Using UnaryOperator<Double> and lambda you can do like this :
UnaryOperator<Double> toCelsius = f -> (5 / 9.0) * (f - 32);
UnaryOperator<Double> area = r -> Math.PI * r * r;

System.out.println(toCelsius.apply(50.0));  // 10.0
System.out.println(area.apply(10.0));       // 314.159265...

UnaryOperator<Double> is same as Function<Double, Double>
Answer: Java has a generic interface Function<T,R> which you can use here to store these in.  The first type parameter is the type of the function's input and the second one is the type of the function's return value.
You could write your functions as
Function<Double,Double> toCelsius = fahrenheit -> 5 * ( fahrenheit - 32 ) / 9;
Function<Double,Double> findArea = radius -> radius * radius * Math.PI;

Then when you want to use them, you could write things like
double freezing = toCelsius.apply(32);
double pizzaSize = findArea.apply(11);

As a side note, don't write 5 / 9 in Java - this is an expression of type int, and its value is 0.
Answer: I'd use the DoubleUnaryOperator functional interface to perform the task at hand and also has the benefit of not boxing primitive types to their corresponding wrapper type or vice versa when performing the computation.
example:
DoubleUnaryOperator toCelsius = f -> 5 * (f - 32) / 9;
DoubleUnaryOperator findArea = r -> r * r * Math.PI;

to retrieve the result:
double celcius = toCelsius.applyAsDouble(40);
double area = findArea.applyAsDouble(24);

Using Java lambda expression


nginx-ingress wont listen on different port number

Question: I am deploying an nginx ingress controller via helm3.  I am using the following values.yaml (Which specifically says to use port 81), but after I deploy it The controller still says it is listening on port 80.  Not sure what I am doing wrong.
<code>$ helm upgrade --install --namespace=default -f values.devops.yaml nic-default stable/nginx-ingress
$ kubectl get svc nic-default-nginx-ingress
NAME                        TYPE           CLUSTER-IP     EXTERNAL-IP                                                               PORT(S)                      AGE
nic-default-nginx-ingress   LoadBalancer   10.100.36.39   somedomain.com  80:30193/TCP,443:30265/TCP   7h53m
</code>
values.yaml
<code>clusterName        : dev
region             : us-east-1
tag                : v1.0.0

revisionHistoryLimit: 3
rbac:
    create: true
defaultBackend:
    enabled: false
serviceAccount:
    create: false
    name  : "nginx-ingress-default"
controller:
    kind                 : "Deployment"
    name                 : "controller"
    ingressClass         : "nginx-default-internal"
    replicaCount         : 1
    minAvailable         : 1
    minReadySeconds      : 5
    hostNetwork          : false
    extraArgs            :
        http: 81
    image:
        tag       : "0.30.0"
        pullPolicy: "IfNotPresent"
    config:
        keep-alive                   : "600"
        upstream-keepalive-timeout   : "600"
        enable-underscores-in-headers: "true"
        ssl-redirect                 : "false"
        force-ssl-redirect           : "false"
        use-forwarded-headers        : "true"  # https://github.com/kubernetes/ingress-nginx/issues/1957#issuecomment-462826897
    nodeSelector:
        namespace: default
    publishService:
      enabled: true
    containerPort:
        http: 81
    service:
        type       : "LoadBalancer"
        enableHttp : true
        enableHttps: false
        ports:
            http: 81
        targetPorts:
            http: 81
        annotations:
            service.beta.kubernetes.io/aws-load-balancer-internal                : 0.0.0.0/0
            service.beta.kubernetes.io/aws-load-balancer-backend-protocol        : http
            service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout : "500"
            service.beta.kubernetes.io/aws-load-balancer-proxy-protocol          : "*"
            service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags: "Cluster=dev,Type=k8s,Namespace=default"
</code>
Answer: I've just tried to install nginx ingress controller on a new eks cluster using the below command and its load balancer service got port 81:
<code> helm upgrade --install --namespace=default  nic-default stable/nginx-ingress --set 'controller.service.ports.http=81'

kubectl get svc | grep controller
nic-default-nginx-ingress-controller        LoadBalancer   10.100.9.106   81:31023/TCP,443:31864/TCP   27m
</code>
Not sure what's the problem on your side.
Note that this chart is deprecated. Use  https://github.com/kubernetes/ingress-nginx/tree/master/charts/ingress-nginx instead.


Significance of difference in means

Question: In "A Comparative Study of Nursing Home Residents …", Aigner et al. write (p. 20)

Acute visits were significantly higher for the nurse practiticoner/physician team at 3.0 visits per year (± 2.4) versus 1.2 visits per year (± 1.5) for the physician-only group (P <0.0001)

Furthermore, (p. 19)

The statistical analysis was performed using the chi-squared or Fisher exact test for comparisons of percent and Student t test for comparison of means

I always thought that if confidence intervals overlap by that much, differences can't be significant. Am I wrong?
Aigner, M. J., Drew, S., & Phipps, J. (2004). A comparative study of nursing home resident outcomes between care provided by nurse practitioners/physicians versus physicians only.  Journal of the American Medical Directors Association, 5(1), 16-23.
Comment: Reporting possible negative number of visits per years in the descriptive statistics looks a bit odd to me "1.2 visits per year (± 1.5)".
Comment: They're probably not confidence intervals for the mean because, as you pointed out, overlap of $(1-\alpha) \cdot 100\%$ confidence intervals is equivalent to rejecting the corresponding two-sample test of means at the $\alpha$ level (assuming the same distribution is used to generate both, e.g. $t$-distribution, which was probably used here).
Comment: The thought is correct, Macro, but the application seems a little bit off: [lack of] overlap of confidence intervals is definitely *not* equivalent to rejecting the hypothesis of equal means at the $\alpha$ level.  It's equivalent to a much stronger test than that.
Answer: The data aren't normal. I presume that the number of acute visits is an integer, i.e. you can't visit a patient 1.5 times. You either visit them once or twice.
As an example, here are some data:
Mean: 3.2 sd: 2.142
8 8 4 1 2 2 0 2 5 2 3 3 3 1 5 4 4 1 4 2

and
Mean:1.25 sd: 1.164
4 0 4 1 1 2 0 1 2 2 1 2 1 0 0 0 1 1 1 1

If you performed a t-test, you would get p=0.001
Comment: At first I thought this reply did not address the question, but then I realized it's pointing out that a t-test is probably inappropriate because the evidence is that the data are (a) few in number and (b) highly skewed. (Normality isn't really an issue with t-tests; normality of the *sampling distribution of the mean* is what matters.) Interestingly, a permutation test of the mean for these data gives a one-sided p-value of 0.00038 (n=100,000), suggesting a two-sided p-value around 0.0008, which is exactly what a Wilcoxon test produces. The t-test lacks a little power, but seems ok here.
Comment: @whuber How do you perform the permutation test of the mean?
Comment: @Antoni Resample repeatedly from the combined dataset. In `R` this could be done efficiently as `x <- scan(text="8 8 4 1 2 2 0 2 5 2 3 3 3 1 5 4 4 1 4 2");
y <- scan(text="4 0 4 1 1 2 0 1 2 2 1 2 1 0 0 0 1 1 1 1");
xy <- c(x, y);
x.n <- length(x);
s <- replicate(1e5,   sum(sample(xy, x.n)));
s <- s / x.n - (sum(xy) - s) / length(y)
stat <- mean(x) - mean(y);
mean(s > stat + 1/2*(s == stat))`. It takes less than one second.
Answer: They're probably not confidence intervals for the mean, but rather standard deviations from the data, just reported weirdly.
This interpretation is supported by the very confused presentation of results in the second quote.  Fisher's exact test is a) not the same as a chi-squared test, b) almost certainly inappropriate given most sampling schemes (both margins are seldom fixed).  And if they used both we'd want to know why.  Neither test compares percentages, although probably results are ultimately reported in percentages.  Finally, applying Students t with such low counts seems risky at best.
From the other side of the paywall its hard to say more, but I think you're seeing a weak analysis ambiguously presented.
Comment: Hi, thanks for your answer. It also seems to me that they are reporting something different than SD of the means. However, in defense of Aigner et al., they do not apply Fischers'exact here but Student's t test.

Significance of difference in means


How to Get Client IP Address using Asp.Net C# - When our Project is Hosted in IIS

Question: i am working in asp.net c#, in that i need to get client IP Address to display the client IP.
i am hosting my project in IIS 7, using the static ip i can connect my application..
i have to fetch the client IP using the following code. but i can't get correct ip address..
every time i get this ip 192.168.1.18..
i use the following code
private void GetIP()
    {
       string userip = Request.UserHostAddress;
        if (Request.UserHostAddress != null)
        {
            Int64 macinfo = new Int64();
            string macsrc = macinfo.ToString("X");
            if (macsrc == "0")
            {
                if (userip == "127.0.0.1")
                {
                    //ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Visited Localhost')", true);
                    lblIPAddress.Text = userip;
                }
                else
                {
                    lblIPAddress.Text = userip;
                }
            }
        }
    }

i am also using the following code also but it showing the hosted ip address like 192.168.1.5, where i am hosted my project in server..
public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            //if (ip.AddressFamily == AddressFamily.InterNetwork)
            if (ip.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return ip.ToString();
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }

i need the correct client ip address, any one help
Comment: This can be helpful http://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net
Answer: try this :

string IP = Request.UserHostAddress;
Answer: It was answered a while ago but theres a similar question here
How to Get IP Address? which uses the HTTP_X_FORWARDED_FOR and REMOTE_ADDR request variables. We used this in a project recently and its been working fine
Comment: sir its working fine when you hosted in cloud, but when we hosted in our own server (which is IIS) its not working.. so that i need help sir..
Comment: We used this on our IIS server and it worked still works
Comment: sir i checked once again, its also shows like this 192.168.1.18
Comment: @Surya you could try reading this http://stackoverflow.com/questions/6914457/why-does-servervariableremote-addr-returns-the-server-ip they seem to have the same problem,
Comment: it shows 127.0.0.1 when i execute the project, but when i hosted it shows 192.168.1.18..