Find maximum $2\sin 5x-3\cos x$.

Question: Is it possible to find the maximum of $2\sin 5x-3\cos x $ without using calculus nor numerical methods?
I suspect there is a way to play around with trig identities until the expression is only in terms of either $\cos$ or $\sin$. I have done some trials but have only managed to make the expression messier.
Comment: I doubt this classifies as a simplification, but we can express everything in terms of $\tan\frac{x}{2}$. If you would like I can post it as an answer.
Comment: Yes. that's perfect.
Comment: Ok.. It's kinda messy so wait a few minutes please.
Comment: Might have made an error on that. I check it again.
Comment: Where did this question come from? It might help if you tell us the motivation for asking this question.
Comment: @Cataline From a trigonometry high school book probably - I found it in my notes. I think this $\sin 5x$ must have been supposed to be $\sin x$.
Answer: what i have found is this expression
$$32\,\sin \left( x \right)  \left( \cos \left( x \right)  \right) ^{4}-
24\,\sin \left( x \right)  \left( \cos \left( x \right)  \right) ^{2}+
2\,\sin \left( x \right) -3\,\cos \left( x \right)
$$
and the first derivative with respect to $x$ is given by
$$f'(x)=32\sin(x)\cos(x)^4-24\sin(x)\cos(x)^2+2\sin(x)-3\cos(x)$$
Comment: A big mess. Good. The answer to my question seems to be "no".
Answer: We have
$$2\sin(5x)-3\cos(x)=\\2\sin(3x+2x)-3\cos(x)=\\2\sin(3x)\cos(2x)+2\cos(3x)\sin(2x)-3\cos(x)$$
We make use of the identities: $$\sin(3x)=3\sin(x)-4\sin^3(x)\\ \cos(3x)=4\cos^3(x)-3\cos(x)$$
and $$\sin(2x)=2\cos(x)\sin(x)\\\cos(2x)=1-2\sin^2(x)$$
Thus we obtain
$$2[(3\sin(x)-4\sin^3(x))(1-\sin^2(x))]+2[(4\cos^3(x)-3\cos(x))2\sin(x)\cos(x)]-3\cos(x)=\\16\sin^5(x)-20\sin^3(x)+6\sin(x)+16\cos^4(x)\sin(x)-12\sin(x)\cos^2(x)-3\cos(x)$$
We can now make use of the rather obscure identities $$\sin(x)=\frac{2\tan(\frac{x}{2})}{1+\tan^2(\frac{x}{2})}$$ and $$\cos(x)=\frac{1-\tan^2(\frac{x}{2})}{1+\tan^2(\frac{x}{2})}$$
to get an expression solely on terms of $u=\tan{\frac{x}{2}}$
Still,I am not sure if this will help though (in terms of not using calculus or numerical methods per request).
Comment: Just for fun, since your intent was of good will, this would take you to the following problem : what is the maximum of $$f(t)=\frac{3 t^{10}+20 t^9+9 t^8-240 t^7+6 t^6+504 t^5-6 t^4-240 t^3-9 t^2+20 t-3}{(1+t^2)^5}$$ I refuse to play with this monster.
Comment: As I said, the intent was good. But, back to serious, the plot this function is much less clear than the original one because the maximum is close to $x=\pi$ and the maximum will take place at $t=6.69357$. In this area, $f(t)$ is quite flat. Cheers :-)
Comment: @ClaudeLeibovici Haha I was planning of calculating it a little later on, but kudos to you sir for doing this hard work and than you for posting it! If it looks menacing to you I will not dare go near it either.
Answer: I suppose that you are allowed to plot the function for $0\leq x \leq 2\pi$. Doing it, you notice that the maximum is located close to $3$; let us say $\pi$.
So, use Taylor expansions around $x=\pi$ to get $$f(x)=2\sin (5x)-3\cos( x)=3-10 (x-\pi )-\frac{3}{2} (x-\pi )^2+\frac{125}{3} (x-\pi )^3+O\left((x-\pi
   )^4\right)$$ Ignoring all terms of degree higher than $3$, consider, as an approximation, that you need to find the maximum of $$g(x)=3-10 (x-\pi )-\frac{3}{2} (x-\pi )^2+\frac{125}{3} (x-\pi )^3$$ The derivative is $$g'(x)=125 (x-\pi )^2-3 (x-\pi )-10$$ which is just a quadratic. Solve it as usual and keep the root which is the closest to $\pi$; it will be $$x_*=\frac{1}{250} \left(3-\sqrt{5009}+250 \pi \right)\approx 2.8705$$ Now $$g(x_*)=\frac{539973+5009 \sqrt{5009}}{187500}\approx 4.7706$$
