How to conditionally load javascript file on view page

Question: I'm trying to load some theme javascript only to one view(multiple displays). I've tried to use the views preprocessor funciton, but maybe I'm doing it wrong:
function themename_preprocess_views_view__viewname__page(&$variables){
  this doesn't run on view page;
}

I've also tried it with the function name themename_views_view(). There's not much documentation on this.
Answer: This should work:
/**
 * Implements template_preprocess_views_view().
 */
function themename_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'view_name') {
    // Standardize the output for rows.
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/js_name.min.js', array('scope' => 'footer'));
  }
}

Answer: Place this in your template.php and clear cache
<?php
function THEME_NAME_preprocess_views_view(&$vars) {
  $view = $vars['view'];

  if($view->name == 'YOUR_VIEW_NAME' && $view->current_display == 'YOUR_DISPLAY') {

    global $theme_path;
    drupal_add_js($theme_path . '/js/myfile.js');
    //OR MAYBE
    drupal_add_library('system','ui.slider');
  }
}


Sending File Attachment by Mail In Flutter

Question: So I want to attach a file to the email in Mailer library. As I see in the Mailer description, it says that you can attach files, but I don't see how:
final message = Message()
..from = Address(username)
..recipients.add('firstname.lastname@example.com') //recipent email
..ccRecipients.addAll(['firstname.lastname@example.com', 'email@example.com']) //cc Recipents emails
..bccRecipients.add(Address('email@example.com')) //bcc Recipents emails
..subject = 'Test Dart Mailer library ::  :: ${DateTime.now()}' //subject of the email
..text = 'This is the plain text.\nThis is line 2 of the text part.' //body of the email

How would I attach a file here (csv file for example)?
Answer: You can check this
  Iterable<Attachment> toAt(Iterable<String> attachments) =>
      (attachments ?? []).map((a) => FileAttachment(File(a)));

  // Create our message.
  final message = Message()
    ..from = Address('$email@example.com', 'My name ')
    ..recipients.addAll(toAd(tos))
    ..ccRecipients.addAll(toAd(args[ccArgs] as Iterable<String>))
    ..bccRecipients.addAll(toAd(args[bccArgs] as Iterable<String>))
    ..text = 'This is the plain text.\nThis is line 2 of the text part.'
    ..html = "
Test
\n
Hey! Here's some HTML content
"
..attachments.addAll(toAt(args[attachArgs] as Iterable<String>));

Comment: I'm getting weird errors, here, any other option, or an example if someone has done it?
Comment: Would you mind to show the error and update  the question? Maybe more detail for your code
Comment: Yep, I'll get on it asap, not at home now, so can't upload it. But I'll see if I can fix it and get back to you asap.
Comment: I solved it with Mailer package, I updated in the main code if anyone has the same issue, just add the `file` in the attachment.


Show a print view of the page

Question: I want to have a page where users can see the printable view of the web page. So that they can see how the page will look like in the print window, and if it looks good, they click a print button, and then the print window will be opened. ( So we can think that we have two buttons in the page, "Print the webpage", "Show as a print view" )
Could anyone let me know how I can show a page as if they are in print window please?
Answer: Every user on your website can use the Ctrl/Cmd + P key to print your site out, or Ctrl/Cmd + S to save it, but you can use:
window.print()

function. It opens a dialog box, where the user can configure the print, and then allows them to print.
Comment: Yes, I can use `window.print()`, but is there a way to show printable view in a normal tab, not the print dialog box.
Answer: This might be what you're looking for. var openingPreview = browser.tabs.printPreview() will open print preview for the active tab. Check the docs here: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/printPreview
Answer: MDN has what you're looking for (See Here) but it has a big limitation that it is supported only by the Firefox web browser, and thus there is no other choice than to use
window.print()

Unless you are going to use it only on firefox

Show a print view of the page


Media Query Wont Edit Photo

Question: I'm trying to move my image based on screen width but my media query for it wont work. I've checked multiple websites and watched many youtube videos but I don't see any problems with the code here's
an example code:
 .bg{
  position:absolute:top:100px;left:10px
  }

  @media screen and (min-width: 776px){
  .bg{
  position:absolute;top:10px:left:5px;
  }
  }

Thought maybe I was missing a specific header or my editor wasn't working but don't think either of that is a problem.
Comment: Typo in `position:absolute:`
Answer: It should be:
@media screen and (min-width: 776px) {
    .bg {
        position:absolute;
        top:10px;
        left:5px;
    }
}

; but not :

Media Query Wont Edit Photo


Phase trasition of $f(x)$ on random graph $G(n,p(n))$

Question: Random graph $G(n,p(n))$ and graph $H$, which shown below, are given.

I'm in need to find $f(x) : f(x) > 0$, such as:

if $lim_{n \to \infty}p(n)f(n) = 0$, then asymptotically almost surely G don't contain subgraph, isomorphic to $H$
$lim_{n \to \infty}p(n)f(n) = \infty$, then asymptotically almost surely G contains subgraph, isomorphic to $H$

