jquery check box some ideas

Question: im trying to make a checkbox that disable the computation in my query here is my
form code:
<input type="hidden" name="stud_no[]" value="<?php echo
$row['student_no'];?>"> <input type="text" name="prelim[]"
value="<?php echo $row['prelim_pts']?>" id="prelim_<?php echo
$row['student_no'];?>" class="txtprelim" >	 <input
type="text" name="midterm[]" value="<?php echo
$row['midterm_pts']?>" id="midterm_<?php echo $row['student_no'];?>"
class="txtmidterm" >	  <input type="text" name="final[]"
value="<?php echo $row['finals_pts']?>" id="final_<?php echo
$row['student_no'];?>" class="txtfinal" >	  <input
type="text" name="average[]" id="average_<?php echo
$row['student_no']; ?>" value="<?php echo $row['average_pts']; ?>"
readonly="readonly"> 	 <input type="checkbox"
name="disable[]" value="<?php echo $row['disable_comp'];?>"
class="dis">

here now is my jquery code:
$(document).ready(function(){
                p="";       m="";       f="";

                $(".txtprelim").keyup(function(){           var id = $(this).attr("id").replace("prelim_","");
                p = $("#prelim_" + id).val();
                m = $("#midterm_" + id).val();
                f = $("#final_" + id).val();            Compute( p,m,f, id);            //alert($(".txtprelim").val());
                });
            $(".txtmidterm").keyup(function(){
                var id=$(this).attr("id").replace("midterm_","");
                    p = $("#prelim_" + id).val();
                    m = $("#midterm_" + id).val();
                    f = $("#final_" + id).val();

                Compute( p, m, f,id);           //alert($(".txtmidterm").val());
            });
            $(".txtfinal").keyup(function(){
                    var id=$(this).attr("id").replace("final_","");
                        p = $("#prelim_" + id).val();
                        m = $("#midterm_" + id).val();
                        f = $("#final_" + id).val();

                    Compute( p, m, f, id);

                    //alert($(".txtfinal").val());

                    //alert($("f").val());      });

        function Compute(p , m , f , studno){       //  alert("p="+p+" m="+m+"
f="+f);             var average="";
             average = parseFloat(p * 0.3) + parseFloat(m * 0.3 )+ parseFloat(f * 0.4);             $("#average_" +
studno).val(average.toFixed());

                //alert(average);       }

                    $("input[type='dis']").change ( function(){
                        var val =$(this).val();
                        if($(this).is(':checked'))
                        {
                            alert($(this).val());
                        }

                    });

                });

Comment: What is your question??
Comment: Agreed with @Will.i.am......!!!!! `^^`
Comment: Sooo, what exactly is your problem?
Comment: I do hope you just pasted the code all messed up because it's full of un-closed functions. Maybe try arranging it again?
Answer: So from what I understood this code should work better. Also in your last function there is no type='dis'. That's a class
$(document).ready(function() {
        p = "";
        m = "";
        f = "";

        var computeValues = function(){
            var id = $(this).attr("id").replace("prelim_", "").replace("midterm_", "").replace("final_", "");
            p = $("#prelim_" + id).val();
            m = $("#midterm_" + id).val();
            f = $("#final_" + id).val();
            Compute(p, m, f, id);
        };

        $("input").bind('keyup', computeValues);

        function Compute(p, m, f, studno) {
            var average;
            average = parseFloat(p * 0.3) + parseFloat(m * 0.3) + parseFloat(f * 0.4);
            $("#average_" + studno).val(average.toFixed());
        }

        $(".dis").change(function() {
            var val = $(this).val();
            if ($(this).is(':checked')) {
                $("input").unbind('keyup', computeValues);
            } else {
                $("input").bind('keyup', computeValues).trigger('keyup');
            }
        });
    });

And a fiddle to test it http://jsfiddle.net/Spokey/nhcsT/
UPDATDE:
You can add an <input type="hidden" id="changeme" value="0"> in your form and when the user selects the checkbox the value of the hidden input will change to 1
$(".dis").change(function() {
                var val = $(this).val();
                if ($(this).is(':checked')) {
                    $("input").unbind('keyup', computeValues);
                    $("#changeme").val('1');
                } else {
                    $("input").bind('keyup', computeValues).trigger('keyup');
                    $("#changeme").val('0');
                }
            });

Comment: thanks for your help it work thanks buy how did you simplify my code sorry newbie here
Comment: im trying to have a 1 value if they check the checkbox then 0 if not to save it on the database
Comment: I updated my post. I also simplified the code by making only a function and firing it on `keyup`. For that I used `.bind()` from jQuery. I suggest you look it up the the jQuery documentation.

jquery check box some ideas


how limit php script to access parent host directory

Question: I've a debian linux server with apache2.2 & php5 installed.
I've created many virtual hosts on my apache server, each virtual host has a separate root directory & php is enabled for all of them. Now I need to limit php scripts in each virtual host in some manner that they can only read, write or modify only in v-host root directory & it's sub-directories (& not parent directories), in other hand, I want create a jail for scripts which are running on every virtual host.
For example, php scripts that located in /var/www/vhost1 can only access to files in same directory & sub-dirs & they don't have access to /var/www/host2 files (not for read nor modifying them).
any idea?
Answer: You would need to create a jail for each and every host and run PHP via CGI/FASTCGI with chroot set to the right directory.
Answer: Well, i doubt you cant even achieve that within single CPANEL/account.
its a horror (you have to set open_basedir,allowOverride,safe_mode and even other restrictions are needed for cgi/perl/cron-jobs...
you'd better to use Reseller(WHM) account, or DirectAdmin(cpanel alternative) Multi-user.


Angular Material Menu rendering at bottom of page

Question: I just added a mat nav menu to a project and now the menu is rendering at the bottom of the page with the following generated style values:
pointer-events: auto;
top: -1688.84px;   <-----??????
right: -140px;

I'm adding a custom css class to counter it but I'm wondering how material is populating this.
Navbar.component.html

      {{item}}

  <button mat-icon-button [matMenuTriggerFor]="navbar">
    <mat-icon  style="color: #e2d4ce; font-size:64px">menu</mat-icon>
  </button>
  <mat-menu #navbar="matMenu" >

   <button mat-menu-item id="{{item}}" >{{item}}</button>

  </mat-menu>

Navbar.component.ts
import { NavService } from './../nav.service';
import { Router } from '@angular/router';
import { Component, OnInit, Input } from '@angular/core';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'
import { MatMenu } from '@angular/material/menu';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
   navbar:MatMenu;
  isHome:boolean
  mobile:boolean;;
  currentNavItems:string[] = ["ABOUT","NEWS","EVENTS","RETREAT","ARTIST OF THE MONTH"];
  constructor(public router:Router, private ns:NavService, public BreakpointObserver: BreakpointObserver) {}

  home: boolean;
  ngOnInit(): void {
    this.BreakpointObserver.observe([
      '(min-width:400px)'
    ]).subscribe((state:BreakpointState) =>{
      if(state.matches){
        this.mobile = true
      }else{
        this.mobile=false;
      }
    })
  }

scroll(event){
    console.log(event.target.id)
    let id = event.target.id.toLowerCase()
    id === "artist of the month" ? id ="artist" : id=id

    const yourElement = document.getElementById(id+"-scroll");
    const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
    window.scrollTo({top: y, behavior: 'smooth'})
  }

}

Comment: Possible duplicate https://stackoverflow.com/questions/57947292/the-mat-menu-always-appears-at-page-end try the first solution by adding @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; to the global styles
Answer: This UI issue occurs when the following warning shows in the Chrome debugger console:

Could not find Angular Material core theme. Most Material components
may not work as expected.  For more info refer to the theming guide:
https://material.angular.io/guide/theming

(Refer to related issue [https://stackoverflow.com/questions/44230852/angular-material-could-not-find-angular-material-core-theme][1])
Solutions which work for me:

Add core theme CSS to styles.scss (recommended in
https://material.angular.io/guide/theming)
@import "~@angular/material/prebuilt-themes/deeppurple-amber.css";

Add core theme CSS to angular.json:
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/styles.scss" ],
Comment: I'm facing this issue, but I don't have any error in my debugger console. The prebuilt theme is already referenced as recommended.


iCarousel performance issue with UITableView (iPad master-detail UI)

Question: I am currently using a master-detail iPad UI: inside a UISplitViewController I have the left (master) side contain a UITableViewController, and the right (detail) side contains an iCarousel. See attached image.
Problem: When scrolling the table view WHILE the carousel is still animating The table view scrolls and decelerates smoothly, and the iCarousel scrolls in a sluggish (that is, barely animating at all) fashion.
What can one do to improve the iCarousel's animation "smoothness" when animating in concurrence to a table view animating/decelerating?

Points for consideration:

Tested on iPad 1 (non-retina), iPad 4G (retina), and in simulator retina and non retina, same results in all platforms.
It does not seem to matter whether you first drag the carousel and then the table or in the other order, the table view always takes "precedence", and iCarousel's smooth animation performance seems to go *^&k!.
Comment: I have no idea about iCarousel, but it sounds like whatever drives its animation is scheduled in the "wrong" run loop mode. Set it to `NSRunLoopCommonModes ` and it should work.
Comment: The control is a (wonderful!) cover flow-like controller named "iCarousel". It seems to animate using an 'NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats', and it intermittently uses '[_timer invalidate]' also '[CATransaction setDisableActions:YES]' and '[CATransaction setDisableActions:NO]' no scheduling in any run loop mode / type seems to be used in the class.
Answer: The problem is that the timer that drives the animation, is scheduled in the default run loop mode, which means that the timer won't fire while you scroll in a UIScrollView (which the table view inherits from). To solve this problem, you have to modify the iCarousel code (line 1737, startAnimation). Add the following:
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
Comment: @RabinDev You are right, sorry! I typed that into SO while trying to eat something, clearly not one of my best ideas! :p
Comment: BTW, got a nice friendly email reply from the author of the mentioned controller as I posted this same question in the github issue tracker for the iCarousel controller. He suggested this solution also. So i guess this makes this answer an even "betterer" one.


How to compare two lists of type string in java

Question: I need to check whether elements of one list or array exists in other list.
The size of lists are same.
Apart from sorting is any simple solution possible?
Comment: [List#contains](http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)) ?
Comment: Hi Chirag, what you tried? Please paste an example
Comment: [List#containsAll](http://docs.oracle.com/javase/7/docs/api/java/util/List.html#containsAll(java.util.Collection))? (Along the same theme as KevinEsche's comment)
Comment: Hi Chirag, try using `list.contains(elements)`
Comment: @AndyTurner There is a limitation to that solution, see my answer.
Answer: You are right in saying that if they are arrays you can't use Arrays.equals(), if they are List<>s then you cannot just use equals. In both cases they also check order.
So yes your main option without writing your own comparison algorithm is to use Collections.sort() on both lists.
If you don't need to check for duplicates you could drop both lists into a HashSet using addAll and then compare the two HashSet or just use List.containsAll. The bad news though is that these would both have the same limitation, if you need to compare lists that might have repeated elements then it may give incorrect results. i.e. "bob", "bob", "fred" would compare as equal to "bob", "fred", "fred".
Comment: The question only ask for a check "*whether* elements of one list or array exists in other list" not for matching number of occurrences, thus, there is no need to handle duplicates specially.
Comment: @Holger Actually the question is unclear, which is why I gave both solutions.
Answer: Please refer to the example below:
public class Example{
    public static void main(String[] args){
        List<String> list1 = new ArrayList<String>();
        List<String> list2 = new ArrayList<String>();

        list1.add("A");
        list1.add("B");
        list1.add("C");

        list2.add("C");
        list2.add("X");
        list2.add("Y");

        for(String s : list1){
            if(list2.contains(s)){
                System.out.println("List 2 contains: " + s);
            }
        }
    }
}

The code above is by all means not the cleanest or the most compact way to achieve what you are asking. But given the information presented, this should suffice.
Comment: While this may solve his problem depending on the requirements it will give incorrect results on some data sets, see my answer. Also note that you could drop the loop by using `containsAll()`.
Comment: @TimB I appreciate your comment. The answer given above satisfies the OPs requirement. It is not based around all possible issues which could occur in relation to data structures. Given the information the OP has presented, the answer, in my opinion, is sufficient.
Answer: To check if your an item of list1 is in list2 you could use this code:
 ArrayList<Integer> list1 = new ArrayList<>();
 ArrayList<Integer> list2 = new ArrayList<>();

 //Adding some object to the list here

 int yourIndex = 1;

 if(list2.contains(list1.get(yourIndex)))
 {
     //do what you want
 }

Comment: While this may solve his problem depending on the requirements it will give incorrect results on some data sets, see my answer. Also note that you could drop the loop by using containsAll()


What is the probability that the person surveyed is male and a democrat?

Question: There were $295$ people surveyed. Of those $295$ people, $141$ were male, and $21$ were democrats. There was a total of $75$ democrats. What is the probability that the person surveyed is both male and a democrat? I thought it would be $$\frac{141}{295} \times \frac{21}{75}$$ but that was not correct
Answer: This question might be simpler than you think. The question states that within the 141 males, 21 were democrats. The probability of randomly selecting someone who is both male and a democrat is simply the number of those with that property (21) divided by total number of possible selections (295).
$$P(\text{male and democrat}) = \frac{21 \text{ male democrats}}{295 \text{ surveyed}}$$


Definir links de site - Pesquisa no Google

Question: é possível definir ordem dos links que aparecem na busca do google na parte onde ele lista 6 links?
Comment: Isso se chama [**SiteLinks**](https://pt.stackoverflow.com/questions/68010/erro-ao-criar-google-sitelinks), só sites com um numero elevado de visitas costumam exibir isto, as vezes também sendo exibido em consultas direcionadas (quando o google nota que o usuário visita muito o site determinado e então exibe os links para facilitar)
Comment: Acredito que essa ordem seja por relevância.
Comment: @GuilhermeNascimento usando Rich Snippets e Schema.Org, vc consegue com que o Google te mostre dessa forma no resultado da pesquisa.
Comment: @hugocsl sim, eu sei, mas só mostra uma possibilidade, não garante que isto será exibido a todos usuários do google.
Comment: Repare que não tem a barra de Search no resultado da pesquisa! Ex: https://marketplace.webkul.com/wp-content/uploads/2017/10/sitelinksearch-without-markup.png aqui tem a Search Bar. A dele não tem...
Comment: @hugocsl isso é uma opção adicional que você pode configurar, e também só será exibida conforme o Google achar necessário, dentro daquilo que eu já citei no primeiro comentário: 1. sites com muitas visitas 2. consultar direcionadas. Outro detalhe é o tempo de indexação, que pode levar meses, no link que deixei como dup esta explicado.
Answer: Não é possível alterar a ordem dos sitelinks, ela se ajusta conforme a necessidade do usuário, geralmente direcionando os links mais buscados ou mais buscados anteriormente pelo usuário, o que pode variar muito conforme o algorítimo do buscador Google muda, conforme respondi em Erro ao criar "Google Sitelinks"
Conforme a propria Google:

Exibimos sitelinks de resultados somente quando achamos que eles podem ser úteis para o usuário. Se a estrutura de seu site não permitir que nossos algoritmos localizem bons links de site ou se você achar que os links para seu site não são pertinentes para a consulta do usuário, nós não os exibiremos.
No momento, os sitelinks são automatizados. Estamos trabalhando constantemente para melhorar os algoritmos dos sitelinks. É possível que no futuro venhamos a incorporar sugestões e informações fornecidas pelos webmasters. No entanto, existem práticas recomendadas que podem ser seguidas para melhorar a qualidade dos seus sitelinks. Por exemplo, para os links internos do seu site, use textos âncora e textos com atributo alt informativos, compactos e sem repetições.

Ou seja a parte que fala:

É possível que no futuro venhamos a incorporar sugestões e informações fornecidas pelos webmasters.

Ela afirma que talvez no futuro o webmaster (você) possa fazer algo para controlar os links/sugestões, mas até o momento os sitelinks são automatizados.
Também vale notar que os sitelinks só são exibidos conforme o algorítimo achar necessário/útil ao usuário. Ou seja pode até mostrar, mas os sitelinks podem variar para cada usuário, mostrando o que o algorítimo acredita ser útil para cada usuário especifico.


Javascript Syntax error

Question: I am trying to set a google tracking event on Javascript store finder for a client of mine. I already have a event tracking on "submit button" which works fine. Every store on the map has a link for more information. I am trying to setup an event for the "More information" link so that it shows which store has the most clicks.
For some reason I get an error as soon as I past the Google event tracking code using OnClick event inside my link. Below is the section which has the store details:
 var contentString =
    '

' +
    location[0] + '

' + location[1] + '
' + location[2] + ', ' + location[3] + ' ' +
    location[4] + '

More information  -  Get Directions

';
    var infowindow = new google.maps.InfoWindow({ content: contentString, maxWidth: 300 });
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

The above code works fine, but when I try to put Onclick event, I get an error:
    var contentString =
    '

' +
    location[0] + '

' + location[1] + '
' + location[2] + ', ' + location[3] + ' ' +
    location[4] + '

More information  -  Get Directions

';
    var infowindow = new google.maps.InfoWindow({ content: contentString, maxWidth: 300 });
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

Notice that the second code has a onclick event on my "More Information" link. This were I get an error everytime I try to use an onclick event. I used single code around it which removed the error, but then the search didnt work.
Any help is highly appreciated!
Thanks,
Comment: just escape your `'`-es with `\'`
Comment: Thank  you so much. Escaping single quotes worked.  Highly appreciated!
Answer: Solved! I had to escape all single quotes inside event tracking block code. Thank you vp_arth

Javascript Syntax error


Extend a form from a custom module

Question: I'm newbie with Drupal 8. I was entrusted with hanging a custom module to a Drupal 8 default login form.

Together with these fields, I would like to see those of my form, which should be generated in this way.
use Drupal\trust_ppg\Consents;

function hooks_enabled()
{
    $value = \Drupal::config('trust_ppg.settings')->get('trust_ppg_module_checkbox_value');
    if ($value == 1) {
        return true;
    }
    return false;
}

// Implements hook_form_FORM_ID_alter(). - REGISTRATION form
function trust_ppg_form_user_register_form_alter(&$form, &$form_state)
{
    if (hooks_enabled() == false) {
        return $form;
    }
    $account = $form['#user'];
    $form = array_merge($form, trust_ppg_policies_form($account));
    $form['#validate'][] = 'registration_extra_fields_validate';
}

// Implements hook_validate(). FIXME -> move to formbuilder
function registration_extra_fields_validate($form, &$form_state)
{
    if (hooks_enabled() == false) {
        return;
    }
    $error_messages = [];
    if ($form_state['input']['tou'] != '1') {
        $error_messages["body"][] = 'In order to proceed with the registration you need to accept the Terms Of Use!';
    }
    if ($form_state['input']['privacy_policy'] != '1') {
        $error_messages["body"][] = 'In order to proceed with the registration you need to accept the Privacy Policy!';
    }
    if ($form_state['input']['cookie_policy'] != '1') {
        $error_messages["body"][] = 'In order to proceed with the registration you need to accept the Cookie Policy!';
    }
    // Add new mandatory policies here
    foreach ($error_messages as $element => $messages) {
        // FIXME - form_set_error($element, theme('item_list', array('items' => $messages)));
    }
}

// Implements hook_form_FORM_ID_alter(). - USER PROFILE form
function trust_ppg_form_user_profile_form_alter(&$form, $form_state)
{
    if (hooks_enabled() == false || $form['#user_category'] != 'account') {
        return $form;
    }
    $account = $form['#user'];
    $form = array_merge($form, trust_ppg_policies_form($account));
}

// Implements hook_help().
function trust_ppg_help($path, $arg)
{
    switch ($path) {
        case "admin/help#trust_ppg":
            return t("Help Hook");
            break;
    }
}

// Implements hook_cron().
function trust_ppg_cron()
{
    Consents::process_consents_batch();
}

/**
 * Implements hook_user_insert().
 * - A user account was created.
 *
 * @FIXME
 * The $edit and $category parameters are gone in Drupal 8. They have been left
 * here in order to prevent 'undefined variable' errors, but they will never
 * actually be passed to this hook. You'll need to modify this function and
 * remove every reference to them.
 */

function trust_ppg_user_insert(\Drupal\user\UserInterface $account, $category, $edit = null)
{
    $tou_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_tou_guid_value');
    if ($tou_guid != 0) {
        $tou_consent = $edit['tou'];
        if ($tou_consent == 1) {
            give_consent_user($tou_guid, $account);
        }
    }

    $privacy_policy_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_privacy_policy_guid_value');
    if ($privacy_policy_guid != 0) {
        $privacy_consent = $edit['privacy_policy'];
        if ($privacy_consent == 1) {
            give_consent_user($privacy_policy_guid, $account);
        }
    }

    $cookie_policy_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_policy_guid_value');
    if ($cookie_policy_guid != 0) {
        $cookie_consent = $edit['cookie_policy'];
        if ($cookie_consent == 1) {
            give_consent_user($cookie_policy_guid, $account);
        }
    }

    $cookie_policy_3rdparties_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_3rdparties_guid_value');
    if ($cookie_policy_3rdparties_guid != 0) {
        $cookie_3rdparties_consent = $edit['cookie_3rdparties'];
        if ($cookie_3rdparties_consent == 1) {
            give_consent_user($cookie_policy_3rdparties_guid, $account);
        }
    }

    $cookie_policy_additional_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_additional_guid_value');
    if ($cookie_policy_additional_guid != 0) {
        $cookie_additional_consent = $edit['cookie_additional'];
        if ($cookie_additional_consent == 1) {
            give_consent_user($cookie_policy_additional_guid, $account);
        }
    }

    $marketing_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_marketing_guid_value');
    if ($marketing_guid != 0) {
        $marketing = $edit['marketing'];
        if ($marketing == 1) {
            give_consent_user($marketing_guid, $account);
        }
    }

    $db_publication_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_db_publication_guid_value');
    if ($db_publication_guid != 0) {
        $db_publication = $edit['db_publication'];
        if ($db_publication == 1) {
            give_consent_user($db_publication_guid, $account);
        }
    }

    $soft_optin_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_soft_optin_guid_value');
    if ($soft_optin_guid != 0) {
        $soft_optin = $edit['soft_optin'];
        if ($soft_optin == 1) {
            give_consent_user($soft_optin_guid, $account);
        }
    }

    $profiling_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_profiling_guid_value');
    if ($profiling_guid != 0) {
        $profiling = $edit['profiling'];
        if ($profiling == 1) {
            give_consent_user($profiling_guid, $account);
        }
    }

    $newsletter_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_newsletter_guid_value');
    if ($newsletter_guid != 0) {
        $newsletter = $edit['newsletter'];
        if ($newsletter == 1) {
            give_consent_user($newsletter_guid, $account);
        }
    }
}

/**
 * Implements hook_user_update().
 *
 * @FIXME
 * The $edit and $category parameters are gone in Drupal 8. They have been left
 * here in order to prevent 'undefined variable' errors, but they will never
 * actually be passed to this hook. You'll need to modify this function and
 * remove every reference to them.
 */
function trust_ppg_user_update(\Drupal\user\UserInterface $account, $category, $edit = null)
{
    $tou_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_tou_guid_value');
    if ($tou_guid != 0) {
        $tou_consent = $edit['tou'];
        manage_consent_wrapper($tou_consent, $tou_guid, $account);
    }

    $privacy_policy_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_privacy_policy_guid_value');
    if ($privacy_policy_guid != 0) {
        $privacy_consent = $edit['privacy_policy'];
        manage_consent_wrapper($privacy_consent, $privacy_policy_guid, $account);
    }

    $cookie_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_policy_guid_value');
    if ($cookie_guid != 0) {
        $cookie_consent = $edit['cookie_policy'];
        manage_consent_wrapper($cookie_consent, $cookie_guid, $account);
    }

    $cookie_3rdparties_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_3rdparties_guid_value');
    if ($cookie_3rdparties_guid != 0) {
        $cookie_3rdparties_consent = $edit['cookie_3rdparties'];
        manage_consent_wrapper($cookie_3rdparties_consent, $cookie_3rdparties_guid, $account);
    }

    $cookie_additional_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_additional_guid_value');
    if ($cookie_additional_guid != 0) {
        $cookie_additional_consent = $edit['cookie_additional'];
        manage_consent_wrapper($cookie_additional_consent, $cookie_additional_guid, $account);
    }

    //
    $marketing_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_marketing_guid_value');
    if ($marketing_guid != 0) {
        $marketing = $edit['marketing'];
        manage_consent_wrapper($marketing, $marketing_guid, $account);
    }

    $db_publication_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_db_publication_guid_value');
    if ($db_publication_guid != 0) {
        $db_publication = $edit['db_publication'];
        manage_consent_wrapper($db_publication, $db_publication_guid, $account);
    }

    $soft_optin_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_soft_optin_guid_value');
    if ($soft_optin_guid != 0) {
        $soft_optin = $edit['soft_optin'];
        manage_consent_wrapper($soft_optin, $soft_optin_guid, $account);
    }

    $profiling_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_profiling_guid_value');
    if ($profiling_guid != 0) {
        $profiling = $edit['profiling'];
        manage_consent_wrapper($profiling, $profiling_guid, $account);
    }

    $newsletter_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_newsletter_guid_value');
    if ($newsletter_guid != 0) {
        $newsletter = $edit['newsletter'];
        manage_consent_wrapper($newsletter, $newsletter_guid, $account);
    }
    // Add new entries here
}

function _expose_var(&$build, $var_name, $var)
{
    $build['#attached']['drupalSettings'][$var_name] = $var;
}

//Implements hook_preprocess_page(). - useful to force redirect, for example
function trust_ppg_page_attachments(array &$page)
{
    $user = \Drupal::currentUser();

    _expose_var($page, 'ga_guid', \Drupal::config('trust_ppg.settings')->get('trust_ppg_ga_guid'));

    /* If you change the default text remember to change all occurences */
    _expose_var($page, 'main_text', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_text'));
    _expose_var($page, 'policy_label', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_label'));

    if (\Drupal::currentUser()->isAuthenticated()) {
        $cookie_policy_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_policy_guid_value');
        $consent = Consents::get_consent($cookie_policy_guid, $user);

        $cookie_policy_3rdparties_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_3rdparties_guid_value');
        $consent_3rdparties = Consents::get_consent($cookie_policy_3rdparties_guid, $user);

        $cookie_policy_additional_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_additional_guid_value');
        $consent_additional = Consents::get_consent($cookie_policy_additional_guid, $user);
        // Add mandatory policies here

        // Expose variables for JS
        _expose_var($page, 'cookie_3rdparties_consent', is_array($consent_3rdparties));
        _expose_var($page, 'cookie_additional_consent', is_array($consent_additional));
        _expose_var($page, 'username', $user->getAccountName());
    } else {
        // Expose policies GUIDs
        _expose_var($page, 'cookie_policy', \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_policy_guid_value'));
        _expose_var($page, 'cookie_3rdparties', \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_3rdparties_guid_value'));
        _expose_var($page, 'cookie_additional', \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_additional_guid_value'));

        _expose_var($page, 'cookie_policy_label', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_policy_label'));
        _expose_var($page, 'cookie_3rdparties_label', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_3rdparties_label'));
        _expose_var($page, 'cookie_additional_label', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_additional_label'));

        _expose_var($page, 'cookie_policy_body', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_policy_body'));
        _expose_var($page, 'cookie_3rdparties_body', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_3rdparties_body'));
        _expose_var($page, 'cookie_additional_body', \Drupal::config('trust_ppg.settings')->get('trust_ppg_popup_cookie_additional_body'));

        if (isset($_COOKIE['consent_3rdparties_cookies']) && isset($_COOKIE['consent_additional_cookies'])) {
            _expose_var($page, 'cookie_3rdparties_consent', $_COOKIE['consent_3rdparties_cookies']);
            _expose_var($page, 'cookie_additional_consent', $_COOKIE['consent_additional_cookies']);
        }
    }

    if (hooks_enabled()) {
        $page['#attached']['library'][] = 'trust_ppg/main';
        //redirect_to_consent('');

        //POPUP
        if (
            \Drupal::currentUser()->isAnonymous()
            && \Drupal\Core\Url::fromRoute("<current>")->toString() != '/privacy-policy-full'
            && \Drupal\Core\Url::fromRoute("<current>")->toString() != '/user'
            && \Drupal\Core\Url::fromRoute("<current>")->toString() != '/user/register'
            && \Drupal\Core\Url::fromRoute("<current>")->toString() != '/company/register'
            && \Drupal\Core\Url::fromRoute("<current>")->toString() != '/research/register'
        ) {
            dpm('popup');
            $page['#attached']['library'][] = 'trust_ppg/modal';
            $page['#attached']['library'][] = 'trust_ppg/disabler';
            dpm($page, '$page');
        }
    }
}

/**
 * Implements hook_node_access().
 *
 * @param string $op
> git for-each-ref --format %(refname) %(objectname) --sort -committerdate
 *      The operation to be performed. Possible values:
 *          "create"
 *          "delete"
 *          "update"
 *          "view"
 * @param string $node
 *         Either a node object or the machine name of the
 *        content type on which to perform the access check.
 * @param object $user
 *
 * @return constant
 *        NODE_ACCESS_ALLOW, NODE_ACCESS_DENY, NODE_ACCESS_IGNORE
 */
function trust_ppg_access($op, $node, $account)
{
    return ($op == 'view' && ($account->hasPermission('permission ro') || $account->hasPermission('administer trust_ppg')));
}

// Implements hook_theme().
function trust_ppg_theme()
{
    return array();
}

function trust_ppg_policies_form_submit($form, &$form_state)
{
    if (\Drupal\Core\Url::fromRoute("<current>")->toString() == 'privacy-policy-full') {
        $user = \Drupal::currentUser();
        $account = $user;
    } else {
        $account = $form['#user'];
    }

    $tou_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_tou_guid_value');
    if ($tou_guid != 0) {
        $tou_consent = $form_state['input']['tou'];
        manage_consent_wrapper($tou_consent, $tou_guid, $account);
    }

    $privacy_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_privacy_policy_guid_value');
    if ($privacy_guid != 0) {
        $privacy_consent = $form_state['input']['privacy_policy'];
        manage_consent_wrapper($privacy_consent, $privacy_guid, $account);
    }

    $cookie_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_policy_guid_value');
    if ($cookie_guid != 0) {
        $cookie_consent = $form_state['input']['cookie_policy'];
        manage_consent_wrapper($cookie_consent, $cookie_guid, $account);
    }

    $cookie_3rdparties_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_3rdparties_guid_value');
    if ($cookie_3rdparties_guid != 0) {
        $cookie_3rdparties_consent = $form_state['input']['cookie_3rdparties'];
        manage_consent_wrapper($cookie_3rdparties_consent, $cookie_3rdparties_guid, $account);
    }

    $cookie_additional_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_cookie_additional_guid_value');
    if ($cookie_additional_guid != 0) {
        $cookie_additional_consent = $form_state['input']['cookie_additional'];
        manage_consent_wrapper($cookie_additional_consent, $cookie_additional_guid, $account);
    }
    //
    $marketing_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_marketing_guid_value');
    if ($marketing_guid != 0) {
        $marketing = $form_state['input']['marketing'];
        manage_consent_wrapper($marketing, $marketing_guid, $account);
    }

    $db_publication_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_db_publication_guid_value');
    if ($db_publication_guid != 0) {
        $db_publication = $form_state['input']['db_publication'];
        manage_consent_wrapper($db_publication, $db_publication_guid, $account);
    }

    $soft_optin_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_soft_optin_guid_value');
    if ($soft_optin_guid != 0) {
        $soft_optin = $form_state['input']['soft_optin'];
        manage_consent_wrapper($soft_optin, $soft_optin_guid, $account);
    }

    $profiling_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_profiling_guid_value');
    if ($profiling_guid != 0) {
        $profiling = $form_state['input']['profiling'];
        manage_consent_wrapper($profiling, $profiling_guid, $account);
    }

    $newsletter_guid = \Drupal::config('trust_ppg.settings')->get('trust_ppg_newsletter_guid_value');
    if ($newsletter_guid != 0) {
        $newsletter = $form_state['input']['newsletter'];
        manage_consent_wrapper($newsletter, $newsletter_guid, $account);
    }
}

How do I create an alleged hook (in Drupal 7 hooks were used, I think maybe they should also be used in Drupal 8) that allows me to add my module to the default form of Drupal 8?
Comment: As side note, there are at least four errors in the code: `hook_form_FORM_ID_alter()` implementations don't return any value, not even the form, since that is passed by reference; it's not true that a `hook_user_insert()` implementation needs to define `$edit` and `$category` as parameters; a `hook_user_insert()` implementation takes the account values from `$account`, the first argument the hook gets; functions defined from a module must be prefixed from its machine name, so a function name like `hook_enabled()` or `registration_extra_fields_validate()` is wrong.
Comment: @kiamlaluno I'll fix the code right away.
Comment: @kiamlaluno I edited the question starting from the working and hooked form in drupal 7. Rather than asking another question, I preferred to edit this (I don't know if I did well). Let me know an opinion. However, the edits can still be consulted.
Comment: Once the question gets answers, it cannot be edited, if the edits invalidate any given answer. If you have a new question, ask it. Questions aren't though as back-and-forth with the users who answer, nor to be re-used to ask a different question.
Comment: @kiamlaluno ok, thanks for the clarification.
Answer: As start, the code shown in the question is wrong in many points, in particular because it is using Drupal 7 code that has not been converted to Drupal 8. Drupal core has modules that alter the user edit form, which could be taken as guide for your own code.
Since you want to alter the user edit form when users create an account and when an existing account is edited, you should look at contact_form_user_form_alter(), which is used for exactly those two forms. From that hook implementation, and the code in AccountForm::form(), you will notice that:

#user_category isn't used anymore
The user account being edit isn't given anymore in $form['#user'] but it can be retrieved with $form_state->getFormObject()->getEntity()
The user editing that account, useful to determine who is editing the account, or to check if somebody is registering an account, can be retrieved with \Drupal::currentUser()
Any submission handler for the button used to create the account or edit it is added with $form['actions']['submit']['#submit'][], while a validation handler is added with $form['actions']['submit']['#validate'][]

As for the form submission and validation handlers:

$form_state isn't anymore an array, but it's an object implementing the FormStateInterface interface
The values submitted in a form element are given from  $form_state->getValue()
In case of validation errors, those errors are added using $form_state->setErrorByName() or $form_state->setError()

In some cases, it can be helpful to understand if a hook implementation like contact_form_user_form_alter() is invoked when people registers their own account, an administrator is creating an account for somebody else, or an account is edited. In those cases, the following code can be helpful.
$account = $form_state->getFormObject()->getEntity();
$user = \Drupal::currentUser();
$register = $account->isAnonymous();
$admin_create = $register && $account->access('create');
$self_register = $register && !$admin_create;

Using that code, $register is TRUE if an account is being registered/created, or FALSE if an existing account is edited; $admin_create is TRUE if the account is being created from an administrator user; $self_register is TRUE when the account is being registered.
As for the hook_user_insert(Drupal\Core\Entity\EntityInterface $entity) and hook_user_update(Drupal\Core\Entity\EntityInterface $entity) hooks (which are documented as hook_ENTITY_TYPE_insert() and hook_ENTITY_TYPE_update()), they only receive an argument: The user object being inserted or updated. Any information about the user needs to be taken from that argument, which is the user object after it has been edited/created. For hook_user_update(Drupal\Core\Entity\EntityInterface $entity), $entity->original returns the user object before it was changed.
As side note, any function implemented by a module should be prefixed by its machine name, to avoid conflicts with other modules. (The functions of all the modules are global.)
You have a hooks_enabled() function that could create name clashes with the Hooks module, when it adds a hooks_enabled() function to its code. You have also a registration_extra_fields_validate() function whose name starts with the machine name of the Entity Registration module.

Extend a form from a custom module


If $f$ is continious ,then $G$ is connected ? True/false

Question: let $X$ be  a  compact  topological space  and let $f : X \rightarrow \mathbb{R}$ be  function .The graph  of $f$  is the set  $G = \{(x,f(x)) : x \in  X \}  \subseteq    X \times  \mathbb{R}$.
Now my Question is that
If  $f$  is continious ,then $G$  is connected ? True/false
i thinks  it  will be true because continious image  of connected set is connected
Any hints/solution
thanks u
Comment: Huh?  $[0,1] \cup [3,4]$ is compact in the real line, but certainly not connected.
Comment: Doesn't look like $X$ is assumed to be connected.
Comment: compact  implies  connected  @Randall
Comment: @Randall good logics.....this logic  did n't  came in my mind
Comment: You've stated that $X$ is compact, not connected. Is that a typo? There are certainly disconnected compact spaces.
Comment: Not  Typo  @dbx  my question is correct   but   my answer may be  wrong im doubtful;
Answer: Consider $X=[0,1]\cup[2,3]$ and define $f:X \to \Bbb{R}$ by

$f(x) = x$ if $x \in [0,1]$ and $f(x)=x-1$ if $x \in [2,3]$.

Then by Pasting lemma $f$ is continuous but has disconnected graph.
Graph of $f$:


How do i do this in a trigger SQL Server

Question: The first line seems to be correct. The second line was my SQLite code. With code i get an exception about an error near trigger. In VS it says the multipart identifier could not be bound. With SQLite the new stands for the row being insert. So i would like to increase the count of whomever the subscription recipient is. How do i do that with a SQL Server trigger?
CREATE TRIGGER  trig_0  ON  subscription
 AFTER INSERT  AS
UPDATE user_data
   SET msg_count = msg_count + 1
 WHERE id = new.recipient;

Comment: My recommendation would be to use a view, and have `msg_count` as a computed column based on using the `COUNT` aggregate function...
Answer: There is no magic 'new' in SQL Server. There is a magic INSERTED, and is a table:
CREATE TRIGGER  trig_0  ON  subscription
 AFTER INSERT  AS
UPDATE user_data
   SET msg_count = msg_count + 1
FROM user_data
JOIN INSERTED ON id = INSERTED.recipient;

Answer: i think there is inserted and delted tables used by the trigger not new '''
3> CREATE TRIGGER myTriggerINSERT
4> ON Employee
5> FOR INSERT
6> AS
7> DECLARE @ID int, @Name nvarchar(30)
8>
9> SET @ID = (SELECT ID FROM inserted)
10> SET @Name = (SELECT Name FROM inserted)

for more detail : http://www.java2s.com/Code/SQLServer/Trigger/Getvaluefromupdatedinsertedanddeleted.htm
Comment: This is a very bad coding practice, insert 2 rows in your batch and your trigger blows up, please read http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/MSSQLServer/best-practice-coding-sql-server-triggers
Comment: this is just example to show that there is inserted table used by sql trigger not new
Answer: assuming subscription  has the column recipient which you can join with user_data.id, here is one way, you can use the inserted pseudo table to join back
CREATE TRIGGER  trig_0  ON  subscription
 AFTER INSERT  AS
UPDATE user_data
   SET msg_count = msg_count + 1
 WHERE exists (Select * from inserted i where user_data.id = inserted.recipient)


Programmatically get menu block & alter classes

Question: I'm invoking a menu block programmatically using:
    module_invoke('menu_block', 'block_view', 13);
What I want to do is change and add classes to the wrapper & ul tags of the menu block, is this possible? I can't seem to find a class_array to add  & have spent a significant amount of time looking through documentation & online but not come up with a solution.
Answer: borrowed from here:
add the following code in your template.php file.
<?php
  function THEME_menu_tree__main_menu($variables) {
    return '
' . $variables['tree'] . '
';
  }
?>

this would update the
 for main menu, adjust as necessary. You can adjust further up the chain within the page.tpl.php file.


Why does this tonal scale from 1737 have both F and E♯?

Question: I've recently encountered Jean Féry-Rebel's "Les Élémens". (Check out that wild opening; it's hard to believe it was written in 1737!)

In the fifth measure of the third staff, why does this descending scale include both F and E♯? (Notice that it uses the French violin clef, so the bottom line is G.) It's apparently not a typo; there are more E♯s in the instrument above this one and in the figured bass as well.
In recordings, this E♯ is clearly a half step lower than the preceding pitch, and thus E♮. Is this a byproduct of a particular tuning system? Is it some type of courtesy accidental so the performer doesn't play E♭ (the music did just cadence in B♭)? Or is it something else entirely?
Comment: Oh, great -- just as I get used to the Tenor Clef, here comes a clef offset even worse :-)
Comment: @coconochao The piece is called "The Elements." He's labeling the motives for each element. Way ahead of his time, right?
Comment: @CarlWitthoft- discounting octave transposition, all seven possibilities for clefs have been used historically.  A friend of mine who has perfect pitch, and had trouble transposing because of it, learned all seven clefs, and now just imagines the appropriate one (with sharps and flats to fit) so she can read at pitch.
Comment: Out of curiosity, what do the inscriptions "L'air", "L'eau", and "La Terre" mean? I mean, in french they mean, "the air", "the water",  and "the earth", but what do they mean in the piece's context?
Comment: Oh right, I missed the title of the piece. Very interesting though!
Comment: @CarlWitthoft just think of it as a bass clef where the instrument sounds two octaves higher.  Easier said than done, I suppose.
Answer: Wow! What you've stumbled upon is not just an impressively early use of a tone-cluster; it's also an impressively late survival of a system of chromatic notation, universal in the Middle Ages and Renaissance, that uses only two accidentals: the flat (written ♭) and the sharp (written  ♮, ♯, or various -like shapes). The flat is used to denote "low" versions of notes such as E♭, B♭, and F♮, and the sharp is used to denote "high" versions such as E♮, B♮, and F♯. As long as music does not get too chromatically adventurous, these signs are unambiguous. (For instance, Palestrina's output does not use sharps beyond D♯ or flats beyond A♭.)
In the present piece, the use of sharps and flats cannot be globally consistent (for instance, three kinds of D occur), but they are given meaning locally by relation to the main key. They most often represent major and minor intervals above the bass. This usage, in connection with a figured bass, is quite venerable. In fact, the first generation of figured basses, published by early Baroque composers such as Monteverdi, does not have figures at all: only a sharp or flat often placed on the line or space a 3rd above the bass note, directing the keyboardist to play a major or minor triad respectively. (See here.)
Answer: Normally there are only 7 lettered notes in a given key. This passage starts with  the notes C,Bb,Ab,then G,F,E#,D,C . I do nor know why this pattern was chosen by Féry-Rebel, but this method of notation preserves the 7-letter rule. He does it again in the next passage going upward. This is not apparently a chromatic passage as then the 7-letter rule wouldn't necessarily apply.
Is there an F# in the key signature? Were the passage in the key of G-major or e-minor, it could be a chromatic alteration. It's almost a reversed Phrygian scale on the note. It's also a c-minor scale with the third note as E# rather than as Eb. One more weird possibility is that the E# is really an E-natural with a 3-flat key signature (c-minor or Eb-Major).
Comment: No F♯ in the key signature, no. And I understand the 7-note rule, but why not just write it as E♮ instead?


How to install interdependent repository?

Question: My yum is not working properly and I don't know why. I already am into production and cannot restart. I am trying to install libjpeg-turbo from rpm and yum is not able to find dependency. The dependency is libjpeg-turbo-devel as well.
Command I have used:
 yum install
 http://mirror.centos.org/centos/6/updates/x86_64/Packages/libjpeg-turbo-1.2.1-3.el6_5.x86_64.rpm

 http://mirror.centos.org/centos/6/os/x86_64/Packages/libjpeg-turbo-devel-1.2.1-1.el6.x86_64.rpm

 Package: libjpeg-turbo-devel-1.2.1-1.el6.x86_64 (/libjpeg-turbo-devel-1.2.1-1.el6.x86_64)
           Requires: libjpeg-turbo(x86-64) = 1.2.1-1.el6
 You could try using --skip-broken to work around the problem

Comment: Why on earth would you do this and not make a new server without this messiness?  It will probably save you hours.
Comment: Why don't you just install the packages normally?
Comment: @Michael Normally means? I don't have rhel subscription. Accidentally used rhel. I will soon migrate to centos.
Comment: @MichaelHampton Actually I was installing postgis. It required libjpeg's .so file but although i had libjpeg installed it didn't find it out. That's why I am updating it to libjpeg-turbo.
Comment: @FalconMomot As you may have know I am new to linux environment. I don't know what messiness is here? After all I am installing software! May be I am doing it wrong way. what is the right way?
Answer: Localinstall installs a local package that's already been downloaded. Install will reach out to a repository and download the package...
All you really need to do here is let Yum do its thing:
yum install libjpeg-turbo libjpeg-turbo-devel

That's it.
Comment: I did that but from remote rpm. when I do yum install libjpeg-turbo libjpeg-turbo-devel then I get "No package libjpeg-turbo available.".
Comment: Then your packages are likely installed. Verify this with `rpm -qi libjpeg-turbo` and `rpm -qi libjpeg-turbo-devel`
Comment: I get "package libjpeg-turbo is not installed" and package libjpeg-turbo-devel is not installed from those command
Answer: I assume you are running the install using a local package file (if not, yum would solve the deoendency for you).
Just install both in one same command, like :
yum localinstall libjpeg-turbo*.rpm


How to integrate $\int \frac{1}{g-kv^2}~dv$

Question: How to integrate $$\int \frac{1}{g-kv^2}~dv$$ where $v$ is velocity and $g,k$ are known constants.
I have been stuck for a while on this and have now turned to SE for help any suggestions?
Comment: Could you do the integral if $g$ and $k$ were both $1$?  I.e., do you know how to integrate $\int{1\over1-v^2}\,dv$?
Comment: Partial fractions then logs?
Comment: As a starter: Factor the denominator, apply the partial fractions decomposition, and then integrate each term. You can do the rest.
Comment: What do you mean factor the denominator?
Comment: Like take out $k$ and then make it the product of two linear terms in $v$?
Comment: @Mechin Exactly.
Comment: @Mechin, yes, partial fractions then logs.  To do partial fractions, you need to factor the denominator (which is what kobe does in an answer).
Comment: @Mechin I provided an alternative methodology that might be useful to you both here and down the road. It uses hyperbolic trigonometric substitution, which is analogous to trigonometric substitution.  Let me know how I can make my answer better. I just want to give you the best possible answer I can give you.
Answer: I'm assuming $g, k > 0$. Let $\omega^2 = g/k$. Then
\begin{align}\int \frac{1}{g - kv^2}\, dv &= \frac{1}{k}\int \frac{1}{\omega^2 - v^2}\, dv\\
& = \frac{1}{2\omega k}\int \left(\frac{1}{\omega - v} + \frac{1}{\omega + v}\right)\, dv\\
& = \frac{1}{2\omega k}(-\log|\omega - v| + \log|\omega + v|) + C\\
& = \frac{1}{2\omega k}\log \left|\frac{\omega + v}{\omega - v}\right| + C\\
& = \frac{1}{2\sqrt{gk}}\log\left|\frac{\sqrt{g/k} + v}{\sqrt{g/k} - v}\right| + C.
\end{align}
Comment: The question I'm working actually states $k>0$.
Comment: This solution assumes $g/k>0$. It works but involves a choice of branch cut if $g/k<0$.
Comment: @Ian, actually it assumes that $gk\gt0$....
Comment: @BarryCipra You're right, sorry.
Comment: $gk > 0$ iff $g/k > 0$
Comment: @abel, I think $gk\gt0$ is a better way to say it, because $g/k$ is not defined (as a real number) when $k=0$.
Answer: Kobe provided an excellent solution using partial fraction expansions.  So, here, I'll use a different approach - hyperbolic trigonometric substitution.
To that end, let $I$ be the indefinite integral of interest, namely $I=\int \frac{dv}{g-kv^2}$.  Now, let's make the substitution $v=\sqrt{\frac{g}{k}}\tanh x$.  Then, we have $dv=\sqrt{\frac{g}{k}}  \text{sech}^2 x dx$ and
$$\begin{align}
I & = \int \frac{dv}{g-kv^2} \\
&= \int \frac{\sqrt{\frac{g}{k}}  \text{sech}^2 x \; dx}{g\left(1-\tanh^2x\right)} \\
& =\frac{1}{\sqrt{gk}} x +C\\
& =\frac{1}{\sqrt{gk}}\tanh^{-1}\left(\sqrt{\frac{k}{g}}v\right) +C
\end{align}$$
which is an acceptable final result.  If one prefers, one may use identity $\tanh^{-1} x = \log (\sqrt{\frac{1+x}{1-x}})$ to yield an alternative expression for $I$ as
$$\begin{align}
I & =\frac{1}{\sqrt{gk}}\log\left(\sqrt{\frac{\sqrt{\frac{g}{k}}+v}{\sqrt{\frac{g}{k}}-v}}\right) +C \\
& =\frac{1}{2\sqrt{gk}} \log \left( \frac{ \sqrt{\frac{g}{k}}+v }{ \sqrt{\frac{g}{k}}-v}\right) +C
\end{align}$$
which recovers the aforementioned result!


Como desabilitar cache da pagina

Question: Tenho uma página que salva a foto do usuário, ao editar a foto o cache sempre continua pegando a foto antiga pra exibir. Já tentei usar :

e tentei usar algumas variações disso e nao funciona. Alguem sabe alguma outra forma?
Comment: Pode usar o nome da foto com o sufixo baseado no timestamp da ultima atualização, por exemplo ``, então a cada vez que atualizar a foto o filemtime vai ser diferente, o que muda a URL e contorna o cache, como expliquei na resposta: https://pt.stackoverflow.com/a/169846/3635
Answer: Há uma forma muito simples de contornar a cache dos browsers, se alterar o nome da imagem o browser irá "pensar" que é uma nova imagem e não assume a cache da antiga.
Outra opção é no ficheiro .htaccess adicionar esta regra
<FilesMatch "\.(gif|ico|jpe|jpeg|jpg|js|png)$">
    <IfModule mod_expires.c>
        ExpiresActive Off
    </IfModule>
    <IfModule mod_headers.c>
        FileETag None
        Header unset ETag
        Header unset Pragma
        Header unset Cache-Control
        Header unset Last-Modified
        Header set Pragma "no-cache"
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
    </IfModule>
</FilesMatch>

Como desabilitar cache da pagina


mat-icon Angular don't appear

Question: I Import the Mat-Icon from Angular, but when i use then, he does not appear. Someone helps me?
Below my code:
app.module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
 declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatIconModule,
FlexLayoutModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

index.hmtl:
<!doctype html>

<meta charset="utf-8">
<title>TeslaAngular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2? family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<app-root></app-root>

My app.component.html when i call the mat-icon:

  <button class="button"><mat-icon>keyboard_arrow_down</mat-icon></button>

When i used the mat-icon i my app.component.html, this appear in this form:
Mat-icon error
Comment: olá, este é o site do SO em português, as perguntas aqui devem ser feitas nesse idioma
Answer: Você precisa adicionar o caminho do arquivo de icones no angular.json na tag de styles. Você deve seguir o seguinte caminho: projects -> "nome do projeto" -> architect -> options -> styles.

mat-icon Angular don't appear


Make background darker when sidebar is open in React + Typescript

Question: I'm trying to customize a sidebar using react-pro-sidebar with React + Typescript.
The sidebar looks fine but I cannot make the other part of the screen darker colored when the sidebar is opened.
Also, I would like to make the button that opens/closes the sidebar as a separate button. Is it possible in this case?
Here is a working sandbox of my code so far:  https://codesandbox.io/s/sleepy-lichterman-qqpp5?file=/src/App.tsx
And the same code put here:
import * as React from "react";
import { useEffect, useState } from "react";
import { ProSidebar, Menu, MenuItem, SubMenu } from "react-pro-sidebar";

import "react-pro-sidebar/dist/css/styles.css";
export interface SidebarProps {
  onChange?: (event: React.MouseEvent, isChecked?: boolean) => void;
  isCheckedInitial: boolean;
}

export function Sidebar({ onChange, isCheckedInitial, ...rest }: SidebarProps) {
  const [isChecked, setCheckedState] = useState(isCheckedInitial);

  useEffect(() => {
    setCheckedState(isCheckedInitial);
  }, [isCheckedInitial]);

  const handleChange = (event: React.MouseEvent) => {
    setCheckedState(!isChecked);
    onChange && onChange(event, isChecked);
  };

  return (
    <ProSidebar collapsed={isChecked}>
      <Menu iconShape="square">
        <MenuItem onClick={handleChange}>click </MenuItem>
        <SubMenu title="Top 1">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
        <SubMenu title="Top 2">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
        <SubMenu title="Top 3">
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
          <MenuItem>Sub menu</MenuItem>
        </SubMenu>
      </Menu>
    </ProSidebar>
  );
}

export default Sidebar;

Answer: You could just use a fixed positioned div for that. I edited your example here: https://codesandbox.io/s/kind-babycat-cg872
I added a button and an overlay div to the sidebar:
<button onClick={handleChange}>click me</button>
// <ProSidebar ...
<div
    className={`overlay ${!isChecked ? 'visible' : ''}`}
    onClick={handleChange}
/>

and added some css:
button {
    position: relative;
    z-index: 1;
}

.overlay {
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
}

.overlay.visible {
    right: 0;
    bottom: 0;
    opacity: 1;
    transition: opacity 0.4s;
}

Comment: The sidebar component supports a `collapsedWidth` property. I updated the codesandbox link accordingly so that the sidebar collapses down to `0px`.
Comment: thanks for the answer, it solves the problem with the darker background. related to the separate button, it isn't what is expected, is it possible to hide all the sidebar when the button is set on 'closed'? Something like this example (https://bootsnipp.com/snippets/y3O1) but with the button being fixed above it and visible all the time.


AngularJS $watch newValue is undefined

Question: I am trying to make a alert service with a directive. It is in the directive part I have some trouble. My have a directive that looks like this:
angular.module('alertModule').directive('ffAlert', function() {
  return {
    templateUrl: 'components/alert/ff-alert-directive.html',
    controller: ['$scope','alertService',function($scope,alertService) {
      $scope.alerts = alertService;
    }],
    link: function (scope, elem, attrs, ctrl) {
      scope.$watch(scope.alerts, function (newValue, oldValue) {
        console.log("alerts is now:",scope.alerts,oldValue, newValue);
        for(var i = oldValue.list.length; i < newValue.list.length; i++) {
          scope.alerts.list[i].isVisible = true;
          if (scope.alerts.list[i].timeout > 0) {
            $timeout(function (){
              scope.alerts.list[i].isVisible = false;
            }, scope.alerts.list[i].timeout);
          }
        }
      }, true);
    }
  }
});

The reason for the for-loop is to attach a timeout for the alerts that has this specified.
I will also include the directive-template:

{{alert.msg}}

When I run this, I get this error in the console:
TypeError: Cannot read property 'list' of undefined
    at Object.fn (http://localhost:9000/components/alert/ff-alert-directive.js:10:29)

10:29 is the dot in "oldValue.list" in the for-loop. Any idea what I am doing wrong?
Edit: I am adding the alertService-code (it is a service I use to keep track of all the alerts in my app):
angular.module('alertModule').factory('alertService', function() {
  var alerts = {};
  var id = 1;

  alerts.list = [];

  alerts.add = function(alert) {
    alert.id = id;
    alerts.list.push(alert);
    alert.id += 1;
    console.log("alertService.add: ",alert);
    return alert.id;
  };

  alerts.add({type: "info", msg:"Dette er til info...", timeout: 1000});

  alerts.addServerError = function(error) {
    var id = alerts.add({type: "warning", msg: "Errormessage from server: " + error.description});
//    console.log("alertService: Server Error: ", error);
    return id;
  };

  alerts.close = function(id) {
    for(var index = 0; index<alerts.list.length; index += 1) {
      console.log("alert:",index,alerts.list[index].id);
      if (alerts.list[index].id == id) {
        console.log("Heey");
        alerts.list.splice(index, 1);
      }
    }
  };

  alerts.closeAll = function() {
    alerts.list = [];
  };

  return alerts;

});

Comment: you should, because your watcher fires up at the first time when your directive initalized
Comment: What is `alertService` ?
Comment: I just added it in the question...
Comment: did you tried to put at the first line of the watcher function before console.log if(newValue === oldValue)  return
Comment: @NarekMamikonyan No, should I do that? Is not the point of the watcher to kick in if there is a new value in the watched object?
Comment: Thats it :) Maybe you could make that an answer I could accept, @NarekMamikonyan?
Comment: done :) good luck :)
Answer: try like this , angular fires your watcher  at the first time when your directive initialized
angular.module('alertModule').directive('ffAlert', function() {
  return {
    templateUrl: 'components/alert/ff-alert-directive.html',
    controller: ['$scope','alertService',function($scope,alertService) {
      $scope.alerts = alertService;
    }],
    link: function (scope, elem, attrs, ctrl) {
      scope.$watch(scope.alerts, function (newValue, oldValue) {
        if(newValue === oldValue) return;
        console.log("alerts is now:",scope.alerts,oldValue, newValue);
        for(var i = oldValue.list.length; i < newValue.list.length; i++) {
          scope.alerts.list[i].isVisible = true;
          if (scope.alerts.list[i].timeout > 0) {
            $timeout(function (){
              scope.alerts.list[i].isVisible = false;
            }, scope.alerts.list[i].timeout);
          }
        }
      }, true);
    }
  }
});

Answer: if you have jQuery available, try this
if(jQuery.isEmptyObject(newValue)){
      return;
}

inside scope.$watch

AngularJS $watch newValue is undefined


como pré-visualizar ficheiro .md durante edição?

Question: Gostaria de criar documentação em markdown para uma biblioteca no github. No entanto como não tenho forma de pré-visualizar o que estou a fazer, é comum fazer erros que apenas são descobertos quando o ficheiro já está publicado.
Existem algumas ferramentas onde seja possível observar em tempo real as edições que estou a fazer em ficheiros .md?
Answer: É possível fazê-lo de forma online através deste site ou então utilizar um dos pacotes que já vem por defeito com o atom, chamado de markdown-preview.
Para ter acesso à visualização do que está a ser editado basta estar com a aba selecionada, de um dos seguintes tipos de ficheiros:

.markdown
.md
.mdown
.mkd
.mkdown
.ron
.txt

E no menu principal do atom selecionar o seguinte:

Packages
Markdown Preview
Toggle Preview

Ou então simplesmente pressionar ao mesmo tempo:
<code>ctrl-shift-m
</code>
Um exempo pode ser visto aqui:
Answer: Existe também um plugin para o Google Chrome chamado MarkViewer, muito bom  e simples. Basta abrir o arquivo no navegador (com o plugin instalado) que ele já reconhece e formata. Não é necessário ficar atualizando a página a cada alteração do arquivo, o navegador já detecta as alterações e atualiza automaticamente.
Site do plugin: http://www.baiyunconsulting.com/portfolio-markview.html


Create template pages

Question: Using Drupal 7 and Clean theme. And my main module is Views. And i want, create template tpl.php file for every page.
I know node id method but don't know how create tpl file for views pages.
Please help, thank you.
Answer: In the views ui, click on 'advanced' and go to 'theme information'. This gives you a number of suggestions for the template file and what code should be in it.
Comment: My views display output: views-view--news.tpl.php  Now, i must put this file in templates directory?
Comment: yep, '/sites/all/themes/YOUR_THEME/templates'.
Comment: Sorry but not working. i want change header img every page. So, i want views id but not working.
Comment: be sure to use the Rescan button in the Views UI > Theme information
Comment: You want to override the page template to change the header. Probably not going to do this with views.

Create template pages


Kaplan's Non-Linearity Test

Question: I've been searching for an R package or function that applies the Kaplan non-linearity test to univariate time series but they are nowhere to be found. Such test has been widely applied in the analysis of financial time series such in the following paper. I would really be grateful if someone can point me to such a package.
Answer: This test is introduced in:
Kaplan, D. (1994), Exceptional Events as Evidence for Determinism, Physica D, 73, 38–48.
It is implemented as the function determinism() in the package fractal, which has been archived for over a year now. You can see the check results that caused the archivation here.
Comment: Hi @Grada Gukovic, Thank you very much for the answer! Do you know of any other package? I tried installing older versions of the package but I failed each time. It's really strange how such a test isn't easily found in R nor python.

Kaplan's Non-Linearity Test


How to catch a random value returned by a function in gdb

Question: In C, if you have a function that returns "always" the same result you can do:
(gdb) p foo()

But if this function always returns a random result, how to print THAT value without use a variable. Other detail, if you don't have debug information of the function, it's from a stripped lib.
(gdb) p myRandom() can't be used, it will result in something different than the value used by application.
You may ask: "Why would you use a random function and don't use its results", lets say that the return is just an extra thing of what that func does.
Comment: Similar question [here](http://stackoverflow.com/questions/267674/inspect-the-return-value-of-a-function-in-gdb).
Answer:
(gdb) p myRandom()
  can't be used, it will result in something different than the value used by application.

Presumably you want to examine the value that was returned to the application in the particular place where the application called myRandom().
You need to set a breakpoint on the instruction that immediately follows the CALL, then examine the register in which the value is returned. For example, on i*86, the value is returned in eax register, so you'll do print $eax.
Alternatively, set a breakpoint on myRandom(), then do finish command (you don't need debug info to do that), then examine the return register.


What is the workaround for "getElementsByTagName" in IE8?

Question: What is the workaround for "getElementsByTagName" in IE8?
Comment: @GSerg — TagName, not ClassName.
Comment: @Quentin The workaround is the same. Both `getElementsByTagName` and `getElementsByClassName` are mentioned in other duplicate questions with same answers (e.g. [here](http://stackoverflow.com/q/11537336/11683))
Comment: @GSerg — The usual workaround for `getElementsByClassName` is "Use `getElementsByTagName` and filter it"! How can the "workaround" for `getElementsByTagName` be the same?!
Comment: @Quentin The workaround is "use `document.querySelectorAll("tag")`".
Comment: @GSerg — That's an alternative to `getElementsByTagName`, but not a workaround (since there isn't a problem with `getElementsByTagName` to work around.) It certainly isn't what the accepted answer on the question you marked as a duplicate says.
Comment: @Quentin As I said, you can use `querySelectorAll` to replace both `getElementsByTagName` (if you don't provide the dot in the selector) and `getElementsByClassName` (if you do). True it's not the accepted answer, which is sad but happens. On a secons thought, I should have voted for [this](http://stackoverflow.com/q/11537336/11683) duplicate instead.
Answer: Internet Explorer has supported getElementsByTagName since IE 5.5 (IE 6 for support for the "*" value as the argument).
There is no workaround, or need for one, for IE 8.


Mail attachment not work android

Question: I tried the following code for attaching images to email. Images may be captured or selected from gallery.
<code>Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("image/*");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"firstname.lastname@example.com"});
i.putExtra(Intent.EXTRA_CC, new String[]{"firstname.lastname@example.com"});
i.putExtra(Intent.EXTRA_TEXT,Html.fromHtml(email_body));
i.putExtra(Intent.EXTRA_SUBJECT,"Vehicle Details");
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, Vehicle_images.uris);
startActivity(Intent.createChooser(i,"Share"));
</code>
Here email@example.com and email@example.com are dummy email ids and Vehicle_images.uris is a array list of uris.
The problem is that i cant to attach images from a Minno tablet, but this works on other devices. Minno tablet runs on Android 4.1 (Jelly Bean). Is this a known issue?
Answer: Try this it works for me
<code> Uri uri = Uri.parse("file:///sdcard/"+"rec1.jpg");
 i.putExtra(Intent.EXTRA_STREAM, uri);
</code>

Mail attachment not work android


Remote desktop software for Linux PCs?

Question: I need to connect to Linux computers from remote. I am using LogMeIn for windows PCs. But it doesn't have client for Linux boxes.
I have tried Team Viewer, but seems very heavy.
Is there any other solution for this??
Comment: Most people just use SSH, and X11 forwarding when needed for admin stuff.
Answer: One of the VNC client variants would be a good choice. There are several forks, I use TightVNC but YMMV.
Comment: Any Other hosted solutions like LogMeIn?
Answer: NoMachine (NX Free Edition in 3.5.0) for Linux will let you access Linux boxes. On your local desktop you'll need to install their client: NoMachine Player (NX Client 3.5.0). They also just released NoMachine for remote access to Windows PCs and Macs.
Answer: Either try using vnc (x11vnc or something) if you need the whole desktop, or ssh with X forwarding (ssh -X) to forward just one window/app.

Remote desktop software for Linux PCs?


Can't solve this differential equation

Question: I am trying to solve this differential equation:
$$xy'' = y$$
But Iam not going anywhere.
I have tried sumation of series but is there some method involving modified Bessel functions?
Thanks
Comment: Make a change of variable of $x=\sqrt{z}$. A Bessel differential equation will pop out.
Comment: My first try would be to "guess" $y(x) = \exp \left( \sqrt x \right)$ and then try to correct this guess.
Answer: Step 1:  Multiply by $x$ to get $x^2D_x^2$
$$
0=x^2D_x^2y-xy.
$$
Step 2: Switch to differential operator of the form $xD_x$:
$$
0=[(xD_x)^2-xD_x]y-xy.
$$
Step 3: Recreate a quadratic in front of $y$ by letting $x=cs^2$ noting $xD_x=\frac12sD_s$ (from the power $2$ on $s$):
$$
0=[(\tfrac12sD_s)^2-\tfrac12sD_s]y-cs^2y.
$$
Step 4: Let $c=\frac14$ to agree with the coefficient of $s^2D_s^2$ except for differing sign
$$
0=[\tfrac14(sD_s)^2-\tfrac12sD_s]y-\tfrac14s^2y
=\tfrac14[s^2D_s^2-sD_s-s^2]y.
$$
Step 5: Unfortunately the $sD_s$ has the wrong sign.  To fix this, let $y=sz$ and so
$$
0=[sD_s^2-sD_s-s^2]sz=[s^2D_s^2+sD_s-(s^2+1)]z
$$
and we recognise this as the modified Bessel's differential equation of order $1$.
Comment: Thank you very much!!
Answer: I am assuming $y$ is a function of $x$. Assume $y(x)$ can be written as $x^m$.
Then the differential equation can be written as
$m(m-1)x^{m-2}-x^{m-1}=0$.
Solve it for $m$.
and do not forget to add the arbitrary constants in your solution

Can't solve this differential equation


Python.exe is 0KB on Windows 7 64 bit

Question: I'm using Windows 7 64 bit and I have installed Python 2.7. After some other installations I have discovered that the python.exe in C:\Python27\ is actually 0KB, so I wanted to reinstall Python but I encounter an error.
I tried to uninstall python both from Programs and features and also from a Python .msi installer. Both ways the following error occurs:

I don't find registry values for python and I have removed the system variable for Python and there is no path to Python in the PATH system variable.
What may be causing this problem?
Thanks
EDIT:
I just deleted the whole folder C:\Python27 but the error still occurs.
Answer:
In explorer go to C:\Users\xxx\AppData\Local\Temp
Right-click properties of `Temp'
Click the Security tab
Click Edit
Click Add under the groups and usernames
Type Everyone in the text box, and hit OK
Then in the bottom text box in the Allow column tick FULL CONTROL
Apply the changed settings
Comment: Thanks for the replay, but I managed to solve the problem and posted an answer, you can check it out. Your answer could have given a hint to me.
Answer: I solved the problem.
These are the things that I did:

Since I had two users on my PC(one of which is no longer used), and I had installed Python 2.7 on the other user I entered C:\Users and deleted the folder of the other User
I deleted the content of C:\Users\xxx\AppData\Local\Temp
I started searching for registries in regedit and started deleting all registries that I found related to Python. After deleting at least 10 registries I decided to stop and give the uninstall another try and it worked.

I don't know if this solution helps others, but It solved the problem in my case. As a whole, the problem was that somewhere something was using python in the background and the uninstall component could not remove it from my PC.

Python.exe is 0KB on Windows 7 64 bit


How do I replace ", ," with ","

Question: My string is as follows "Increase in housing cost,  Create sense of Financial security,  Reduced Travel,  ,Happiness for Family, Financial Security".
I want to remove the space and extra comma in the string using JavaScript. So the final string should be "Increase in housing cost,  Create sense of Financial security,  Reduced Travel, Happiness for Family, Financial Security"
The string is coming from a variable "myString"
I tried using
myString = myString.replace(", ,",","); but it does not work.
Comment: `replace(", ,", ", ")` - you missed the space in the second argument.
Answer: Match , and , with whitespace (or none) in between them. This is called regular expression or regexp and it's a language to describe actions that can be done on text (this is my free interpretation).
In this specific instance, this matches comma followed by \s (whitespace) 0 or more times * then followed by comma. The g at the end means match all not only the first.

var reg = /,\s*,/g
console.log("Increase in housing cost, Create sense of Financial security, Reduced Travel, ,Happiness for Family, Financial Security".replace(reg, ', '))
Comment: Thanks for the solution. Can you please explain the code?
Answer: let myString = "Increase in housing cost, Create sense of Financial security, Reduced Travel, ,Happiness for Family, Financial Security";
myString  = myString.replaceAll(", ,",",")

How do I replace ", ," with ","


How do I specify include and lib paths to node.js npm

Question: I'm trying to install a node.js module (zmq in this case) with npm install. The C lib needed for this module is not installed in a standard location. How do I specify extra include paths and lib paths to npm? I've tried things like "CFLAGS="-I/path/to/include" npm install" with no effect.
Comment: I've been fighting the same issue, and got it working by setting `CXXFLAGS` before, along with the `-L` in `LDFLAGS` before the npm install.
Comment: possible duplicate: https://stackoverflow.com/questions/29832321/node-gyp-and-custom-dependency-library-header-install-path
Answer: The zeromq module can be built as follows (other modules may work the same):

download the zip file and unpack into a temporary location e.g. /tmp/zeromq.node-master
edit the binding.gyp file
find the section that corresponds with your OS and add your include -I and library -L paths there.

e.g.
['OS=="linux"', {
  'cflags': [
    '<!(pkg-config libzmq --cflags 2>/dev/null || echo "")',
    '-I/usr/local/zeromq3/include'
  ],
  'libraries': [
    '<!(pkg-config libzmq --libs 2>/dev/null || echo "")',
    '-L/usr/local/zeromq3/lib'
  ],
}],

Run npm install on the temporary directory:  npm install /tmp/zeromq.node-master
Answer: Another solution (does not require any file changes) is to use pkg-config's PKG_CONFIG_PATH variable, which should point to the location where the libraries are installed. If zmq has been installed at /opt/zmq then PKG_CONFIG_PATH=/opt/zmq/lib/pkgconfig pkg-config libzmq --libs should return -L/opt/zmq/lib -lzmq and npm install can be run with
PKG_CONFIG_PATH=/opt/zmq/lib/pkgconfig npm install
Before node app is started LD_LIBRARY_PATH must be set accordingly, i.e: LD_LIBRARY_PATH=/opt/zmq/lib node app.js


Simple question about Ornstein-Uhlenbeck process

Question: My question comes from this paper. The picture bellow provides a summary of the equations.
Suppose prices of two stocks satisfy (2.1) SDE. Then X(t) is expressed as (2.2) and can be modeled with as an OU process (2.3). To estimate OU coefficients we run an OLS (2.4) where R1 and R2 are time series of two stocks. Then we calculate the random walk series X(k) (2.5) and run a lagged regression on it (2.6). From which we estimate mu, sigma and theta.
Author says that after we obtain OU parameters "At this stage, we can use the standardized version of X(t) , called Z-score as trading signal." Ok, Z score is (X(t) - mu)/sigma.
What is X(t) in the Z-score? are those residuals series from (2.5) or residuals from OLS in (2.4)? How do we fit the OU coefficients to model the spread as an OU process?

EDIT:
Since I searched the internet far and wide for the implementation of the equations above and found nothing that would be usefull for this task, I wrote a Python script, it's rusty, but it does the job. Hopefully it will help someone to avoid troubles that I encountered
<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os
from sklearn import linear_model

path = "C:\Users\PC\Desktop\Magistr\models\\test_data"
os.chdir(path)
data = pd.read_csv("stocks.csv", index_col = 'Date')
startDate = 0
endDate = 60
s_scores = []

for i in range(0, 100):
    #S-score estimation
    Y = data['007310 KS Equity'][startDate+i:endDate+i] #cointegrated securities
    X = data['001680 KS Equity'][startDate+i:endDate+i]
    Y = (Y.shift(1) / Y - 1)[1:]
    X = (X.shift(1) / X - 1)[1:]
    clf = linear_model.LinearRegression()
    clf.fit(np.array(X).reshape(len(X),1), np.array(Y).reshape(len(Y),1))
    beta_hr = clf.coef_[0]
    alpha = clf.intercept_[0]
    residuals = Y - beta_hr*X - alpha #residuals of the OLS (2.4)
    Xk = np.cumsum(residuals) #auxiliary values (2.5)
    #Xk = Xk[:-1] #remove the last value which is 0

    #create two time series for AR(1) process
    x_k = Xk[0:-1] #x(t-1)
    y_k = Xk[1:] #x(t)
    clf = linear_model.LinearRegression()
    clf.fit(np.array(x_k).reshape(len(x_k),1), np.array(y_k).reshape(len(y_k),1))
    ar1_beta = clf.coef_[0]
    ar1_alpha = clf.intercept_[0]
    ar1_resids = np.array(y_k) - ar1_beta*np.array(x_k) - ar1_alpha #calcualte residuals of AR(1)
    mu = ar1_alpha/(1-ar1_beta) #calculate MU
    sigma_eq = np.sqrt(np.var(ar1_resids)/(1-ar1_beta**2)) #calculate sigma
    s = -mu/sigma_eq #s-score
    s_scores.append(s)
</code>
Answer: The method discussed in the article you mention is directly inspired from the paper 'Statistical Arbitrage in the U.S. Equities Market' by Avellaneda & Lee (2008). Most of your questions are answered in the Appendix p.44.

Suppose we are at the end of trading day $D$. In the Avellaneda & Lee paper the s-score is defined as
$$ s = \frac{X - m}{\sigma_{eq}} $$
It is a measure of the distance to equilibrium of the current cointegration residual $X$ i.e. how far away is $X$ (in standard deviation units) from the theoretical equilibrium value $m$ predicted by a mean-reversion model yet to be estimated.
In practice, using the notations of your paper and considering a 60-days trailing estimation window, $X$ evaluates as
$$ X := \sum_{j=t_1}^{t_{60}} \epsilon_j $$
with $\{\epsilon_j\}$ the regression residuals computed as
$$ \epsilon_j = R_j^1 - \left(\hat{\beta}_0 + \hat{\beta}R_j^2\right),\ \ \ \forall j=t_1,...,t_{60} $$
where $\{R_j^i\}$ figures the 60 most recent close-to-close returns of the 2 securities of interest in case of pairs trading.
If $\hat{\beta}_0$ and $\hat{\beta}$ are OLS estimators then it is well-known that the regression residuals $\{\epsilon_j\}$ will be uncorrelated and have zero mean such that $X = 0$ and the s-score becomes
$$ s = -\frac{m}{\sigma_{eq}} $$
where the parameters $m$ (stationary mean) and $\sigma_{eq}$ (square root of stationary variance) of the Ornstein-Uhlenbeck (OU) process  $(X_t)_{t\geq0}$  are estimated as follows:

Calculate the auxiliary values $\{X_k\}$ as follows
$$X_k = \sum_{j=t_1}^{k} \epsilon_j,\ \ \ \forall k = t_1,\dots,t_{60}$$
where the $\epsilon_j$ are the factor model regression residuals discussed above (note that $X = X_{60}$ by construction).
Calibrate an AR(1) model to the previous values
$$X_{k+1} = a + b X_k + \zeta_{k+1},\ \ \ \forall k = t_1,\dots,t_{59}$$
i.e. perform yet another linear (lagged-)regression to determine $\hat{a}$, $\hat{b}$ (intercept and slope) along with the regression residuals $\{\zeta_{k}\}$,.
Comparing the Euler discretisation of the Ornstein-Uhlenbek SDE (see equation 2.3 in your paper) to the AR(1) model above, infer the parameters of the OU process from $\hat{a}$, $\hat{b}$ and the auxialiary regression residuals $\{\zeta_{k}\}$, see original paper. At the end you should end up with
$$ m = \frac{\hat{a}}{1-\hat{b}} $$
$$ \sigma_{eq} = \sqrt{\frac{\text{var}(\{\zeta_{k}\})}{1-\hat{b}^2}}$$

The idea is then that, depending on the strength of the mean-reversion signal (= the value of the $s$-score), we decide on day $D$ to buy/sell at tomorrow's open (or close an existing position), see original paper.
Obviously, on day $D+1$, based on the new closing prices that you will observe end of day, you will be able to compute a new $s$-score by repeating the steps above (sticking to a 60-days trailing estimation window, which will now contain the most recent return corresponding to day $D+1$, while the oldest one corresponding to $D-61$ will have disappeared). Repeating this on different days allows you to plot a graph where the $s$-score evolves through time as in Figure 10 of the original article.
Comment: Thanks Quantuple, great answer. So now, if I understand you correctly I should use X from the auxiliary values series (2.5) to fit in the Z-score equation. Regarding the Avellaneda papers, the notation that ***s=(-m)/sigma*** is a bit confusing to me, since both ***m*** and ***sigma*** are constants the s-score will also be constant, but Figure 7 from the paper, shows its evolution as a mean reverting process, is that example calculated using auxiliary values? In the 3rd section it is defined as per equation (2.1) above.
Comment: @Arti, I have edited my answer for you to get a better grasp of what really happens in practice. Please re-read everything since I've added details everywhere :) If the answer suits you, don't hesitate to accept it: if it helped you it might help others.
Comment: Quantuple, do you have any experience of implementing this algo? I ran several simulations estimating s-scores for each day based on the historical 60 days period. I estimated around 100 s-scores and then applied trading tresholds from Avellaneda paper, the results are just random trading there is no visible edge at all. Is it correct to run the regression everyday? shouldn't some parameters be kept constant for some time?
Comment: @Arti No I never ran this strategy myself. My bad: I only mentioned this daily re-calibration to illustrate why $s$-scores were not constant as you initially claimed. If you look in your reference (bottom right paragraph at page 1 and figure 2.2), you see that they suggest to keep $\hat{\beta}$ (OLS weights obtained when regressing $R^1$ on $R^2$) piecewise constant over intervals of 5 days to preclude rebalancing costs from eating up the profit from trading mean reversion. Also I suggest you first benchmark your impl using the same data set as the reference paper to see how it compares.
Comment: Do I understand correctly that after running OLS: 1) I get beta and alpha, 2) I estimate OU parameters, 3) then I hold all parameters constant for next 5 days, 4) get 5 residuals from the regression, add them up to X(k) one by one, 5) estimate Z score for rach of these 5 days via (X(k)-mu)/sigma,  where mu and sigma are OU parameters obtained in step 2).
Comment: Personally, this is what I understand. Day 1, (1) run OLS to get $\hat{\beta_0}$ and $\hat{\beta}$, (2) build auxiliary process from regression residuals and estimate OU parameters (3) generate signal and trade accordingly. Day 2 to Day 5, instead of step (1) just use the value found at day 1 and continue with steps (2) and (3) as usual. Day 6, do as Day 1 that is find the new $\hat{\beta}$ etc. **Maybe you would get more insight if you asked this question on Quantitative Finance Stack Exchange**, please be specific on what you tried and what you already know if you do so people there can help


merge some ogg audio files using java programming language

Question: I have some .ogg sound files that must be merged together.But the problem is in that the java only support .wav extension (as I used AudioSystem and AudioInputStream).
I've searched among different pages for converting and I've not found a better way than.
Do you know a better way other than using Command line tool?
Answer: I think you may have to inspect and tinker with the source code. This can be obtained from various libraries that have JOrbis and other files needed for ogg playback and encoding (there are several on github).
For a project where I needed to load decompressed ogg files (that were originally wav) into memory, I used source code from the example OggPlayer (usually included in the package) and intercepted the bytes before they were written to a SourceDataLine. You can maybe also find a hook in example code that compresses wav to ogg and then link the two parts.


How to test amount of differences in T-test in R for large samples?

Question: We have good discussions on hypothesis testing in large data: With large amount of data, even tinny difference between two samples can be detected, and we are almost certain to reject NULL hypothesis.
Effect size is one "fix", but I am interested in other fix, where, in addition to say they are different, but say how much the difference are.
I not know how to do it in R. Let us assume we are doing two sample T test, how can I say I want to test if the means are different by say certain amount say $0.1$ ?
The following code is test if two means are equal. How to modify it to test if two means are difference by $0.1$?
sample1=rnorm(1e5)
sample2=rnorm(1e5)
t.test(sample1,sample2)

    Welch Two Sample t-test

data:  sample1 and sample2
t = -0.5542, df = 2e+05, p-value = 0.5794
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.01124444  0.00628720
sample estimates:
    mean of x     mean of y
-0.0002658978  0.0022127222

Edit:
I was trying to ask if the amount difference on mean of two samples within range of $-0.1$ to $0.1$, not exactly to equal $0.1$.
Reading Peter Flom 's comment, modifying T test will not meet my needs?
Comment: In a regular two sample t-test the null is "the two means are equal".  In a test of equivalence, the null is "the two means are different by at least XXX".  I think you want something else, namely null is "the two means are withing XXX"
Answer: R code questions are actually off-topic here but it is:
t.test(sample1, sample2, alternative = "two.sided", mu = 0.1)

I think the question should stay here, however, because it raises a statistical question. My view is that looking for an effect larger than a certain amount makes a lot of sense, but it can be hard to choose an amount.
Comment: No, it's not a stack overflow question either - because it's not really about programming.  It's an interesting statistics question along with a very basic R question.
Comment: two.sided not two-sided.  But I'm not sure this is right, I think the OP really wants the null hypothesis is mu is between -0.1 and 0.1, and alternative is that abs(mu) > 0.1 (not mu = 0.1).?
Comment: Thanks, I thought to ask it to stack overflow.. but as you said, it raises a statistical question.
Comment: Thanks for the syntax fix but I think what I had does test abs(mu) > 0.1.  Exactly 0.1 doesn't make sense.  Unless I am missing something (which certainly could be the case).  Are you suggesting OP wants a test of equivalence?
Comment: @PeterFlom sorry I was trying to ask within range of -0.1 to 0.1, not exactly to equal 0.1
Comment: What is -0.1 to 0.1? Confidence interval?
Comment: Now you've got me confused.  A test of equivalence is inherently quite different from a (regular) t test. I don't think a TofE is a solution to the big data issue.
Comment: I'm pretty sure your test has the null hypothesis that difference = 0.1 and "alternative hypothesis: true difference in means is not equal to 0.1" (from the output).  So the small p-value it returns just means there is evidence against the difference in means being exactly 0.1.
Comment: I think @hxd1011 needs to clarify his question
Answer: There is not a usual way to use a t-test to test if the absolute difference is larger than 0.1, or even to test if the difference lies within a given range.
However, your goal of assessing how large the difference is can be achieved by using the confidence interval. It's already in your results, since R and most statistical packages produce a confidence interval when told to perform a t-test:
95 percent confidence interval:
 -0.01124444  0.00628720

Comment: I think this is the best approach.  Fuzzy null hypotheses are tricky in the frequentist paradigm, and more attention to the effect size rather than a sharp hypothesis test is the best and simplest thing to explain and encourage.
Answer: I'm not going to attempt to answer the R portion of this question, but I wanted to comment on this: "Effect size is one "fix", but I am interested in other fix, where, in addition to say they are different, but say how much the difference are."
The purpose of effect size is to attach a measure of magnitude of effect, or difference, between the populations (or treatments).
If you are not familiar with effect sizes, I recommend you read:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3444174/
and
http://www.leeds.ac.uk/educol/documents/00002182.htm

'Effect size' is simply a way of quantifying the size of the difference between two groups.

As a statistical consultant, I always push for reporting of effect sizes to any statistical product.
An Edit:
I want to comment on this: "I was trying to ask if the amount difference on mean of two samples within range of −0.1−0.1 to 0.10.1, not exactly to equal 0.10.1."
I think there needs to be some clarity on this. What exactly is -0.1 to 0.1? Is this a confidence interval? Acceptance region?
Comment: +1, I think may need your help to say it formally. What in my mind, is: we know they are different, but can we say they are different by $x$ amount?
Comment: No. That's the purpose of a confidence interval. You're 95% confident that the difference between Pop A and B is -0.1 to 0.1. Also, note that that's another big issue. If 0 is in your Conf Interval, then it's REALLY difficult to accept that there is a difference at all.
Answer: You can just subtract or add 0.1 to one of the datasets.
Comment: thanks, my question was not clear. could you take a look at my edit?