Approximate Lebesgue measure of closed set

Question: Let $F \subseteq \mathbb{R}$ be a closed set and assume that it has finite Lebesgue measure. We know that the sequence $(f_n)$ where $f_n:\mathbb{R} \to \mathbb{R}$ is defined as $f_n(x) = \max(0, 1-n\cdot d(x, F))$ approximates the characteristic function of $F$, where $d(x, F)$ is the distance function defined as $d(x,F) = \inf\{|x - y| : y \in F\}$.
My question is, can we conclude that $\int_\mathbb{R} f_n \to m(F)$? For open sets, something similar holds but in that case we can prove it using the Monotone Convergence Theorem.
Comment: @LázaroAlbuquerque Unless I am mistaken we have $f_n \geq \chi_F$.
Comment: We have $f_n \le 1$ and $m(F) < \infty$, so dominated convergence should be enough.
Comment: @LázaroAlbuquerque I meant the integral over $\mathbb{R}$. I will edit the post.
Comment: It still works. We have $f_n \le 1_F$ and $\int_{\mathbb{R}} 1_F = m(F)$.
Comment: I have posted a detailed answer to your question. Please, let me know if you have any question regarding my answer. If my answer provides relevant / helpful information regarding your question, please, upvote it. If my answer actualy answers your question, accept it too, please. To upvote, click the triangle **pointing upward above the number** (of votes) in front of the question. To accept the answer, click on the check mark beside the answer to toggle it from greyed out to filled in.
Answer: The result, as stated, is false. Here is a simple counter-example.
Consider $F=\Bbb N $. Clearly, $m(F)=0$.
Let $(f_n)$ where $f_n:\mathbb{R} \to \mathbb{R}$ is defined as $f_n(x) = \max(0, 1-n\cdot d(x, F))$. It is clear that $(f_n)$ approximates the characteristic function of $F$.
However, for $n\in \Bbb N$, $n \geqslant 1$, let $A_n= f_n^{-1}\left(\left[\frac{1}{2},1 \right]\right)$. Then, we have
$$A_n= f_n^{-1}\left(\left[\frac{1}{2},1 \right]\right) = \left\{ x \in \Bbb R, d(x,F) \leqslant \frac{1}{2n} \right\} = \bigcup_{a \in \Bbb N} \left [a -\frac{1}{2n} , a+\frac{1}{2n}  \right ]$$
It follows that $m(A_n) = +\infty$, and for all $x\in A_n$, $f_n \geqslant \frac{1}{2}$. So, we have, for $n\in \Bbb N$, $n \geqslant 1$,
$$\int_\mathbb{R} f_n  \geqslant \int_{A_n}\frac{1}{2} = \frac{1}{2} m(A_n)=  +\infty  $$
So clearly, $\int_\mathbb{R} f_n$ does not converge to $m(F)$.
Remark: If you replace the condition "$F$ has finite Lebesgue measure" by the condition that "$F$ is bounded" then the result is true.
In fact, if $F$ is bounded, then there is $[c,d]$ compact interval such that $F \subseteq [c,d]$.
It follows that  for $n\in \Bbb N$, $n \geqslant 1$,
$$ |f_n| = f_n \leqslant \chi_{[c-1, d+1]} $$ and
$$\int_{\Bbb R}  \chi_{[c-1, d+1]}  < +\infty$$
So by the Dominated Convergence Theorem, we have that
$\int_\mathbb{R} f_n \to \int_\mathbb{R} \chi_F = m(F)$.
Comment: @GiorgosGiapitzakis , You are welcome. Having only the hypothesis that $F$ has finite measure, I don't see any single way (independent of $F$) to define the sequence  $(f_n)$  such that it  would make the result work.
Comment: Thanks for the detailed answer. Is it possible for the result to hold if we replace $(f_n)$ with another sequence of functions?
Comment: I see. Thanks for your help!


Sample Size Estimation for two data loggers on a plane

Question: I have two computers that have access to the same sensor on a plane and both log speed every second. What sample size formula should I use for testing a null hypothesis of equivalence in terms of speed logged?
Assuming the speeds logged are normally distributed
#1 Sample Sizes for Two Independent Samples, Continuous Outcome
#2 Sample Size for Paired Samples, Continuous Outcome
Comment: When you say "what sample size formula should I use for testing a null hypothesis of equivalence in terms of speed logged", I assume that you are looking for a statistics test that allows you to determine whether both computers are logging speed the same way?
Answer: Too few information about your problem is provided. My understanding is that you want to perform an equivalence test. The simplest approach is the TOST (Two-One-Sided T-test) procedure https://en.wikipedia.org/wiki/Equivalence_test. It is already well documented on this site https://stats.stackexchange.com/a/500121/321901
Concerning the sample size, same comment, too few information is provided, but you might be interested by this article: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5012670/ and the R package powerTOST


Using a scalar value function with declared variables to run through multiple records in a select statement

Question: Good day,
I have a scalar value function that I used to determine a payment value (PMT function in Excel) in SQL Management Studio. I imported the following C# function:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class FinancialFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDouble PMT(double r, int nper, double pv, double fv, int type)
    {
        double pmt;
        if (nper == 0)
            pmt = 0;
        else if (r == 0)
            pmt = (fv - pv) / nper;
        else
            pmt = r / (Math.Pow(1 + r, nper) - 1)
                * -(pv * Math.Pow(1 + r, nper) + fv);

        if (type == 1) pmt /= (1 + r);

        return pmt;
    }

The function is then called as follows in SQL:
DECLARE @LoanValue decimal(38,20)
DECLARE @APR decimal(20,15)
DECLARE @FullTerm int

SET @LoanValue     = VALUE of each individual loan
SET @APR           = INTEREST RATE for each individual loan
SET @FullTerm      = TOTAL TENURE for each loan

DECLARE @PMT decimal(38,20)

SET @PMT = dbo.PMT(@APR/12.0, @FullTerm, @LoanValue, 0, 0)

SELECT @PMT AS PMT

How would write a script to run through multiple loans with varying values, interest rates and durations?
Your assistance would be greatly appreciated.
Thank you.
Comment: Not sure I understand. If you mean *"How do I use this is a `SELECT` statement?"* then you use it like any other function. `SELECT {Other Columns}, dbo.PMT(YT.APR, YT.FullTerm,YT.LoanValue,0,0) AS PMT FROM YourTable YT...`
Comment: Thank you @Larnu. I've been sitting in front of this laptop for so long that I forgot basic scripting. Appreciate the assist and pointing the obvious out to me sir.
Answer: create a Table with all the values you need for the function.
  SELECT LoanValue, APR, FullTerm, fv, type ,
         dbo.PMT(APR/12.0, FullTerm, LoanValue, fv, type) as result
  FROM YourTable

Comment: Thank you kindly Juan, appreciate the assist with something so trivial.


Como colocar scroll em collapse do Bootstrap?

Question: Gostaria de colocar o efeito de scroll suave ao clicar no "veja mais" do collapse no código abaixo. Estou usando HTML, CSS, jQuery e Bootstrap.
HTML:
 <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Portfólio</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Portfólio

Nome Projeto

                      Veja mais

Titulo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pulvinar et urna vitae porta. Integer venenatis nisi in nisi congue lobortis. Proin fermentum ut tortor eget facilisis. In nec felis vulputate, suscipit nisl non, blandit tellus. Nullam eget tortor urna. In dignissim lectus non dolor sodales molestie. Duis in vulputate augue, sed tristique sem. Donec commodo ex a elit tempor laoreet. Quisque tortor libero, lobortis id metus eu, dignissim efficitur nunc. Suspendisse eu lorem at urna volutpat sagittis.

                    ACESSE O SITE

                    CONHEÇA A HISTÓRIA

Eu editei a pergunta, pois tinha colocado as informações de forma errada. Gostaria de fazer o scroll da página quando o usuário clicasse no "Veja mais". Eu tentei fazer mas quando eu clicava pra fechar o collapse que abria, a tela descia novamente bugando a tela.
Comment: Cara está meio confuso seu código da para explicar um pouco melhor o efeito, nem scroll tem na página...
Comment: Dá uma olhada no Scrollspy do Bootstrap pra ver se te ajuda. https://www.w3schools.com/bootstrap/bootstrap_scrollspy.asp
Comment: Não é exatamente isso que eu queria. O problema não é colocar scroll na página o problema é o scroll com o collapse.
Comment: @hugocsl eu editei a pergunta, acredito que agora dê pra ver certinho.
Comment: Vc quer descer a tela ao clicar no "veja mais"?
Comment: Sim, exatamente. Mas somente quando o "modal" debaixo não estiver aberto.

Quando você clica no "veja mais" a primeira vez ele abre uma caixa embaixo e quando clica pela segunda vez a caixa debaixo fecha novamente e some. Gostaria que quando clicasse no "veja mais" pra abrir o "modal" quando abrisse, a tela fizesse um scroll suave até o "modal".
Answer: É só usar o callback do evento shown.bs.collapse (veja doc) e rolar a tela com animate até a div que foi aberta:

$(function(){
   $('#collapseExample').on('shown.bs.collapse', function(){
      var id = $(this).attr("id");
      $('html').animate({scrollTop: $("#"+id).offset().top})
   });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Portfólio

Nome Projeto

                      Veja mais

Titulo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pulvinar et urna vitae porta. Integer venenatis nisi in nisi congue lobortis. Proin fermentum ut tortor eget facilisis. In nec felis vulputate, suscipit nisl non, blandit tellus. Nullam eget tortor urna. In dignissim lectus non dolor sodales molestie. Duis in vulputate augue, sed tristique sem. Donec commodo ex a elit tempor laoreet. Quisque tortor libero, lobortis id metus eu, dignissim efficitur nunc. Suspendisse eu lorem at urna volutpat sagittis.

                    ACESSE O SITE

                    CONHEÇA A HISTÓRIA

Comment: Opa, cara. Era justamente isso que eu queria. Eu consigo mudar até onde o scroll desce na página? No projeto que tô desenvolvendo eu tenho um menu fixo, e quando o a página desce uma parte do "modal" que abre é coberto com o menu
Comment: Sim. Vc ajusta a posição subtraindo um valor. Por exemplo, afastar 50 pixels do topo: `$("#"+id).offset().top-50`


What does $\arg(z-z_1)-\arg(z-z_2)=\phi$ represents.

Question: What does $\arg(z-z_1)-\arg(z-z_2)=\phi$ represents.
where $z$ is point in argand plane
My Doubt:
I am attaching a Image for the doubt because I don't know How to draw in latex. I'll be grateful if you can tell me how to do that.
I am considering $z_1$ is right of $z_2$
I've drawn $4$ diagram for locus. Can you tell me Are the arrow marked for angle by me are correct?
Also you can give me more information If you have.
Also locus of $z$ will be full circle or half circle if $\phi$  is $\dfrac{\pi}{2}$. If it is full circle what will be arrow mark for angle.
Comment: The locus is a part-circle, depending on the values of $z_1$, $z_2$ and $\phi$
Comment: It depends a bit on how you define $\arg$, as an equivalence class or a real number.
Answer: I am adding My Own Answer
Here I'm Attaching two Images in which I've plotted Locus of $z$ because I don't know how to plot them Digitally.
Arrow Must end at $(z-z_1)$ and must originate from $z-z_2$.
Also I am considering Principle Argument that is $(-\pi,\pi]$.


Comparison and Extraction using SSE

Question: What is the best way for pairwise comparison of two integer registers and extraction of equal elements using SSE instructions? For example, if a = [6 4 7 2] and b = [2 4 9 2] (each register contains four 32-bit integers), the  result should be [4 2 x x]. An alternative form of this question is how to obtain a binary mask of equal elements (..0101b) that can be used for shuffling or as an index to lookup a parameter for shuffling instruction in the precomputed table.
Comment: Subtraction will turn equal pairs of numbers into 0.
Answer: It is not possible to extract and move equal elements with one instruction. But a mask of equal elements can easily be achieved with pcmpeqd:
__m128i zero = _mm_set1_epi32(0);
__m128i a = _mm_set_epi32(6, 4, 7, 2);
__m128i b = _mm_set_epi32(2, 4, 9, 2);

__m128i mask = _mm_cmp_epi32(a, b);     // mask is now 0, -1, 0, -1
mask = _mm_sub_epi32(zero, mask);       // mask is now 0,  1, 0,  1

Edit:
If you want some index for a lookup table with shuffle constants, you need additional operations. Like
static const __m128i zero = _mm_set1_epi32(0);
static const __m128i bits = _mm_set_epi32(1,2,4,8);

__m128i a = _mm_set_epi32(6, 4, 7, 2);
__m128i b = _mm_set_epi32(2, 4, 9, 2);

__m128i bitvector = _mm_and_si128(bits, _mm_cmp_epi32(a, b));
bitvector = _mm_hadd_epi32(bitvector, bitvector);
bitvector = _mm_hadd_epi32(bitvector, bitvector);
// now a index from 0...15 is the the low 32 bit of bitvector

There might be better algorithms than using a lookup table for computing the shuffle, possibly calculating the shuffle directly using a De Bruijn mulitiplication. OTOH if you have more than 4 ints to compare, additional 4 int's would only come at the cost of one additional phaddd.
Comment: I actually meant a bit mask that can be used in shuffling instruction directly or as a small index to lookup a mask in the precomputed table, i.e. in this example `mask = ..0101b = 5d`.
Answer: I would probably use a variant of what drhirsch proposes:
int index = _mm_movemask_ps((__m128)_mm_cmp_epi32(a, b));

This gives you the same index to use in looking up a shuffle mask using only two operations.

Comparison and Extraction using SSE


What is a reasonable model measurement for a binary classification on an imbalanced data set? Accuracy? ROC?

Question: We analyzed whether or not user comments contain customer needs or not. The comments are manually labeled by experts (comments with needs = 330, comments with no needs = 1600). We used different algorithms for classification (like Random Forests, Random Trees, Bayes Net, Naive Bayes) and different sampling methods (undersampling, oversampling, SMOTE) as well as 10-fold-cross-validation.
We are very happy with the precision and recall of different combinations, but we are struggling with finding a good/suitable/reasonable measurement for comparing the results. So far we would just go with accuracy, but it doesn't take a lot of things into account. Should we go with a ROC Analysis? Or is there another reasonable measurement for our models?
Comment: Area under the precision-recall curve is often more suitable for imbalanced problems, as they are more sensitive to differences between models that can appear minor in terms of area under the ROC curve. You can refer to the [seminal paper of Davis & Goadrich on the relationship between precision-recall and ROC curves](http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_DavisG06.pdf)  for more background.
Answer: Accuracy is not a great measure, particularly when dealing with highly imbalanced datasets. To see that, assume your negative set constitutes 99% of the population - then just by predicting that everyone is a negative you'll achieve 99% accuracy, but your predictions won't be helpful.
AUC (and potentially partial AUC, depending on your overall objective) would be a much better measure in this case. Note that the model with the best AUC might not necessarily be reflective of the "best" model in your case - it really depends on what you want to do with the data. For example, if you're going to choose a cutoff that only flags 300 comments, then you're only concerned with how the model performs on that subset, and you don't care too much about the other observations. That being said, in practice AUC would likely be a good comparison.
Comment: Thank you so much for your answer! We want to use the trained model to apply it to huge sets of (comment) data to automatically identify comments containing needs. Having this in mind, would you still go for AUC?


Drupal 7 website layout/styling breaks all a sudden (random), how to debug? there are no logs

Question: One of my websites running Drupal 7 goes out of format, most often when user login.

This is how it should be
After running out of format this how it looks

This may be a CSS issue, it may be a caching issue, or it may be something else. As I know Drupal core code is almost perfect but contributed, custom modules and themes can spoil something by adding bad code.
After spending sometime doing research I come across many question and answer which were not that clear at all because there are many factors that can cause such a problem therefore it is really hard to say what is happening specially in some cases when there is no sign of error or warning.
For example in my case I am using Drupal7, Superfish menu  and following modules
addressfield, addressfield_staticmap, admin_views, ajax_register, auto_nodetitle, autoassignrole, backup_migrate, captcha, ckeditor, colorbox, content_access, css_injector, ctools, currency, custom_search, date, entity, entity_translation, faq, field_collection, field_permissions, field_slideshow, flexslider, flood_unblock, follow, galleria, gmap, google_analytics, i18n, i18nviews, image_captcha_refresh, jquery_update, l10n_update, lang_dropdown, languageicons, libraries, link, Location, login_destination, markup, menu_block, mlpanels, modal_forms, money, mortgage_calculator, page_manager_redirect, panels, pathauto, real_estate, realname, rules, select_translation, serial, simple_fb_connect, simple_gmp, simpleads, simplify, smart_ip, social_share, superfish, tablefield, tabtamer, taxonomy_acces, taxonomy_acces_fix, taxonomy_csv, token, translation_overview, unique_field, user_role_field, variable, viewfield, view, view_bulk_operation, views_content_cache, views_data_export, views_field, views_horizontal_slider, views_jqfx, views_jqfx_Cycle, views_php, view_Slideshow, views_slideshow_galleria, workspace, wysiwyg
The website is hosted in Cpanel
Itry may options to look for the error and identify the problem which where not helpful at all, I tried Mozilla browser and Firebug and there is no error or warning at all. I tried to add parameters into setting.php
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And still nothing changed. finally I decided to post the question here and ask all the great and genius developer to post their view and solution on:

What can cause a Drupal website to run out of format and broke the layout
What are the available tools or option that we can use to debug a Drupal

Can anyone please explain how to debug Drupal and deal with theme issue  in a step-by-step way to make it simpler for everybody?
Comment: If you must post a list of modules as screenshot, please select "list" display (or your OS equivalent). Currently it is unreadable.
Comment: @Mołot The photo is in high resolution and could be view clearly if you zoom the page with your browser
Comment: Yes, we can go around your unwillingness to spend a minute to make helping you easier for us. But if you don't want to spend that minute, why do you want others to spend a lot of time helping you? Does it sound fair to you?.. It should be in your best interest to make answering as easy as possible. After all, you have this problem, not we.
Comment: @Mołot
Your right, I just updated the question with all modules name.
Comment: single drush command to get a list of active modules - drush pm-list --type=Module --no-core --status=enabled
Answer: Above all, I assume that you have Google Analytics Installed. Go to the Behaviours menu and from there look at Site Speed and Page Timings to see how much times it takes to load a page. Use the Speed Suggestion option to allow Google suggest you a number of fixes/tricks that can potentially improve the performance of your web page. This is very handy.
This is clearly a problem of CSS. Open your site in chrome, enable the development tool F12 and then keep refreshing and monitor Network and Console windows. I observed that every reload of the page causes a request to a CSS to break (hence the resource is never downloaded - each time a different CSS from a different module).
It would be a great idea if you could give this module a go https://www.drupal.org/project/advagg, I highly recommend that you aggregate all your site's CSS into few or single CSS file.
It is always better to download one slighty larger file than make over a hundred calls to a web server requesting for tiny tiny CSS files, because there is high chance that your request fail or die (to to waiting).
I will update my answer with more findings but, give that module and a go and let us know your findings.
Comment: At the end of the day, I decided to do some changes in my server setting 'increase max_execution_Time' and also got rid of few module.
Comment: Thank you very much for the help @Raf, Advanced CSS/JS Aggregation is a handy modules but not really useful with the current version of Drupal because it need the Aggregate and compress CSS files and Aggregate JavaScript files option to be enable. After doing some research I found out that still there are many issues with both compress CSS files and Aggregate JavaScript files option. for example of the issues is [https://www.drupal.org/node/1335366]. but overall your answer did helped a lot with identifying the problem and looking for the error.
Answer: After the user logs in, the menu in the left upper corner appears (appearance to edit shortcuts) Your css is probably reacting to it (relative positioning etc.). For debuigging:
Navigate with firebug to the menu's uppermost   (most likely with the class user-menu or navigation) Then add in the styles frame in firebug (on the right side) for that class
display: none;
Thats mostly faster for debugging than doing it through your css files. If its the problem change your css files accordingly.
Another often encountered problem is that while using https for certain content (after a user logged in) the same-origin-policy of most browsers prevents the loading of additional resources, like javascript or css. Are you using https?


Change tabula separator to another character

Question: I need to capture some data from a pdf and input into an excel file, but to create a macro to organize the cells I need a character other than ",". Because some value datas need the "," for cents. Any ideas ? (A character like "/" or "-" would solve the problem)
When i convert my pdf to csv, all the data are located into one cell, that's why i need to use a macro.
How my data is organized into excel
from tabula import read_pdf
from tabula import convert_into
convert_into("B.pdf", "BBBBB.csv", output_format="csv", pages=1,coding = 'latin-1',stream=True, guess = False ,
         area = (306.9,253,379,570),
         columns = (347,399.1,443.4,481.6,514.3,543.5,572))

Answer: The "," inside the data values are correctly escaped inside " " markers and will just work. What is wrong is your Excel which is not using the , as the field delimiter. IIRC, you can overcome this on Excel's side by using File->import instead of just trying to open the CSV file. This way Excel will prompt you for the CSV parameters.
Otherwise, the Python CSV writter parameter to change the delimiter character is exactly "delimiter" -
Unfortunateely Tabula-py is just a wrapper around tabula-java called via an external process, and that accept no option to change the delimiter character. Otherwise, it would be a matter of adding a delimiter=...
 parameter on your call.
As it is, however, the easiest way to go seem to be to re-convert your CSV file generated on the Java side to one with ";" delimiters after the data is extracted:
(The example has a quite complete wrapper function, but the conversion takes place at just four lines of code at the end)

import csv
from pathlib import Path
from tabula import read_pdf
from tabula import convert_into

def convert(input_file, output_file, encoding="latin1", area=None, columns=None, delimiter=";"):
    if area is None:
        area = (306.9, 253, 379, 570)
    if columns is None:
        columns = (347, 399.1, 443.4, 481.6, 514.3, 543.5, 572)

    if delimiter != ",":
        final_output = Path(output_file)
        # temporary name
        output_file = final_output.parent / (final_output.stem + "_tmp" + final_output.suffix)

    # perform the actual data extraction and CSV output
    convert_into(
        input_file,
        output_file,
        output_format="csv",
        pages=1,
        coding="latin-1",
        stream=True,
        guess=False,
        area=area,
        columns=columns,
    )

    if delimiter != ",":
        # if needed, convert the CSV file to use the required delimiters:
        try:
            with open(output_file) as tabula_csv, open(final_output) as final_csv:
                reader = csv.reader(tabula_csv)
                writer = csv.writer(final_csv, delimiter=delimiter)
                writer.writerows(reader)
        else:

            # if everything was ok on conversion, remove temporary file:
            output_file.unlink()

Comment: I tried to open with excel the file, and the "," persist, i think its the delimiter that tabula's uses. And the code didn't work :/
Comment: Sorry for that - I went to check the docs, and in fact it does not work - I will add  to the answer an example of the CSV conversion on teh Python side now.
Answer: If you want to keep using convert_into you can set output_format="tsv", which converts table with tab delimited format. https://tabula-py.readthedocs.io/en/latest/tabula.html#tabula.wrapper.convert_into
Other than that, you can convert to DataFrame with read_csv then use df.to_csv with setting delimiter.
Comment: YES! THANK YOU! the translate to tsv has worked a lot


Using su to copy/move a file

Question: I'm pulling out my hair trying to get a copy or move of a file to work using su.
I've tried:
<code> Runtime.getRuntime().exec("su -c cat " + sourceLocation.getAbsolutePath() + " > " + targetLocation.getAbsolutePath());
</code>
and
<code> Runtime.getRuntime().exec("su cp " + sourceLocation.getAbsolutePath() + " " + targetLocation.getAbsolutePath());
</code>
I'm sure I'm missing something stupid and obvious, but I can't pin it down.
Also, is there any way to request SU one time for all my processes?  Each time I use it, it's triggering another dialogue.
Comment: I would recommend checking out [RootTools](https://code.google.com/p/roottools/w/list)
Answer: Root tools takes care of the trickiness.
<code> CommandCapture command = new CommandCapture(0, "cp -f " + sourceLocation + " " + targetLocation);
 RootTools.getShell(true).add(command);
</code>

Using su to copy/move a file


Change of variables in a double integral-proving injectivity

Question: I want to make the following change:
$$u=x^2 - y^2 \quad v=xy$$ where my region is in the first quadrant bounded by:
$x^2-y^2 = 3 , \quad xy=1 , \quad x^2-xy-y^2 = 1 $  .
How can I prove this change of variables is legitimate ? (i.e., how can I prove this change is injective [one-to-one])
I have tried solving $$ x_1 ^2 - y_1 ^2 = x_2 ^2 -y_2 ^2 , \, x_1 y_1 = x_2 y_2 $$ but this implies $x_1 = x_2 , y_1 = y_2 $ as required, but also: $x_2 = y_1 $ for example.
Will you please help me figure out how to prove the injectivity of this ?
Thanks a lot
Answer: Original strategy of mine
Claim
$$\left\{\begin{array}{c}
u=x^2-y^2 \\
v=xy
\end{array}\right.
\iff
\left\{\begin{array}{c}
x=\sqrt{\frac{u+\sqrt{u^2+4v^2}}{2}} \\
y=\sqrt{\frac{\sqrt{u^2+4v^2}-u}{2}}
\end{array}\right.
$$
Proof. As an intermediate step, let $a=x^2,b=-y^2$. The first system then becomes:
$$\left\{\begin{array}{c}
u=a+b \\
-v^2=ab
\end{array}\right.$$
The equation $z^2-uz-v^2=0$ has solutions $a,b$, but the solutions can also be expressed as $\frac{u+\sqrt{u^2+4v^2}}{2}$ and $\frac{u-\sqrt{u^2+4v^2}}{2}$, by the solution formula for second-degree equations. It would seem we have an ambiguity, but in fact we don't. Because remember $a,b$ are expressed in terms of $x^2,y^2$, so we know their signs. In particular, $a=x^2>0$ and $b=-y^2<0$, so $a$ must be the one with the plus, and $b$ the one with the minus, since the one with the minus has $u-\sqrt{u^2+4v^2}<0$ as a numerator. This inequality is proven by placing the root on the right side, noting that if $u<0$ the inequality is obvious, and squaring to produce the obvious inequality $4v^2\geq0$ in the $u>0$ case. Thus the above system has yielded:
$$\left\{\begin{array}{c}
a=\frac{u+\sqrt{u^2+4v^2}}{2} \\
b=\frac{u-\sqrt{u^2+4v^2}}{2}
\end{array}\right.,$$
which implies:
$$\left\{\begin{array}{c}
x^2=a=\frac{u+\sqrt{u^2+4v^2}}{2} \\
y^2=-b=\frac{\sqrt{u^2+4v^2}-u}{2}
\end{array}\right.,$$
which is exactly the second system on top, provided that $x,y$ are positive as in the hypothesis of the question. $\square$
Alternate proof. Compute $u(x(u,v),y(u,v))$ and $v(x(u,v),y(u,v))$, i.e. shove those expressions of $x,y$ into $u,v$, and reach the identity. This proves $\Leftarrow$. Shoving $u,v$ into $x,y$ gives $x=|x|,y=|y|$, thus proving $\Rightarrow$ when $x,y>0$. $\square$
OP-suggested strategy
As suggested by the OP in a comment to this answer, one could try assuming $u_1=u_2,v_1=v_2$ and seeing what this implies. Let us write the two equations in terms of $x_1,x_2,y_1,y_2$:
$$\left\{\begin{array}{c}
x_1^2-y_1^2=x_2^2-y_2^2 \\
x_1y_1=x_2y_2
\end{array}\right.$$
Assuming $y_1\neq0$, we can divide the second equation, getting to:
$$x_1=\frac{x_2y_2}{y_1}.$$
Substituting this into equation 1 yields:
$$\frac{x_2^2y_2^2}{y_1^2}-y_1^2=x_2^2-y_2^2\iff x_2^2y_2^2-y_1^2y_1^2=x_2^2y_1^2-y_2^2y_1^2\iff x_2^2(y_2^2-y_1^2)=-y_1^2(y_2^2-y_1^2),$$
which in real numbers necessarily implies $y_2^2-y_1^2=0$, i.e. $y_1=\pm y_2$. So let us rewrite the system to then substitute this into equation two:
$$\left\{\begin{array}{c}
y_1=\pm y_2 \\
x_1=\frac{x_2y_2}{y_1} \\
y_1\neq0
\end{array}\right.
\iff
\left\{\begin{array}{c}
y_1=\pm y_2 \\
x_1=\pm x_2 \\
y_1\neq0
\end{array}\right.$$
Adding the hypothesis that the $x$'s and $y$'s be positive (or nonnegative) rules out the $\pm$s, yielding $x_1=x_2,y_1=y_2$. Of course, we still have the $y_1=0$ case to analyze. Let us add this hypothesis to the starting system and rewrite it accordingly:
$$\left\{\begin{array}{c}
x_1^2=x_2^2-y_2^2 \\
0=x_2y_2
\end{array}\right.$$
Equation two yields $x_2=0$ or $y_2=0$. Substituting $x_2=0$ into equation 1 yields $x_1^2=-y_2^2$, which has no real solutions. Thus, the hypothesis $y_1=0$ in the real field implies $y_2=0$, so $y_1=y_2$. The first equation then reduces to $x_1^2=y_1^2\iff x_1=\pm x_2$, which again is turned to $x_1=x_2$ by the sign hypothesis, proving injectivity. Of course, finding the inverse can be handy, but it is not necessary to prove injectivity in this case.
Comment: Great !!! Thanks a lot MickG! You were very helpful and helped me a lot !
Comment: Thanks a lot for the detailed answer! But, isn't there any easier way to prove the injectivity of the mapping I mentioned? Something like assuming $(x_1 , y_1 ) = (x_2,y_2) $ and proving $x_1=x_2 , y_1=y_2$ ?
Comment: I guess you meant assuming $u_1=u_2,v_1=v_2$ because $(x_1,y_1)=(x_2,y_2)$ is by definition $x_1=x_2,y_1=y_2$. I do not know if this leads anywhere.
Comment: $u_1=u_2,v_1=v_2$ would mean $x_1^2-y_1^2=x_2^2-y_2^2$ and $x_1y_1=x_2y_2$. The second equation leads to $x_1=\frac{x_2y_2}{y_1}$ if $y_1\neq0$. Substitute it into the first equation and $\frac{x_2^2y_2^2}{y_1^2}-y_1^2=x_2^2-y_2^2$, then the only sensible thing to do would be tp end up in 4th degree equations by multiplying by $y_1^2$, I wouldn't go on :).
Comment: I tried it, and will edit my answer with a new proof.
Comment: @CrazyStatistician see the edit.
Comment: I wouldn't say it's easier. If length measures easiness, then mine is shorter thus easier :).


The development of the musical staff: If and when did it have fifteen lines?

Question: I am doing research on music history and I cannot find information between the four line chant staff and the grand staff.  Also, I do believe that at different times in its development the staff actually had 12, 13, 14, and 15 lines.  Where can I find proof or evidence of this?
Comment: The "[citation needed]" cliche applies here.  Who or what suggested to you that there were such large linesets?  This excellent history of notation makes no mention whatsoever of such:  http://www.cartusiana.org/files/Origins%20Musical%20Staff.pdf
Comment: 16th century keyboard music was often written on a 6-line staff, e.g. https://en.wikipedia.org/wiki/Staff_(music)#/media/File:Byrd_manuscript_sample.jpg. For your "12-15 lines" are you getting confused with lute tablature, which sometimes used a separate line for each unfretted bass string? But trying to read from 15 lines doesn't sound a very practical idea.
Comment: You're not thinking of the grand staff as an 11-line staff, are you?  There's no real historical basis for that.  Keyboard music has been notated using two staves, one for each hand, for centuries (or three, for organ).  If you're looking for a gradual increase from four to 11 lines, you won't find it; it was more like an increase to 5 lines, and then a doubling. See, for examples, https://www.google.com/#q=early+keyboard+notation
Comment: I often explain to students that it started out as an 11 line staff, which was found to be unwieldly, so the middle line (floating C) was omitted. It may be apocryphal, but it makes a lot of sense when trying to understand treble and bass.
Comment: @Tim yes, it's apocryphal.
Answer: I do not believe, except maybe in rare instances, that staffs that large were used. You may be thinking of Lute tabs.
All early music scores were written by hand. It's very time consuming to do this and they were after the most efficient use of space. This is why the 4 line staff with clefs and ligatures were used.
I would start, of course, start with Guido of Arezzo (inventor of staff, I went to his house once!). His treatise: https://en.wikipedia.org/wiki/Micrologus
A really great resource for notation, early music, and its evolution in a cultural and historical context is Richard Taruskin's "MUSIC FROM THE EARLIEST NOTATIONS TO THE SIXTEENTH CENTURY". I'm not a huge fan of his 20th century analysis, but as a former performer, scholar, and interpreter of early music, this one is hard to beat.


How do I change the current language in a Kernel test?

Question: I'm writing a test for something that returns a Url from an entity. This should be language-aware, so the test needs to change the current language.
I started off writing a Kernel test for this, because they're faster, but I can't figure out how to make the test code change the current language:
<code>  public static $modules = [
    'system',
    'user',
    'language',
    'content_translation',
    [SNIP]
  ];

  protected function setUp() {
    parent::setUp();

    $this->installConfig(['language']);
    $this->installEntitySchema('configurable_language');

    $this->languages['de'] = ConfigurableLanguage::createFromLangcode('de');
    $this->languages['de']->save();

    $config = $this->config('language.negotiation');
    $config->set('url.prefixes', [
      'en' => 'en',
      'de' => 'de',
    ])->save();

    \Drupal::service('kernel')->rebuildContainer();
    \Drupal::service('router.builder')->rebuild();
    $this->languageManager = $this->container->get('language_manager');
    $this->languageManager->reset();

    [SNIP]
  }

  public function testCurrentLanguageChange() {
    // Change the site's current language.
    dump(\Drupal::languageManager()->getCurrentLanguage());

    \Drupal::service('language.default')->set($this->languages['de']);

    dump(\Drupal::languageManager()->getCurrentLanguage());
  }

}
</code>
In the test code above, both dump() calls output the 'English' language object.
Answer: Looks like I needed to call:
<code>    \Drupal::languageManager()->reset();

</code>
No, wait, that doesn't seem to be the whole story.... ARGH.
EDIT:
For the entity to be treated as translatable and so return the right URL, I also needed to set the bundle as translatable:
<code>    $this->entityTypeManager->getStorage('language_content_settings')->create([
      'target_entity_type_id' => 'node',
      'target_bundle' => 'page',
    ])->save();
    $this->container->get('content_translation.manager')->setEnabled('node', 'page', TRUE);
</code>


Any way to find the Ajax Request from which page or function in PHP MVC?

Question: I am working on Bitrix24 CRM which is based on PHP. I want find the the ajax request url called page(source) or function.
Is there ant way to find Ajax request source page or function.
Answer: In Chrome's Developer Tools, go to the Sources tab, and open the XHR/Fetch Breakpoints section in the right sidebar. Check the box labeled "Any XHR or fetch". Then when an AJAX request is sent, the debugger will pause the application and show you the source line where the request is coming from.


Kaplan-Meier Estimate with no censoring

Question: Let $T_i$ is the survival time for individual $i$ $(i=1,2,\ldots, n)$ and $C_i$ be the time to censoring. Let $U_i=\min(T_i,C_i)$. And $\hat S(U_i)$ is the Kaplan-Meier estimator for the censoring distribution. Suppose $R_i$ and $Z_i$ are two indicator functions. Also, $p$ is a probability. Consider the following estimator of cumulative distribution function:
$$\hat F(t)= \sum_{i=1}^{n}\frac{I(T_i<C_i)(1-R_i+R_iZ_i/p)I(U_i\le t)}{\hat S(U_i)},$$
where $I(.)$ is an indicator function.
Now it is written that, with no censoring $\hat F(t)$ becomes
$$\hat F(t)= \sum_{i=1}^{n}(1-R_i+R_iZ_i/p)I(T_i\le t).$$
I understand that if there is no censoring, then $I(T_i<C_i)=1$, that is, we will always observe the survival time. Also, with no censoring $U_i=T_i$ and hence $I(U_i\le t)=I(T_i\le t)$.
But I do not understand why does Kaplan-Meier estimator for the censoring distribution, $\hat S(U_i)$, which appears in the above first equation vanish in the second equation with no censoring?
Comment: Recall, KM and most survival methods are based on unique failure times, as the informativeness for survival comes from failures only -- not censored.   Also, each object (patient, mouse, etc) contributes to a failure variable (0-censored, 1-failed) and a time variable [$t$=time to failure or time to censoring (end of study or loss to follow-up)].   If you look at the product limit variant of KM, there's not a censoring time and a failure time, but rather bin counts for failures as a function of time interval.
Comment: Can you give a source to where you found this expression? I am not following the meaning of $R$ and $Z$. In Fine/Gray JASA 1999 Proportional Hazards Model for the Subdistribution of a Competing Risk, $Z$ is the modeled effect of covariates and $R$ is a cause-specific indicator matrix. You might want to start with a simpler case.
Answer: The Kaplan-Meier Curve does not disappear when there is complete data.  The true survival function is S(t)=1-F(t).  The Kaplan-Meier is also called the product limit estimator.  If you look it up in wikipedia you will find the case of complete data and the form of the KM curve as a product.
Comment: There should only be one censoring time C in the study and that is the time you stop to finalize the result.  In the complete data case all event times are less than C.  So the indicator functions should all equal 1.
Comment: In the formula of Kaplan-Meier Estimator :the censored individuals are excluded from the denominator of 'at risk' individuals at the point when they are censored, however, are included at each preceding point. They are not included in numerator at any point.   (continuing)
Comment: (continuation) But  in https://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator#Basic_concepts also has a sentence that `When no truncation or censoring occurs, the Kaplan–Meier curve is the complement of the empirical distribution function.` Then why does $\hat S(t)$ disapper from the second equation of the post instead of reducing to empirical distribution function?
Comment: Does it mean the second equation of the post  inaccurate?
Comment: I now see how the substitutions  for the complete case that you exhibit in equation 2 loses the survivor function in the denominator but I don't know what the indicator functions R_i and Z_i represent.  Also what does the probability p refer to?
Comment: Were you able to find the formula for the KM estimator in wikipedia?
Comment: Go to https://en.wikipedia.org/wiki/Kaplan-Meier-estimator .

Kaplan-Meier Estimate with no censoring


How to show $f(x) =(\sqrt[3]{x}+x)\sqrt{x}$ is injective and surjective?

Question: $f : [0, \infty) \to [0,\infty) d$ and $f(x) =(\sqrt[3]{x}+x)\sqrt{x}$.
How should I go, if I wanted to show that it is bijective?
Comment: Please make sure I've correctly formatted the question (I'm not sure what that "d" is doing, in particular, but I suspect I've got the function right).
Comment: To prove it is injective simple inequalities suffice. To prove it is surjective I recommend you first prove it is continuous, and then use the intermediate value theorem.
Answer: Note that $f(0) = 0$ and $\lim_{x \to \infty} f(x) = +\infty$. Thus by the intermediate value theorem, since $f$ is continuous, it must take every value in $[0,\infty)$; that is, $f$ is surjective. Next, we see $$f'(x) = \tfrac 5 6 x^{-1/6} + \tfrac 3 2 x^{1/2} > 0 \,\,\, \text{ for } x > 0$$ which shows that $f$ is strictly increasing. That is, for $x < y$, we note that $$f(x) - f(y) = \int^y_x f'(t) dt > 0 \,\,\, \implies \,\,\, f(x) > f(y).$$ Thus for unequal $x,y$, we cannot have $f(x) = f(y)$; that is, $f$ is injective.
Comment: Monotonicity follows more simply from the fact that the function is the sum and product of increasing functions.
Answer: For injective is enough to see that:
$$f'(x)=\frac{5}{6x^{1/6}}+\frac{3x^{1/2}}{2}>0$$
so, $f$ is monotone increasing.
For surjective, take $y_0 \in (0, \infty)$ (because if $y_0=0$ take $x=0$) then
$$f(x)=x^{5/6}+x^{3/2}=y_0$$
$p=x^{1/6}$ then
$$g(p)=p^5+p^9-y_0=0$$
The polynomial $g$ has real coefficients and odd degree so there is a odd number of real roots.
Also there is a positive root because the product of all roots is $y_0>0$.


React-Native detecting if a user is driving and opening up a warning popup modal

Question: I am busy building a react-native app.
I am a bit stuck with my next task and not quite sure where to start.
In the app, if you as the user are driving a pop up modal should open to say that 'It appears that you are driving, pull over for safety' (something like that).
My question is: Is there a package that can detect if a user is driving?? I saw the react-native-activity-recognition package but the documentation is a bit confusing.
-> If using this package how would i included the popup modal with it??
Has anyone implemented something similar?? And if you have can you please point me into the right direction.
Thank You
Comment: Please look at this https://stackoverflow.com/questions/43996944/is-it-possible-to-track-acceleration-and-speed-using-gps-data as it has already been answered
Comment: Does this answer your question? [Is it possible to track acceleration and speed using gps data?](https://stackoverflow.com/questions/43996944/is-it-possible-to-track-acceleration-and-speed-using-gps-data)
Comment: No Not really. I don't need to track speed. I just need to track movement basically and if there is a specific amount of movement then the modal should pop up
Answer: From documentation to https://github.com/Aminoid/react-native-activity-recognition
import ActivityRecognition from 'react-native-activity-recognition'

...

// Subscribe to updates on mount

  useEffect(() => {
    ActivityRecognition.subscribe(detectedActivities => {
      const mostProbableActivity = detectedActivities.sorted[0];
      console.log(mostProbableActivity);
    });

// Stop activity detection and remove the listener on unmount

    return ActivityRecognition.stop();
  });

...

// Start activity detection

const detectionIntervalMillis = 1000
ActivityRecognition.start(detectionIntervalMillis)

detectedActivities is an array of objects [{type: "WALKING", confidence: 2}] where type can be for IOS:

RUNNING
WALKING
STATIONARY
AUTOMOTIVE
CYCLING
UNKNOWN


Ratio between two groups

Question: I want to know among what is the ratio of insured people with disease $x$ to uninsured people with disease $x$.  Here are my numbers.

Insured, disease $x = 3600$
Uninsured, disease $x = 950$
Insured, no disease $x = 100$
Uninsured, no disease $x = 150$

I'm struggling to understand if I should use $3600:950$ or if I should use $(3600/3700):(950/1100)$. Thoughts?
Answer: Let:

$d_I=3600$ be the number of people with the disease among the insured;
$d_U=950$ be the number of people with the disease among the uninsured;
$\overline{d_I}=100$ be the number of people without the disease among the insured;
$\overline{d_U}=150$ be the number of people with the disease among the uninsured.

The ratio of insured people with disease $x$ to uninsured people with disease $x$ is:
$$
\frac{d_I}{d_U} = \frac{3600}{950}
$$
It is the odds of finding someone insured among the diseased.
Other odds that might be of interest are:

The odds of finding someone insured among the non-diseased $\frac{\overline{d_I}}{\overline{d_U}}$;
The odds of finding someone with the disease among the insured $\frac{d_I}{\overline{d_I}}$;
The odds of finding someone with the disease among the uninsured $\frac{d_U}{\overline{d_U}}$.

And finally, we could also compute the odds ratio $OR$:
$$
OR
= \frac{\frac{d_I}{d_U}}{\frac{\overline{d_I}}{\overline{d_U}}}
= \frac{\frac{d_I}{\overline{d_I}}}{\frac{d_U}{\overline{d_U}}}
= \frac{d_I \cdot \overline{d_U}}{\overline{d_I} \cdot d_U}
= \frac{3600 \times 150}{100 \times 950}
\approx 5.68
$$
Since $OR > 1$, it means that the odds of having the disease (vs not having the disease) among the people with insurance is larger than the odds of having (vs not having the disease) the disease among the people without insurance.

Your final expression is the relative risk $RR$, a concept similar to the $OR$ but related with risk (probability) instead of odds.

The risk of finding someone with the disease among the insured $\frac{d_I}{d_I + \overline{d_I}}$;
The risk of finding someone with the disease among the uninsured $\frac{d_U}{d_U + \overline{d_U}}$;
The risk of finding someone insured among the diseased $\frac{d_I}{d_I + d_U}$;
The risk of finding someone insured among the non-diseased $\frac{\overline{d_I}}{\overline{d_I} + \overline{d_U}}$.

The relative risk of having the disease among the insured vs having the disease among the uninsured is then:
$$
RR_d
= \frac{\frac{d_I}{d_I + \overline{d_I}}}{\frac{d_U}{d_U + \overline{d_U}}}
= \frac{\frac{3600}{3700}}{\frac{950}{1100}}
\approx 1.13
$$
Note that this is different to the relative risk of being insured among the diseased vs being insured among the non-diseased :
$$
RR_I
= \frac{\frac{d_I}{d_I + d_U}}{\frac{\overline{d_I}}{\overline{d_I} + \overline{d_U}}}
= \frac{\frac{3600}{4550}}{\frac{100}{250}}
\approx 1.98
$$
Comment: This is what I was trying to get at but couldn't articulate. In essence was looking for the risk ratio.  Thank you for your help!
Answer: Since the amount of insured people with the disease is $3600$ and the amount of uninsured people with the disease is $950$, the ratio is indeed
$$
3600:950.
$$
Comment: Thank you for responding. If I were to use the other calculation, I.e. ratio of (3600/3700):(950/1100), what would that tell me? I guess I know the two approaches are different, but I don't understand why.
Comment: The second calculation corresponds to "the ratio of insured people to uninsured people", regardless of having the disease or not.
Comment: I realized that what I was looking for was the risk ratio and not simply the ratio. I know how to calculate it. Thanks again for your help.
Comment: @user25025 No problem. Don't forget to upvote the response if it was helpful :)

Ratio between two groups


cobertura report without stopping tomcat

Question: i followed the steps that are given for cobertura report and i generated report with following steps given in the URL Cobertura on Tomcat
but now my problem is to generate cobertura report without stopping tomcat
Answer: There are only 2 Ways to create a coverage data file.

Stop Tomcat
Execute a piece of code, that tells cobertura to write the file

Regarding the Second approach: You have to call this function yourself, after your tests run. You could (for example) put this code in a servlet (which you call at the end of your tests).
If you don't stop Tomcat or execute the function, you will not get a coverage data file.
This is from the cobertura FAQ

Cobertura only writes the coverage data file when the application server shuts down. We do not want to stop our application server after running our tests.
  It is possible to instruct Cobertura to write the data file. One of
  your classes should call the static method
  net.sourceforge.cobertura.coveragedata.ProjectData.saveGlobalProjectData().
  For example, you could add something like this to a "logout" method in
  your web application:
try {
    String className = "net.sourceforge.cobertura.coveragedata.ProjectData";
    String methodName = "saveGlobalProjectData";
    Class saveClass = Class.forName(className);
    java.lang.reflect.Method saveMethod = saveClass.getDeclaredMethod(methodName, new Class[0]);
    saveMethod.invoke(null,new Object[0]);
} catch (Throwable t) {}

Comment: what is the use of coberturaflush.war file
Comment: thanks for the reply. in my source code i have large no of java files..so i cant add above one to source code.my second question with out adding to source code can we generate report.
Comment: you can't create a report, without writing the coverage data prior. You need to stop Tomcat OR execute the java code. There is no way around it.
Comment: thank u for the reply.. i have lot of java programs that is my problem
Comment: hi oers i have written the above code in the java program but still i am unable to get coverage report. i am having one doubt i have written in regular java program not in logout method.when i am running my test cases i am not the touching the java class file where i have written above code then still it gives report.
Comment: You have to execute the code at some point, it won't run automatically. Maybe put it in a special Servlet or something that fits your needs. Maybe you are looking in the wrong place for the file, [try specifying](http://cobertura.sourceforge.net/faq.html) **-Dnet.sourceforge.cobertura.datafile=DIRECTORY/cobertura.ser** for tomcat. This will define where cobertra.ser will appear.
Comment: i think this is the not correct one to generate report with out stopping tomcat. in my test case i have not covered the java class in which it has the above code then it doesn't create report. if they source code is too large then we cant include the code in the program
Comment: If you can't execute the code you have to stop Tomcat. There is no third way.
Comment: what is executing the code means???   i am sorry if am asking silly questions and troubling u. i am thank fully for the replies u gave it helped me a lot
Comment: You have to write a java class with a method that contains the code above. You have to include this code in somewhere your web application (maybe a special servlet). After all your tests are done you have to call/execute/run this method on your tomcat. I can't put it any clearer, sry.
Comment: when we write any another program or servlet which contains above source code in separate module or other source code  rather than project  then its show its coverage report rather than project report(may be i am thinking like that)
Comment: It has to be in the same web application(war) that you test. It won't affect your coverage statistics, it just triggers writing of the coverage data.
Comment: thanks for the help oers.by inserting piece of code i got the report but my questions now is if u running one test case and produce the report(with out stopping tomcat) now i want to flush the coverage.ser to 0% and execute another test case(here i am not stopping tomcat for running other test case)..sorry for my weak english
Comment: you have to delete the cobertura.ser, but I'm not sure if this will work (it may include the first test)
Comment: i am making a jar file of project1 and placing the jar file in project2.for project2 i am able to creating the coberatura report.my question is can get cobertura report for project1 (which is in jar) while running proejct2?can we ge cobertura report for jar files? jar file is important for project2 otherwise project will not run
Comment: the link for above question is here http://stackoverflow.com/questions/9117739/cobertura-report


Find $\int_{0}^{\infty} \frac{\ln(x)}{1+x^2}dx$

Question:
Find $\displaystyle \int_{0}^{\infty} \dfrac{\ln(x)}{1+x^2}dx$.

How should I change the limits of integration to evaluate this?
Answer: Hint: First consider
$$\int_0^1\frac{\ln x}{1+x^2}dx\quad (*)$$
It is easy to show that the integral $(*)$ is finite. Then use the substitution $x=\frac{1}{t}$ and simplify, one can get
$$\int_0^1\frac{\ln x}{1+x^2}dx=-\int_1^\infty\frac{\ln t}{1+t^2}dt$$
Therefore
$$\int_0^\infty\frac{\ln x}{1+x^2}dx=0$$
Comment: Of course, it is also necessary to know that $\int_0^1 \ln(x)/(1+x^2)\, dx$ is finite.
Comment: @CarlMummert That's a good point. But this is not very hard to see.
Answer: HINT:
Set $x=\tan y$  to get $$I+\int_0^\infty\dfrac{\ln x}{1+x^2}dx=\int_0^{\pi/2}\ln(\tan y)dy$$
Now using $\int_a^bf(x)\ dx=\int_a^bf(a+b-x)\ dx$
$$I=\int_0^{\pi/2}\ln\{\tan(\pi/2-y)\}dy=\int_0^{\pi/2}\ln\cot y\ dy=-\int_0^{\pi/2}\ln(\tan y)dy=-I$$


Using the google javascript api within a sandboxed iframe environment

Question: I have an HTML5 app which uses the google javascript API. I discovered recently that this app needed to run within an iframe sandboxed environment. I know that it looks like trying to workaround the very goal of the sandboxed environments; however some features are still allowed for the iframe (see constraints below), which makes me think that there is some hope.
I am facing issues during the authentication process: when loaded, the google javascript api appends an iFrame on the original page (which is already an iframe in my case) and uses a postMessage mechanism to communicate between windows. I would like to use the google api for the OAuth2.0 authentication process as well as for querying the API.
Here is a reproduction case; I am using a simplified version of the authSample.html page provided by google.
<!DOCTYPE html>

    <meta charset='utf-8' />
    <title>original auth page</title>

    <button id="authorize-button">Authorize</button>

Not authentified

The containing page, which will be used by the end-users looks like:
<!DOCTYPE html>

    <meta charset='utf-8' />
    <title>iframed page</title>

Obviously you will have to execute this page after replacing the actual src for the iframe by your server authSample.html url.
If you run it on different browsers, you will notice different behaviors for the failure. I tried to exploit the fact that the popups are allowed but it seems that browsers have implemented differently the fact that the opened window should also be openned in a sandboxed environment.
I would like to avoid writing my own webservices for the authentication. In addition, I believe that users would be more secure entering their credentials using the usual google web page (with an url accounts.google.com). If you have an idea, that may work with recent browsers, feel free to submit it.
Thank you
Answer: I have found a solution,
the basic idea is to do the auth flow in a popup that will not inherit the sandbox cross origin security restrictions. Indeed, the sandbox has the following attributes sandbox="allow-scripts allow-forms allow-same-origin ms-allow-popups allow-popups"
I wrote a small blog post explaining in detail the solution.
EDIT (September 2016):
At Keluro we released an open source code sample to leverage the sign-in technicalities. It is used more for connecting to Azure AD/Office 365 but the client side using dialogApi and the popup as a fall back can be reused.
Answer: It's not difficult to authenticate users yourself and not have to rely on an api as a crutch. With a few php mysqli_connect calls and access to the DB via phpmyadmin or something, you can validate clients first-hand. From there, you'll easily query the DB to find the user and their related information.
Use the same POST/GET methods you have within your form and you'll be able to create a php variable within the form with action="<?php echo $_SERVER["PHP_SELF"];?>"
Then in your php source,
$userid = mysqli_real_escape_string($con,$_POST['FORMID'])

where $con is your connection string via mysqli_connect
Comment: Your answer describes how to connect to a MySQL database, but the OP is specifically trying to use the Google Analytics API.


Calling menu in a certain way from page.tpl.php

Question: My menu structure looks like the structure in the left part of the image. I want the output to look like the right part of the image when I'm in the 'oranges' page for example. This works great if done from Drupal's admin panel, but is there any way I can code it in my page.tpl.php?

Currently, I'm using the code below to output my menu, but I can't seem to get it to look exactly the way I want.
<code><?php
  $main_menu = menu_navigation_links('main-menu', 2);
  print theme('links', array(
  'links' => $main_menu,
  'attributes' => array(
  'id' => 'main-menu',
  'class' => array('links', 'clearfix'),

),

  'heading' => array(
  'text' => t('Main menu'),
  'level' => 'h2',
  'class' => array('element-invisible'),
),
));
?>
</code>
Any ideas?
Answer: You can use menu_tree_all_data function to get all nested menus. And then you can add your own html to display menus with your style
<code>$menutree_produce = menu_tree_all_data('menu-produce');
</code>
And if you want to Active current menu on related page you can use menu_get_item and menu_set_item on that page
<code>$menu_item = menu_get_item(drupal_get_normal_path('produce/oranges'));
menu_set_item(NULL, $menu_item);
</code>


If $n\gt 2$ then there is a prime number $p$ such that $n\lt p\lt n!$

Question: I'm trying to prove that

For all integers $n>2$ there is a prime number $p$ such that $n \lt p \lt n!$

I was trying to solve it by contradiction and supposed that $p\geq n$, then by definition of prime numbers, $p$ is a divisor of $n!.$  I am stuck here and wonder what would be my next step?
Thank you.
Comment: Have you tried modifying Euclid's proof that there are an infinite number of primes?
Comment: What divides $n! -1$?
Comment: Assuming $p \le n$ won't do lead to a contradiction because there *are* primes less than or equal to n.(!!!)  You need to assume there are no primes between n+1 and n!-1. ... which... might not be the best approach.
Comment: @fleablood: ah, that is the much more elegant argument...
Answer: For all $2< k \le n$ it follows that $k|n!$ so no $k | (n! -1)$.  So either $n!-1$ is prime or there is a prime number greater than $n$ that divides $n! -1$.
Either way there is a prime number between $n$ and $n!$.
Answer: Let $n=3$ be our base case, then $p=5$ proves this case since $3\lt 5\lt 3!=6$.  Now suppose that the theorem is true for $2\lt n\le k$, and let $p_k$ be the smallest prime such that $p_k\gt k$.  Note this means that $p_k\ge 5$.  Consider the number
$$q = p_k\# +1 = 1+ \prod_{p\text{ is prime}\atop p\le p_k}p$$
Now consider the case $n = k+1$.  If $p_k \gt k+1$ then we are done.  Otherwise, we must have $p_k = k+1$.  Note that our number $q$ must be less than $(k+1)!$ since $4$ is not a factor of $q-1$.  Further, $q$ has no factors in common with any prime $\le p_k$, and therefore is either prime or has prime factors all of which are greater than $p_k$.  Therefore there must exist a prime $r$ such that $r\mid q$ and $k+1\lt r \lt (k+1)!$.


Expectation of Geometric random variable .

Question: For a discrete random variable a negative island exists-  $$\Bbb E(X) = \sum_{x=0}^\infty \Bbb P(X\ |\!\!\!>x)$$
I need to use it, to calculate the Expectation of Geometric random variable.
Now, I don't have any data about number of trials. So, how I do it? I know $x$ can be $1$, $2$, $3$, $\ldots$ and I know that the expectation of $x$ is $1/p$. So, how can I show it?
Comment: any help please?
Comment: ..................
Comment: any help please???
Comment: The question is bad written. "A negative island"?
I understand that you should use the formula above, to calculate the expectation of a geometric random variable.
So apply the formula: you need to calculate, for each $x$, which is the probability $\mathbb{P}(X | X>x)$ and then sum them up.
Answer: We know that $\mathbb P(X = n) = p(1-p)^{n-1}$ and from that we conclude that
$$\mathbb P(X \leq n) = p \sum_{i=1}^n (1-p)^{i} = p \frac{1-(1-p)^n}{1-(1-p)} = 1-(1-p)^n$$ from the geometric series formula, namely
$$\sum_{i=0}^{n-1} q^i = \frac{1-q^n}{1-q}.$$
Now we can conclude that $\mathbb P(X >n) = 1- \mathbb P(X \leq n) = (1-p)^n$. Now we use the given formula to calculate the expected value, using $(1-p) < 1$ (because if $p=0$ we don't have an interesting distribution anyway, therefore we have $p>0$) and the formula for the geometric series (where the $q^n$-part goes to zero because $|q|<1$ in our case):
$$\mathbb E[X] = \sum_{x=0}^{\infty} \mathbb P(X >x) = \sum_{x=0}^{\infty} (1-p)^x = \frac{1}{1-(1-p)} = \frac{1}{p}$$


Lista encadeada em C - Invertendo os nós de maneira recursiva

Question: Estou seguindo as notas de Projetos de Algoritmo do professor Paulo Feofiloff, e estou com dificuldades em resolver uma questão do capítulo de Listas Encadeadas, transcrito à seguir:

Exercícios 5

Escreva uma função que inverta a ordem das células de uma lista encadeada (a primeira passa a ser a última, a segunda passa a ser a
  penúltima etc.). Faça isso sem usar espaço auxiliar, apenas alterando
  ponteiros. Dê duas soluções: uma iterativa e uma recursiva.

Eu consegui chegar em uma solução iterativa, porém não consegui nem desenhar uma solução recursiva.
Então peço que me direcionem pra solução recursiva deste problema. Obrigado!
Segue código da solução iterativa (favor indicar melhorias).
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} NODE;

/*
Esta função recebe uma lista encadeada de inteiros e inverte a posição das
células desta lista usando apenas ponteiros. Ex.: o primeiro nó troca de lugar
com o último, o segundo nó troca de lugar com o antepenúltimo, etc.
*/

// versão iterativa
void swap_nodeI (NODE **head) {
    // if list is empty or there is only one node, nothing to do
    if (*head == NULL) return;

    // declare variables for first half of the list
    NODE *prevX = NULL, *currX = *head;
    int countX = 1;

    // declare variables for second half of the list
    NODE *prevY = NULL, *currY = *head;
    int countY = 1;

    // count nodes (countY)
    for (; currY->next != NULL; currY = currY->next, ++countY);

    // swap nodes
    NODE *temp;
    int i, j;
    while (countX < countY) {

        // setup pointers
        for (currY = *head, i = 1; i != countY; ++i) {
            prevY = currY;
            currY = currY->next;
        }
        for (currX = *head, j = 1; j != countX; ++j) {
            prevX = currX;
            currX = currX->next;
        }

        // swap X and Y
        if (prevX != NULL) prevX->next = currY;
        else *head = currY;
        if (prevY != NULL) prevY->next = currX;
        else *head = currX;
        temp = currY->next;
        currY->next = currX->next;
        currX->next = temp;

        // update counters
        ++countX;
        --countY;
    }
}

Comment: Eu já respondi uma questão assim...
Comment: https://pt.stackoverflow.com/a/217757/64969
Comment: Valeu, Jefferson! Eu tava quebrando a cabeça pra achar uma solução recursiva que não envolvesse informar o tamanho da lista encadeada. Você sabe se é possível assim? Obrigado, de qualquer forma. Vou tentar implementar com a sua estratégia.
Comment: Tem sim, a ideia é fazer a inversão entre o anterior e o seguinte, `anterior -> atual -> seguinte` para `anterior <- atual <- seguinte`
Comment: Meu Deus.. só agora a ficha caiu.. Eu tava fixado em trocar pares equidistantes! Quando bastava inverter a lista inteira..
Comment: Por favor, não utilize a pergunta para postar a resposta. Utilize o campo abaixo para responder com a sua solução.
Comment: Responder à minha pergunta?
Comment: Sim, no campo abaixo acima do botao "publique sua resposta"
Answer: Após perceber que a estratégia de inverter a lista atende ao enunciado, tudo clareou. Eu estava fixado em tratar os pares equidistantes da lista, dificultando a solução. Inclusive a solução iterativa ficaria muito mais simples:
void reverse(NODE **head) {
    NODE *prev = NULL;
    NODE *curr = *head;
    NODE *next;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    *head = prev;
}

Segue solução recursiva:
void reverseR(NODE **head) {

    /* Tratar lista vazia */
    if (*head == NULL) return;

    /* Atribuir um ponteiro para o nó atual
       e outro ponteiro para o restante da lista */
    NODE *curr;
    NODE *rest;
    curr = *head;
    rest = curr->next;

    /* Retornar ao chegar no final da lista */
    if (rest == NULL) return;

    /* Chamar a recursão até atingir o final da lista */
    reverseR(&rest);

    /* Inverter os nós e acertar a cabeça da lista */
    curr->next->next = curr;
    curr->next = NULL;
    *head = rest;
}

Comment: Essa solução é iterativa, não recursiva. Então ainda falta uma metade da questão
Comment: Só fui mexer com isso hoje. Mas já adicionei a versão recursiva. Tem sugestão pra melhorar os códigos? Obrigado.
Comment: Funcionou a primeira função?
Comment: YODA, pelo que me lembro ela até funcionou.. mas quando eu pensei na "swap_nodeI" eu não havia entendido muito bem o conceito do exercício. A função "reverse" é bem mais eficiente.


How to create dynamic radiobuttons in CodenameOne

Question: Using CodenameOne, I created an array of RadioButtons based on the count of records on a database table.
Container searchDisplayContainer = findMyContainer(f);

for(int i=0; i < records.length; i++) {
    RadioButton rdb = new RadioButton();

    rdb.setName("rdb"+i);

    rdb.setText("rdb"+i);

    rdb.setGroup("locations");

    searchDisplayContainer.addComponent(rdb);
}

With this code, a number of RadioButtons are displayed on the simulator screen.
My problem is that after displaying the radiobuttons, I cannot check which one is selected.
Usually I can create the radiobutton in the theme.res and call it in the code with:
RadioButton rdb1 = findRadioButton(f);

and check if the button is selected with if(rdb1.isSelected)
However since I am not creating my radio buttons initially in the theme.res, I cannot use the findRadioButton(f) method.
My question is how do I create a number of RadioButtons within the code and then be able to check if they are selected after the submit button is pressed?

Question Modification
package userclasses;

import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;

/**
*
* @author Your name here
*/
public class StateMachine extends StateMachineBase {

    private Container searchDisplayContainer;
    private final int recordLength = 5;
    private ButtonGroup bg = new ButtonGroup();
    private RadioButton[] rdbs = new RadioButton[recordLength];

    public StateMachine(String resFile) {
        super(resFile);
    }

    /**
     * this method should be used to initialize variables instead of
     * the constructor/class scope to avoid race conditions
     */
    protected void initVars(Resources res) {
    }

    @Override
    protected void beforeMain(Form f) {
        searchDisplayContainer = findContainer1(f);

        for(int i=0;i<recordLength;i++){
            rdbs[i].setName("rdb"+i);
            rdbs[i].setText("rdb"+i);
            //add to button group
             bg.add(rdbs[i]);
             //add to container
            searchDisplayContainer.addComponent(rdbs[i]);

        }
    }
    @Override
    protected void onMain_ButtonAction(Component c, ActionEvent event) {
        System.out.println(bg.getSelectedIndex());
    }
   }

Answer: You need to create an instance of the ButtonGroup class and add the radio buttons to it in order to associate it to the other buttons in the group.
Comment: You get a NullPointerException because you allocated the array and didn't allocate the elements within it so rdbs[i] is null. Look at the stack it will actually say null pointer exception as well and point you at the specific line.
Comment: Hi Shai, thanks for your tip however I did try using ButtonGroup before posting my initial question. I have modified the question to include a test scenario. As can be seen, I have created an instance of the ButtonGroup and also created arrays of RadioButtons. However when I click the Submit Buttton (onMain_ButtonAction). I get the error "java.lang.reflect.InvocationTargetException" and the simulator closes before displaying the radioButtons. I would like to be able to print the index of the selected radio button when the submit button is clicked. Please your insight. Thanks!


configuring dedicated internet access

Question: I have taken a dedicated internet access service from my ISP. for which i received one P2P IP  address with a specified gateway, and 6 IP addresses on a /29 subnet. but they havent specified any gateway for these 6 addresses. Further, they say that is an internal range for my account. What does this mean? that these 6 addresses are not public IPs? if so, how do I configure them  ? any help would be appreciated.
Comment: I did and all the info they gave me, is what I've put up. I've asked to talk to a senior level support guy to help on this matter, but no response so far. I was wondering maybe if I could do this on my own without having to wait for their reply. I tried looking for similar scenarios online, and maybe someone who has used a similar service
Answer: Five of those addresses can be assigned to hosts. One of those IP addresses should be assigned to your router. The gateway for the 5 of those addresses not assigned to your router is the one you do assign to the router. The gateway for your router is the gateway they gave you.
Comment: ok,so that means they are not actually public ip addresses, and i will have to do port forwarding from the P2P address to this range which i have been given so that i can host whatever service i need
Comment: They're public IP addresses. You don't have to do port forwarding. This is how normal routing is done.
Answer: You mean that you have a P2P (/30) address between your router and the ISP equipment?
Internal range usually just means that they will be routing the /29 subnet towards your routers P2P IP address.
You'd need to assign the /29 to an interface pointing towards your LAN on the router using one of the ip addresses in the range. Then you can assign the remaining addresses to hosts with a default gateway of whatever address you just assigned on your router interface towards the LAN.
Comment: ok,so that means they are not actually public ip addresses, and i will have to do port forwarding from the P2P address to this range which i have been given so that i can host whatever service i need.
Comment: It doesn't necessarily mean they aren't public ip addresses. It is a common practice for addresses to be provided this way. Do the addresses fall within the RFC address space? (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
Comment: No, they are in the 62.x.x.x address space
Comment: @BahrainAdmin Why do you think they're not actually public IP addresses?

configuring dedicated internet access


how to make cron run once at specific time per day?

Question: I want the cron run only once at say 01:00 hours after midnight, just to save shared hosting resources as cron empties the caches. My new site is using too much of resources and I'm trying my best to stick with shared hosting. I want to set cron run once in a day. It should run at midnight so that some cache is built before day time, when traffic is high.
I've only two somewhat related threads: make sure hook cron is only run once a day setting
and
How to run cron more often than every hour?
But for such simple thing it don't want to use Elysia module.
From this post: How do I get the (date)timestamp since last cron run? I understand if we manually set cron_last variable then may be next cron time will be calculated with respect to this.
Another way I can do is to run drush cron from a script from crontab which will run it at a particular time. Similarly we can call cron from crontab ( as in here).
I'd want it to be done from within a module etc so that whenever I move my site, it'll work at any new setup without doing any configuration.
Any suggestions?
Comment: you can run some jobs every day at a specified hour using http://drupal.org/project/elysia_cron
Comment: @Bala "[...]don't want to use Elysia module."
Comment: Why can't you just set your crontab up to hit cron.php at the specified time?
Comment: I'm having dozen sites, and keep moving between hosting accounts etc. This will increase maintenance steps which I'd need to remember.
Answer: I think you've covered the options well in your question.  However, your combinaton of requirements - i.e.:

no poking of cron.php from crontab;
settings kept in database to be migrated along with the site ("done from within a module");
the management module must not be Elysia.

is a problem. This combination excludes all the possible answers. There is no solution that will satisfy all three requirements.
If you want to use a module, that module is Elysia cron.
You seem to think Elysia cron is overkill for this.  I happen to agree.  Besides, Elysia does not work too well when triggered by the built-in default poorman's cron.  You really want to use an external crontab poke together with Elysia to get the type of fine-grained control you seem to be after, with Elysia.
So while your first requirement rules out poking of cron.php from crontab, that is my suggested solution.
Actually, since the crontab entries for all your sites can be kept in a single file on a single server, I do not see how this set-up should be considered too difficult to maintain.
Comment: suppose I've set cron to be run once in a day and then in my hook_cron module  if I set cron_last with a calculated time  so that it runs next day as per cron_last set by me -- will it not work?
Answer: This is an old question, but I recently had to implement a similar feature in Drupal 8, so this might be helpful to others.
Guarantee that a cron task runs exactly once per day, as close to a specified time of day as possible, without any control over when the cron itself runs.
The basic idea is to keep the time of the last execution in a state variable, then check whether the scheduled time of day has passed by between then and now. For example, if the scheduled time is at 23:30, the last run was Jan 1 00:06, and now it is Jan 1 23:29, it shouldn't run - but if it is Jan 1 23:40, it should.
This ensures that the runs will be (on average) 24 hours apart, and the task happens on the first cron execution after the scheduled time. (The more frequently Drupal cron is run, the closer it will be.)
Rough structure of the service:
class MyModuleCron {

  public function cron() {
    $now = \Drupal::time()->getRequestTime();
    if ($this->shouldRun($now)) {
      $this->queueTasks();
      $this->state->set('mymodule.last_cron', $now);
    }
  }

  public function shouldRun($now) {
    // Get these from config or something:
    $scheduled = '07:30';
    $timezone = new \DateTimeZone('Region/City');

    $timestamp_last = $this->state->get('mymodule.last_cron') ?? 0;
    $last = \DateTime::createFromFormat('U', $timestamp_last)
      ->setTimezone($timezone);
    $next = clone $last;

    $next->setTime(...explode(':', $scheduled));
    // If the cron ran on the same calendar day it should have, add one day.
    if ($next->getTimestamp() <= $last->getTimestamp()) {
      $next->modify('+1 day');
    }

    return $next->getTimestamp() <= $now;
  }

  public function queueTasks() { }
}

And the hook_cron:
function mymodule_cron() {
  \Drupal::service('mymodule.cron')->cron();
}


Como usar string em C++?

Question: Estou com problemas pra lidar com string.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

bool ArqExiste(string Arquivo)
{
    ifstream verificacao (Arquivo.c_str());
    if(verificacao.is_open())
    {
        verificacao.close();
        return true;
    }
    else
    {
        verificacao.close();
        return false;
    }
}

int main()
{
    string file = "C:\\Temp\\aipflib.log";

    printf("%b", ArqExiste(file));
}

Na linha ifstream verificacao (Arquivo.c_str()), deu o erro:

variable 'std::ifstream verificacao' has initializer but incomplete type

Eu uso o Codeblocks pra programar.
Comment: Não que seja o motivo do problema, mas tem alguma razão para usar o `c_str()`? Experimenta adicionar: `#include `
Comment: Não seria necessário um segundo parâmetro para este construtor? pois dependendo do seu objetivo será necessário passar um segundo parâmetro http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
Comment: Qual a versão do C++ que esta utilizando? (C++11 ou C++98) pois possuem construtores direfentes.
Comment: Resolveu o problema com a solução que te passei?
Comment: Sim, resolveu. Obrigado mesmo, fera.
Comment: Quanto á versão do C++, eu não faço ideia. Qual é o melhor programa pra C++. Codeblocks? Visual Studio?
Comment: @MarceloNascimento não existe o melhor programa, isto é gosto, cada um tem suas vantagens e desvantagens. De qualquer forma estes programas que você falou são apenas o IDE e não o compilador, apesar de que cada um deles vem com compiladores específicos.
Answer: O problema é que você não inclui o cabeçalho necessário no caso o #include <fstream>.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

bool ArqExiste(string Arquivo) {
    ifstream verificacao (Arquivo.c_str());
    if(verificacao.is_open()) {
        verificacao.close();
        return true;
    } else {
        verificacao.close();
        return false;
    }
}

int main() {
    string file = "C:\\Temp\\aipflib.log";
    printf("%b", ArqExiste(file));
}

Veja funcionando (aproximadamente) no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Também tirei o conio que por sorte não está sendo usado neste código. Esse cabeçalho nunca deveria ser usado em códigos modernos.
Considere também não usar o c_str() aí, ele não é necessário.
Comment: Valeu mesmo pela ajuda.

Como usar string em C++?


Error while using NZload

Question: I am trying to use nzload to load a file residing in a unix directory to a NZ database but I keep getting the following error:
nzsql "nzload -u $NZ_USER -pw $NZ_PASSWORD -host $NZ_HOST -db $NZ_DATABASE -df  -lf log.txt -bf err.txt"
nzsql: database name exceeds limit
my database name is only 18 bytes
Where am I going wrong? Is there a work around for this?
Answer: You are mixing two commands in one, NZSQL and NZLOAD are two different commands. Please use following command -

user@domain dir]# nzload -u $NZ_USER -pw $NZ_PASSWORD -host $NZ_HOST -db $NZ_DATABASE
  -df your_file_name -lf log.txt -bf err.txt

Hope this will help.

Error while using NZload


Dealing with node language when manually updating node

Question: I'm trying to manually update a node and I'm not sure how the language works.
The node is in English, so $node->language = 'en';
However, all my fields data are organized like this in the node:
$node->field_name['und'][0]['value']

I thought 'und' means "language undefined", so shouldn't it be 'en' instead?
I'm trying to automate the process so is it safe to assume fields will always use 'und' in nodes?
Answer: Yes - it is safe to assume this. The locale module will deal with this by setting it to the language code of the default language, ex 'en'.
Citing from: http://drupal.org/update/modules/6/7#drupal_language_none
In Drupal 7, the LANGUAGE_NONE constant should be used for nodes or other items that do not have a specific language associated with it.

http://api.drupal.org/api/drupal/includes--bootstrap.inc/constant/LANGUAGE_NONE/7

Answer: You can get field values without use LANGUAGE_NONE.
$field_items = field_get_items('node', $node, 'field_name');
$value = $field_items[0]['value'];

Answer: Instead of specifying a language, I prefer to just use entity_metadata_wrapper().
For example:
$node = entity_metadata_wrapper('node', SOME_NODE_ID);
$value = $node->field_something->value(); // returns field value
$node->field_something->set('new value'); // sets field value
$node->save();

Source: https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
Comment: Hey hey, welcome to DA. Nice snippet. But I don't actually see how this answers OP's problem?
Comment: It's more of a different way to solve the root problem so that the actual question becomes a moot point.


Unable to access microphone when another app is using it in Android

Question: I'm using code from the following URL in order to get sound data from the microphone with AudioRecord:
http://www.dreamincode.net/forums/topic/303235-visualizing-sound-from-the-microphone/
The problem I'm seeing is that if another app is also using the microphone, I'm getting an error (status -3) from AudioRecord. Everything works as expected if I kill the other app which is using the microphone. Is there an elegant solution to allow my app to access the microphone even if another app is already using it?
Thank you.
Comment: Some more information: AudioRecord.read is returning -3, which I believe means that it read zero bytes.
Comment: Do you want to *switch* which app is using the microphone, or allow them both at the same time? If the latter, this is a duplicate of [Share Audio Input?](http://stackoverflow.com/q/9758946/752320) Simply put, only one app can use it at a time.
Comment: I want to switch which app is using the microphone. I assumed that the app in the foreground would get control of the mic, but it seems that whichever app has it first will keep control. Thanks for any help.
Answer: Sadly, only one app at a time can access the microphone (just like the camera).
Also, there is no standard way to inform another app that you want access to the microphone (so that they release the resources and let you access it). You could however send a broadcast to all other apps ("requesting the microphone"), but the other apps would have to implement this feature (and very few or zero developers will do this).
I would recommend you to simply inform the user that the microphone is currently not available, because you can't do anything else.
Comment: Thank you. I ended up just informing the user that it can't access the microphone like you said, and to close any other apps that are using it. I have it restart access to the microphone once they come back to my app.
Comment: How do I become the other app here? If i want to implement the feature when i receive a broadcast to relinquish the microphone resources ?
Answer: If you are using the "OK Google" function with the option to access it from any page, try turning that off (the 'any page' bit From Google app screen MENU>SETTINGS>VOICE>"OK GOOGLE DETECTION">FROM ANY SCREEN=OFF): it hijacks the microphone, or can do.


Edit field in contentType B when creating or editing node of contentType A

Question: I need to edit a field in contentType B when I create or edit nodes of contentType A.
I know it's possible to use rules for this but I need to have more control so I want to do it in my own module.
Tried this code without success:
<code>function MYMODULE_node_presave($node) {
    MYMODULE_change_value($node);
}

function MYMODULE_change_value($node) {
    $node = node_load($node->nid);

    $referenced_nid = $node->referenced_node[LANGUAGE_NOE][0]['target_id']

    $referenced_node = node_load(referenced_nid);

    $referenced_node->my_field[LANGUAGE_NONE][0]['value'] = 12345.0;
    node_save($referenced_node);
}
</code>
Am I choosing the wrong hook?
Comment: It's D7 or D8 ?
Comment: Sorry., I always forget. It's D7.
Comment: you use this module [entityreference module](https://www.drupal.org/project/entityreference) to reference nodes ?
Comment: Yes. The nodes of contentType B are referenced in nodes of contentType A.
Answer: Try the following:
<code>/**
 * Implements hook_node_presave().
 */
function yourModule_node_presave($node) {
  if ($node->type == 'your_typeA') {
    yourModule_change_value($node);
  }
}

function yourModule_change_value($node) {
  if (isset($node->field_node_referenced[LANGUAGE_NONE][0]['target_id'])) {
    //- Get referenced node id
    $referenced_node_id = $node->field_node_referenced[LANGUAGE_NONE][0]['target_id'];
    //- Load referenced node
    $wrapper = entity_metadata_wrapper('node', $referenced_node_id);
    $wrapper->field_name->set(array(
      'value' => 'test new field value'
    ));
    $wrapper->save();
  }
}
</code>
Comment: The field that I want to change is a taxonomy term. Using your code, I get this error: EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node(26)->my_field: array ( 'tid' => 6, ). I changed your line: 'value' => 'test new field value' to 'tid' => 6
Comment: try with `field_name->set(6)` without value
Comment: I was also looking for a solutio and that's exactly what I've found. It depends on the type of value you want to change. Thanks for you support berramou!
Comment: you are welcome!
Comment: I have a related question. I'm passing the $node variable to my "change_value" function. Is it possible to pass also the previous node values?
Comment: how is previous node value? for example you want to create nodeA of typeA which node you would pass  ?
Comment: I can pass all the previous node or a specific field. If it's only a field, it would be the referenced node.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/84490/discussion-between-zephirus-and-berramou).


How can I look for correlations between variables with large deviations?

Question: I'm researching the correlation between the magnitude (a measure of brightness) and redshift ($z$ - a measure of distance) for a variety of galaxies called quasars. Plotting the magnitude against $log(z)$ for one set of data looks like this:

and this pattern is similar for all of the sets of data I'm looking at (black/blue plot same set as above):

These plots are for only a small set of the data, but I expect them all to follow roughly the same pattern; fairly closely packed at low redshift, and much more scattered at high redshift.
I've been trying to fit a straight line to the data, so that I can use the magnitude of a quasar to estimate its redshift. While the correlations are highly significant, the $r$ and $r^2$ values are far too low (only around 0.5 for some of the best fits) to lead to a useful estimate, shown here for the black/blue plots above:

I'm looking at the problem as a physicist, but since my knowledge of statistics is poor, I'm wondering if there's a better way to determine a tight correlation between the magnitude and $log(z)$ that I'm missing.
Is there a statistical way to tighten up the regression coefficient?
Comment: Could you add a quick list of references to describe your variables?  Just the regression equation, and then references ($y = $ blah blah blah, $z = $ bleh bleh bleh).
Comment: Do you mean like in the legend of the second graph?
Comment: Oh, I understand now.  You wrote *"redshift (z - a measure of distance)"*.  I thought this meant $z$ and "a measure of distance" were two variables being differenced.  You meant *"redshift ($z$, a measure of distance)"*
Comment: So you are looking for some relationship $M \sim \alpha + \beta_i \cdot z$?  In this case, $M = $ magnitude.
Comment: Yes, exactly. That way, we can estimate $z$ just from the brightness, without requiring to look at the atomic frequencies in the light.
Answer: Based on this Quora answer, you may want to try something with a bit more complexity.  $M \sim \alpha + \beta_1 z + \beta_2 z^2$ is a suggestion in this article, though I personally wouldn't go this route right away.  You should check your residuals to see if you are missing some higher-order relationship.  This could indicate "A missing higher-order term of a variable in the model to explain the curvature."  Since you only have one predictor, finding which explanatory variable is missing a higher term would be pretty easy.  Unfortunately, a pattern in your residuals could also indicate a missing explanatory variable.  This is why I would not advise jumping to this method without some further checking.
Unfortunately, since you are only looking at two dimensions (magnitude, redshift), there is little you can do.  This is pretty helpful for your specific case, I believe.  A quote from the article:

In some cases, it's possible that additional predictors can increase the true explanatory power of the model. However, in other cases, the data contain an inherently higher amount of unexplainable variability. For example, many psychology studies have R-squared values less that 50% because people are fairly unpredictable.

Without additional predictor variables to add dimensionality, it would be difficult to increase your $R^2$.  Here is a link to an article discussing the significance of $R^2$.  According to the author,

Just because effect size is small doesn't mean it's bad, unworthy of being interpreted, or useless.  It's just small.  Even small effect sizes can have scientific or clinical significance.  It depends on your field.
If the only point of the model was prediction, my client's model would do a pretty bad job.
But it wasn't.  The point was to see if there was a small, but reliable relationship.  And there was.

If you were looking to draw some sort of conclusion from the aggregate data, you could do this with a low $R^2$.  Prediction could prove problematic, though.  One last quote, this time from a different statistics blog, explaining that you may be able to draw meaningful conclusions from your model, just not predict very well:

A low R-squared is most problematic when you want to produce predictions that are reasonably precise (have a small enough prediction interval). How high should the R-squared be for prediction? Well, that depends on your requirements for the width of a prediction interval and how much variability is present in your data. While a high R-squared is required for precise predictions, it's not sufficient by itself.


Possible to abort mid-task on error?

Question: Given a task that performs a service restart on five different hosts, is it possible to tell ansible that if the restart fails on host1, to abort the entire run without doing the restart on hosts 2-5?
The any_errors_fatal setting combined with --forks=1 and serial: 1 settings all seem promising but don't seem to it.
- hosts: all
  serial: 1
  any_errors_fatal: true
  become: yes
  roles:
    - service_control

Answer: Can you try setting max_fail_percentage to zero? From Maximum Failure Percentage
- hosts: all
  serial: 1
  max_fail_percentage: 0
  become: yes
  roles:
    - service_control

Possible to abort mid-task on error?


PHP: How do I unescape user input from $_POST?

Question: I have a PHP page receiving input from an HTML form via $_POST. The strings in $_POST have quotes and backslashes escaped with '\'. I don't know what else it will escape/encode. I'd like to have exactly what the user typed (as UTF-8 ideally) and I'm sure there's some simple function to do this, but I'm not sure which is the right one.
I know I have to be careful with this when I insert it into a database, or return it in the middle of some HTML, but in my code I'd like to have my hands on exactly what the user typed.
EDIT: magic_quotes_gpc was escaping some things, but even after removing that I still get HTML entities like Ą from $_POST. Is there a simple way to decode $_POST back to the original user input (preferably in UTF-8)?
Comment: Processing post data securely and properly is an "extraordinarily narrow situation" is it? I can't believe how many good questions are closed on SO.
Answer: Try PHP's stripslashes function.
Just a side note, it sounds like you have magic_quotes_gpc on, which isn't recommended for security reasons, and it is even removed in later versions of PHP.
Comment: So magic_quotes_gpc is what's escaping stuff on me? How do I turn that off?
Comment: Yes, most likely. It's a configuration option in PHP, here's some more information about it: http://php.net/manual/en/security.magicquotes.php
Answer: Looks like I didn't have the charset properly set to UTF-8 on the page with the form. When I corrected this, everything came out ok.


How to create firebase collection at runtime with polymer's firebase-collection

Question: I have a polymer app that has a  bound to my app's data which is its state.  the state is pushed to all connected clients via firebase.  Now I want to add "chat rooms".  it's not chat but the analogy works.  how do i create a chatroom and have it bound to my custom element's data property at runtime?  i wanted to do something like:
<code><my-app><my-room chatId="{{currentChatId}}"></my-room></my-app>
</code>
and keep an array of chat room id's in my-app and the current chat room's data in my-room.  so if my firebase data looked like {rooms : {room1: {chatId: 111...}} i wanted to the firebase-collection element in my-room to have its location property = "https://appname.firebase.io/{{chatId}}" and have the data property bound to a property in my-room.  but since chatId will be null at creation time this solution doesn't work.  I tried setting the firebase-collection location property in the observer for chatId at runtime but it didn't create any data when I changed the local data bound to the firebase-collection's data property.
so my question is how do i have a firebase-collection element bound to data that doesn't exist at creation time?
Answer: Thinking there may be other problems here, but a quick solution to the ? might be to use conditional templates - https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-if, i.e. you could wait to stamp the firebase-collection element until your chat id exists.
Again seems like there is potentially something else here that should be addressed but this might be a quick & dirty fix for you.
Answer: I don't know what I was doing wrong before but setting the location property at runtime does work.


Simple Mediation Analysis Interpretation

Question: I want to do a mediation analysis for variables Y,X,M in statistical package R.
I have perform the following regression models:
Y=intercept1+a0*X
M=intercept2+a*X
Y=intercept3+c*X+b*M

For the mediation analysis i have used the package:
library(mediation)
The results from the estimated parameters from regression models are:
a0=-0.86
a =-1.01
c =-0.19
b = 0.66

The parameter c is non significant (p=0.2).
The results from mediation analysis are:
               Estimate 95% CI Lower 95% CI Upper p-value
ACME             -0.660       -0.878        -0.45  <2e-16 ***
ADE              -0.195       -0.503         0.07     0.2
Total Effect     -0.855       -1.178        -0.52  <2e-16 ***
Prop. Mediated    0.772        0.535         1.12  <2e-16 ***

I don't know how to interpret the negative but statistically significant ACME (a0-c) parameter. Can someone help me ?
Answer: $a_0$ measures the total (direct+indirect) effect of $X$ on $Y$, while $c$ is the direct effect (since you are now including the mediator in the regression). $a_0-c$ then measures the difference between total and direct effect, i.e. the indirect effect: its negative value means you have a negative mediation effect. You have both a total and an indirect negative (and highly significant) effect, while (as you noticed) no significant direct effect. Thus, you have evidence for mediation, and can't reject the hypothesis of complete mediation (i.e., null direct effect).