Thank you for your suggestions.
Comment: Do you know about balanced subgraphs in random graphs?
Comment: I looked up definition here: http://link.springer.com/chapter/10.1007%2FBFb0071616 and here http://en.wikipedia.org/wiki/Signed_graph.
Sorry, I couldn't link it to my problem.
Would you elaborate on it a bit?
Answer: I don't know if I really understood the question, so tell me what you think about this "solution". (If you already have one, please, let me know!)
Fix 6 vertices and put on them an order (label them). Suppose the first six vertices $\{1,2,..,6\}$. Then, the probability that exists a subgraph isomorphic to $H$ using these 6 vertices is bounded by $6!p^7$. You force the seven connections and permute theirs labels.
So, $P( \exists H \subset G(n,p(n)) \le 6!\binom{n}{6}p(n)^7$. Here you get a candidate to $f(n)$. Take $f(n)=6!\binom{n}{6}p(n)^6$ and you have that $\lim_n f(n)p(n) = 0$ implies $G(n,p(n))$ doesn't have a $H$ a.a.s.
On the other hand, put again the vertices in order and force the existence of a $H$ using only 6 disjoint vertices. I mean, form $\lfloor \frac{n}{6} \rfloor$ sets of 6 vertices. Then $P( \exists H \subset G(n,p(n)) \ge \lfloor \frac{n}{6} \rfloor p(n)^7$. And now, take $f(n) = \frac{1}{p(n)(\lfloor \frac{n}{6} \rfloor  p(n)^7 -1)}$.
And then you get $\lim_n f(n)p(n) = \infty$ implies $G(n,p(n))$ has a $H$ a.a.s.


Add html5 banner in Revive 4.1.1 gives PHP fatal error: Cannot redeclare Plugin_BannerTypeHTML_delivery_adRender

Question: When I add a html5 banner to a campaign in Revive 4.1.1 and click 'save changes', I get an empty page in the admin. The Apache error log contains:

PHP Fatal error:  Cannot redeclare Plugin_BannerTypeHTML_delivery_adRender() (previously declared in /home/applinet/local/ads/www/lib/OX/Extension/bannerTypeHtml/bannerTypeHtmlDelivery.php:31) in /home/applinet/local/ads/www/lib/OX/Extension/bannerTypeHtml/bannerTypeHtmlDelivery.php on line 31

What may be causing this?
I'm using Revive 4.1.1 (upgraded from 4.0 and OpenX before that) with PHP 7.0 and MySQL 5.5 on Debian 9.2 Linux.
Comment: Are you including / requiring the same file twice? If so, maybe you want to use `include_once` or `require_once` _(note: I dont know about anything you're using, just php really)_.
Answer: I would say that you should locate where the function is being declared again and remove it. however....
a dirty fix for this is like so;
locate where the Plugin_BannerTypeHTML_delivery_adRender() function is being declared ( in bannerTypeHtmlDelivery.php by the looks of it)
then add this code;
<code>if (!function_exists('Plugin_BannerTypeHTML_delivery_adRender')) {
    // the funtion doesnt already exists so declare it here
function Plugin_BannerTypeHTML_delivery_adRender(){
//all the function stuff here.
}
}
</code>
to clarify.... simply wrap the existing function in the if block.
as i said it is a dirty fix.


Pagination Firestor CollectionView Swift Programmatically

Question: Regarding Pagination with Firestore I followed the guide on their website and on Youtube but I don't understand one thing:
Practically speaking, if we have a collectionView displaying cells from a first query of 10 documents.
We scroll to the bottom of the collectionView when all the data of the first query have been visible, where do we call the next query from the controller?
I searched online but didn't find much, I was thinking maybe with some delegate methods of UIScrollViewDelegate of the CollectionView (?) but It doesn't seem to offer the right methods to do that.
Also for better user experience I was thinking that is better to call the next query when the user is approaching the bottom of the collection and not when he already reached it.
Comment: `collectionView(_:willDisplay:forItemAt:)`
Answer:  func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if newInstrumentList.count-1 == indexPath.row && isMoreDataAvailable{
        self.presenter?.showMorePage()
    }
}

This is what is use for pagination, generally during an API call I get the total number of item and depending on that I set a bool property. Whenever the collection view cell index matches with the indexPath.row, next data is requested.
Comment: Thank you, what do you mean with ```get the total number of item```, you firstly make an api call to get all the documents first?
Comment: No you don't get all the documents first. This is what pagination is for, you just get the total  `number`  of documents or files. You need to know how many items are there, how many are loaded. If there are no more documents, it won't make sense to make a network call to request for more elements.
Comment: But by knowing the total number of documents doesn't it mean that We're already reading them firsthand?


How to remove/hide 'to time' in time field

Question: I need to show only one time, no need of start and end time. Or I need to show only start time. Please anyone help me on this.
Comment: Are we using date/events ? Please explain
Comment: Yes. I need to show only start time. How can I remove the end time field.
Comment: It's a configuration in field settings.. Edit field and change settings..
Comment: Thanks Anil. But I didn't see any section to hide the end time field.
Answer: You can change in the field setting
Go to your content type, Now when we add a field of Date type. Then it will show a section for start and end date mentioned in the image

For already added field, you can not edit it i think because there is already content with end date. You can hide it if neccessary
Hope it will help!


MonoGame Mac Templates Installation

Question: I am having trouble installing the MonoGame templates in MonoDevelop on Mac. I have placed the MonoDevelop.MonoGame.2.5 folder in MonoDevelop.app/Contents/MacOS/lib/monodevelop/AddIns/ as instructed by the readme but after restarting monodevlop, the template is not available in the new projects section. Can anyone help with this problem?
Answer: Mac templates should be available in the 2.5.1 bug fix release, due soon.

MonoGame Mac Templates Installation


How to read data from a table and assign them to variables of correct underlying data type generically in.NET

Question: I want to read data from a table and assign them to variables of correct underlying data type generically. That is, once the logic is implemented, it can be used for any table containing any data type of column, in .NET
Answer: Sounds like you should just use an ORM, like Linq to SQL or Entities Framework, or NHibernate (etc.).  They do exactly that; map database tables to .NET classes, doing all of the proper type conversions.
Comment: it is not used in this scenario.


VBS File Read: Change CR FF to CR LF

Question: I have txt and csv files to be read per line. A line ends with CR-LF.
But in some files, there is CR and no LF; instead, next physical line starts with FF. UFT 12 reads them together, as if it was one line.
I read files using fso:
Dim FileRead : Set FileRead = fso.OpenTextFile(file1)
Dim file2Read : Set file2Read = fso.OpenTextFile(file2)

FileStrR = FileRead.ReadLine
File2StrR = FileRead.ReadLine

I need to compare each line of these file with another text file:
if FileStrR = File2Str Then...

I tried to separate the FileStrR as array:
FileStrA = REPLACE(FileStrR, ChrW(12),"**")
strarray = split(FileStrA,"**")
For h = 0 to UBound(strarray)
    FileStr = strarray(h)
    if FileStr = File2Str Then...
...

But here I stuck to read next line from the File2 to compare with whatever comes after FF.
UPDATE
Tried to SkipLine:
Do Until fileRead.AtEndOfStream
ln=ln+1
FileStrA = REPLACE(FileStrR, ChrW(12),"**")
strarray = split(FileStrA,"**")
For h = 0 to UBound(strarray)
    FileStr = strarray(h)
    For s=1 to (ln+h)-1
       File2Read.SkipLine
    Next

print ln&"-"&ln+h&"-"&h

    File2Str = File2Read.ReadLine
    if FileStr1 = File2Str Then...
print "F1: "&FileStr
print "F2: "&File2str
    Next
    Loop

In this peace of code, the line print ln&"-"&ln+h&"-"&hprints correct numbers (ln should be the number of the line currently read). But the string print (print "F1: "&FileStr & VBNewLine & "F2: "&File2str)gives the following:

F1: 2|8122|TX|...
F2: 4|8123|FG|...

It seems even if ln+h is 'ln' while 'h' is 0, but the fso skips one more line.
Comment: Something is not right with your file encoding, that's for sure. What does a hex editor show? Can you include that in your question for both files? Also show the code that reads the file (the definition of `FileRead`)
Comment: I open it in Notepad++, also printed what UFT reads. For those lines (it is like 1 in 65 lines), it is as follows:
`...`
`Line 64 Text CR-LF`
`Line 65 Text CR`
`FF Text CR-LF`
`Line 67 Text CR-LF`
`...`
Comment: It says UTF-8.
Tried to convert to ANSI; it added a `LF` after `CR`.
Problem is, ideally I cannot and have no access to redefine encoding or save file as new file with other encoding that it has originally ((
Answer: See this to learn that you can't use

the FileSystemObject to read/write UTF-8
.ReadLine if the EOLs are messed up (not CrLf or Lf)

If your files are ANSI/UTF-16 and not to big, you can use

.ReadAll to slurp the 'bad' file
Replace CrFF with CrLf
Split on CrLf to get an array of lines
these lines to compare to the .ReadLines from the 'good' file

If .ReadAll is not possible, you must write your own version of .ReadLine that scans for CrLf or CrFF and returns the data before those EOLs.
Comment: @Salek use `ADODB.Stream` with `Charset = "UTF-8"`. See https://stackoverflow.com/a/13855268/692942
Comment: @Salek - My answers has the link (chain) to the docs that unequivocally state that FSO is **NOT** for UFT-8. So you are like the man jumping from a high building who still grins when passing the 5th floor - even worse, you invite other people to jump after you.
Comment: Files are UTF-8, and their size vary from couple KB to couple dozens MB...(((
By the way, FSO reads any file with not messed up EOLs really well, dependless of the size )
Comment: @Salek if you are using FSO to read a UTF-8 file, that is your problem. While it may "appear" to read it right what you end up with is a encoding mismatch which will come back to bite you. You need to stop assuming you know best and heed the advice being given.
Comment: Cannot change anything in original file, but with ReadAll replaced FF to LF and saved as new file with ANSI. Now, ReadLine works ))
Comment: @Salek fine, it works you go do it your way. What you are failing to understand is due to the way UTF-8 is organised some common character will map fine, but they are still UTF-8 encoded. So by reading them as ASCII you will end up with mismatched encoded characters, it is that simple. But hey, you know better then us right.
Comment: @Lankymart, I got that point) But so far found no option to read files by other method but FSO readline - thats lack of my knowledge, need more research. Unfortunately, at the moment have no time for that due to deadline. For now, this is solving the current problem.
By the way, thnx to comments here, learned more about encodings and file reading. Will return to this issue and try to find a better solution.
Really appreciate your help))

VBS File Read: Change CR FF to CR LF


Standard Error of the MLE for Laplace Distribution

Question: Given the Laplace distribution parametrized by $\mu$ and $b$,
$f(x\mid \mu ,b)={\frac  {1}{2b}}\exp \left(-{\frac  {|x-\mu |}{b}}\right)\,\!$ ,
I know that $\hat \mu$, the maximum likelihood estimator of $\mu$, is the sample median. But how do we find the standard error of the MLE? I'm not sure how to proceed since the Fisher Information is undefined when $x = \hat \mu$, which, for my purposes, I must assume will happen.
I'm aware of the answers provided to the question here. What I'm looking for in general is a method to compute the standard errors when the log-likelihood is not twice differentiable.
Comment: Isn't the Fisher Information the [expectation](https://en.wikipedia.org/wiki/Fisher_information) of the logarithmic derivative of the density?  In this case, since the function will fail to be differentiable only on a set of measure zero, this shouldn't affect its applicability.
Comment: @whuber yes, but in practice the observed Fisher Information is often used in place of the Fisher Information (though please correct me if I am mistaken). In any case, I'd like to know how to find the standard error when the Information evaluated at the MLE does not exist.
Answer: Appeal to the Fisher information gives you an asymptotic approximation to the standard error.  As whuber correctly points out in the comments, so long as this function is almost surely differentiable, that should be sufficient to obtain your result.
However, in the present case it is also possible to obtain the exact distribution of the MLE via first principles methods, without appeal to the asymptotic theory of MLEs.  Your MLE is the median, so its distribution can be obtained using standard distributional results for order statistics, where the underlying distribution is continuous.  To derive the result we will assume an odd number of observations for simplicity in dealing with the median.
In this case we have $n = 2k+1$ for some non-negative integer $k$ and the MLE is $\hat{\mu} = X_{(k+1)}$.  We let $f$ and $F$ be the respective density and distribution functions for the (zero-mean) sample distribution.  For IID values from a continuous distribution we then have:
$$\begin{equation} \begin{aligned}
\mathbb{V}( \hat{\mu}) = \mathbb{E}( (\hat{\mu} - \mu)^2 )
&= \int \limits_{-\infty}^\infty t^2 f(t) \text{Beta}(F(t) | k+1, k+1) dt \\[6pt]
&= \frac{(2k+1)!}{k! k!} \int \limits_{-\infty}^\infty t^2 f(t) F(t)^k (1-F(t))^k dt \\[6pt]
&= \frac{(2k+1)!}{k! k!} \int \limits_{-\infty}^\infty t^2 f(t) (F(t)-F(t)^2)^k dt \\[6pt]
&= \frac{(2k+1)!}{k! k!} \sum_{i=0}^k {k \choose i} (-1)^{k-i} \int \limits_{-\infty}^\infty t^2 f(t) F(t)^i F(t)^{2k-2i} dt \\[6pt]
&= \frac{(2k+1)!}{k! k!} \sum_{i=0}^k {k \choose i} (-1)^{k-i} \int \limits_{-\infty}^\infty t^2 f(t) F(t)^{2k-i} dt. \\[6pt]
\end{aligned} \end{equation}$$
For the Laplace distribution we have $F(t)(1-F(t)) = \tfrac{1}{2} \exp(- |t|/b) - \tfrac{1}{4} \exp(- 2|t|/b)$ and $f(t) = \tfrac{1}{2b} \exp(- |t|/b)$ so that:
$$\begin{equation} \begin{aligned}
\mathbb{V}( \hat{\mu})
&= \frac{(2k+1)!}{k! k!} \sum_{i=0}^k {k \choose i} (-1)^{k-i} \int \limits_{-\infty}^\infty t^2 f(t) F(t)^{2k-i} dt \\[6pt]
&= 2 \frac{(2k+1)!}{k! k!} \sum_{i=0}^k {k \choose i} (-1)^{k-i} \int \limits_0^\infty t^2 f(t) F(t)^{2k-i} dt \\[6pt]
&= b^2 \frac{(2k+1)!}{k! k!} \sum_{i=0}^k {k \choose i} (-1)^{k-i} \Big( \frac{1}{2} \Big)^{2k-i} \int \limits_0^\infty t^2 \exp (-(2k-i+1)t) dt \\[6pt]
&= b^2 \frac{(2k+1)!}{2^{k-1} k! k!} \sum_{i=0}^k {k \choose i} \frac{(-1 /2)^{k-i} }{(2k-i+1)^3}. \\[6pt]
\end{aligned} \end{equation}$$
This gives us a closed form (finite sum) expression for the variance of the MLE estimator (i.e., the sample median).  (It is important to be careful of rounding error when evaluating the variance expression, since it involves a product of very large and very small terms.)  A related expression has been investigated in some excellent analysis by Claude Liebovici in this related question, which shows that $\mathbb{V}( \hat{\mu}) \approx b^2 / n$ as $n \rightarrow \infty$.  This limiting result accords with the asymptotic theory of the sample median, which has $\mathbb{V}(\hat{\mu}) \rightarrow 1 / (4n f(\mu)^2) = b^2 / n$.
Comment: Looking at https://math.stackexchange.com/questions/2721263/establishing-properties-of-a-complicated-finite-sum/2721443#2721443 I have been playing a little and it "seems" that the constant is $\frac 14$.
Comment: Thank you for the thorough answer, as well as the example. The only thing I cannot follow is your calculation of the standard error of the sample mean at the very end of your post. Is that a typo?
Comment: Yeah, that bit was wrong.  Removed.
Comment: @Claude: Owing to investigation of the asymptotic variance, I noticed an error in the last step of my variance expression where I had omitted an additional multiplicative term of 2 (i.e., my expression was half of what it should have been).  This means that the summation expression is now twice as big as the one you investigated.  Results have been adjusted accordingly.


Moments of an exponential random variable

Question:
If $X$ is an exponential random variable with mean $\frac{1}{γ}$, show that $\\E[X^k]=\frac{k!}{γ^k},\,\,$ for $\, \, \, k=1,2,3$...

How would I go about proving this?
Comment: Induction? ${}{}{}$
Comment: Can you prove it for $k=1$?  How about $k=2$?  What approach do you use for $k=2$?  Generalize.
Answer: The induction step uses integration by parts.
$$E[X^{k+1}] = \int_0^\infty x^{k+1} \gamma e^{-\gamma x} \mathop{dx}
= (k+1)\int x^k e^{-\gamma x} \mathop{dx} = \frac{k+1}{\gamma} E[X^k].$$
Answer: Moment generating function of the exponential RV is $$\frac{1}{1-t\gamma^{-1}},\,t<\gamma$$ So $$M_X(t)=\mathsf{E}\{e^{tX}\}=1+t\mathsf{E}\{X\}+\frac{t^2\mathsf{E}\{X^2\}}{2!}+\frac{t^3\mathsf{E}\{X^3\}}{3!}+\cdots=\sum_{k=0}^{\infty} t^k\frac{\mathsf{E}\{X^k\}}{k!}=\frac{1}{1-t\gamma^{-1}}$$
Expanding the RHS using
$\frac{1}{1-x}=\sum_{n=0}^{\infty}x^n,\,|x|<1$ for $x=t\gamma^{-1}$
$$\frac{1}{1-t\gamma^{-1}}=1+t\gamma^{-1}+(t\gamma^{-1})^2+\cdots=\sum_{k=0}^{\infty} t^k(\gamma^{-k})$$
and the coefficients of $t^k$ should be identical.  That is
$$\gamma^{-k}=\frac{\mathsf{E}\{X^k\}}{k!}\Rightarrow \mathsf{E}\{X^k\}=\gamma^{-k}k!$$
Comment: So circular.  You do realise that Ryan Smith is likely being asked to find $\mathsf E(X^k)$ as a lead into *deriving* the moment generating function, right?  (Although this is still useful as a guide to reverse engineering a method to do so.)
Comment: Yes @GrahamKemp, that is also a possibility. But in that case the MGF can be derived more easily by directly calculating $\mathsf{E}(e^{tX})$. I think the main idea is to understand the term-by-term relation of the Taylor expansion of MGF and the moments of the RV, which is highlighted here.


MRPT SLAM MRPT::slam::CMetricMapBuilderICP warning Pose Extrapolation failed

Question: I am using MRPT library's Map Builder ICP to implement a 2D slam on C++ by using Sick LMS151 to get CObservation2DRangeScan.
Whenever I am providing the 2D range scan to the map builder, it generates a warning that the Pose Extrapolation has failed. How do I know where the fault is in my codes?
<code>mrpt::slam::CMetricMapBuilderICP mapBuilder;

double RANGE_MAX = 20.0;
double RANGE_MIN = 0.05;

py::list processObservation(double timestamp, py::list scanRanges, py::tuple pose) {
    /* Takes observation and pose and returns the pose that is predicted by SLAM */
    mrpt::obs::CObservation2DRangeScan *rangescan = new mrpt::obs::CObservation2DRangeScan();
    //Set Intensities to false, as our lidar does not send it
    rangescan->setScanHasIntensity(false);
    //Set Tolerance of Scan to +- 0.8radians in pitch and roll
    rangescan->isPlanarScan(0.08);
    rangescan->timestamp = mrpt::system::time_tToTimestamp(timestamp);
    rangescan->aperture = M_PI*1.5;
    rangescan->maxRange = RANGE_MAX;
    mrpt::poses::CPose3D Pose;
    //Sensor Pose for Observation
    Pose.setFromValues(pose[0].cast<double>()+base_to_lidar,pose[1].cast<double>(),0,0,0,pose[2].cast<double>());
    rangescan->setSensorPose(Pose);

    std::vector <float>scanranges;
    std::vector <char>valid(scanranges.size());

    for(auto i: scanRanges) {
        float range = i.cast<float>();
        valid.push_back(range<=RANGE_MAX && range>=RANGE_MIN);
        scanranges.push_back(range);
    }

    rangescan->loadFromVectors(scanranges.size(), &scanranges[0], &valid[0]);

    mrpt::obs::CObservation2DRangeScan::Ptr obs_ptr(rangescan);

    try {
        mapBuilder.processObservation(obs_ptr);
    }
    catch(...) {
        std::cerr<<"Cannot Process Observation. The old pose will be returned\n";
    }

    mrpt::poses::CPose3DPDF::Ptr predicted_pose = mapBuilder.getCurrentPoseEstimation();

    mrpt::math::CMatrixDouble cov;
    mrpt::poses::CPose3D mean;
    predicted_pose->getCovarianceDynAndMean(cov, mean);

    std::vector <double> pos_vector;
    pos_vector.push_back(mean.x());
    pos_vector.push_back(mean.y());
    pos_vector.push_back(mean.yaw());
    pos_vector.insert(pos_vector.end(), cov.begin(), cov.end());
    py::list list_pose = py::cast(pos_vector);
    return list_pose;
}

</code>
The expected output was to be the 2D pose as predicted by the ICP-slam algorithm, which is not the case.
However, the output is as follows:
<code>[10:36:40.1430|WARN |CMetricMapBuilderICP] processObservation(): new pose extrapolation failed, using last pose as is.
Cannot Process Observation. The old pose will be returned
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
</code>
[x, y, yaw, covariances]
Answer: As long as this does not happen all the time, it is just a warning, not an error, so you should not worry too much.
It means that the initial pose used by ICP will be the last pose, without an additional refining step that consists in extrapolating (guessing) the robot pose at the timestamp of the LiDAR, using its velocity vector.


problems with memo.lines.add

Question: I am trying to make a chat application that will post a message into a memo in the form like this:
USERNAME-> Message

but it is posting to my memo like this:
USERNAME

Here is my code:
const
  cnMaxUserNameLen = 254;
var
  sUserName: string;
  dwUserNameLen: DWORD;
  text : string;
begin
  dwUserNameLen := cnMaxUserNameLen - 1;
  SetLength(sUserName, cnMaxUserNameLen);
  GetUserName(PChar(sUserName), dwUserNameLen);
  SetLength(sUserName, dwUserNameLen);

  text:= sUserName + '-> ' + edit1.Text;
  memo1.Lines.Add(text);

Any suggestions on how to fix it?
Comment: In addition to David's answer, you might want to consider only calling `GetUserName` the first time and saving the result, since it won't change during the run of this program. Then you save the overhead of repeated calls to `SetLength`, `GetUserName` and `SetLength` again; they're only called once.
Answer: The value returned in dwUserNameLen includes the null-terminator. And you are thus including it in the text. When the string is send to the Windows edit control behind the TMemo, the string is passed as a null-terminated string. And so the stray null from the user name terminates the data transfer.
Change the code like this:
SetLength(sUserName, dwUserNameLen-1);

You should also check the return value of GetUserName in case there is an error, but I will leave that detail to you.

problems with memo.lines.add


What happens when merging random variables in Dirichlet distribution?

Question: Imagine that
$$ X_1,\dots,X_k \sim \mathrm{Dirichlet}(\alpha_1,\dots,\alpha_k) $$
Since $x_i \in (0,1)$ for all $x_i$ and $\sum_{i=1}^k x_i = 1$, then $x_i$'s follow the first two axioms of probability and Dirichlet can be (and is) used as "distribution over distributions". Intuitively it should follow that
$$ X_1,\dots,X_{k-2},X_{k-1}+X_k \sim \mathrm{Dirichlet}(\alpha_1,\dots,\alpha_{k-2}, \alpha_{k-1}+\alpha_k) $$
since the properties of $x_i$'s would not change and the total "mass" of $\alpha_i$'s would not change.
But it's probability density function is
$$ f(x_1,\dots,x_k) \propto \prod_{i=1}^k x_i^{\alpha_i - 1}$$
and
$$
x_{k-1}^{\alpha_{k-1} - 1} \times x_k^{\alpha_k - 1} \ne
(x_{k-1} + x_k)^{\alpha_{k-1} + \alpha_k - 1}
$$
So merging of random variables in Dirichlet distribution does not seem lead to Dirichlet distribution over $k-1$ variables. What does it lead to?
Comment: Wouldn't the inequality have to be $x_{k-1}^{\alpha_{k-1}-1} \mathrm{x} x_k^{\alpha_k-1} \neq (x_{k-1}+x_k)^{\alpha_{k-1}+\alpha_k - 2}$?
Comment: Actually, I think the exponent should be only ${}-1$, as if it were plugging $\alpha_{k-1} + \alpha_k$ into the distribution as one parameter.
Comment: One more bit of nitpicking: You turned the exponent into $\alpha_{k-1}-\alpha_k - 1$, instead of $\alpha_{k-1}+\alpha_k - 1$.
Comment: @JarkoDubbeldam it seems I should have had a coffee before posting this question :)
Comment: @JarkoDubbeldam yes, it seems you're right, fixed it.
Comment: I am intrigued by this question, but I cannot reproduce the problem. That is to say, I tried simulating the data in R by summing two variables and drawing from the distribution with the sum of their $\alpha$ and they turned out to be similarly distributed. I can share the code if you want and would take this to chat, but I don't know how.
Answer: It is a Dirichlet distribution having the expected parameters.
To see this, note that the vector-valued random variable $\mathbf{X}=(X_1, X_2, \ldots, X_k)$ has the same distribution as the variable
$$\frac{1}{\sum_i^k Y_i}\left(Y_1, Y_2, \ldots, Y_k\right)$$
where $Y_i \sim \Gamma(\alpha_i)$ are independently Gamma distributed.  Write $Y_i^\prime=Y_i$ for $i=1, 2, \ldots, k-2$ and $Y_{k-1}^\prime = Y_{k-1}+Y_k$.  The sum of all the $Y_i$ equals the sum of all the $Y_i^\prime$ and the distribution of $Y_{k-1}^\prime=Y_{k-1}+Y_k$ is $\Gamma(\alpha_{k-1}+ \alpha_k)$.  Thus
$$X_{k-1} + X_k = \frac{1}{\sum_i^k Y_i} Y_{k-1} + \frac{1}{\sum_i^k Y_i} Y_{k} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime$$
and, for $i < k-1$,
$$X_i = \frac{1}{\sum_i^k Y_i} Y_{k-1} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime.$$
Therefore $\mathbf{X}^\prime=(X_1, X_2, \ldots, X_{k-2}, X_{k-1}+X_k)$ has the same distribution as
$$\frac{1}{\sum_i^{k-1} Y_i^\prime}\left(Y_1^\prime, Y_2^\prime, \ldots, Y_k^\prime\right).$$
This demonstrates that $\mathbf{X}^\prime$ has a Dirichlet$(\alpha_1, \alpha_2, \ldots, \alpha_{k-2}, \alpha_{k-1}+\alpha_k)$ distribution, QED.