Using calculus (not simple), you would find that the maximum value of the function is $\approx 4.8613$ corresponding to $x\approx 2.8450$.
Comment: Isn't Taylor expansion contained in Calculus?
Comment: @choco_addicted. You are probably correct. May I confess that I do not know what are the boundaries of *calculus* ? At the time I took it, it was part of it but this was in France. It would very instructive for me if you tell what are, for you, the boundaries. I am serious asking this question. Thanks for answering. Cheers.
Comment: *Calculus 1*, written by Hong Jong Kim, deals with Taylor expansion in Chapter 3. [More info](http://www.yes24.com/24/goods/4283269?scode=029). Also *Calculus*, written by James Stewart, deals with it. [More info](http://www.amazon.co.uk/Calculus-International-Metric-James-Stewart/dp/0538498846/ref=sr_1_1?s=books&ie=UTF8&qid=1459687062&sr=1-1&keywords=calculus+james+stewart) I worry whether it is sufficient to answer you.

Find maximum $2\sin 5x-3\cos x$.


Ansible: clone repo or install helm chart from private github

Question: Any idea how to install Helm chart (tgz) from private Github repo using Ansible? Is it possible at all to do this using Github token only and not ssh key or maybe it is easier to clone private git repo first with Ansible and then install it?
Comment: What exactly is the command or task you are executing? git works just fine with checkout URLs with embedded authentication information.
Answer:
Personal access tokens can only be used for HTTPS Git operations.

GitHub documentation: using-a-token-on-the-command-line
The token can be used as a password when using https. So it might be necessary switch the remote from git to https when a token should be used as a password.
In general the token is mainly meant as a secyre authentication mechanism against the REST API:

As previously announced, beginning November 13th, 2020, we will no longer accept account passwords when authenticating with the REST API and will require the use of token-based authentication (e.g., a personal access, OAuth, or GitHub App installation token) for all authenticated API operations on GitHub.com.
GitHub announcement

The token could be used to manage the access to GitHub repos like so:
<code>- name: Read SSH public key to authorize
  ansible.builtin.shell: cat /home/foo/.ssh/id_rsa.pub
  register: ssh_pub_key

- name: Authorize key with GitHub
  local_action:
    module: github_key
    name: Access Key for Some Machine
    token: '{{ github_access_token }}'
    pubkey: '{{ ssh_pub_key.stdout }}'
</code>
Ansible github_key_module
But in my reading of the announcement it is not meant to replace ssh public key authentication for normal Git operations. So it should be possible to continue to clone repos from GitHub authenticating with ssh keys or with a token when using https protocol for the remote.
Comment: Thanks Henrik. I found the same, I was hoping it is possible to use token from vault only.


Issues on DCT transform: results are incorrect

Question: I am implementing DCT transform using this formula:

But the results are incorrect. For some 8 by 8 matrix,
 0  0  0  0  0  0  0  0
 210  210  210  210  210  210  210  210
 255  255  255  255  255  255  255  255
 210  210  210  210  210  210  210  210
 0  0  0  0  0  0  0  0
 210  210  210  210  210  210  210  210
 255  255  255  255  255  255  255  255
 210  210  210  210  210  210  210  210

The results I got after passing the data to dct transform function are:
1350.000000    0.000000    -0.000000    0.000000    0.000000    0.000000    -0.000000    -0.000000
  -250.897627    -0.000000    0.000000    -0.000000    -0.000000    -0.000000    0.000000    0.000000
  -0.000000    0.000000    0.000000    -0.000000    0.000000    -0.000000    0.000000    -0.000000
  -461.931139    -0.000000    0.000000    -0.000000    -0.000000    -0.000000    0.000000    0.000000
  -510.000000    0.000000    0.000000    -0.000000    -0.000000    -0.000000    0.000000    0.000000
  156.770200    0.000000    -0.000000    0.000000    0.000000    0.000000    -0.000000    -0.000000
  -0.000000    -0.000000    -0.000000    -0.000000    -0.000000    0.000000    0.000000    -0.000000
  -260.946562    -0.000000    0.000000    -0.000000    -0.000000    -0.000000    0.000000    0.000000

(Only 1st column has non-zero values)
The problem is that I was told that the correct results should be only non-zero values at upper left corner of the matrix. And I am not sure where might be wrong in my code. Can anyone help me? Thanks.
Here is my DCT code:
static double C(int val){
   if(val == 0)
    return 1.0 / sqrt(2.0);
   else
    return 1.0;
}

void dctTransform(int matrix[8][8], double dctMatrix[8][8]){
    int u, v, x, y;
    double temp;

    for(u=0; u<8; u++)
      for(v=0; v<8; v++){

         temp = 0;
         dctMatrix[u][v] = 0;

         for(x=0;x<8;x++){
           for(y=0;y<8;y++){
             temp += matrix[y][x]*cos(((2*x+1)*u*M_PI) / 16)*cos(((2*y+1)*v*M_PI) / 16);
            }
         }
         dctMatrix[u][v] = C(u) * C(v) * 0.25 * temp;
      }
}

Comment: But it should not affect the locations of non-zero values, right?
Comment: Yes. Switch x and y, get the same results.
Comment: Run the IDCT the results and see if you get your original values.
Answer: Aren't you supposed to first change the input values from 0..255 to -128..127? Haven't you also switched x and y in matrix[y][x]?
If I subtract 128 from the input values to center them around zero, and then switch x and y, your code at least gives me the correct values according to the example in Wikipedia.


Removing IE's scrollbar

Question: First of all, I don't want to just remove  it, I want to ensure that there is still scrolling capabilities there also.
This is because I would like to have a 'slide show' affect on the website, where you can click 'next' and before, however with the scroll bar there, you can just go through it.
I have hidden the scrollbar in other browsers using:
::-webkit-scrollbar {
    display: none;
}

for webkit browsers and overflow: -moz-scrollbars-none; for Firefox. However, when it comes to IE, I can't find anything to simply hide it.
I found these on the internet:
scrollbar-3dlight-color:;
scrollbar-arrow-color:;
scrollbar-base-color:;
scrollbar-darkshadow-color:;
scrollbar-face-color:;
scrollbar-highlight-color:;
scrollbar-shadow-color:;

I thought by changing the colour to transparent, it would disappear, but it did not (just reverts back to normal).
Is there a way I can simply hide the scrollbar (simply like display:none or something else), in IE? I am open to css and js options.
jsFiddle of problem
NOTE: Adding overflow:hidden; stops the page from going past the second div when clicking the a tag.
Comment: Your edit shows a severe lack of both understanding the provided answer and proper use of the shift / caps lock key.
Comment: I bolded it because I didn't want that answer @PeeHaa
Comment: As I stated: lack of understanding
Comment: I find this post quite offensive as the bold capital text feels quite shouty, we're here to help, not to take commands, if you need to explain something simply make your question clear instead of going bold-capslock mode.
Comment: @SidneyLiebrand, it's hard to convey how I am saying it. It's not that I am shouting, I just wanted to state that I wanted another method other than `overflow:hidden;`. Sorry.
Comment: @PeeHaa, If I use overflow:hidden, I can no longer use my mousewheel to get to off-screen elements. I still want to use my mousewheel to get around.
Answer: See here for fiddle using your current code
Try this trick
body, div, html{
    height:100%;
    width:100%;
    padding:0;
    margin:0;
}
body{
    overflow:hidden;
    position:fixed;
}
div{
    overflow-y:scroll;
    position:relative;
    right:-20px;
}

It offsets a scrollable div so its vertical scrollbar is outside the viewable area.
Comment: @BeatAlex - fixed...this was annoying me so I worked on it, please see revised answer
Comment: I know this, but this prevents scrolling on the page. I still want to be able to scroll, just without scrollbars showing (using `a` tags to name's and scrolling)
Comment: You can try adding:
Comment: Tried that, I'll update the question, that didn't do anything.
Comment: If I do `overflow:hidden;` and use an `a` tag to go to a div off the page, the page wont scroll.
Comment: @BeatAlex - I've updated with another example, which uses a CSS trick to hide the scrollbar
Comment: @ExtPro here is a jsFiddle of what I mean. http://jsfiddle.net/SKu45/ I just want the scrollbar to disappear whilst still using the mousewheel to get around
Comment: @ExtPro Yes and when I get to the second div, it stops working, similarly to `overflow:hidden;`.
Comment: Maybe I should close this and open another question as to why `overflow:hidden;` stops working after the second div scroll? That might be easier to understand?
Comment: There is no second div in the fiddle I've posted.
Comment: Yes, but when I apply this method to MY jsFiddle, it wont go past the second div.
Comment: I'm going to open another question which will be clearer. Thank you for trying to help me. I'll give you a +1 but since it wasn't the answer, I can't accept.
Answer: I have similar problem, I don't need scroll bars on main page, but i have to have inside of my page content like in div's and span's.
So I found solution like this:
body {
    -ms-overflow-style: none;
}
div, span {
    -ms-overflow-style: auto;
}

Removing IE's scrollbar


A question about the convergence of an integral

Question: I've a positive continuous function :
$$q : \mathbb{R} \rightarrow \mathbb{R^+}.$$
Assuming that the function $ t \mapsto t\cdot q(t) $ can be integrated (i.e.
$ \int_0^{x}{t\cdot q(t)dt}$ converges when $x$ tends to infinity).
I want to show that $x \mapsto \int_x^{\infty}{q(t)dt}$ can be integrated on $\mathbb{R^+}$.
Any ideas?
I already derived :  $$\lim_{x \rightarrow \infty}{x\cdot\int_x^{\infty}{q(t)dt}} = 0.$$
Answer: To me, the key idea would be noting the exchange of integrals
$$
\int_0^\infty \bigg( \int_x^\infty q(t) \, dt \bigg)\, dx = \int_0^\infty \bigg( \int_0^t dx \bigg) q(t)\,dt.
$$
This is valid since the integrand is nonnegative (Tonelli's theorem).
To be more precise, consider the function
$$
Q(t,x) = \begin{cases}
q(t), &\text{if }t>x, \\ 0, &\text{if } t\le x.
\end{cases}
$$
Then each side of the above equation equals $\int_0^\infty \int_0^\infty Q(t,x) \,dt \,dx$, and the use of Tonelli's theorem becomes easier to see.
Comment: That's annoying :) You could try, in the definition of $Q$, replacing the $0$ with $\frac32-\frac x{2t}$ when $\frac x3<t\le x$ (and leaving it $0$ when $t\le \frac x3$); now $Q$ is continuous. That choice makes the right-hand side of the first equation equal to $\int_0^\infty 2tq(t)\,dt$, which you're assuming converges. And I think it only increases the left-hand side, so the fact that the increased function is integrable implies that $\int_x^\infty q(t)\,dt$ is also integrable.
Comment: Hey, thank for your answer. I don't understand how you can apply the Tonelli's theorem here, because the domain of integration of the second integral $[x, \infty]$ depends on the free variable x. Can you be more explicit ?
Comment: @Adri That's a fair question - see edits above.
Comment: Thank you, it is now clear :). (but I can't use your proof because I know only a restrictive -and stupid- version of the Tonelli's theorem where the function have to be continuous...)
Comment: Haha, good hack, thank :)
Answer: I found this proof to be simple:
$$\int_0^a{\int_x^{\infty}{q(t)dt}} = [x\int_x^\infty{q(t)dt}]_0^a + \int_0^a{xq(x)dx} $$
And since :
$$\lim_{x \rightarrow \infty}{x\cdot\int_x^{\infty}{q(t)dt}} = 0$$
We have the result.
I think it works but it's not as quick as Greg Martin's proof.


How can I set a category link to show a custom page template?

Question: everyone!
So, I'm using a BreadCrumbs, the code is this:
//====== BreadCrumbs
function my_breadcrumbs() {
if(!is_front_page()) {
    echo '';
    echo 'Você está aqui: '."Início".'';
    if (is_category() || is_single()) {
        the_category('  ');
        if (is_single()) {
            echo '  ';
            the_title();
        }
    } elseif (is_page()) {
        echo the_title();
    }
    echo '';
    }
}

But I have a custom template page to show each category and when I'm in a post from a specific category, the BreadCrumbs show the link from category (returning a Not found page when clicked). I would like to know if there is a way to change this to call my custom template page. If so, how could I do this?
Comment: The standard way of using dedicated category template files is by adding their ID to the name of the file. For example: category-18.php (if that is what your theme is using). WP sould automatically look for this file when the breadcrumb has a link to that category.
Answer: You can create a PHP file like category-categoryname.php and put in child themes function.php and put below code in the file ( eg:- documentation )
<?php get_header();?>

                    <?php
                        echo '
';

                            $current_category = get_the_category();
                            $current_category_id = $current_category[0]->cat_ID;

                            foreach( get_categories(array('hide_empty' => 0, 'child_of' => 78 ,'orderby' => 'count' , 'order' => 'DESC')) as $cat ) :
                                 echo '

' . $cat->name . '

';
                                 process_cat_tree( $cat->term_id );
                             endforeach;

                             wp_reset_query(); //to reset all trouble done to the original query

                            function process_cat_tree( $cat ) {

                            $args = array(
                                 'category__in' => array( $cat ),
                                 'numberposts' => 6,
                                 'tax_query'     => array(
                                                    array(
                                                        'taxonomy'  => 'category',
                                                        'field'     => 'id',
                                                        'terms'     => 77,
                                                    ),
                                ));
                             $cat_posts = get_posts( $args );

                             if( $cat_posts ) :

                             echo '
';
                             echo '
 Documentation
';
                             foreach( $cat_posts as $post ) :
                             echo '
';
                             echo 'ID ) . '">' . $post->post_title . '';
                             echo '
';
                             endforeach;
                             if(count($cat_posts)>5)
                                 echo ' See all Articles
';
                             echo '
';
                             endif;

                             $next = get_categories('hide_empty=0&parent=' . $cat);

                             if( $next ) :
                             foreach( $next as $cat ) :
                             echo '

' . $cat->name . '
';
                             process_cat_tree( $cat->term_id );
                             endforeach;
                             endif;

                             echo '
';
                            }

                        echo '
';
                    ?>

<?php get_footer(); ?>


Mac's Apache virtual hosts playing up

Question: I'm hitting the most frustrating problem with the devlopment environment on my Mac at work (OS X 10.6.6, Apache 2.2.15, PHP 5.3.3 - all default installs with very little modification). Last night I started working on a new website, I added a virtual host and added a few domains to /etc/hosts to resolve to my local machine.
My hosts file entry looks like this:
10.10.11.199    dev.example.com
10.10.11.199    example.com

And my virtual host looks like this:
<VirtualHost *>
    DocumentRoot "/Volumes/Websites/ExampleClient/example.com/source"
    ServerName example.com
    ServerAlias *.example.com
</VirtualHost>

I'd like to think it's something stupid I've done, but the annoying thing is it was working last night! The only thing that's changed since then is that I restarted my machine this morning. The domain example.com works as expected, but dev.example.com doesn't, the request drops into the default virtual host at /Volumes/Websites/Personal/Rowan Manning.
Things I've tried:

Explicitly setting dev.example.com as a virtual host ServerName with no aliases
Restarting apache with sudo apachectl restart;
Restarting apache with sudo apachectl stop; sudo apachectl start;
Restarting my Mac (again)
Checking that the /Volumes/Websites/ExampleClient/example.com/source directory is OK
Checking the permissions for /Volumes/Websites/ExampleClient/example.com/source
Checking that I'm editing the right virtual hosts file by forcing it to error

I'm stuck! Any ideas?
Edit (21st March 11):
The problem seems to have resolved itself over the weekend. I haven't changed anything, yet again... I'm completely mystified but glad it's working!
Comment: Look at logs (error.log and access.log)
Comment: I just did, but there's nothing there to indicate a problem. The access log just shows requests to `/` and `/favicon.ico` and the error log contains nothing related to this (just some PHP errors and missing favicons etc.)
Comment: Do you have NameVirtualHost *:80 somewhere in your config?
Comment: I do have a `NameVirtualHost *` in my config @Marcin, see comments on @Jari's answer below for more details
Answer: Some thoughts:
1) Try adding the port number to the VirtualHost directive, like
<VirtualHost *:80>

Make sure that it matches with the port number of the default VirtualHost directive and the NameVirtualHost directive.
2) Try using IP address 127.0.0.1 instead of 10.10.11.199, if the server is on localhost.
3) Remember to reload the page in your browser (or better, restart the browser), and not just access the domain directly, after you have changed the configuration.
4) How does your default VirtualHost configuration look like?
Comment: Thanks Jari, I didn't mention but I have tried points 1–3 without any luck. My default virtual host is like this: ` DocumentRoot "/Volumes/Websites/Personal/Rowan Manning" `
Comment: Do you have ServerName defined for the default VirtualHost? Also, make sure you don't have DocumentRoot directives specified outside the VirtualHost blocks (in httpd.conf or somewhere else).
Comment: And, you could try sudo apachectl -t -D DUMP_VHOSTS if you'd like to see more information about your virtual host configuration.
Comment: Thanks for those (I didn't know the DUMP_VHOSTS bit - really useful) but still not working! Banging my head against the desk here... The annoying thing is that `example.com` and even `testing.example.com` work fine, but `dev.example.com` doesn't. I don't even understand how that's possible! There are no other virtual host configs that reference the example.com domain

Mac's Apache virtual hosts playing up


Ajaxly login/signup in bootstrap modal

Question: This is sample modal sample of boostrap modal

                <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

and this is a line trigger modal in header.html.twig,

 {{ 'SIGNUP'|t }}

goal: open login form in bootsrap modal.
I find the name of file I can customize user-login block , it's block--userlogin.html.twig
then my markup

                <button type="button" class="close" data-dismiss="modal">×</button>

Login

                <form method="post" action="{{ path( "user.login" ) }}"   role="form" name="loginform">
                    {% if error %}

{{ "Could not login" }}

{{ "A valid username and password is required to login." }}

                    {% endif %}

                        <input type="email" value="{{username }}"   name="_username" tabindex="1" class="form-control" id="email" placeholder="{{ "username or email :"|t}}">

                        <input type="password" class="form-control" id="pwd" ame="_password" placeholder="{{ "Password"|t }}">

                        <input type="checkbox"> Remember me

                    <button type="submit" class="btn btn-default">{{ "Sign In"|t }}</button>
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

but with this action action="{{ path( "user.login" ) }}" it redirect me to user/login page.
I want to know how can I login/signup usuer ajaxly in modal without redirect to user/login page?
Comment: Only +50? I will be building an ajax login/signup module soon for my D8 project.
Comment: @NoSssweat I'm not rich :D. 50 is good ;)
Answer: There are two questions:
1.) goal: open login form in bootsrap modal.
In your code by redirecting to a new path the page will reload, and not display a modal login.
But you don't need a new path, your form is already there. It is in the block content and you should be able to place {{ content }} in the bootstrap modal dialog like this.
block--userlogin.html.twig:

                <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

                {{ content }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

2.) ajaxifing the login (not reloading after submit)
For this there is some work to do, you can see this in the D7 module:
https://www.drupal.org/project/ajax_register
For D8 you need to code something similar.
Comment: @NoSssweat well done, tnx.
Comment: Thank you for for attention, but  I need  ajax login/singup more
Comment: can you provide ajax login syntax and snippets?
Comment: At the moment only D7 code exists: http://cgit.drupalcode.org/ajax_register/tree/ajax_register.module
Comment: Finally I did what I need with custom code :(, this is not solution for what I asked
Comment: @zhilevan where you able to do ajax form validation? Ex: Wrong password message appears inside your modal.
Comment: @NoSssweat finally I did what I want, thanks for your attention, yes I did it in modal. in modal if user not authorized I show boostrap danger message to him.
Comment: @zhilevan ok cool, I am putting the finishing touches to my module.
Comment: @zhilevan Why not post your solution/approach as and answer here, for other's looking for this exact same thing and landing here from Google? Like me :)
Answer: function YOUR_THEME_preprocess_page(&$variables) {
  // You will most likely want to show and render the form for anonymous users.
  $variables['login_form'] = FALSE;
  if (!\Drupal::currentUser()->id()) {
    $form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
    $render = Drupal::service('renderer');
    $variables['login_form'] = $render->renderPlain($form);
  }
}

Put {{ login_form }} in your twig file
Comment: what is this  ? you get rendered login form and pass it by variable to page.
No, what I ask about is , how can ajaxly login in boostrap modal
Comment: i am not very good in drupal 8, but logic is you need to do every thing at your own, means from model box containing login form, then hit an ajax request on your custom url made by hook menu and at hook menu callback function  you need to login finalize and return response. after getting response in ajax just reload the DOM. you are now logged in

Ajaxly login/signup in bootstrap modal


multilinearform over finite dimensional vector space is continuous

Question: How do I prove that a multilinearform over a finite dimensional vector space is continuous? So, think of a multilinear map $A:V_1 \times ... \times V_n \rightarrow W$. Why is this always continuous?(I am looking for a proof that does NOT use that $A$ is bounded.)
Comment: Because it's a polynomial in the coordinates, basically.
Answer: Write $V_j = span\{e^i_j\}$ and write
$$
A(x_1,x_2,\ldots, x_n) = \sum \alpha^1_{j_1}\alpha^2_{j_2}\ldots \alpha^n_{j_n} A(e_{j_1}, e_{j_2}, \ldots, e_{j_n})
$$
Now let $M$ be the max of all the terms $\|A(e_{j_1}, e_{j_2}, \ldots, e_{j_n})\|$.
Does that help?
Alternatively, perhaps induction on $n$ might also work.
Comment: This is of course the standard technique (as far as I know), but I wonder, is there any other way to obtain this result?
Comment: @Lipschitz There are only finitely many combinations of basis vectors, so the maximum is taken of a finite set.
Comment: why does this maximum exist?( I have troubles to see how your $e_{j_1},...,e_{j_n}$ are related to the span given by you)
Comment: ah, thank you Daniel Fischer, I did not understand the meaning of this notation.


Geometry problem, triangle, angles, exercise from 2022 local competition

Question: Problem:
Consider the triangle $ABC$, $\angle A = \angle B = 40^\circ$. The point $D$ on $AC$ is such that $\angle ABD=10^\circ$. Consider the point $E$ on $AB$ such that $BC=EB$.
Prove that $DE \parallel BC$.
Context: This is the reformulation (the conclusion is simplified) of an exercise from 2022 local competition. The official solution has -- in my opinion -- a big gap. They say:
Let $A'$ be symmetric to $A$ wrt $CE$. Then $AA'C$ is equilateral. From the sum of measures of angles in the triangle $AA'D$ we get that  $\angle ADA'=100^\circ$. Then $DE \parallel BC$. $\square$
The problem is that they took for granted that $E$ lies on $A'D$. This is equivalent to the conclusion and I don't understand how considering $A'$ can help.
My tries: Conclusion $\iff \angle AED = 40^\circ\iff \angle EDA = 100^\circ \iff AD=ED \iff E\in A'D$.
Comment: @DS, you're right. In the original proof they didn't use it. The colinearity of $A'$, $E$ and $D$ magically happens for them.
Comment: To verify that you made a faithful reproduction, can you post the entire problem/solution? Even a screenshot would be helpful.  $\quad$ It's not immediately clear to me how simple calculations show $ \angle ADA' = 100^\circ$ (without already assuming $DEA'$ is a straight line), so my guess is that they had to have done that already somewhere. Maybe that's what you meant by "the problem is that ..."?
Comment: @CalvinLin $\angle CAE = \angle CA'E = \angle CA'D$ where the last equality holds if $E$ lies on $A'D$. That, combined with $ACA' = 60^\circ$, gives the required result.
Comment: @DS Right, my point is that we had to assume E lies on A'D for a simple calculation.  I'm trying to figure out if that's what OP meant (hence the further clarifications to my comment), and if so it would have been better to show that directly (hence the request for the original solution).
Comment: This is equivalent to proving the reflection of $D$ lies on $AB$ (the point where the dotted line meets the blue one)
Comment: @DS $\angle DBA = 10^{\circ}$
Comment: @ShahainRDM oh, sorry, it was a typo. Mateo, I meant to say that you have not used the fact that $\angle DBA = 10^\circ$
Comment: @CalvinLin The conclusion was to prove that the area of triangles BEK and CKD are equal, where $\{K\} = BD\cap EC$. You're right. They assumed it in the whole proof.
Comment: @CalvinLin, I've changed my question to add a sentence: From the sum of measures of angles... This is precisely what they wrote.
Answer: Let $F$ be the intersection of $CA'$ and $AB$.
The goal is to show that $DC = CF$.
From there, $F$ is the reflection of $D$ along $CE$ and  $AEF$ is a straight line implies that it's reflection $A'ED$ is also a straight line (which is what OP wanted to show).
Let $BC = 1$.
Apply sine rule in triangle $BCD$: $DC / \sin 30^\circ = BC / \sin 50^\circ$, so $ DC = \frac{1}{2 \sin 50^\circ}$.
Apply sine rule in triangle $BCF$: $CF/ \sin 40^\circ = BC / \sin 100^\circ$, so  $CF = \frac{ \sin 40^\circ } { \sin 100^\circ}$.
Since $ \frac{\sin 40 ^\circ} { \sin 100^\circ} = \frac{ \sin 40 ^\circ } { 2 \sin 50^\circ \cos 50^\circ } = \frac{ 1 } { 2 \sin 50 ^\circ}$, so $DC = CF$ as desired.
Notes

If we used this route, we didn't really need to use $A'$ to complete the original problem.

We have $FE = DE = DA$, which gives us that $DEA$ is isosceles and similar to $CBA$, so $ DE \parallel  CB$.
Comment: How did you calculate that  $\angle CFB = 100^{\circ}$? Assuming that you used $\triangle CFB$ for your second sine rule calculation.
Comment: @ShahainRDM $\angle A'C E = \angle ACE = 30 ^\circ$. So $\angle A'CB = 40^\circ$ and thus $\angle CFB = 100^\circ$. (I was looking out for 40-40-100 triangles)
Comment: Ok, then by virtue of symmetry it follows that $DC = CF$ anyways and then $\angle DEC = 70^{\circ}$ and without any hassle it simply follows that $\angle DEA = 40^{\circ}$ as desired.
Comment: @ShahainRDM That is to complete the solution that OP posted? If so, I added how we can do so via another way in the notes. $\quad$  I'm focusing only on showing that $A'ED$ is a straight line (which is what OP asked for), instead of showing the "some simple calculations implies $DE \parallel BC$".
Comment: @CalvinLin, thank you for the answer. I didn't find a solution, since I tried very hard to reproduce their proof, without using trigonometry, but instead using some 'clever movement', like searching for equilateral triangles, some rotation, reflection, extension of a segment, searching for four points on a circle and so on.


Normalise scoring

Question: I'm trying to solve the following problem. Multiple people score multiple vendors. The problem is that some people are less critical than others which results in them giving higher scores in general. Both #people and #vendors is low. Thus if you just sum all the scores for one vendor, the person being more generous has a bigger impact on the outcome.
The strategy I applied first was:

calculate z score within one person's scores
Map to 0 - 1 range within person's scores
Divide each score of person by sum of his scores.

This way I keep the proportionality of their scores and the total "points" they gave is 1, making it equal for everyone.
Is this the correct way to tackle this problem or not?
Answer: If I understand correctly, you are trying to get a mean score for each vendor and you have multiple raters (people) who rate the vendors, but their scores are unreliable (because they consistently underrate or overrate a vendor).
In that case one option would be to z-score (standardization) the raters' scores (not the vendors'), such that all scores for each rater are on the same scale. So if a rater consistently assigned higher scores than usual, this higher score will become his "normal" score - his average.
After that you can estimate a mean z-score for each vendor. This will change the interpretation of the score. What you will get is a measure of which vendors are above average (>0) and which are below average (<0), and the magnitude will tell you by how much they are far from average (based on the raters' opinion).
Comment: Yes that is exactly the problem.

I think that's what I did? Except I put that on a different scale? After step 1 I just translated the z score and scaled it to the range of [0..1] and then normalized divided it for one person by the total amount of scoring they did so they in total only gave one point. This would give the same results, no?
Comment: @Spyral It's not exactly the same, I would say your additional steps are unnecessary.

Normalise scoring


Convert arbitrary Prolog term to one structurally equivalent with all variables

Question: Wondering how to do this in SWIProlog, e.g., convert term
    [elvis, [was, dead]]
into
[A, [B, C]]

How to do this with arbitrary data structures?
For example, convert term
ty(simple, _)

into
ty(A, _)

and convert term
    ty(ty(complex, _), _)
into
ty(ty(A, ), _)

Comment: What do you expect `G` to be in `ty(T,G)` for: `T = [a|non_list]` `T = [[]]`? It seems you do not want to generalize the `[]` away, but this is quite tricky.
Answer: Your examples suggest that you want a term template constructed from a term. As a bound term can be depicted as a tree, the construction of the term template can be seen as replacing the bound tree leaves with fresh variables. Therefore, a solution is to traverse the tree and do the necessary transformation to its leaves. This can be accomplished by using the standard functor/3 and =../2 predicates. For example:
% template(@term, -term)

template(Term, Template) :-
    (   var(Term) ->
        true
    ;   Term = [_| _] ->
        template_arguments(Term, Template)
    ;   functor(Term, Functor, Arity),
        functor(Template, Functor, Arity),
        Term =.. [Functor| Arguments],
        Template =.. [Functor| TemplateArguments],
        template_arguments(Arguments, TemplateArguments)
    ).

template_arguments([], []).
template_arguments([Argument| Arguments], [TemplateArgument| TemplateArguments]) :-
    (   compound(Argument) ->
        template(Argument, TemplateArgument)
    ;   % variables and atomic terms
        true
    ),
    template(Arguments, TemplateArguments).

Some queries:
?- template(ty(ty(complex, _), _), Template).
Template = ty(ty(_G1211, _G1212), _G1191).

?- template([elvis, [was, dead]], Template).
Template = [_G1196, [_G1202, _G1205]].

?- template([elvis, [was, dead]| _], Template).
Template = [_G1199, [_G1205, _G1208]|_G1117].

Maybe you can adapt this solution to solve your problem?
Comment: Sometimes the 2nd argument shares variables with the first and sometimes not.
Comment: The special case for `[_|_]` seems to introduce the problems. Similar problem in `template_arguments/2`
Comment: Yes thanks very much, I had a feeling the goal was not far from the reach of some standard built-ins, but I was frustrated by the action of `=@=/2` which does what I wanted in a way, but only for terms instantiated by variables.  At least I'm glad I did not miss some incredibly easy solution or library function, as this solution seems somewhat involved and has to completely decompose the term.


Equivalence relations - countability

Question: The equivalence relation $\sim$ on the set of transcendental $X$ is defined by the following property:
$x\sim y$ if and only if $x-y\in \mathbb{Q} $.
Now the set $Y$ is the set of equivalence classes generated by $\sim$.
How do we know that a particular equivalence class $[x]$ is countable?
Comment: Typing note: `$~$` is used to increase space between objects while `\!` is used to decrease space between objects.  E.g. `$1~~~2\!3$` produces $1~~~2\!3$.  To have the symbol `~` appear as a symbol, use instead `$\sim$` to produce $\sim$.
Comment: Hint: $[x] = \{ z \mid \exists q \in \Bbb{Q}\cdot z = x + q\}$.
Answer: Hint. If $a$ is a representative of the class $[x]$, then observe that
$$
[x]=\{a+q : q\in\mathbb Q\}.
$$
Hence $|[x]|=\aleph_0$.

Equivalence relations - countability


Why have I more spelling errors (CA1704 rule) in VSTS?

Question: I forced Code Analysis execution on VSTS (with Hosted2017 agent) to build a VS2017 solution using .NET framework 4.6.1. But I don't have the same spelling errors (CA1704 rule) on VSTS and on my machine with VS2017 Enterprise. On my machine, I fix all spelling errors. But on VSTS, I have more spelling errors !
MSBUILD : error CA1704: Microsoft.Naming : Correct the spelling of
How can I fix this problem ?
Comment: How do you specify code analysis rule? Project properties or MSBuild argument? Which rule you used? Can you share the detail log on the OneDrive? (Set system.debug variable to true, then queue build and share this log)
Comment: I created my ruleset file in VS2017 in project properties and on the MSBuild task on VSTS, I added these arguments : /p:RunCodeAnalysis=true;CodeAnalysisRuleSet=../MyProject.ruleset
Answer: Ok, I found the problem. FxCop was executed in a different culture on my VS2017 (french) and on VSTS (english). I changed the language of my VS2017 in Options\Environment\InternationalSettings to English and restart VS2017. Now I get the same list of Code Analysis errors on VSTS and on my VS2017 !


Translating Equations to Algorithms

Question: I can't understand equations. But I'm a software engineer. I think the brevity of the equation is confusing to me where a program spells it all out.
Trying to translate the equation for a bezier curve into javascript. The equation on wikipedia appears as-

Translating this to javascript looks like this-
function B(t, p0, p1, p2, p3) {
  return Math.pow((1 - t), 3) * p0 + 3 * Math.pow((1 - t), 2) * p1 + 3 * (1 - t) * Math.pow(t, 2) * p2 + Math.pow(t, 3) * p3;
}

But this doesn't make sense. A point is made up of an x and y coordinate. How can multiple values be represented by a single value in a meaningful way? How is this equation usable?
Comment: The equation as stated is actually two equations, one for the x-component and one for the y-component. All the same operations are done in each, just on different components of each vector. You might find it easier to work with each component separately, or set up something to do both, although I don't know how the mechanics of javascript will do that.
Comment: Are not the $\mathbf{P}_i$ vectors, i.e. ordered pairs of coordinates?
Comment: Maybe. But how would you write that? For the first operation do you multiply `Math.pow((1 - t), 3)` by P0.x and P0.y?
Comment: Back on this trying to figure it out. I must have written func B wrong?

http://jsbin.com/reyebokoqe/edit?html,console,output
Comment: Updated version-

http://jsbin.com/vedicediko/1/edit?html,console,output
Comment: At this point I got it working by copying javascript I've found. But I'm trying to figure out why **I** wasn't able to do it. I've got to do Linear, Quadratic, Cubic, Quartic, and Quintic functions.
Answer: As others have mentioned, the "$\mathbf{P}$" things are 2D points; each of them has an $x$ coordinate and a $y$ coordinate. Or, actually, in some situations, the $\mathbf{P}$ objects might be 3D points having $x$ , $y$ and $z$ coordinates.
So, suppose $\mathbf{P}_0$ has coordinates $(x_0,y_0)$, and, similarly, $\mathbf{P}_1 = (x_1,y_1)$, $\mathbf{P}_2 = (x_2,y_2)$, and $\mathbf{P}_3 = (x_3,y_3)$. Then the necessary code is:
s = 1-t
f0 = s*s*s
f1 = 3*s*s*t
f2 = 3*s*t*t
f3 = t*t*t

x = f0*x0 + f1*x1 + f2*x2 + f3*x3
y = f0*y0 + f1*y1 + f2*y2 + f3*y3

There are ways to write this that involve slightly fewer arithmetic operations, but I thought clarity would be more important than performance, at this stage.
I don't know much about Javascript, but in other languages (C# for example) you would create a Point class and you would overload the "+" and "*" operators. Then you woud be able to write code that looks exactly like the formula you cited:
p = f0*p0 + f1*p1 + f2*p2 + f3*p3

Here f0*p0 represents the number f0 multiplied by the point p0, and so on.
Comment: Thanks. Others comments as well as your answer definitely points me in the right direction.

Translating Equations to Algorithms


UIButton category issues

Question: I have made extension for UIButton class. Now if I use it everything works good. But I have another class that create for me array with UIButton objects and here I have some problem.
I have Helper class with method that return for me array with UIButton objects.
In ViewController.m in viewDidLoad callback I request for this array and also here in ViewController.m I import my UIButton+Extension.m
So, now I have extension for each UIButton object that I will use in ViewController.m
But if I use extension I have got error on method that call
[thumbButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:11.0]];

but if I don't use extension this method invoke correct.
this is my UIButton+Extension.h file
#import <UIKit/UIKit.h>

@interface UIButton (extension_button)

- (void)centerButtonToView:(UIView *)view;
- (UIImage *)cropeImage:(UIImageView *)imageView;

@end

this is my UIButton+Extension.m file
#import "UIButton+Extension.h"

@implementation UIButton (extension_button)

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)centerButtonToView:(UIView *)view {
    CGRect rect = view.frame;
    CGRect rectSelf = self.frame;
    rectSelf.origin.x = (rect.size.width / 2.0f - rectSelf.size.width / 2.0f) + rect.origin.x;
    rectSelf.origin.y = (rect.size.height / 2.0f - rectSelf.size.height / 2.0f) + rect.origin.y;
    self.frame = rectSelf;
}