The fault in the argument in the question lies in confusing the arithmetic sum of values $x_{k-1}+x_k$ with the sum of random variables $X_{k-1}+X_k$.  The latter is performed with a convolution, of course.
Comment: Thanks. While doing some search on it I actually found [your answer about sum of gamma distributions](http://stats.stackexchange.com/a/72486/35989) but somehow missed the very first sentence mentioning the facts in your answer above.
Answer: Like I mentioned in the comments, all I am trying suggests that what you are suggesting actually does work.
As you mentioned, intuitively it makes sense if this would work, if $X_i$ represents the posterior draw for some probability $p_i$ for event $i$ happening, you should indeed be able to sum multiple $X_i$ to get the probability of multiple events $i$, if there is no possibility of both events happening at the same time. Since this is a multinomial setting, this is not the case, so we're good.

So let's show my simulations:
<code>library('gtools')

K <- 10
alpha <- c(rpois(K, 50)) #randomly generated alphas, just cause
k <- 2 # the number of alphas we are summing together

sim <- rdirichlet(10000, alpha)
plot(density(rowSums(sim[, 1:k]))) # the density of the summed variable

lines(density(rdirichlet(10000, c(sum(alpha[1:k]), alpha[-(1:k)]))[,1]), col = 'blue')
# the density of the variable drawn from the Dirichlet distribution with summed alphas
</code>
Let's start with $\alpha = \{10, 10, 10\}$. Summing $\alpha_1$ and $\alpha_2$ should get us $Dir(2, \{20, 10\})$:

These marginal densities look pretty similar. According to wikipedia and this random lecture I found on the internet (through wikipedia), the marginal distribution of $X_i$ to the Dirichlet distribution is as follows:
$$X_i = Beta(\alpha_i, \sum_{k=1}^K\left[\alpha_k\right] - \alpha_i)$$
This relies on actually the same principle: summing all the $\alpha$ that are not $\alpha_i$ together, turning the corresponding multinomial to a binomial distributions with the outcomes $i$ and $not\textrm{-}i$. And indeed, if we fit the marginal distribution we would expect from the sum over the density in the previous picture, we see that it looks the same:

So theoretically, we should be able to take a Dirichlet distribution with a high $K$, sum all but one together and end up with a Beta distribution. Heck, let's try:

(99 times $\alpha \sim Pois(50)$ and 1 $\alpha = 1000$, summing together the random $\alpha\mathrm{s}$.)
To show that it also works for the joint densities, this is an example with $K=4$ and $\alpha = \{10,10,10,10\}$:

And this is with $K=3$ and $\alpha=\{20,10,10\}$:

$$\ddot{\smile}$$

So where does the confusion about $x_1^{\alpha_1-1}x_2^{\alpha_2-1}\neq (x_1 + x_2)^{\alpha_1+\alpha_2 -1 }$ come from?
Because when we sum $x_1$ and $x_2$ together, we don't just care about the density at $x_1$ and $x_2$, but for any combination of two $x$ that sums to $x_1+x_2$. I am not that strong in integration, so I'll not try and burn myself with that, but I really suggest reading this (page 3-4) for more information.
EDIT:
As @whuber correctly remarked, here is an example with low alphas, $K=4$, summing the first two $X_1$ and $X_2$:
Comment: This is a nice idea for testing the situation.  However, because the Dirichlet marginals are very close to Normal for large $\alpha_i$, choosing large values is not much of a test.  You ought to have carried it out with *small* values of the $\alpha_i$.  Values less than $1$ are especially interesting due to the extreme skewness of their marginals.
Comment: @whuber you're right. Your answer has a better explanation for why this does work (+1). I added an example for a lower alpha, for completeness.


How to search for a substring and a regex in a string?

Question: I have to verify if my string contains a substring followed by a regex.
Lets say the string looks like:  "Abcd 03:02:01"
How can i verify that the string contains the substring "Abcd" and the regex for "03:02:01".
I am using jscript in TC9.
I tried using find for the Substring and checked regex using Test.This involves checking the input string twice in If loops.
But is there any other way to do this?
Thanks
Comment: `/Abcd \d\d:\d\d:\d\d/` (this requires it to be `Abcd DIGITDIGIT:DIGITDIGIT:DIGITDIGIT`).
Comment: Yes, why don't just include Abcd in the regex?
Comment: Thanks for you response. But how can i  use it to search in the input string.The string Abcd keeps changing ,hence cannot really add it in regex
Comment: Currently i am checking the input string in two parts.  var check=aqString.Find(Inputstring,"Abcd",0)   var matches=regex.test(Inputstring)  if(check !=1){  if(matches)  //do something  }
Answer: If I understood well your question, you want to match the existence of Abcd 03:02:01in a string, based on that, you can use:
var s = "Abcd 03:02:01";
if (/^Abcd \d{2}:\d{2}:\d{2}$/.test(s)) {
    // Successful match
} else {
    // Match attempt failed
}

Answer: You can use variables in a regex expression.
var str = "Abcd 03:02:01";
var beginning = "Abcd";
var pattern= RegExp(beginning + " \\d\\d:\\d\\d\\:\\d\\d");
var result = pattern .test(str); //bool return


jQuery AJAX plugins with Flask

Question: A lot of jQuery plugins have AJAX support, for example the autocomplete jQuery UI plugin or the form validation plugin.
Most of the documentation about the AJAX support of the plugin is shown using PHP:
Autocomplete:
$(function() {
    $( "#birds" ).autocomplete({
        source: "search.php",
        minLength: 2,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.value + " aka " + ui.item.id :
                "Nothing selected, input was " + this.value );
        }
    });
});