- (UIImage *)cropeImage:(UIImageView *)imageView {
    CGRect rect;
    rect.origin.x = self.frame.origin.x - imageView.frame.origin.x;
    rect.origin.y = self.frame.origin.y - imageView.frame.origin.y;
    rect.size.width = self.frame.size.width;
    rect.size.height = self.frame.size.height;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect drawRect = CGRectMake(-rect.origin.x,-rect.origin.y, imageView.image.size.width, imageView.image.size.height);
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));
    [imageView.image drawInRect:drawRect];
    UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return subImage;
}

@end

Helper.m (method that return array for me and here I have problem on setFont method)
+ (NSMutableArray *)createThumbnailsForCropSize {

    CGFloat width = 0.0f;
    CGFloat start_pos = 0.0f;

    if (IS_IPHONE) {
        width = 320.0f;
        start_pos = 62.0f;
    }
    else {
        width = 768.0f;
        start_pos = 286.0f;
    }

    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSArray *resolutionArray = [NSArray arrayWithObjects:@"30x40",@"33x48",@"35x40",@"35x45",@"36x47",@"37x47",
                                @"40x50",@"40x60",@"43x55",@"45x50",@"50x50",@"50x70", nil];
    NSInteger pos_x = start_pos;
    NSInteger page = 0;
    for (NSInteger idx = 0; idx < 12; idx++) {
        if (idx%3 == 0 && idx != 0) {
            page++;
            pos_x = start_pos + width * page;
        }
        UIButton *thumbButton = [[UIButton alloc] init];
        [thumbButton setTag:idx];
        [thumbButton setFrame:CGRectMake(pos_x, 13, 60, 60)];
        [thumbButton setTitle:[NSString stringWithFormat:[resolutionArray objectAtIndex:idx]] forState:UIControlStateNormal];
        [thumbButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica" size:11.0]];
        [thumbButton setTitle:@"!00" forState:UIControlStateNormal];
        [thumbButton setBackgroundImage:[UIImage imageNamed:@"block_without_photo.png"] forState:UIControlStateNormal];
        [arr addObject:thumbButton];
        pos_x += 68;
    }
    return arr;
}

Answer: You need to remove initWithFrame: from your category. By including it, you are removing the normal implementation, and this will be preventing your buttons from being created properly, you will in fact be returning a UIControl.
Calling the super implementation in a category does not call UIButton's implementation, but the superclass of UIButton - UIControl. Categories are different to subclasses. (And you shouldn't subclass UIButton either, as it is a class cluster).
If you do have specialist initialisation code in there, you will have to add it to a separate method and call it during your creation loop.
Comment: `UIButton` is not a class cluster. Its class method `buttonWithType:` might not return an instance of your subclass, but methods in the `init` family will.

UIButton category issues


Showing/Hiding Content-Type Fields Based On User

Question: I have a content-type that has many fields for different translations. How do I set it up in a way that it shows the translation field based on user selection only. I mean user selects his/her language, then only that content-field appears on the post.
Appreciated...
Comment: I don't think you will have this feature out of the box, why didn't you use the Mutli language features? That'd be the way to go. Otherwise i would just otheride that node template and add some custom code to display only certain field depending on the user preference..
Comment: As I figured, Multi-Language thing is for the entire site. I have different types of data under different content-types, only one content type needs translation.
I think I should set some cookie using PHP code, and based on that I should show one CSS block of translation and hide rest of them, I mean using display:none,  What you think?
Answer: Yeah you could do that as well, though if you have lot of data hidding things on the server side would be better. You could just override the node template page, with something like :
node--nodeType.tpl.php, then in the variables of that page you will have your node with all its Fields available, you can then do a simple check (cookie or sessions) to render appropriate language.
Comment: Thanks, this is good, the unnecessary data does not need to be downloaded just for the browser to hide it.


D3 graph not loading.. Showing blank page D3.Js and python

Question: I am new to D3js and python. I am trying to load data from postgresql and pass the JSON to D3js and draw a line chart. I am receiving error
  <anonymous> hello:61
  d3.json/<() d3.v2.js:2950
  ready() d3.v2.js:2940
  d3.xhr/req.onreadystatechange().