Validation plugin:
$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"
    }
  }
});

My question is know how can this be done using the Flask Framework? And what type of object do I have to return?
Thanks in advance!
Answer: Configure the plugin to use one of your app's URLs, e.g. source: '/search', and define the view with this route:
@app.route('/search')
def search():
    # If it's a GET request, the data will be provided as request.args.  In case
    # of POST or PUT you'll have to use request.data or request.json (depends on
    # how the plugin is sending the data).
    query = request.args.get('query')
    # Perform the search here.
    results = ...
    # What to return here depends on what the plugin expects, consult the docs
    # to figure this out.  Most likely it'll be some JSON encoded data structure.
    return jsonify(results=results)

jQuery AJAX plugins with Flask


Condition based access to amazon lamda results?

Question: Wondering if it's possible to have a webapp upload a file (userid.input.json) to Amazon S3, which triggers a lambda function that reads the file, does some processing, and saves the result as another (userid.output.json).
However userid.output.json should not be immediately accessible to the web application.  The webapplication has to complete a Stripe payment and once the payment completes, the web application can access the (userid.output.json) file on amazon s3.
Before I ask how, I figured I'd first ask if this this scenario can be facilitated / architected on AWS?
Approach
Note that this is an update to the question based on more research.  It looks like Amazon Cognito will be the perfect tool for signing in users and tying their user credentials to an IAM role that can read and write to S3 buckets.
So once the user is signed in through Amazon Cognito and has the proper credentials then their files can be uploaded to an S3 bucket and processed by a lambda.  The result is then written to the same bucket.
Now earlier I suggested writing to a sealed bucket and having a Stripe webhook trigger moving the result from the sealed bucket to an accessible bucket.  But it seems this is necessary, per the indication in the answer provided by @Snickers3192.
Once the stripe payment completes the webapp can set a boolean that is used to control access to the output and that completes the cycle?
Part of the rational for having a hidden bucket was that someone might pull the credentials out of the browser and execute them in a different script.  I assume this is impossible (Famous last words :) ), but just in case I wrote a follow up question here.
In other words the credentials that are pulled into the client post signin with Amazon Cognito cannot be used to executed scripts outside of the application context?
Approach Part 2
Per my follow up questions it does not appear that relying on state within the webapp for making security decisions is good enough, as someone can probably figure out a way to get the token authentication token and manipulate the applications API directly using a client other than the core app.
So now I'm thinking about it like this:
1) Write the result to the sealed bucket (Processing Lambda)
2) Have the Stripe webhook update the users a transaction record in the users profile indicating payment paid = true (Stripe Lambda)
3) Create another lambda that has access rights to the sealed bucket but will return results only if paid=true.  (Access Result Lambda)
So since Stripe is tied to an IAM user that is allowed to update the Application user profile and set paid=true and the sealed bucket can only be accessed by lambda that first checks if paid=true before returning the result, I believe that should guarantee security.
If anyone has a simpler approach please let me know.
Comment: Why would you want to impose limitations on your own webapp?
Comment: The general idea is for the lambda to a service then once the computation completes the client in shown some of the results, but not all.  In order to get the complete set of results, checkout must first be performed, and then the client can retrieve the entire result set.
Comment: So restrict what the client has access to, not the webapp.
Answer: This really is more a question of where you want to put the security, which in AWS there are many options, in your application logic which could mean:

Lambda/Webapp
S3 policies
IAM roles/groups

These decisions are usually dictated by where your identity store is kept, and also if you want to keep the notion of AWS users VS. users of your app. My preference is to keep these two pools separate, in that security logic like this is kept in the webapp/lambda and AWS security only deals with what rights developers have to the environment as well as what rights applications themselves have.
This means the webapp can always access the input and output buckets, but it keeps a record in a database somewhere (or makes use of your payment system API) who has paid and who hasn't paid and uses that information to deny or grant access to users. IMO this is a more modular design, and it enables you to lock down your AWS account better and is more clear to developers where security is located. In addition if you do go with IAM/S3 it will be more difficult to run and debug locally.
EDIT: After all your comments and additional security concerns you may also want to consider emailing a short lived URL link to the processed file, so that a user needs both email access as well as knowing their credentials to the application. This will mean even if your access token is stolen at the browser level, without the email access a hacker still can't get the processed file. If you want to be EXTREME SECURITY CORE, have the link that not only is authentication required, but also MFA so that they need to enter in a code which is constantly refreshing as you should have setup for your AWS account when you login.
I'm by no means a security expert but just follow best practices and do your due diligence and you will meet security expectations.
Comment: Thanks - I updated the question a bit with some more research into Cognito and a follow up question.  I seems like once the stripe payment completes we can set a boolean within the application since it is aware that the payment completed, but my only hesitation on that is whether the credentials obtained from Cognito could somehow be fished out and used in a different context outside of the application.
Comment: great tip in the updated edit!  Also made an edit to the question right before I saw your edit.  I really like those ideas.  I'm not a security expert either, so trying not to get blown up on my first attempt at this :)


R + Shiny: qr code generation and download

Question: I want to create an app where the user can input a link or some text and download the corresponding QR code as a pdf.
I have already the fundamental building blocks, but I cannot glue them together.
For instance, for the pure QR code generation part
library(qrcode)

qr <- qr_code("https://www.wikipedia.org/")

pdf("qr_code.pdf")
plot(qr)
dev.off()
#> png
#>   2

Created on 2022-01-04 by the reprex package (v2.0.1)
for inputting text in Shiny
library(shiny)

ui <- fluidPage(
  textInput("caption", "Caption", "Your link/text here"),
  verbatimTextOutput("value")
)

server <- function(input, output) {
    output$value <- renderText({ input$caption })

}

shinyApp(ui, server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.

Shiny applications not supported in static R Markdown documents
Created on 2022-01-04 by the reprex package (v2.0.1)
and for saving a plot as a pdf in Shiny
library(shiny)
library(tidyverse)

df <- tibble(x=seq(10), y=seq(10))

ui <- fluidPage(
 sidebarLayout(
        sidebarPanel(

 downloadButton("save", "Download plot"),
 ),

mainPanel(
     plotOutput("tplot" )
)

)

)

server <- function(input, output) {

      tplot <- reactive({

plot(df$x, df$y)

      })

        output$tplot <- renderPlot({
tplot()
    })

# downloadHandler contains 2 arguments as functions, namely filename, content
  output$save <- downloadHandler(
    filename =  function() {
      paste("myplot.pdf")
    },
    # content is a function with argument file. content writes the plot to the device
    content = function(file) {

        pdf(file) # open the pdf device
      plot(x=df$x, y=df$y) # draw the plot
        dev.off()  # turn the device off

    }
)

}

shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.

Shiny applications not supported in static R Markdown documents
Created on 2022-01-04 by the reprex package (v2.0.1)
Can anyone help me put all of this together?
Thanks!
Answer: Here's how you can do this:
UI:
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(

      textInput("link", "Enter Link here", "www.google.com"),
      downloadButton("save", "Download QR")
    ),
    mainPanel(
      plotOutput("tplot" )
    )
  )
)

textInput takes arguments inputId, label, and value.

inputId is what you'll refer to the input inside your code.
label tells what will be written over the input field. It is something that user can see and identify what to enter in the field.
'value` is the default value that your input field will have. It can be blank.

Server:
server <- function(input, output) {
  tplot <- reactive({
    qr <- qr_code(input$link)
    plot(qr)

  })
  output$tplot <- renderPlot({
    tplot()
  })

  # downloadHandler contains 2 arguments as functions, namely filename, content
  output$save <- downloadHandler(
    filename =  function() {
      paste("myplot.pdf")
    },
    # content is a function with argument file. content writes the plot to the device
    content = function(file) {
      pdf(file) # open the pdf device
      plot(qr_code(input$link)) # draw the plot
      dev.off()  # turn the device off
    }
  )
}

Notice that I've used qr_code inside the reactive field so that you can use it further in output.
The shiny app will now, show the QR code as you keep typing inside the input field. Since it is reactive, it reacts to your input.
The download functionality also works as expected.
Comment: Happy New Year!


Grand Piano Cracked Soft Pedal, Possible Missing Parts for Soft and Sustain Pedals

Question: I have a 1912 Symphonic baby grand piano and I noticed two problems. This question is a two-parter:

I noticed at the top of the beam for the soft pedal, the wooden piece is cracked. We thought of zip-tying it to keep it together. Is this a good fix? If not, what would be a recommended fix at home? If there is none, would I have to seek help from a technician?
I also noticed that my sostenuto/middle pedal has a block on the bottom of it, but my sustain and soft pedals do not. I believe this block is responsible for keeping the pedals from wobbling and pressing so easily, as both pedals wobble and go down super easy, whereas the sostenuto/middle pedal is harder to press and doesn't wobble. I have a 3D printer and I can design a block for the other pedals (I understand the block felt wraps around the pedal to keep it firm, and lifts up with it). If I printed such a part, would it work well, or is this something I would have to have a technician look at?

If anyone is able to answer these questions, that would be greatly appreciated. Thanks for reading!

(link to full-size image (too big to upload): https://drive.google.com/file/d/19uo30dWLefv6ornwdnQwv1TWbmDI-cW4/view)

(link to full-size image (too big to upload): https://drive.google.com/open?id=1jPsbzV0mfBW1vjVkR8Uo_iwt1LBnhSVX)
Comment: Were it mine, I'd open up the split with a couple of screwdrivers, fill it with two-pack, and bind it - or use a couple of exhaust clamps, right size, till it's set. Making a new one isn't difficult, but matching the thread may well be. obviously loosen the threaded rod before applying adhesive.
Answer: To address the first question:
This is a simple mechanical issue.  Eventually the wooden piece might have to be replaced.  But wrapping will  possibly get a further 100 years use from it, and can't do any harm!   Or just leave it until your tuner/technician next visits.  It's only the soft pedal, probably not in constant use.  No great urgency.  Tale his advice.
Note that it MAY have split due to the screwed rod being screwed in too far, indicating excessive wear and play in another part of the mechanism.   I'm afraid old pianos don't mature into valuable heirlooms, they just wear out!
Comment: That will be one reason you're supposed to remove the lyre for transportation :\
Comment: The movers did adjust the rods which helped the entire pedal box stop shaking side to side while pressing on them. Maybe they went quickly and over-tightened it. I also remember one time pressing the pedal and hearing a crack. I just thought it was the piano being old. I won't be able to get a tuner or technician at my house due to the present circumstances, so I may just zip-tie it. Thank you!


postfix bounce configuration

Question: What I have is:

Windows server generating emails with own app and sending them to relay server (2) - this works fine
Relay server that sends emails received from (1) - CentOS - working fine

What I need is to additionally configure CentOS postfix to send bounce messages to Windows server (to work on them using own app on specified port).
I tried to add in /etc/postfix/transport line:
test.pl        bounced:[188.8.131.52]:29990

and run
postmap /etc/postfix/transport

but I have no idea what I should do more to make it work.
In maillog I have:
Mar  6 12:00:22 ubuntu postfix/qmgr[1633]: 9CBB260899: from=<root@ubuntu>, size=197, nrcpt=1 (queue active)
Mar  6 12:00:22 ubuntu postfix/qmgr[1633]: warning: connect to transport private/bounced: No such file or directory
Mar  6 12:00:22 ubuntu postfix/error[1744]: 9CBB260899: to=<email@example.com>, relay=none, delay=1890, delays=1890/0/0/0.01, dsn=4.3.0, status=deferred (mail transport unavailable)

Comment: Do you have `transport_maps = hash:/etc/postfix/transport` in your `main.conf`?  Have you restarted or reloaded postfix since making these changes?
Comment: Yes, I have this line in main.cf. Yes, I've runned postfix reload.
Answer: In transport, you normally only have 4 options. Local, Virtual, Relay or Default. If you're going to create another, you'll need to define what it does in the master.cf file. That's why you are getting file not found errors. You've told it to send it to bounced, but not created bounced.
You should probably have a look at this to start you off in the right direction.
Comment: That helped me a little, but didn't give the resolution. I'll put the answer myself.
Answer: What have I done to make it work:

Written a python script to send standard input through TCP to bounce server (fixed IP and port)
Added a line to postfix master.cf file, to send bounce emails to python script:
bounced unix - n n - - pipe user=bounce argv=/etc/postfix/mailpipe.py

Added a line to /etc/services and corresponding postfix services file:
bounced     23232/tcp           # bounce

Made transport file for postfix:
domain.com          bounced:[18.104.22.168]:23232

"Compiled" postmap transport file:
postmap /etc/postfix/transport

Made user bounce and added it to group postfix
Restarted by:
postfix reload

postfix bounce configuration


Ocultar texto entre chaves em javascript

Question: Como posso ocultar um texto que esteja entre chaves na minha div
Ex:

 Hello {World}

Comment: Sabe expressão regular? É uma das maneiras de se fazer isso...
Comment: Adicione uma tag span em volta ao texto que queres oculta inserindo um id ou class, e em seguida basta manipular o texto com JS. Exemplo:  Hello {World}
Comment: Seria tão facil assim, mas não posso editar essa div :(
Answer: Olá, tente com essa expressão regular:

let getDiv = document.querySelector('.teste').innerHTML;

let newTeste = getDiv.replace(/(\s\{.*?\})/, '');

document.querySelector('.teste').innerHTML = newTeste;

Hello {World} !

Answer: Usando Expressão Regular

var text = $("div").text();
$("div").html('').append(text.replace(/(\s\{.*?\})/, ''))

 Hello {World}

Comment: Oi Netinho, ótimo ajudou muito! e seu eu querer replicar pra varias divs?
Comment: @Josimara, se suas divs estiver do mesmo jeito da div da pergunta, você poderá usar o Jquery.each() para varre as divs. Fiz um exemplo, caso seja o que tu queres eu edito a resposta. Veja o exemplo executando aqui: https://jsfiddle.net/1p5m48wq/3/
Comment: Isso mesmo ótimo, valeuu!
Answer: Pega o texto da div, faz um replace usando expressão regular

var textoDaDiv = $("div").text();

$("div").text(textoDaDiv.replace(/ *\{[^)]*\} */g, ""));

 Hello {World}


How do I create a base content type and subtypes ("bundles")?

Question: I've been trying to figure out how to create a base content type and subtypes (bundles) in Drupal 8, but haven't been able to figure it out.
For example:
Base Content Type

Base Event (fields: event name, start/end dates and times, location, etc.)

Subtypes (Bundles)

Seminar
Conference

I looked into:

ECK (Entity Construction Kit) module: didn't seem to be working 100% in Drupal 8.  Using their example, I was able to create a 'Vehicle' ECK base type and 'Car' and 'Truck' ECK subtypes, but wasn't able to define any fields for the 'Vehicle' base type that would be shared between 'Car' and 'Truck'.  Also, the types appeared under 'ECK Types' in 'Admin > Structure', so not sure if they would be usable throughout Drupal in the same way that regular Content Types are used/referenced?
Paragraphs module: doesn't seem to the right module for this

It looks as though I have to do this through code somehow, but couldn't find any clear documentation that explains step-by-step how to do this in Drupal 8.
Any help would be greatly appreciated.  Thank you.
Comment: It should be called entity in Drupal. Base Content Type make me confused....
Answer: Creating entity is quite complicated, but it will be easier if you generate a base code with Drupal console command first.
drupal generate:entity:content [options]

Options

--module  The Module name.
--entity-class    The content entity class
--entity-name The content entity name
--base-path   The base-path for the content entity routes
--label   The label
--has-bundles Entity has bundles
--is-translatable Content entity translatable

I post some useful tutorial / documentation here:

https://www.acquia.com/resources/webinars/creating-custom-entities-drupal-8
https://www.drupal.org/developing/api/entity
Comment: Thanks again Jimmy!  I will check out those links that you kindly provided.
Comment: Sorry for the delay.  Personal issues and other work pulled me away from working on this one.  Your answer nicely describes how to create an entity, but how do you create sub-entities (like a subclass in Java), where the sub-entities share the common attributes of the parent (base) entity?  Thanks again!
Comment: Thanks for your prompt reply Jimmy.  I appreciate it.  Is there an article/link that explains the files that are generated and how to customize them?  Thanks again!
Comment: I have updated in answer. Drupal console only generate the scaffolding, its structure is quite similar to the example in documentation.
Comment: @kvjava1 Why not just create different bundles of the entity?


How do I play the synthesizer on my own?

Question: I recently bought the Novation Mininova and now I would like to practise playing it. In my mind a synthesizer like this is hard to just play around with, without any other instruments playing. I would like some hints about how I can practise on my own (just using the synth and some headphones)...
I would like to utilize the fact that this is a synth (and not a keyboard or electrical piano) because my goal is to use this item to produce some great electronic music! So I already know that the keys are not weighted and such things...
Thanks!
Comment: @Dave: but you wouldn't be able to play anything _over_ that bass loop, since the Mininova is monotimbral.
Comment: The Mininova specs indicate that it has an arpeggiator -- this should allow you to get at least a bass-loop going.
Answer: The first thing I'd do is find a loop station. This will allow you to record various parts, and layer them, using all the various new sounds available from your synth. Most have rudimentary drum tracks if you need them, and if you mess up with the next layer of sound, you can delete it without losing anything else.
Another option is to use some of the backing tracks so readily available on Youtube, etc. Often produced with guitarists in mind, but what's wrong with adding synth noises instead ?
Comment: Great suggestions. I'd add that the next step, eventually, will probably be to get some sort of sequencing software to build your own tracks with. I use Reason, which is also a full DAW and has many of its own synths you can control with your Minimova. Many other options like Ableton Live are also great. However, there are definitely much cheaper less full-featured options out there that might make for a better starting place.
Comment: I go with this suggestion. I have set up Ableton Live to act as a loop station, works quite well! Thanks!
Answer: In addition to loop suggestion, I'd also see if you can split the keys into different instruments.
This will allow you to play bass or percussion with one hand and melody with the other making for a full sounding performance without having to rely on recording layers.
In terms of backing tracks, check out the fantastic app iReal Pro
Comment: Interesting suggestion! Do you know if that is possible to do with just the Mininova?
Comment: Doesn't look like the synth supports this but you could easily set it up if you're playing through a DAW like Ableton.
Answer: The next step is to add some kind of recording system, so that you can play some drum loops and record multiple keyboard tracks over them. As great as your synthesizer is by itself, it has a MIDI port that can integrate with a recording system and open up multitrack recording and many more sounds. What you want to do is start with some drum loops as a drum track, play a bass part over it, then play a melody part over it, and you'll be making sophisticated music, not just playing one part alone. The key thing is you want to get 2 or 3 parts going at once, because then you get something that is bigger than the sum of its parts. And once you have some drums and bass going, you can jam for a long time and it is more educational than just playing alone as well.
If you have an iPhone or iPad, you can get an iRig MIDI interface for a fairly low price and hook your synthesizer into the iPhone or iPad and run the GarageBand software, which is either included on your iPhone or iPad, or is $5 extra. It's very easy to choose some drum loops in GarageBand and play your synthesizer over top and record multiple tracks and make real music, even with no experience or training. GarageBand has drum loops built-in, all kinds of synthesizer sounds, and also guitars and basses and strings and other instruments.
The reason I recommend GarageBand on iPad or iPhone as a starter solution is you can just play music with it right away, without doing any kind of technical stuff. And also it is the cheapest and smallest solution. And if you move to something Mac-based later — like Logic or Ableton Live — the iPad or iPhone solution is still useful as a mobile rig. And the songs you create in GarageBand on iOS can be opened up on a Mac running Logic or GarageBand for mixing and publishing, either by you or by someone you hand the songs off to for them to mix for you. So even though you're just getting started and may only be recording on an iPhone, there is no limit to what you can do.


onclick ScrollBottom dentro de "table"

Question: Quando clicar em contatar o formulário se expande, no entanto o usuário tem de rolar o scroll para vizualizar o mesmo. Preciso fazer com que ao clicar em contatar automaticamente seja enviado para o fim da "table".

Contatar

  <form ....>

Comment: para o fim da table? não entendi, seu código está incompleto e não dá para entender exatamente o que ocorre e o que deveria ser
Answer: Script para expandir
    function toggleTable() {
    var lTable = document.getElementById("collapseTable");
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}

Html
A utilização de âncoras permite a inserção de marcações em determinados pontos de um documento, possibilitando o deslocamento direto para estes pontos, através da criação de referências.
O recurso da criação de âncoras é bastante utilizado como índice de documentos, facilitando o deslocamento do leitor diretamente para um ponto desejado.
Um link pode ao mesmo tempo, referenciar e ser uma marcação. Essa prática é utilizada em páginas demasiadamente extensas possibilitando que o usuário se desloque do início para o fim do documento ou vice-versa. Como valor deste atributo devemos informar o nome da marcação, precedida do sinal #, caso esta marcação pertença à mesma página da referência.  href="#Bottom"
Destino: A marcação será o objeto alvo de uma referência.
Uma marcação de âncora é definida utilizando o atributo (name) que receberá como valor o nome pela qual esta marcação será referenciada.
Ao se clicar no link que faz referência a esta marcação, será dado um salto para este ponto da página onde foi inserida esta marcação.

Portanto coloque essa marcação no local exato que você desejar

Contatar

  <form>

  </form>

onclick ScrollBottom dentro de "table"


Who will qualify for semi-final?

Question: I wonder which team will qualify if following scenario happen?
Here is the scenario:

According to group A's point table after Bangladesh defeat New
  Zealand, if match between Australia and England washout in the rain
  who will qualify for the semi-final?

Here is the Group A's Point Table
Answer: It's a moot point now as England did beat Australia, but it was a very good question.
According to Sportskeeda if points are equal then the team with the most wins will go through before it goes to Run Rate, if that is equal then it goes to team seeding. Therefore Bangladesh would have qualifies as they had won a game whereas Australia had not.
Comment: @Kevin Anthony please note you need to correct your answer because as you quoted here yourself ***"if the points are equal, the team with more wins will go through"*** -- Bangladesh after defeating NZ had 3 points from a win and a no-result in the above table; and if England-Australia match had been washed out, Australia would've had 3 points (same as BD) but no win -- in which case Bangladesh would have qualified ahead of Australia because number of wins is the first tie-breaking rule and net run rate comes only next, for teams with same number of points and same number of wins; seeding last.
Comment: @Kevin Anthony It's good of you to update your answer, but you should also change the conclusion and say "*if the points are equal, the team with more wins will go through* -- since Bangladesh had a win and Australia had no wins, **Bangladesh would have qualified** ahead of Australia if both teams had finished on 3 points after England-Australia match had been washed out."
Comment: @ Kevin Anthony Does order matter that mention on the sportskeeda? if that matter than Bangladesh will qualify not Australia
Comment: Please read the link again:
Note:If the points are equal, the team with more wins will go through.If they are still equal, equation goes down to NRR comparison.If still equal, the team with higher seeding goes through

In your example, the points and NRR were equal, therefore the team with the higher seeding would go through, that is Australia, they were seeded ahead of Bangladesh in both the tournament seeding and the world seeding.
Comment: @ Kevin Anthony i got it.
Comment: Thank you @EnglishStudent I have updated my answer accordingly.
Comment: Good point. Updated again.

Who will qualify for semi-final?


How to set content inset for UITextView in ios

Question: I'm having a UITextView and set content inset as
[atextView setContentInset:UIEdgeInsetsMake(0, 10, 0, 0)];
This code working in iOS 6.1 and below, but nothing happens in iOS 7.0.
Comment: Is there a way to do this **IN STORYBOARD** ?!
Comment: did you tried updated answer?
Comment: Yes there is , check my solution below Joe Blow
Comment: @BencePattogato thanks for the update.
Answer: got answer:
[atextView  setTextContainerInset:UIEdgeInsetsMake(7, 7, 0, 0)];

fixed my problem.
And in Swift...
@IBOutlet var tv:UITextView!
override func awakeFromNib() {
    super.awakeFromNib()
    tv.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

UPDATE: another option to do that.
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[msgtext setLeftViewMode:UITextFieldViewModeAlways];
[msgtext setLeftView:spacerView];

Comment: replace `setTextContainerInset` instead of `setContentInset`. If you want to provide previous versions of ios, then check a condition reg., current device system version
Comment: hey @murugha23 , I need you help on how you solved textview setContentInset problem in IOS7
Comment: it would be good if you can provide me a sample code of your class,including keyboard and textview's various methods ,so i can I have clear idea
Comment: actually whats your problem ? is it setting improperly or completely not setting?
Comment: Yes I am posting question and posting link soon
Comment: Note that you should only use one or the other.  Using both together will result in undesirable additive behavior.
Comment: before using above code i will check condition for ios version
Comment: What I've discovered is that there is some odd (buggy) interaction between the setTextContainerInset UIEdgeInsets values. I was able to get the behavior I wanted as discussed here: http://stackoverflow.com/questions/19422578 I'd recommend (blindly) messing around with the 4 values to try and find an acceptable behavior.
Answer: An alternative and maybe a little more convenient way to do it, by subclassing the UITextField and add an @IBInspectable inset property.
import UIKit

class UITextfieldWithInset: UITextField {

    @IBInspectable
    var textfieldInset: CGPoint = CGPointMake(0, 0)

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

}

Comment: This is a nice answer for `UITextField`, but the question is about `UITextView`


Prove that the collection of sets where two finite measures agree in not necessarily a sigma-algebra.

Question: I was given this tricky question where states as follow:

Let $(X,M,\mu)$ be a measure space and let $\nu$ be another measure on $(X,M)$. Moreover, assume that $µ(X) = ν(X) < ∞$. Prove, by constructing a suitable conunterexample that
the family $\mathscr{A} = \{A ∈ M : \mu(A) = \nu(A)\} $ is not necessarily a σ-algebra.

One hint I was given: You can take $X = {a, b, c, d}$ and $µ$ the counting measure.
So far, instead of trying to find the counter-example, I think I proved that the collection has to be a sigma-algebra as follow:
If $A\in\mathscr{A}, \mu(A) = \nu(A)$, $\mu(A^c) =\mu(X)-\mu(A) = \nu(X)-\nu(A) = \nu(A^c)$, it means A is closed under complimet. Then, if $A,B \in \mathscr{A}, \mu(A\cup B) = \mu(A)+\mu(B)-\mu(A\cap B) = \nu(A)+\nu(B)-\nu(A\cap B) = \nu(A\cup B)$. Hence it is a algebra. Given the hint, the X is finite, so $\mathscr{A}$ is a sigma algebra.
Where did I miss? What can be a proper counter example?
Many Thanks!
Comment: @philbo_baggins well as stated in the question, $\mu(X)=\nu(X)$
Comment: How do you conclude that $\mu(A\cap B)=\nu(A\cap B)$ in the second part of your proof?
Comment: Hmmm, I guess you are right. I should not assume that. But I still have no clue in constructing a counter example.
Comment: Possibly stupid question: what happens if you take $\nu$ to be the trivial measure? Then they only agree on the empty set which is not a sigma algebra...
Answer: Suppose $$\begin{align}
\nu(\{a\})&=\frac12\\
\nu(\{b\})&=\frac32\\
\nu(\{c\})&=\frac32\\
\nu(\{d\})&=\frac12\\
\end{align}$$
and $\nu$ is extended to all of $\mathcal{P}(X)$ in the obvious manner.  Then $$\begin{align}
\nu(\{a,b\})&=2=\mu(\{a,b\})\\
\nu(\{a,c\})&=2=\mu(\{a,c\})\\
\nu(\{a,b\}\cap\{a,c\})&=\frac12\neq1=\mu(\{a,b\}\cap\{a,c\})
\end{align}$$


Prevent page creation for a published custom content type

Question: I have a Drupal 8 custom content type that is used in views only.  I would like to prevent this type from creating a web page for content that is published.
Answer: One easy method would be to add Rabbit Hole module and set it to "Page Not Found" when that content types view route is accessed.


How to read R program P-Value for Logistic Regression

Question:
I'm not used to that kind of p-value form as I don't know how to interpret it...
It's usually shown a p-value with stars (significant codes) on its sides
Can anyone help? How to read if the variable significant or not...?
Comment: Start by taking a look at `str(myModel)` and `str(summary(myModel))`.
Comment: Also look at this link : http://www.r-tutor.com/elementary-statistics/logistic-regression/significance-test-logistic-regression
Answer: It would show star if the p-value is small enough, <0.05 or <0.001. P-value here gives you likelihood of zero-value parameter. Statistically speaking, null hypothesis is parameter of variable being zero, and p-value is under this hypothesis, the probability of large z occurs. With such high p-value, we cannot reject this null hypothesis. So from the Z-value and P-value in your model, there are no variables with significant impact.
Comment: I see, thank you for your answer, I checked the variables again and turns out the _salstotalaktiva_ is the problem somehow


Convergence in measure preserves measurability

Question: I'm trying to prove that given a convergent in measure sequence of measurable function $\{f_n\}_n$ from a measure space $X$ to $\mathbb{C}$, if $f$ is (any of) its limit in measure, then $f$ is also measurable.
$\{f_n\}_n$ converges in measure to $f$ means that
$$\lim_n\mu(\{x\in X : \quad |f_n(x) - f(x)|>\epsilon\})=0$$
To me the main dificulty is that with this type of convergence I have no idea of how $f$ looks like at any point.
I'm not sure if this is supposed to be proved using the definition of measurable function or if there is some "smart trick" to use.  In the first case I take an open set $A\subset\mathbb{C}$ and I want to conclude $f^{-1}(A)$ is measurable. I think that maybe $f^{-1}(A)$  can be expressed in terms of the functions of the sequence but I don't see how.
Any hint or attept is welcome, I've asked this question 8 months ago when I was taking the course of measure theory but I didn't recieve any atention, now I'm preparing for the exam and I can't still solve it.
Comment: But the usual domain consists of equivalence classes modulo measure zero sets of measurable functions. And $\mu(\{x\in X : \quad |f_n(x) - f(x)|>\epsilon\})$ doesn'teven make sense unless we know that $\{x\in X : \quad |f_n(x) - f(x)|>\epsilon\}$ is a measurable set- which is no guaranteed unless $f$ is measurable.
Comment: This is a bit like asking to show that if a sequence of real numbers converges to $x$, then $x$ is a real number. What kind of objects did you define convergence in measure for if not measurable functions?
Comment: @MichaelGreinecker well I guess you can prove a sequence of real numbers don't converge to $i$
Comment: @MichaelGreinecker and as the answer below shows you can prove that the pointwise limit of a sequence of measurable functions is measurable, so I think the problem is not meaningless. In fact this was one exercise of a problem set of the course
Comment: Yes, you can prove that a sequence of reals does not converge to $i$when working in $\mathbb{C}$. What space are you working in? That the pointwise limit of measurable functions is measurable holds in the space of all functions, so there we do not have any issues.
Comment: @MichaelGreinecker well I guess it is assumed that we are working with the space of all function here as well
Comment: @MichaelGreinecker I understand, I suppose that problem is wrong then. Thanks fo clarifying
Answer: Because the sequence converges in measure, there is a subsequence that converges pointwise, $\mu$-a.e. That is, there is a subsequence $n(k)$ and a measurable set $N$ with $\mu(N)=0$ such that $\lim_k f_{n(k)}(x) =f(x)$ for all $x\in X\setminus N$. Define $g(x):=\limsup_k \mathfrak{R}(f_{n(k)}(x))$ and $h(x):=\limsup_k\mathfrak {I}(f_{n(k)}(x))$ ($\mathfrak{R}$ and $\mathfrak{I}$ denote real and imaginary parts). Then $L:=g+ih$ is a complex-valued measurable function such that $f=L$, $\mu$-a.e. This is the best you can say (in general) about the measurability of $f$; if $\mu$ is complete, then $f$ is measurable.


Convergence of Sequences

Question: I came across the following problems on convergence of sequences during the course of my self-study of real analysis:

Suppose $a_n \to a$. Define $$s_n = \frac{1}{n}\sum_{k=1}^{n} a_k$$ Prove that $s_n \to a$.

So $(a_n-a)$ is a null sequence. I want to show that $(s_n-a)$ is a null sequence. By a previous exercise, I know that $(x_n)$ is a null sequence $\implies$ $(y_n)$ is a null sequence where $y_{n} = (x_1+ \cdots+ x_n)/n$. So can we do something analogous to "adding $a$ to both sides" to get the desired result?

Show that the sequence $$a_n = \left(1- \frac{1}{2} \right) \left(1- \frac{1}{3} \right) \cdots \left(1- \frac{1}{n+1} \right)$$ is convergent.

So $a_1 = \frac{1}{2}$, $a_2 = \frac{1}{3}, \dots, a_n = \frac{1}{n+1}$. So I conjecture that $(a_n)$ is a null sequence. In other words, for each $\epsilon >0$, $|a_n| \leq \epsilon$ for all $n>N$. Let $\epsilon = \frac{1}{n}$. Choose $N = n+1$. Then the convergence follows?

Prove that the sequence $$a_n = \frac{1}{n+1}+ \frac{1}{n+2} + \dots + \frac{1}{n+n}$$ is convergent to a limit $\leq 1$.

So $a_{n} < a_{n+1}$ for all $n$. Then I need to show that it is bounded above by $1$. To show this should I consider $(1-a_n)$? All the terms are $<1$.
Comment: @amWhy: One reason is that Damien actually seems to have shown efforts to solve each problem he has asked so far, the questions are well formatted and he shows genuine interest in learning. Of course, by taking it slower (i.e. giving more thought rather than asking here) would only help Damien and he should consider asking only when he is really really stuck. I agree with that, if that is where you are coming from.
Comment: Damien: There's nothing wrong about asking questions; that's what this site is for.  But I become a little concerned when one user posts as many questions as you have in such short a period of time.  Whether self-study or homework...I don't know if its such a good idea to become too "dependent" on others for solutions.  To your credit, you do show work, speculate, etc., and we really appreciate that.  Sometimes struggling a little while longer with a problem before asking for help can go a long way...and helps you better clarify the concepts that are *really* problematic for you?
Comment: Yes, @Aryabhata...see my follow up post which I was writing before I saw your comment.  I did take note: to Damien's credit, he really has done a good job of showing work, speculating, engaging...etc.  To Damien: I understand; it can get really frustrating when you have no where to turn.  I'm not suggesting you stop posting questions; not at all.  But sometimes working through a set of exercises, first, helps you identify conceptual difficulties, and choosing one or two exemplary exercises to ask about may prevent you from asking about "A?", then having to post a follow up "A II?"
Comment: @amWhy: Yes. Should I write something else?
Comment: @amWhy: I have no teacher to check my work. Also the book doesnt have solutions. Hence I post some problems here.
Comment: @amWhy: I don't think self-learning is an appropriate tag. It is more appropriate for questions like "which books do I need?" etc. Almost every question can be tagged self-learning, if you use it that way!
Comment: @amWhy: No worries. In general, tagging with "meta" tags is usually discouraged, as they normally don't give an idea as to what subjects the question could fall into. There are discussions about this on meta (both math.meta and meta.stackoverflow).
Comment: Damien, do you realize you've posted 17 questions in the span over the last two days, each beginning with "I came across this problem...)? To others, note that in two day's time Damien has earned 365 points by asking 17 questions.  Others who post more elementary questions this frequently rarely receive this kind of positive reinforcement!
Comment: Damien: what text are you using?  Perhaps we can recommend a supplementary text which has more examples, and some solutions to its exercises which might help you work through your text; also, if you try googling using the text title, author's name, and, say "lecture notes", you will likely encounter course material, notes, practice tests, solutions, available at a real analysis course website for which the required text is the text you are working from.
Comment: @Damien: regarding your question about whether you should write something else as a "lead in" to your question.  The tags: , and  should be sufficient to inform us of those aspects; so you can pretty much start with your question, or perhaps add a preliminary comment about the section of the text your dealing with; that sort of detail helps us better tailor answers to where you're at, rather than telling you what you already know, or perhaps worse, providing a solution that involves material/theorems you haven't covered yet.
Comment: @amWhy: But I don't want to write in the imperative tone. Thus I start my questions like that.
Comment: @Aryabhata: sorry then, about the suggestion to use the self-learning tag.  @Damien: I guess the "self learning" tag isn't a great idea.  A brief mention that "I'm studying t analysis on my own ... and wondering about this problem/...and I'm stuck on this problem... and I don't understand this problem, (proof, exercise...)...I'm not sure where to start with...  Not a big deal, really...And I wouldn't worry too much, because your questions have been consistently well-stated, nicely formatted, etc.
Answer: You got the first one: If $x_n = a_n - a$  then $y_n = \frac{1}{n} \sum x_n = s_n - a$.
And the second one is a telescoping product and you got that right too.
For the third one: Hint: $\frac{1}{n+5} \lt \frac{1}{n+4}$
(Spoiler)

 We have $\frac{1}{n+k} \le \frac{1}{n+1}$ for $k \ge 1$ and thus $a_n \le \frac{n}{n+1} \lt 1$
Comment: @Damien: In the second problem, you noticed that $a_n=\frac{1}{n+1}$.  You could have stopped there.  The $\epsilon$-$N$ argument is trivial in this case, you have done it before.
Answer: For the last sequence, you could use the fact that
$$  \left(1+\frac{1}{n}\right)^n <e <\left(1+\frac{1}{n}\right)^{n+1}$$
Take logarithms of this inequality, and you'll get some nice telescopic bounds for $\frac{1}{n}$.
Comment: Do you mean $\frac{1}{n+1} \lt \log (n+1) - \log n \lt \frac{1}{n}$? One easy way to see that is to apply the mean value theorem... +1 though.
Comment: yes, that's it. Nice proof. Mine is just without using differentiability.
Comment: Yes, I guessed so :-)

Convergence of Sequences


How to get date ranges from an array of static dates in jquery or javascript

Question: I want to create date ranges from statics dates of array.
Here is an example of what I want:
var collDates = [
  "2017/01/01",
  "2017/01/02",
  "2017/01/03",
  "2017/01/04",
  "2017/01/08",
  "2017/01/09"
];

This should be transformed to:
[
  { start_date: "2017/01/01", end_date: "2017/01/04" },
  { start_date: "2017/01/08", end_date: "2017/01/09" }
];

Comment: Why don't you first show what you have tried so far? and what was the problem in that?
Comment: OP - please try something first, use your noggin. @SaurabhAgrawal yes, this seems to be the case.
Comment: so you want logic?
Comment: Please @SaurabhAgrawal  see the answer. I have resolved it.
Comment: I was going to do the same @PrabhdeepSingh
Answer: I have resolved the issue and here is an example code.
var staticDates = ["2017/01/01", "2017/01/02", "2017/01/03", "2017/01/04", "2017/01/08", "2017/01/09", "2017/01/10", "2017/01/11", "2017/01/12", "2017/01/13", "2017/01/14", "2017/01/15", "2017/01/16", "2017/01/17", "2017/01/18", "2017/01/19", "2017/01/20", "2017/01/21", "2017/01/22", "2017/01/23", "2017/01/24", "2017/01/25", "2017/01/26", "2017/01/27", "2017/01/28", "2017/01/29"];
var coll_dateIntervals = [];
var arr_temp = [];
var i = 1;
$.each(staticDates, function(index, moment_date){

//Day difference in # of days
 var diff = Math.abs(moment(staticDates[index]).diff(staticDates[index + 1], "days"));

   arr_temp.push(moment_date);

  //Check the date difference in days.
  if(diff <= 1 && diff !== undefined){

   //If the difference is 1, than add the date to the temporary array
   arr_temp.push(moment_date);

  //If it's more than 1 day, or the last object
 } else if (diff > 1 || diff === undefined){
   //Store the interval in an object
   console.log(arr_temp[arr_temp.length - 1]);
   var obj_dateInterval = { start_date: moment(arr_temp[0],  "YYYY/MM/DD").format('YYYY-MM-DD'), end_date:    moment(arr_temp[arr_temp.length - 1], "YYYY/MM/DD").format('YYYY-MM-DD')};
   coll_dateIntervals.push(obj_dateInterval);

   //Empty the array to start the new loop
   arr_temp = [];

 }

});
console.log(coll_dateIntervals);

Answer: Without a library, you just need a couple of simple functions for parsing and formatting. Doesn't do anything with invalid dates, but not difficult to add if required.
Step through the dates to create ranges. Begin with a start date, calculate the next day as current date plus one. When get a date that isn't the next day, end the range and start a new one. Also end when run out of dates.
For single dates, creates a single date range.

/* Parse date in format y/m/d
 ** @param {string} s - string to parse
 ** @returns {Date}
 */
function parseYMD(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1] - 1, b[2])
}

/* Collate array of date strings in y/m/d format to ranges
** @param {Array} dateArray - array of dates to parse in y/m/d format
** @returns {Array} ranges in format {start_date: yyyy/mm/dd, end_date: yyyy/mm/dd}
*/
function datesToRanges(dateArray) {

  return dateArray.reduce(function(acc, currentDate, index) {
    var d = parseYMD(currentDate);

    // Start of a processing, initialise accumulator
    if (!acc) {
      acc = {range: {start_date: currentDate}, ranges: []};

      // If not continuing range, end current range, store and start new
    } else if (acc.previousDate.setDate(acc.previousDate.getDate() + 1) != +d) {
      acc.range.end_date = acc.previousString;
      acc.ranges.push(acc.range);
      acc.range = {start_date: currentDate};
    }

    // Keep current values for next iteration
    acc.previousDate = d;
    acc.previousString = currentDate;

    // If at end of dates, end current range
    if (index == dateArray.length - 1) {
      acc.range.end_date = currentDate;
      acc.ranges.push(acc.range);
    }

    return acc;
  }, null).ranges;
}

// Tests
var collDates = [
  "2017/01/01", // Start 4 day range
  "2017/01/02",
  "2017/01/03",
  "2017/01/04", // End 4 day range
  "2017/01/06", // Zero day range
  "2017/01/08", // Start one day range
  "2017/01/09", // End one day range
  "2017/01/15", // Zero day range
];