Below is my D3 js call.
d3.json ("http://184.108.40.206/books/",function (error,data) {
if (error) return console.error(error);
console.log(data);
data.forEach(function(d) {
d.year = parseDate(d.year.toString);
d.buys = +d.buys;
});

My parsedate function below:
var parseDate = d3.time.format("%y").parse;

JSON:
{
"data": [
{
  "buys": 5841,
  "year": "1986"
},
{
  "buys": 54,
  "year": "1954"
},
{
  "buys": 176,
  "year": "1967"
},
{
  "buys": 9389,
  "year": "1991"
},

My full code below:
<!DOCTYPE html>
meta charset="utf-8">
<title> flask+D3 hello </title>

May i know where i am going wrong?
Answer: from d3.parseDate Error cannot read property 'forEach' of undefined:

d3.json(url[, callback])
Creates a request for the JSON file at the specified url with the mime
  type "application/json". If a callback is specified, the request is
  immediately issued with the GET method, and the callback will be
  invoked asynchronously when the file is loaded or the request fails;
  the callback is invoked with two arguments: the error, if any, and the
  parsed JSON. The parsed JSON is undefined if an error occurs. If no
  callback is specified, the returned request can be issued using
  xhr.get or similar, and handled using xhr.on.

so print the error and double check the url.
Comment: Hi. I printed the error and changed the URL. Still the page is not loading. I am getting a different error. Have updated the thread above. Pls assist


Confusion about Definitions of rings

Question: Yesterday we cover the definition of rings briefly in class. My teacher wrote that an algebraic structure is called ring  $(R,+,.)$ if the set R is abelian group under addition, and multiplication is associative over addition etc.Here, what I stuck in is $(R,+,.)$, all books use addition and multiplication with the definition of R must be group under addition.
My question is that should we always use addition and multiplication as binary operations while defining the rings. Moreover, is the order of binary operations important. For example, if it were $(R,.,+)$ instead of $(R,+,.)$, then would we still say that it must be group under addition ? Otherwise, would we say that it must be group under multiplication ? Briefly can we say that if it is defined as $(S,\alpha,\beta)$, then it can be a ring if the set $S$ is an abelian group under operation of $\alpha$ no matter what $\alpha$ is, and it satify other conditions under $\beta$ no matter what operation the $\beta$ is. So, the order of binary operations determine the role of opeartions in definition. Can you explain or correct me ?
Comment: It rather looks like you have qualms about _notation_ rather than _definition_.  There really isn't any universal truth to why we use the notation we do.  We try to pick it to be predictable, convenient, and memorable as possible so that it is easy to work with.  The symbols don't determine the meaning, we choose the symbols to remind us of the meaning.
Comment: @rschwieb what do you think about my thought about the notation. Can you please look at my comment under the accepted answer
Comment: `hımm, so the order of operations determine their roles.` Yes and no. "Yes" because _that's the convention most of us use_ and "no" because it could just as well have been a convention to do it the other way around.  The order doesn't determine their roles, our _convention_ to write it in that order is what alerts us to which is which.  I think mainly this is an outgrowth of considering $(R,+)$ first as an abelian group, then layering on another operation after the fact to extend it to $(R,+,\cdot)$.  The second operation is "less nice" and "later" somehow.
Comment: @rschwieb look at the [comments](https://math.stackexchange.com/questions/2768789/what-are-the-binary-operations-of-a-ring) between me and Eric, I think that you miss the thought of ring is an ordered triple
Comment: @rschwieb look at [here](https://student.cs.uwaterloo.ca/~zj4li/notes/ringtheory.pdf)
Comment: Such (syntactic) matters are considered more precisely in model theory, e.g. see Hodges' remarks [here](https://math.stackexchange.com/a/41697/242).
Comment: @BillDubuque **chatgpt says**: we can use different symbols to denote the operations in a ring, as long as the operations satisfy the axioms of a ring. The symbols of addition and multiplication are commonly used, but they are not mandatory.
For example, in a Boolean ring, the addition operation is defined as the Boolean operation of OR, and the multiplication operation is defined as the Boolean operation of AND. In this case, we use the symbols "+" and "·" to denote the operations, respectively.
Comment: @BillDubuque the order of binary symbols in ring notation is important. The symbols used for addition and multiplication in a ring are typically denoted as "+" and "⋅" respectively. However, the order in which these symbols are written can affect the interpretation of the expression.
The most common way to write the expression is to use the infix notation, where the operator is placed between the operands. For example, if a and b are elements of a ring R, we write a + b and a ⋅ b to denote the addition and multiplication operations, respectively.
Comment: In terms of the axioms of a ring, the "+" symbol is typically used to denote the operation that satisfies the axioms of a commutative group, which include closure, associativity, the existence of an identity element, and the existence of inverse elements.
Comment: @BillDubuque I agree with OP, what do you think ?
Comment: @Not As is usual with overloaded math notation what matters is that it is uniquely readable *in the ambient context*. In many contexts it is unambiguous which operations are addition and multiplication so no further conventions are needed to distinguish them. Otoh if the notation is to be parsed by a machine (e.g. a computer algebra system) then more pecise notation may be necessary.
Comment: Related: some algebraic structures (e.g. groups) have a variety of common axiomatizations using various operations.  But the choice of which operations to use in the definition may be constrained by the context, e.g. for groups we need to include the inverse operation in the signature in order for the universal notions of homomorphism and substructure to specialize to the classical notions for groups, cf. [here](https://math.stackexchange.com/a/41845/242).
Answer:
My question is that should we always use addition and multiplication as binary operations while defining the rings.

Do you mean the symbols $+$ and $\cdot$? You don't have to, but by convention one of these (under which $R$ is an abelian group under addition) is called addition, and the other is called multiplication, so these are the most natural choices of symbol to use.
(This is especially true since rings are meant to be "integer-like", and the integers naturally have notions of addition and multiplication. You could even argue that this is reflected in the name of the structure, in a sense, though this is tenuous. Some worthwhile reading on the etymology here on MO.)
Of course, in other contexts, especially with particular examples, others could be used.

For example, if it were $(R,.,+)$ instead of $(R,+,.)$, then would we still say that it must be group under addition ?

This is another matter of convention. If you are consistent in whatever framework you're working in (e.g. homework you're writing, textbook you're writing, paper you're writing), and your definitions clear, I don't think anyone is going to care about the order, so long as you still maintain the obvious that

$+$ is addition
$\cdot$ is multiplication
$(R,+)$ is an abelian group
$(R,\cdot)$ satisfies its list of axioms
distributivity is satisfied

This doesn't address the implicit question of "okay, so why do we list addition first in the tuple?" to which I have no good answer.
On the other hand, if your question is "can I notate addition by $\cdot$ and multiplication by $+$?", you can, but there is the natural follow-up question of "why in the world would you use such a counterintuitive notation for a generic ring?" Give the operations whatever symbols you please and the technicalities will work out, but the choice of notation should be deliberate and made for a reason.
Comment: actually this doesnt fully answer my question. I am looking for the definiton of ring without depending on addtion and multiplication. what do you think about my alpha beta definition ? I am trying to understand that whether the order of operation in parentheses determine their role. Or , the order of opeartions doesnt affect their roles in definiton of ring but their functions determine their roles.
Comment: The symbols chosen to denote the operations, and the order of the symbols in the notation for a ring is totally irrelevant to the underlying definition. The symbols are a convention established so you don't have to say the entire definition over again when writing a new ring.  Most people use "+" and "$\cdot$" and put them in the order $(R,+,\cdot)$ because it uses familiar symbols and is memorable once explained. For sure you could obscure things and use $\alpha$ for addition and $\beta$ for multiplication and scramble the symbols into $(\beta, R, \alpha)$... at the cost of causing confusion.
Answer: You can say that $(R,\alpha,\beta)$ is a ring for any binary operations $\alpha$ and $\beta$ such that $(R,\alpha)$ is an abelian group and [blah blah blah whatever else]. For the sake of learning I'd say pretend that the order matters so the second element $\alpha$ of the tuple will be the one for which $(R,\alpha)$ is a group. But if you walk into a seminar one day and say $(R,\cdot,+)$ is a ring nobody is going to be mad or confused as long as you really mean $(R,+)$ is the abelian group (you would never even write the full triple in this circumstance anyways).
Comment: @junior_student Yes you can take this as correct. The truth is any rings people actually talk about in practice have a clear addition operation, a clear multiplication operation, and we don't bother to write the whole triple $(R,+,\cdot)$; rather we just say "let $R$ be a ring". So people don't really actually worry about this kind of thing in practice, there are never situations where it's ambiguous which operation is the "addition" and which is the "multiplication"
Comment: hımm, so the order of operations determine their roles. The first operation from the left side is used to check whether the set is group and the last operation determine whether the set satisfy the other conditions. IN $(R,\alpha,\beta)$ , we check whether it is abelian group with respect to $\alpha$, and in $(R,\beta,\alpha)$ we check whether it is abelian group with respect to $\beta$,. Am I right ?

Confusion about Definitions of rings


Notepad++ regex -> newLine

Question: I use Notepad++ and I need to delete all lines starting with, say "abc".
Attention, I don't need to replace the line starting with "abc" with a empty line, but I need to completely delete these lines.
How do I proceed (using regex, I suppose)?
Comment: This may help you http://stackoverflow.com/questions/918158/how-to-delete-specific-lines-on-notepad
Answer: Try replace
^abc.*(\r?\n)?

with
nothing

The ^ indicates the start of a line.
The . means wild-card.
The .* means zero or more wild-cards.
x? means x is optional.
The \r?\n covers both \r\n (generally Windows) and \n (generally Unix), but must be optional to cover the last line.
Comment: Yes. And << (^|\r?\n)abc.*\r?\n >> for "abc..."
Comment: Does not work for last line of the file, when the file has no new line at the end.
Answer: Search for this regular expression
^abc.*\r\n

Replace with nothing.
Comment: Does not work for last line of the file, when the file has no new line at the end.
Answer: Try the regex \nabc.* in "Find and Replace" --> "Replace"
Leave "Replace With" field empty.
EDIT : This won't work with first like (because '\n' means "new line")
Answer: Searching a little bit more on regex in Notepad++ I discovered that the new line character is not \n as I expected (Windows), but the \n\r.
So, my regex replace expression should be:
Find: abc.*\r\n
Replace with: (nothing, empty field)
Comment: This would match lines with abc in the middle also.
Answer: Press  Ctrl+H to bring up the Replace window. Put
^abc.*(\r?\n)?

in the Find what and leave Replace with empty. Select Reqular expression and hit Replace All.
This reqular expression handles all the edge cases:

When the first line of the file starts with abc
When the last line of the file starts with abc and there is no new line at the end of the file.

Notepad++ regex -> newLine


Loss function for generalized linear models

Question: What is the loss function in the GLMs. We only deal with the mean posterior of response given input $E[Y|X]$, therefore I assume underneath we assume $L_2$ loss. Is that correct? What about other loss functions (e.g. $L_1$ loss or other surrogate loss functions common in ML)? Please point me to relevant documents if I'm just very confused.
Answer: GLMs are fit via maximum likelihood so if you want to view it as a minimization, you'd have the negative (log) likelihood as your loss.
For some likelihoods (like a Gaussian linear model) this is equivalent to minimizing an $L_p$ norm but it doesn't have to be. A standard example is logistic regression where the log likelihood for $n$ observations is
$$
\ell(\beta\mid y, x) = \sum_{i=1}^n y_i \log g^{-1}(x_i^T\beta) + (1-y_i)\log(1 - g^{-1}(x_i^T\beta))
$$
for $g = \text{logit}$ being the link function.
Comment: Maybe I can elaborate a bit more on my question. In general we are trying to minimize $E[L(\delta(X),Y)]$. Assuming that loss function $L$ is $L_2$, then the optimal (Bayes?) estimator is found by $\delta(X) = E[Y|X] = g^{-1}(X^T\beta)$, right? Now if instead of $L_2$ we had $L_1$ the answer would be $median(Y|X)$. In that case, would the answer still be equal to $g^{-1}(X^T\beta)$? What if I use a different loss?
Comment: @AhmadKhaled in practice the least squares solution will not be quite the same as the maximum likelihood solution as the logs in the log likelihood make it much worse for that one to be confidently wrong (e.g. for a single point, with least squares the worst case loss is bounded above by $1$ which is for predicting a $0$ when $y_i = 1$ or vice versa; for the MLE the worst case for one point is unbounded since $1 \cdot \log 0 = -\infty$). I've written about this a bit [here](https://stats.stackexchange.com/questions/326350/).
Comment: I think I have a better picture now. Assuming other loss functions won't change the underlying problem of estimating the best parameter for $g^{-1}(X^T\beta)$. Assuming $L_1$ loss and solving $median(Y|X)=g^{-1}(X^T\beta)$ won't change anything as the problem is still to find the best $\beta$ (because we assumed a linear model in parameter space anyways). In most cases, anything other than mean is useless, for example in Bernoulli distribution the median is either 0 or 1, and solving $g^{-1}(X^T\beta)=0$ or $g^{-1}(X^T\beta)=1$ won't give us a useful beta.


Maximum value of sum of sines

Question: $$\begin{array}{ll} \underset{a,b,c,d,e}{\text{maximize}} & \sin (a) + \sin (b) + \sin (c) + \sin (d) + \sin (e) \\ \text{subject to} & a + b + c + d + e = 2\pi \end{array}$$
How do I prove that the objective is maximized only when $a = b = c = d = e = \frac{2\pi}{5}$?
Comment: Seems like a job for induction, although I could be mistaken.  Suppose that $\sin(r) > 0$ and you wanted to choose a value of $s$ so as to maximize the sum $$\sin(r+s) + \sin(r-s) = 2\sin(r)\cos(s).$$  What value of $s$ would you choose?
Comment: If you know Lagrange multipliers, the answer is immediate.
Answer: Using the method of Lagrange multipliers you immediately get to this.
Let me first define $g=a+b+c+d+e-2\pi=0$ then the lagrange function is $$L(a,b,c,d,\lambda)=E-\lambda g=\sin(a)+\sin(b)+\sin(c)+\sin(d)+\sin(e)-\lambda(a+b+c+d+e-2\pi)$$
Now for lagrange you need to compute all partial derivatives. $$\frac{\partial L}{\partial x}=\cos(x)-\lambda$$ for $x\in \{a,b,c,d\}$ and $$\frac{\partial L}{\partial \lambda}=a+b+c+d+e=2\pi$$ Then you only need to solve the system$$\frac{\partial L}{\partial x}=\cos(x)-\lambda=0\Leftrightarrow \cos(x)=\lambda$$ for $x\in \{a,b,c,d\}$ and you immediately get that $$a=b=c=d=e=\frac{2\pi}{5}$$
I hope this helps.

Maximum value of sum of sines


Stata automatically tests collinearity for logistic regression?

Question: I'm using Stata for logistic regression. This software automatically checks for collinearity and remove (drop) some variables as we can see below:
. logit I A B C D XX

note: XX omitted because of collinearity
Iteration 0:   log likelihood = -289.73552
Iteration 1:   log likelihood = -230.69547
Iteration 2:   log likelihood = -203.22756
Iteration 3:   log likelihood = -198.37658
Iteration 4:   log likelihood = -198.27812
Iteration 5:   log likelihood = -198.27791
Iteration 6:   log likelihood = -198.27791

Logistic regression                             Number of obs     =        418
                                                LR chi2(4)        =     182.92
                                                Prob > chi2       =     0.0000
Log likelihood = -198.27791                     Pseudo R2         =     0.3157

------------------------------------------------------------------------------
           I |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           A |   8.694651   1.250269     6.95   0.000     6.244168    11.14513
           B |  -1.384168   .5934295    -2.33   0.020    -2.547269    -.221068
           C |   .1348553   .1269632     1.06   0.288    -.1139881    .3836986
           D |  -.2188249   .1664487    -1.31   0.189    -.5450583    .1074085
          XX |          0  (omitted)
       _cons |   1.956985   .3378121     5.79   0.000     1.294886    2.619085
------------------------------------------------------------------------------
Note: 0 failures and 14 successes completely determined.

I think Stata only checks for perfect linear relationship between independent variables (100% correlation). Is this true?
If the answer to that question is yes, is this true based on theoretical framework? We should only consider perfect collinearity?
Comment: Despite the total focus on Stata, there is a statistical question here. In return: what is your idea of imperfect collinearity that Stata might use to vet predictors? If any correlation between predictors is suspect, no statistical software would be any use for anything but single-predictor models.
Comment: Stata terminology: best not to say that Stata drops variables, as the word is used for the `drop` command which removes data from the dataset in memory. The word used in the output is much better: Stata omits (= does not use) certain variables, their coefficients being returned as 0.
Comment: @Penguin_Knight I have known both people who have answered so far for several years and I know them quite well. I feel confident that the word "adult" is not intended offensively at all. On the contrary, the intended sense is that Stata pays you a compliment in expecting that you are happy to take on the responsibility for modelling choices such as selection of predictors. So "adult" is meant positively without any contrast with "childish" at all.
Comment: Note that correlations are best not reported as percents. I am not going to try to answer fully on Stata's behalf here, not least because the details of particular software are off-topic here. I am trying to get you to pose a sharp statistical question and I can't see one yet. What does "statistically true" mean? Why should "working on a paper" be pertinent here? If you have a problematic model, then you need to experiment with including and excluding particular predictors, and you can always check to see whether some different software agrees.
Comment: Again, I am not sure what you are asking, but typically if you know that two predictors are correlated at 0.98 then it's usually a bad idea to include both in a model. You shouldn't leave it to Stata to tell you that is a bad idea. But much depends on context. For example, there can be good reasons to include $x$ and $x^2$ in a model and their correlation could be very high. See also `[R] estimation options` on `collinear` in the Stata documentation.
Comment: @NickCox thanks for stepping in. I don't have the privilege of knowing the posters personally but I have been respecting their contributions and believe the intention is not of negative nature.
Comment: Thank you for answer. So Stata only check extreme situation (perfect collinearity) as default? Is this sufficient in real models? I'm comparing 98% correlation between two variables and 100%. Stata only consider perfect linear and there isn't any boundary here. Is this statistically true?
Comment: Suppose that I'm working on a paper. Can I use only Stata procedure for collinearity?
Comment: That's true but suppose that in variable correlation plots we have high correlation of 0.98 between two independent variables. We should consider this high correlation in our model designing(or consider only perfect collinearity)?
Comment: I'm offended by the repeated appearances of the word "adult" in the answers, given the OP's question does not demonstrate any trait of being childish or throwing a temper tantrum. Knowing how to operate a software or master a technique has nothing to do with age or maturity. "Independent and well-informed user" maybe, "adult" probably not necessary.
Answer: Whether or not you want to omit a variable (or do something else) when the correlation is very high but not perfect is a choice. Stata treats its users as adults and lets you make your own choices. With perfect collinearity there is no choice: there is no information present in the data that allows Stata to separate the two effects. It could return an error message and not estimate the model, or Stata can chose one of the offending variables to omit. StataCorp chose the latter.
Answer: Too long for a comment:
As a side note, I find the coefficient of 8.69 of the A variable to be bizarrely high. If it were a 0/1 variable, then it would imply ~exp(8.69)=5943 difference in incidence of I in the two categories of A, but you only have 418 cases, so the difference in rates cannot realistically be more than 1:418 or so. More likely, A is a continuous variable with little variability. At any rate, as you seem to be running into computational issues, rescaling A to have approximately unit variance may help. Even though Stata is very, very good in computational issues, as @MaartenBuis put it, you need to be an adult in working with it and help it out if you can. It may also be that either A or XX is causing the perfect prediction that Stata mentions.
Comment: @user2991243 `abs(X-mean(X))/STD(X)`?? Not sure what the `abs()` is doing there, but it ensures that your "standardized" variable is not centered on 0, and is not centered on some standard quantity. It also does not ensure the variance of the "standardized" variable is 1. Don't you instead want [`(X - mean(X))/STD(X)`](https://stats.stackexchange.com/tags/z-score/info)?
Comment: Thank you for answer. I standardized every independent variable using `abs(X-mean(X))/STD(X)`. So here we are talking about effect of one standard deviation change on dependent variable. What do you think about this structure? We have correct results in this framework?
Comment: Can you plot `lowess I A` and `lowess I XX` to see how these variables are related? I continue to think there's something weird about them.
Answer: Using correlation between predictors is not nearly as informative as the variance inflation factors (VIFs) or the condition number (ratio of largest to smallest eigenvalue, $\sqrt{\lambda_{\max}/\lambda_{\min}})$ of the inverted Hessian matrix, $(\mathbf{X}^{\textsf{T}}\mathbf{X})^{-1}$ or $\left[\partial^2 \cal{l}(\boldsymbol{\beta})/\partial \beta_j \partial \beta_k \right]^{-1}$), to determine whether multicollinearity is present among predictors.  (Yes, VIFs can be run for predictors of logistic regression, since they're derived from regressing each predictor on the remaining predictors -- has nothing to do with the dependent variable).
I have seen very bad ill-conditioned logistic regression models with between-predictor correlation of $|r|<0.5$, i.e., not perfect ($|r|=1$), with VIFs $\gg10$  - indicating severe multicollinearity.  Thus, hunting down perfect correlation ($|r|=1)$ won't help because extreme multicollinarity can occur with $|r|<0.5$.   You need to determine VIFs or look at the condition number of the inverted Hessian.


Encrypted Laravel model feilds do not update

Question: I'm having trouble updating the github_oauth_token and github_oauth_refresh_token fields in my User model that have the encrypted cast. All other fields update fine and the casting is working as expected however the fields will not save to the database.
User model
namespace App\Models;

use App\Mail\EmailVerification;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'email_verification_token',
        'password',
        'github_oauth_token',
        'github_oauth_refresh_token',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'github_oauth_token' => 'encrypted',
        'github_oauth_refresh_token' => 'encrypted',
    ];

    /**
     * Set the user's github oauth token.
     *
     * @param string $value
     * @return void
     */
    public function setGithubOauthTokenAttribute($value)
    {
        $this->github_oauth_token = Crypt::encryptString($value);
    }

    /**
     * Set the user's github oauth refresh token.
     *
     * @param string $value
     * @return void
     */
    public function setGithubOauthRefreshTokenAttribute($value)
    {
        $this->github_oauth_refresh_token = Crypt::encryptString($value);
    }
}

User migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('first_name', 45);
            $table->string('last_name', 45);
            $table->string('email')->unique();
            $table->string('email_verification_token', 30)->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('github_oauth_token')->nullable();
            $table->string('github_oauth_refresh_token')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Controller method
public function handleGitHubCallback()
    {
        $gitHubUser = Socialite::driver('github')->user();

        $user = Auth::user();

        $user->github_oauth_token = $gitHubUser->token; // does not update
        $user->github_oauth_refresh_token = $gitHubUser->refreshToken; // does not update
        $user->first_name = 'Johnathan'; // updates fine

        $user->save();

        return redirect()->route('space.list.get')->with('success', Lang::get('messages.success_github_linked'));
    }

Answer: The issue is in User Model.You are casting both fields in $cast property
 protected $casts = [
        'email_verified_at' => 'datetime',
        'github_oauth_token' => 'encrypted',
        'github_oauth_refresh_token' => 'encrypted',
    ];

So no need to add Mutators so remove both below Mutators.
public function setGithubOauthTokenAttribute($value)
{
    $this->github_oauth_token = Crypt::encryptString($value);
}

public function setGithubOauthRefreshTokenAttribute($value)
    {
        $this->github_oauth_refresh_token = Crypt::encryptString($value);
    }

Also if you want to use mutators then you have an error it should b like below
public function setGithubOauthTokenAttribute($value)
    {
          $this->attributes['github_oauth_token ']= Crypt::encryptString($value);
    }

    public function setGithubOauthRefreshTokenAttribute($value)
        {
           $this->attributes['github_oauth_refresh_token ']= Crypt::encryptString($value);
        }

Comment: As you suggested I removed the mutators but that didn't work and resulted in the same behaviour. I removed the fields from the casts array and it worked (through the mutators). Ideally, I'd like to just use the encryption cast but it does not seem to be working in my case...
Comment: i have tested both scenario and it works well for me .any one you have to use. Either cast or mutators


Simple keypress script with loop in Autohotkey

Question: Whenever you press w you get into a loop that press e around every 10 seconds. Another button has to be pressed to get out of it again at any moment (and making it possible to start over again). This is what I have so far:
w::
Loop
{
Send, e
Random, SleepAmount, 9000, 10000
Sleep, %SleepAmount%
x::Break
}
Return

I don't understand why it is not working yet. It presses e once and doesn't do anything anymore after that.
Answer: x::Break

is the short form for
x::
    break
return

and therefore terminates the current subroutine. Never define a hotkey within any other execution bodies. Instead, define the x-hotkey outside the w hotkey and make it stop the loop.
Example using goTo (note that goSub is different for the latter will not terminate the subroutine):
w::
    Loop {
        send e
        Random, SleepAmount, 9000, 10000
        Sleep, %SleepAmount%
    }
    after_loop:
return

x::
    goTo after_loop
return
; or, more compact:
; x::goto after_loop

Since gotos are pretty bad programming style, you might consider using a timer (instead of the loop). But to be honest, it's not worth it because your sleep amount is not fix.
Comment: I can't test this right now, but this old answer of mine seems to be nonsense: the `x` hotkey spawns a new thread that just goes to `after_loop` and then stops again. It does not change the *other* thread of `w::` which will keep running regardless of the other one... Instead, a variable should be set in `x` and `w` should break based on that


Question about finding implicit derivatives generally

Question: I have a challenging question for homework. I have done implicit differentiation before in the textbook run-of-the-mill fashion but I do not know how one would go about setting up this an equation for a question like this:

Another user told me to set it up as $(DY/DX)(DX/DT) = (DY/DT)$ , but if that is correct, I do not understand how this was arrived at. Can anyone provide an example or explanation?!
Answer: Yes, by the chain rule, it is true that given a function $y(x(t))$ $$\dfrac{dy}{dx}\cdot \dfrac{dx}{dt} = \dfrac{dy}{dt}\tag{1}$$
It also (then) follows that $$\dfrac{dy}{dx} = \dfrac{dy/dt}{dx/dt}\tag{2}$$
So given functions $y(t), x(t)$ we can compute, separately, $\dfrac{dy}{dt}$, $\dfrac{dx}{dt}$, to obtain using $(2)$: $\dfrac{dy}{dx}$.
We can then find $\dfrac {d^2y}{dx^2}$.
Comment: They actually take a lot of work (low, late, reopen) and the others are target rich, still take work, but are not bad. Helpful Flags is also tough.
Comment: Hi dear friend. I know you have very delighting moments ever. :-)


How do you target a specific type of content?

Question: I have the content type (node), article, page, recipe.
The code below can be used to flag any type of content.
How do you target a specific type of content ?
For example I only want to flag the article and recipe content type.
<?php

/**
 * @file
 * Holds hook implementation for the Admin Task Notify module.
 */

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_node_update().
 */
function admin_task_notify_node_update(Node $node) {

    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);

}

Answer: You need to configure your moderate_node flag in either the UI or in configuration management.
In the flag module, a flag entity is defined by the entity type (i.e. node) and bundles (e.g. article, page, recipe) that are allowed on it. If no bundles are specified, then all bundles are allowed.
In your example code, $flag->getBundles() method will return the bundles that are allowed (empty means all). Once set, the $flag_service->flag method will kickback exceptions if you try to flag bundles that do not apply to that flag. You'll need to adjust the code accordingly to handle those scenarios.
Comment: thank you for the explanations
Answer: If you want your hook code to only run on specific content types, simply add a conditional
function admin_task_notify_node_update(Node $node) {

  if ($node->getType() == 'article' || $node->getType() == 'recipe') { // conditional
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);
  }

}

I have several types of content to add, is there a shorter way to do
it ?

Using in_array()
$allowed_c_types = ['article', 'recipe', 'some_other'];
$c_type = $node->getType();

if (in_array($c_type, $allowed_c_types)) { // conditional

But don't hard code, use $flag->getBundles() to get the list as mentioned by Shawn
$allowed_c_types = $flag->getBundles();

Comment: Awesome it works. I have several types of content to add, is there a shorter way to do it ? for example `if $node->getType() == 'article, recipe'`
Comment: @sdfff see updated answer.


How do I upload a PDF for users to download?

Question: I am very new to Drupal. I simply want to provide a link in an article for users to download a pdf document. How do I upload the document on the admin side and then link to it in an article?
Answer: It's easy, in admin/structure/types/manage/article/fields make file field like so:

All other stuff is logical:

Don't forget to put PDF as an allowed extensions:


Dealing with grouped / rounded data

Question: I have a dataset that includes variables about customer income levels.  The income was collected in binned fashion (Which range describes your income? 0-25k, 25k-50k,...).  My question is how best use this for modeling using glmnet and gbm packages in R.
I have looked at the grouped packaged in R but it seems to do everything (coursening and regression) for you. Is there a package that converts binned data back to continuous data for use in with other algos?
EDIT: The current method I'm using is to convert them to the mid-point of the range (0-25k -> 12500), then using an ifelse() stmt to code a few variables to convey the fact that there is a relationship between the levels.
incOver25k <- ifelse(df1$income >= 25000,1,0)
    incOver50k <- ifelse(df1$income >= 50000,1,0)

Then use these flags instead of using model.matrix().
Was curious if there were any better ideas.
Comment: Midpoints are just one of several possible treatments. Depending on the shape of the distribution, midpoints would be too low in some cases and too high in others. So, using midpoints implies a need for some sensitivity analysis. You haven't told us the number of bins (or indeed the currency units!), but if your questionnaire is typical of many, there won't be more than about 10 bins. There's quantitative juice in your lemon, but it is hard to squeeze out.
Answer: I would keep treating those as categorical variables. Since glmnet requires for its input a matrix for the independent variables rather than the usual 'formula', you would need to use the model.matrix function to set this up.
One more gotcha here - glmnet also standardizes the dependent variables, which doesn't make sense for categorical variables. So you should pass in standardize = FALSE as an argument. If you have continuous data as predictors as well, you should be standardize those manually before model.matrix
Answer: You can't restore detail that has been thrown away -- or in this case never supplied in the first place -- so the presumption that coarsening can be inverted or reversed is surprising.
You could see how far the cumulative probabilities for 25k, 50k, etc. are consistent with various distributions, e.g. lognormal. Odds are that (1) you have rather few bins or classes (2) the important uppermost class is open-ended.
As Affine says, you could fall back on treating income as categorical; at least it is ordinal or graded.

Dealing with grouped / rounded data


Masonry - carregá-lo novamente após aplicação de filtros no resultado

Question: Seguinte tenho uma página aonde aplico o plugin masonry.js nessa página eu tenho um filtro de conteúdo, o problema é o seguinte quando abro a pagina esta tudo ok tenho duas colunas de card com um espaçamento x entre elas, porem após aplicação do filtro ele limpa todo os elementos da tela e me retorna somente os elementos filtrados e nesse procedimento o masonry deixa de funcionar fazendo que o espaçamento x entre as colunas diminua ouuuu até mesmo fazendo com que os cards fique um em baixo do outro em somente uma coluna. Não estou conseguindo fazer com que o masonry seja iniciado novamente após o filtro.
O código é o seguinte:

var refreshFeed = function(month, studentId, materialName, programId, page) {
    console.log(materialName);
    clearFeed();

    var tempFeed = feed.sort(predicatBy("build_at"));

    var numWorks = 6;

    var filteredFeed = [];

    $.each(tempFeed, function( index, value ) {

      var build_at = formatDatetime(value.build_at);

      if ((month == 0 ) || (month == build_at[1])) {
        if ((programId == 0 ) || programId == value.program_id){
          if ((materialName == "") || materialName == value.material.name) {
            if ((studentId == 0)) {
              filteredFeed.push(value);
            }else {
              $.each(value.work_students, function( index, work_student ) {
                if(work_student.student != null ) {
                  if(work_student.student.id == studentId) {
                    filteredFeed.push(value);
                  }
                }
              });
            }
          }
        }
      }
    });

    if (page == undefined) {
      page = 0
    };
    var finalFeed = pagination(filteredFeed, numWorks, page)

    $.each(finalFeed, function( index, value ) {
      createWorkArticle(value, month, studentId);
    });

  }

E para chamar o masonry eu uso o código:

    var $container = $('#container-masonry');
    // initialize
    $container.imagesLoaded( function() {
      $container.masonry({
        columnWidth: 540,
        itemSelector: '.item',
        isFitWidth: true,
        gutter: 60
      });
    });

A dúvida é, como faço para carregar o plugin novamente após aplicação do filtro?
Não sei se ficou claro, mas qualquer coisa tento melhorar a pergunta.
Answer: Coloca isso dentro de uma função:
function chamaMasonry(){

 var $container = $('#container-masonry');
    // initialize
    $container.imagesLoaded( function() {
      $container.masonry({
        columnWidth: 540,
        itemSelector: '.item',
        isFitWidth: true,
        gutter: 60
      });
    });

}

Chama essa função quando carregar a página e chama ela na função do filtro.


How to sort manual buckets created in Pandas?

Question: I have a column :
hourly_ticket
(0,1]
[1,2)
[2,3)
[3,4)

and so on till [23,24)
when I am using this column in a pandas pivot table it is getting re-arranged in a way like: [0, 1)    [1, 2)  [10, 11)    [11, 12)    [12, 13)    [13, 14) unlike of how I want which is in ascending order.
How do I fix this? How do i sort it? the dtype of this columns is "O" which is Object
Answer: The .sort_values function can take a key function that is applied to the column you wish to sort on.
Assuming the column stores the bins as a str, the parse_hourly_ticket first strips all brackets and parenthesis for each row, and return the first number in each "bucket" which then are used to sort the dataframe.
parse_hourly_ticket = lambda x: x.apply(lambda s: float(s.strip('[]()').split(',')[0]))
df.sort_values('hourly_ticket', key=parse_hourly_ticket)


What does arena means in the output of JVM NMT

Question: I ran 'jcmd  VM.native_memory detail' for a Java application, and the output was like:
Total: reserved=4741MB, committed=3506MB
-                 Java Heap (reserved=2350MB, committed=2350MB)
                            (mmap: reserved=2350MB, committed=2350MB)

-                     Class (reserved=1676MB, committed=751MB)
                            (classes #151986)
                            (  instance classes #144245, array classes #7741)
                            (malloc=24MB #383379)
                            (mmap: reserved=1652MB, committed=727MB)
                            (  Metadata:   )
                            (    reserved=628MB, committed=626MB)
                            (    used=613MB)
                            (    free=13MB)
                            (    waste=0MB =0.00%)
                            (  Class space:)
                            (    reserved=1024MB, committed=100MB)
                            (    used=92MB)
                            (    free=8MB)
                            (    waste=0MB =0.00%)

-                    Thread (reserved=214MB, committed=26MB)
                            (thread #219)
                            (stack: reserved=213MB, committed=25MB)
                            (malloc=1MB #1316)
...
OMIT SOME LINES HERE
...

-                  Internal (reserved=10MB, committed=10MB)
                            (malloc=10MB #9058)
-                    Symbol (reserved=44MB, committed=44MB)
                            (malloc=41MB #560526)               --> isn't malloc function backed up by arena under glibc?
                            (arena=2MB #1)                      --> what does this line mean?

-    Native Memory Tracking (reserved=19MB, committed=19MB)
                            (malloc=1MB #7348)
                            (tracking overhead=18MB)

-        Shared class space (reserved=17MB, committed=17MB)
                            (mmap: reserved=17MB, committed=17MB)

-               Arena Chunk (reserved=6MB, committed=6MB).           --> What does this block suggest?
                            (malloc=6MB)

-                    Module (reserved=3MB, committed=3MB)
                            (malloc=3MB #18535)

Take Symbol block for example, what is the difference between malloc and arena? The java application is running on Linux using glibc, so I think (maybe I am wrong) it is arena that actually takes responsibility for memory management. But why is there another separated line below noting memory allocated by arena?
And what does Arena Chunk block mean?
Could you please enlighten me? Thanks.
Answer: This is unrelated to glibc arenas.
In HotSpot, Arena is a structure for fast native memory allocation, optimized for the particular pattern:

Allocation from Arena is thread local. No synchronization is involved.
Memory from an Arena cannot be reclaimed partially. Arena is disposed all at once.

A typical use case for Arena allocation is JIT compilation. When the JIT compiler works, it allocates many small objects (e.g. IR graph nodes). These objects are used locally just by one compiler thread. The life time of these temporary objects is short: when the compilation of a method completes, the entire Arena holding all these objects is deleted at once.
Arena consists of large chunks allocated with a regular malloc. Allocation inside an Arena is a simple pointer increment. When Arena runs out of free space, a new chunk is created.
(arena=2MB #1) in the above NMT report means that the Symbol area has an Arena which includes one chunk of 2MB.
Arena Chunk section summarizes all active Arenas.


Why is pole position located on the outside of the first corner?

Question: At the 2012 Spanish Grand Prix, Pastor Maldonado got pole position in qualifying, and started at P1 on the grid before the race. I noticed that P1, at this track, was on the outside, from the perspective of the first corner. So, in this case, the driver in P2 would have the inside line at the first corner, and in my opinion, the inside line is better than the outside line.
My question is, why is P1 located on the outside of the first corner? Is this only at certain tracks, or do all tracks have this kind of layout? I think that the driver on pole position should have the inside line for the first corner, so if the first corner is a right-hand turn, then pole position should be on the right-hand side of the grid.
For reference, you can see in this image that Pastor Maldonado is on the left-hand side of the grid, whereas the first turn is a right-hand turn.

PS: My question is not related to the cars' paces, so I don't want to take the perspective where "the car is faster".
Answer: This isn't defined in the technical regulations.  But in most cases you can think of which side is closer to the racing line, then pole will be on that side.
The grand prix usually isn't the only race run on the weekend.  There are often other races, plus practices and qualifying.  After all that driving, the racing line should be swept pretty clear, while the less-driven areas nearby will have bits of tire wear.  You will almost always want to start on the clear line.  Any "marbles" are likely to reduce your ability to start and that can be worth more than being on the inside or the outside.
But if that's not a big consideration, you'll probably want to be on the outside.  In most cases you'll be able to keep more speed if it's a simple turn.
It's not always clear-cut.  In Singapore, the racing line moved from the right to the left along the starting straight as it positioned for the right-hand turn 1.  So P1 was set on the left.  But in 2011, several drivers requested that the left was more likely to be contaminated and preferred pole be set up on the right.  The director agreed and it was changed: Autosport article.
From the race you showed, Alonso gets a better start.  I have no idea why (better reaction, better car, better grip, ...), but that lets him pull a lead well prior to the first turn.  At that point it doesn't matter which direction the turn is in, he seems to be in control of the start.  Inside or outside wouldn't have mattered.
Comment: This is exactly it. Famously, pole position at Suzuka used to be situated *off* the racing line, so that the driver who qualified 2nd actually had the advantage at the start. Alain Prost got that advantage over Ayrton Senna three years in a row, and the third time, Senna asked the FIA to move pole position over to the other side because he *knew* Prost would just overtake him at the start again. The FIA refused, so Senna did [this](https://www.youtube.com/watch?v=IbeBnn0Ufsc).


Does Assets size impact Angular7 Application performance?

Question: I have to place a lot of help videos in assets folder of my application. Eventually, the size of assets folder is exceeding 250mbs. I wonder, if it will impact the performance of my application or not? I tried to place my videos outside my project but it was giving errors that can't download the video file. Any help will be appreciated.
Answer: Here is what I've found
https://blog.ninja-squad.com/2018/09/06/angular-performances-part-1/
By compressing you should get smaller packages
https://medium.com/angular-in-depth/optimize-angular-bundle-size-in-4-steps-4a3b3737bf45
Hope it helps!