console.log(datesToRanges(collDates));

PS
Can't see what this has to do with jQuery. There's no moment.js tag so I haven't used it. ;-)


How to do two way binding mat date picker inside mat table

Question: I am trying to show a few details of an employee on the mat table. The same table I made as editable. Except for datepicker every field is working .for date picker values are coming the same(last element in the array) since it is looping .please help on doing two-way binding in datepicker.
<ng-container matColumnDef="Exp">
    <mat-header-cell *matHeaderCellDef> Total Exp.(Yrs.) </mat-header-cell>
        <mat-cell contenteditable=true [textContent]="row.totalexp_yrs" (input)="row.totalexp_yrs=$event.target.textContent" *matCellDef="let row">
           {{row.totalexp_yrs}}
        </mat-cell>
</ng-container>

<ng-container matColumnDef="startdate">
    <mat-header-cell *matHeaderCellDef> Start Date </mat-header-cell>
    <mat-cell contenteditable=true *matCellDef="let row;let i=index">
        <input matInput [matDatepicker]="empfrom_i" name="empfrom_i" placeholder="Choose a date">{{row.emp_from}} </input>
        <mat-datepicker-toggle matSuffix [for]="empfrom_i"></mat-datepicker-toggle>
        <mat-datepicker #empfrom_i></mat-datepicker>
    </mat-cell>
</ng-container>

<ng-container matColumnDef="enddate">
    <mat-header-cell *matHeaderCellDef> End Date </mat-header-cell>
    <mat-cell contenteditable=true *matCellDef="let row">
        <input matInput [matDatepicker]="empto_i" name="empto" [(ngModel)]="row.emp_to" placeholder="Choose a date">
        <mat-datepicker-toggle matSuffix [for]="empto_i"></mat-datepicker-toggle>
        <mat-datepicker #empto_i></mat-datepicker>
        {{row.emp_to}}
    </mat-cell>
</ng-container>

Answer: I don't know how others do it but I did it with a combination of using the [value] attribute and the (dateInput) emitter.
<mat-cell contenteditable=true *matCellDef="let x">
     <input matInput [matDatepicker]="y" [value]="x.effectiveDate" name="empto" placeholder="Choose a date" (dateInput)="OnDateChange(x.fieldName, $event.value)">
     <mat-datepicker-toggle matSuffix [for]="y"></mat-datepicker-toggle>
     <mat-datepicker #y></mat-datepicker>
</mat-cell>

So in my example I have a collection of things and the 'key' in my case is the 'fieldName' so I know which row in a table got the updated date.  So the value even if I set to dual way with [(value)] will not work.  However I can use the event emitter of 'OnDateChange' and it can capture the event of the date change.  In this case I only want the 'value' of the emitting event.
OnDateChange(name: string, eventDate: Date) {
    const margin: MarginDiffernce = this.marginChanges[this.marginChanges.findIndex(x => x.fieldName === name)];
    margin.effectiveDate = eventDate;
}

In this example I have a collection of 'marginChanges' and just need to find when a date changes off of a key in the collection.  Then update the field.
Comment: could you pls open stackblitz ?


How to pass Block ID to a view?

Question: I have a Custom Block type called HomeBlocks. This bundle has a paragraphs field which allows multiple paragraphs.
I then place (using Layout Builder) an instance of this block type on my home page (a node type called Landing Page). In the layout of the block type I have a View which lists some of the paragraphs added to that specific block. The view lists my paragraphs but lists all the paragraphs of that type. If I add a contextual filter for Parent ID to the view and set as Fixed with the value being the BlockID of the block which I placed on my home page; then it filters to only the ones added to that block. Perfect.
The question is then; how to dynamically set this contextual filter?
I can think of 2 approaches:

Create a contextual filter plugin which passes the BlockID.
Pass BlockID from the Layout to the View.

I looked at option 2 a while back and found some work being done to allow arguments to be passed back from LB; but it was only supporting static values (as opposed to tokens).
Option 1 seems pretty simple and I set that up. To start with I simply pass back the static ID value and this works as expected.
The missing piece here is how to get a list of blocks (of a certain type) which are placed on a specific node?
I tried doing this with a view and I can get a list of BlockIds of all the blocks of this type; but can't see how to filter to the the one used on the specific node.
If there will ever be only 1 instance of this block used on the site; then I can use my existing view (that lists the only block of this type). I am not concerned about having multiple versions of this block on a single page; but I am trying to accommodate that there could be multiple pages with this block added.
Answer: So if I understand correctly, here's what you did:

Created some paragraph types.
Created a block type, with a paragraph field referencing the paragraph types in #1.
Created a view with a Block display of Paragraphs, with a contextual filter for Parent ID.
Added the view in #3 to a display of the block type in #2 via Layout Builder.

I'm assuming you have other things going on in the layout, otherwise, this would simply just be a View Block of Paragraphs or just added the paragraph field directly to the layout.

Created instances of the block type in #2 and added them on a page.

There's a couple of crucial steps that are easy to miss:

In step 3 (creating the view), create a relationship to the Block entity type. Then, instead of creating a contextual filter for the paragraph's Parent ID, create a contextual filter for the related Block's ID field.
In step 4 (adding view block to layout), when you add the View block onto the layout of the block, Layout Builder will ask you about the block title and its visibility. Right after that, and because of the previous changes to the view, it will now ask you what value to pass as the contextual filter value. There will be an option that represents the current block.

The end result should be a view inside the layout of a block filtering paragraphs by the ID of the block that contains it.
Comment: oddly enough i did that exact same case sensitive search across entire site and came up with nothing. But a little digging and guessing you have this patch in place: https://www.drupal.org/node/2799479. The one from #163 as I have the one from #158 which had not yet added this relationship. Thanks for the help.
Comment: awesome but perhaps patches required? Your description of what i have is correct. There is no relationship for "block entity type". I have relationship to the content using the fields added to that type. Using one of those i have arg for "Custom block ID".  After placing block i have contextual links for "control visibility" (patch), manage attrs (styling) and configure. In configure i see only title and override title . I can also enable to ask for args in the View under block settings; but this only takes a static id in layout.
Comment: I'll try setting this up on a vanilla D9 site. Perhaps you have patches, or i do not have latest (I am on D9.2) or patches i do have are interfering.
Comment: Tried a vanilla D9.2 site with only a couple patches to allow paragraphs to work at all with blocks in LB and i get same results as mentioned. I'll try updating to latest D9.3.
Comment: @liquidcms I just checked, the relationship is named like "By id: Custom block using ``". When you add the contextual filter, the field to filter is "Custom block ID". Then one minor detail I missed, when you configure the contextual filter, you check "Specify validation criteria", with validator set as "Block", and Single ID as argument. I think this last bit is what finally made the selection appear for me the last time I did this. And this was available since 9.1 without patches.
Comment: Sadly no relationship anywhere near that name. Perhaps a contrib module you have? I'll see I if i can track it down. Thanks.
Comment: @liquidcms A quick search for "By id" (match case and words) in the code reveals that this feature is from `entity_reference_revisions`, a dependency of `paragraphs`, which you should already have.
Comment: And even with that patch.. there is still no option to pass in current block id (or anything else to the view). I suspect another patch providing this part of the solution. For now I will go back to my solution of a custom argument plugin to pass in the "parent id". This does work but at the moment only grabs the first block of this type as I can't find the answer to my original question - "how to get a list of the blocks placed on a node?".

How to pass Block ID to a view?


PHP não pega os valores de preenchimento automático

Question: Bom dia,
Estou com um pequeno problema e espero que vocês possam me ajudar:
Busca_CEP

  <form method="get" action=".">
    Cep:
    <input name="cep" type="text" id="cep" value="" size="10" maxlength="9" />

    Rua:
    <input name="rua" type="text" id="rua" size="60" />

    Bairro:
    <input name="bairro" type="text" id="bairro" size="40" />

    Cidade:
    <input name="cidade" type="text" id="cidade" size="40" />

    Estado:
    <input name="uf" type="text" id="uf" size="2" />

    IBGE:
    <input name="ibge" type="text" id="ibge" size="8" />

  </form>

Estou utilizando esse código disponibilizado pelo site http://viacep.com.br/exemplo/jquery/,
ele está funcionando perfeitamente, porém quando eu tento dar um $_POST['uf'] ou em qualquer outro input que não seja cep num arquivo PHP, o campo aparece em branco para mim.
Vocês teriam alguma ideia para me ajudar?
Agradecido
Answer: O erro é devido ao método definido na tag .
Está como GET
<form method="get" action=".">

Troque para POST
<form method="post" action=".">

Comment: Já havia percebido tal fato e havia trocado para post, mas na hora da minha action, em que chamo o PHP, não consigo capturar o valor. Só consigo capturar os valores digitados. Agradeço pela ajuda.
Answer: Consegui resolver meu problema, como o preenchimento não estava chegando ao php fiz uma requisição com o curl dentro da minha página php ao endereço viacep.com.br/ws/"cep da requisição post aqui"/piped/ e consegui preencher o restante dos campos que estavam sem dados.


Performance of classic music

Question:
Possible Duplicate:
What does a conductor actually do?

I've heard different versions of Johann Strauss II: "Tales from the Vienna Woods", - they were guided by the different conductors?
So what is the difference of performing the same musical composition under the guidance of different conductors? I thought that notes makes it unambiguous.
Answer: The written notes actually miss a lot of information. If you would write down every little tempo change, every little accent, small and large scale rubato, microdynamics, articulations, etc. etc., the score would be impossible to read, and it would probably still miss something. What the composer writes down is just a skeleton of the piece and the most important details. The rest is filled in by the performer(s).
Now every performer has a different background on which they base their interpretation. Thus the piece will sound different when played by different people. This is a problem when many people play together since the piece would not sound logical. So, one job for the conductor is to unify the interpretations (or rather, probably force his own). Of course the conductors also have different backgrounds so the results will again be different, even if the orchestra doesn't change.
Comment: It's maybe beneficial to add that the conductors don't just show up the day of the performance even though the piece may be 300 years old. They make it extremely clear what they want from the orchestra at any point. Some of them are even notorious for their nitpicking.
Answer: One useful way of looking at it is that the orchestra is a single musical instrument, and the conductor is the player, playing the orchestra.
While the notes and durations are written on the sheets, the conductor indicates to the musicians the exact timing and articulations of important melodies. Sections that have long rests may receive a cue when they come back in.
Answer: Any piece can actually be performed in an incredibly wide variety of ways, and the controller of style, flow, feeling, pace etc is the conductor.
Generally the conductor is considered the most important person in an orchestra once the skill level of the individual musicians is high enough.

Performance of classic music


Question regarding logarithms

Question: Can you factor out the $m$ out of $\ln(c\cdot x^m)$  where $c$ is a constant?
Comment: **HINT**: Use this rule first: $\ln(ab)=\ln(a)+\ln(b)$
Comment: If you mean $\ln(cx^m)$, with $c>0$ and $x>0$, then you can write it as $\ln c+m\ln x$.
Answer:
We use the fact that $\ln(ab) = \ln a + \ln b$,
and the fact that $\ln(a^b) = b\ln a$

$$\ln(cx^m) = \ln(c) + \ln(x^m) = \ln(c) + m\ln(x)$$
Answer: If we have $y=ln(c.x^m)$, then $y=ln(c)+mln(x)$, so $\dfrac{y-ln(c)}{m}=ln(x)$ and so:
$$x=e^{\dfrac{y-ln(c)}{m}}$$
Answer: If $m\not = 0$, then we have
$$ \ln\left(cx^m\right) = \ln c + \ln x^m = \ln c + m\ln x = m\left(\frac1m\ln c + \ln x\right)$$

Question regarding logarithms