Why does this makefile not apply includes to all objects?

Question: This makefile does not behave as I expect. I want it to build .o files for each .c file in the current directory and subdirectories, and put them in a static library. However, it stops applying my $(INCS) after the first or second file. When it tries to build the second .o file, I don't see the -I paths in the build line and it complains about not finding a header file therein. Names have been genericized to simplify things. I'm using cygwin on Windows XP. I'm using an ARM cross compiler that is not under the cygwin tree. I based this makefile off an answer here.  There are only about two dozen .c files so the overhead of creating the dependency files this way isn't a big deal.
# Project specific options
CC = my-cross-gcc
INCS := -I. -Iinc
INCS += -Imy/inc/path

CFLAGS := -Wall -fPIC -static -cross-compiler-specific-options

OUT := bin/libmylib.a

MKDIR:=mkdir -p

### Generic C makefile items below:

# Add .d to Make's recognized suffixes.
SUFFIXES += .d

NODEPS:=clean
#Find all the C files in this directory, recursively
SOURCES:=$(shell find . -name "*.c")

#These are the dependency files
DEPFILES:=$(patsubst %.c,%.d,$(SOURCES))
OBJS:= $(patsubst %.c,%.o,$(SOURCES))

#Don't create dependencies when we're cleaning, for instance
ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))
    -include $(DEPFILES)
endif

#This is the rule for creating the dependency files
%.d: %.c
    $(CC) $(INCS) $(CFLAGS) -MM -MT '$(patsubst %.c, %.o,$(patsubst %.c,%.o,$<))' $< > $@

#This rule does the compilation
%.o: %.c %.d %.h
    $(CC) $(INCS) $(CFLAGS) -o $@ -c $<

# Now create a static library
all: $(OBJS)
    @$(MKDIR) bin
    ar rcsvq $(OUT) $(OBJS)

clean:
    rm -rf $(OBJS) $(OUT) $(DEPFILES)

Why does this makefile not apply $(INCS) when building subsequent .o files? How do I fix it? Output resembles this:
$ make all
my-cross-gcc -I. -Iinc -Imy/inc/path -<compiler options> -o firstfile.o -c firstfile.c
my-cross-gcc -I. -Iinc -Imy/inc/path -<compiler options> -o secondfile.o -c secondfile.c
my-cross-gcc -<compiler flags> -o thirdfile.o -c thirdfile.c
thirdfile.c:23:18: fatal error: myinc.h: No such file or directory
compilation terminated.

When I go to the command line and type in the gcc line to build thirdfile.o and use the -I paths, the object file is successfully built.
Comment: Please don't post fake examples. Simplify your makefile as much as possible, but then test to make sure it still exhibits the problem and post *real* output. For instance, your example output doesn't show creation of the .d files, but I don't know if that's because of a problem or because you edited it.
Comment: Not related to your question, but you don't seem to be including the dependency files anywhere, making them useless.
Comment: Is there by any chance a `firstfile.h` and a `secondfile.h` but no `thirdfile.h`?
Comment: interjay, I seem to have oversimplified the makefile I typed in. I'll add those lines back above.
Comment: I second @interjay's request: eliminate all the irrelevant stuff (dependencies, etc.), and boil your makefile down to the simplest version possible that still causes a problem.
Answer: There are two different mechanisms for handling header files at work here:
When the compiler is trying to build foo.o from foo.c, and in foo.c it encounters #include "foo.h", it goes looking for foo.h. The -I flags tell it where to look. If it is invoked without the flags it needs to find foo.h, it will complain and die.
When Make is trying to build foo.o, and considering which rule to use, it looks at the prerequisites. The prerequisites for your rule are foo.c foo.d foo.h, so it goes looking for those prerequisites. How is it to know where foo.h is? Note that the compiler flag inside one of its commands is of no use-- it won't make any deductions about that. If it can't find (and doesn't know how to make) a prerequisite, it will reject that rule and look for another one, such as the implicit %.o rule which knows nothing about your $(INCS) variable, and that leads you to the problem described above.
If this is the problem (and you can check by looking at the locations of the headers and doing some experiments) you have a couple of options:
A) You can use the implicit rule, and it's variables. Just add INCS to CFLAGS and you'll probably get the results you want. This tells the compiler what to do, but it still leaves Make in the dark about the dependencies, so you'll probably have to double-check that your dependency handling is correct.
B) You can tell Make where to find the header files:
vpath %.h inc my/inc/path

(You may notice that this is redundant with your INCS variable, and redundancy is bad-- you can eliminate this redundancy, but I urge you to get it working first.)
Comment: You nailed it. When it got to thirdfile, the makefile was invoking the implicit rule. I added INCS to CFLAGS and then did not need the explicit %.o rule any more, and it works beautifully. Thank you.
Answer: I'm going to guess that you have files named firstfile.h, secondfile.h, but no file named thirdfile.h?
I would then suppose that make cannot use the rule you gave it because and can't find or build the .h file. So it decides to use the default implicit rule instead.
Comment: These header files do indeed exist with the paths specified with the -I flag. The difference is that with thirdfile.c the gcc line omits the -I information. If I type in the line by hand, with the -I parts, the .o file builds just fine.
Answer: All I can imagine is that for "thirdfile" your depfile is somehow out-of-date or corrupt.  Perhaps it is bad enough that it's confusing make into calling some other default target.


Related Links Blender Plugin for Wordpress

Question: I have a problem with plugin Related Links Blender. It's the best of all related links plugins, really - it's simply edited and everything, but if you add some related links to post, you can't change it any more.
I mean:
In administration (below post editor) it's deleted, changed, everything what you want and what you clicked. But in post it's still showing just your first choice.
Here is the code of part about deleting:
<code>    function deleting_a_link() {
    $link_info = json_decode(stripslashes($_POST['link_info']), true);
    $nonce_check=check_ajax_referer('my_nonce','nonce',false);

    if ( ! current_user_can('edit_post',$link_info['post_id']) )  {
        echo json_encode(array('success'=>false,'response'=>'You don\'t have permission to make this change.'));
    } else if (!$nonce_check) {
        echo json_encode(array('success'=>false,'response'=>'Illegal connection.'));
    } else {
        $current_links=get_post_meta(intval($link_info['post_id']),'related_links_blender_links',true);

        if (is_array($current_links)) { //$current_links is false if empty
            unset($current_links[$link_info['link_no']]);
            update_post_meta(intval($link_info['post_id']),'related_links_blender_links',$current_links);
            $this->smush_the_links($link_info['post_id'],$current_links);
            echo json_encode(array('success'=>true,'link_no'=>$link_info['link_no']));
        } else {
            echo json_encode(array('success'=>false));
        }
    }
    die();
}
</code>
I can't see mistake. Do know anyone, what's wrong?
Answer: Once Deactivate your Plugin and after that Re-Active your Plugin it Solves Your Problem.
Comment: No, problem is still here. I tried it and now I'm trying it again - and nothing is changed. In database is still what I don't want. It's really bad for me.
Comment: Here is all of this code: http://stackoverflow.com/questions/18367761/related-links-blender-plugin-wp-doesnt-work-well


Authenticated user can access login/register routes in SF3

Question: I'm working on a project which uses FOSUser Bundle to manage my users but I'm encountering an issue.
In fact, an authenticated user still can access /login or / register routes.
Even though, my access_control looks like this:
<code>access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, role: ROLE_ADMIN }
</code>
What's wrong with that and how can I correct it ?
Answer: There's no restriction in place that would prevent authenticated users from accessing the login and register routes, so naturally they're able to access the said routes.
If however you wish to redirect already logged in users to another route please check this answer: FOSUserBundle - How to redirect already logged-in users when trying to access the login_path
Comment: So bad that FOSUser doesn't have this feature by default :/ But thank you !


Local JSON File not being recognized in React with fetch()

Question: I am having some trouble with my local JSON file not being recognized in React with fetch()
Code below:
import React, { useState, useEffect } from 'react';
import Datatable from "./datatable";
import Data from './data/data.json';
import './App.css';

require("es6-promise").polyfill();
require("isomorphic-fetch");

export default function App() {
  const [data, setData] = useState([])
  const [q, setQ] = useState("");
  const [searchColumns, setSearchColumns] = useState(["first_name", "last_name"]);

  useEffect(() => {
    fetch(Data)
    .then(response => response.json())
    .then(json => setData(json));
  }, []);

... some add'l code continues which I can add if helpful.

I'm literally just getting a blank page. I also tried fetching the actual path to the JSON file out of curiosity, but I received a webpack loader error.
Any insights would be helpful.
Comment: It depends on what you are trying to do, but you may not need fetch at all (fetch is for getting files from a web server, not local files). See: https://stackoverflow.com/questions/50007055/fetch-request-to-local-file-not-working
Answer: If you already have your data locally, you don't need to fetch it on remote server. Try is instead :
export default function App() {
  const [data, setData] = useState([])
  const [q, setQ] = useState("");
  const [searchColumns, setSearchColumns] = useState(["first_name", "last_name"]);

  useEffect(() => {
    // use your data here
    setData(Data);
    console.log('data', Data);
  });

  return(

yeah it works !

  )
}

Here is an working example : https://stackblitz.com/edit/react-can3gq?file=data.json


I want to Toast will show after multiple clicks

Question: I want to implant toast messages on click but it should show after multiple clicks like we do click on build number 7 times to enable developer option.
I mean toast message should show only after multiple clicks like when we click 3,4 or 5 times.
Toast should not show at first click.
Answer: Just do, initialize a variable i=0, increment the variable i++ on every click, check when the variable i == 5  then show toast message. If you want the app to remember the value just put in sharedpref file.
Below code for java(android)
here
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int i;
Button btn;

   @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        i = 0;
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(this);
        }

   @Override
    public void onClick(View v) {

        if (v == btn) {
          i++;
           if(i == 5)        //assuming you want click to be five times
            {
                Toast.makeText(MainActivity.this,
                        "your Message", Toast.LENGTH_LONG)
                        .show();
            }  else{
                 int j =5-i;
                 Toast.makeText(MainActivity.this,
                        "you are"+j+"steps away", Toast.LENGTH_LONG)
                        .show();
    }
 }
}
}

Comment: Can you please explain it me inside onclicklistner?
Comment: Thank you very much
Answer: Just keep track of the number of times your view has been clicked and print toast only when the value goes past a point,
class MainActivity : AppCompatActivity() {

    var clickCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        button.setOnClickListener {
            clickCount++
            if (clickCount > 2) {
                Toast.makeText(this, "Your text", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Comment: I'm  just checking if the click count has exceeded 2. Take a look at [that](https://www.tutorialspoint.com/java/java_basic_operators).


MX Records and A Records Updated But Email Addresses Can Still Send Email

Question: I have updated the MX Records, the A records, the Z records and the cname for a particular domain but the emails registered with the hosting provider can still send email. The changes have definitely propagated since the mail boxes can no longer receive email.
Why can these email addresses still send outgoing email? The test messages I've sent to my google account say "encryption:  name_of_hosting_provider.com did not encrypt this message".
I need these email addresses disabled, unable to send or receive email.
Comment: I don't understand your question. Please give us more details.
Comment: Short answer - You can't. It doesn't matter if you get that service closed down or not. If someone wants to send email as a domain they can. The most you can do is try and protect the domain with things like SPF records but even then if they aren't checked for at the other side it doesn't matter
Comment: Are you trying to stop someone sending email from an account by changing where the accounts are held?
Comment: Drifter104 Yes, you nailed it.
Comment: joeqwerty: The domain name and hosting account were registered separately and I no longer have control over the hosting account.

Since I was going to get new hosting for the domain anyway, I thought changing the MX records would disable the email addresses that were registered with the old hosting provider (because their MX records will be obsolete) but that did not happen. Now I am trying to figure out why this didn't happened and if there are any other methods I could use to avoid getting this domain blacklisted for spamming
Comment: Drifter104: If I create the same email account on another server (lets say email@example.com) with a different password, will firstname.lastname@example.com still be accessible from the old host using the old password?
Comment: MX records designate which hosts receive email for a given domain. They have nothing to do with which hosts can send email for a given domain. SPF records designate which hosts may send email for a given domain. Additionally, neither has anything to do with email accounts or mailboxes.
Comment: Yes - If you think about it why wouldn't it be able to?
Comment: @joeqwerty One would have thought that the receiving server would check if the MX Record matched the address of the originating server or not. Apparently they don't. Reminds me of how you could spoof emails without a password using telnet back in the day.

Thank you for your help. Any pointers on how to set up SPF? I haven't looked into the infrastructure of emails in a very long time.
Comment: @Drifter104 That does not seem to work either, I can use webmail on the old and new servers to access the same account with two different passwords and send out emails...that does not make a lot of sense tbh
Answer: I'm going to adress your question and some of your comments in this answer. You have a misunderstanding of how email works and how hosting providers work.
I have updated the MX Records, the A records, the Z records and the cname for a particular domain but the emails registered with the hosting provider can still send email
Of course they can. The MX and A records have nothing to do with what user accounts and email addresses I can set up on my email server. I can set up an email server for microsoft.com and create a user account and email address for firstname.lastname@example.com and use that to send email to my hearts content. Whether or not a receiving server accepts these emails is entirely up to them. If they check for and use SPF, DKIM and DMARC then chances are my email will be rejected. That doesn't negate the fact that I can set this up if I so choose. There's no universal database or authority that says "Hey, you can't set up an email server for Microsoft and send email from email@example.com!". Of course, I can't receive any email to my email@example.com email address... because I'm not really Bill Gates and I don't control the MX record for the microsoft.com domain and therefore can't designate my email server as the MX record for the microsoft.com domain. The MX record doesn't prevent me from setting up my email server for the microsoft.com domain, it only prevents me from receiving email for the microsoft.com domain (and in most cases will prevent my email from firstname.lastname@example.com from being accepted. It doesn't prevent me from sending it, but most email servers will reject it upon receiving it).
Since I was going to get new hosting for the domain anyway, I thought changing the MX records would disable the email addresses that were registered with the old hosting provider (because their MX records will be obsolete) but that did not happen
MX records have nothing to do with user accounts or mailboxes. MX records designate which host(s) receive email for a given domain. They're not used to validate user accounts or email addresses. Changing the MX record means that the old email server will no longer receive email for that domain but it doesn't mean that those user accounts and mailboxes are now magically disabled. They are completely internal to the hosting provider and unrelated to DNS. Email from those user accounts and email addresses can still be sent. It's up to the receiving server to decide whether to accept them or not (based on SPF, DKIM and DMARC).
One would have thought that the receiving server would check if the MX Record matched the address of the originating server or not. Apparently they don't
They're completely independent accounts hosted at two entirely different providers. The fact that they share the same usernames and email addresses is meaningless. Furthermore, MX records designate which host(s) receive email for a given domain while SPF records designate which host(s) send email for a given domain. These hosts are not always and not necessarily the same. So what if I had one host that receives email for my domain and another host that sends email for my domain? Imagine what would happen if your email server checked the MX record for my domain when I sent you an email and your server said "Hey, this server sending me email from email@example.com isn't the same server that receives email for firstname.lastname@example.com, I'm going to reject this email!"? My configuration is perfectly valid (an quite common) but your server rejects my email under the false pretense that the server that receives email for a domain (MX) should be the same server that sends email for a domain (SPF).
Comment: Thank you, that was extremely helpful.

I set up an SPF rule of type TXT with the value "v=spf1 a mx ip4:xx.xx.xx.xx -all", hopefully that will work.

I was confusing everything with everything else. Uptil 2007, you could telnet into Hotmail and Yahoo servers and send emails from any account with no verification whatsoever, Gmail was the only exception. By 2008, this had changed and no one let you spoof emails like that. I mistakenly thought webmail would behave in a similar fashion.

Google kept returning results on how to block emails which was pretty useless.
Answer: The MX record is telling the other email server the IP or hostname of the email server. Your client accounts need to be deleted/removed or disabled. Depending on your host provider your setting may vary. Just login to your cPanel and go into your mail accounts and either delete the account or change the user/account password. If you are hosting the mail server you can go in manually and disable etc. Hope this was of some use...
Comment: Sadly, the problem is that I don't have the password for the old hosting account and the person who does have the password is who has to be kept away from these accounts.
Comment: @SyedAliIrtazaKazmi You need to contact the Hosting company directly online. They should be able to help you further!
Comment: I did, they told me if I didn't have the password they couldn't/wouldn't do much.Initially kept telling me about spam hammer for some reason though
Comment: @SyedAliIrtazaKazmi Do you know if the Webmaster (The person) ever sent any of the information to anyone else?
Comment: They did not, at least not since they changed the password


Limit where they have taken out the absolute value

Question: Could someone explain step by step what they are doing here. I don´t understand how it is possible to take out the absolute value in this way! As fare as I can see we are dividing by the x, or sqrt(x^2). But then -x is equal to sqrt[-x^2], how does that get to become positive I would get negative 1 and I do not understand the absolute value. I guess it has something to do with the - infinity. But I do not see it.
Answer: If $x < 0$, then $|x|=-x$, so
$$\begin{align*}\sqrt{x^2+2x}-x&=\sqrt{x^2(1+(2/x))}-x\\
&=|x|\sqrt{1+(2/x)}+|x|\\
&=|x| \left ( \sqrt{1+(2/x)}+1 \right )\end{align*}$$
Answer: Notice
$$\sqrt{x^{2}+2x}=\sqrt{x^{2}(1+(2/x)}=|x|\sqrt{1+(2/x)}$$
and since we are taking limit as $x\rightarrow -\infty$ as we take this limit $-x=|x|$ thus we finally have
$$|x|\sqrt{1+(2/x)}+|x|=|x|\left(\sqrt{1+(2/x)}+1\right)$$


Email notification based on purchased item

Question: I am working on the magazine site using Ubercart. In this site individual magazines can be bought or subscribed to. When a new issue of a magazine which the customer has subscribed to is created, I need to send a notification to all the customers who have subscribed to that magazine.
Can I achieve this using the messaging and notification module? Is there any other way?
Answer: Have you tried rules? The trigger would be when new content is added, and the condition would be that the content type is appropriate. Not sure how you've stored the data connecting subscribers to their magazine, but that will be needed for the action. I don't think you'll be able to do this out of the box (specifically I'm not sure if you can send an email to multiple addresses using rules) - so you might need to write a custom action.
Comment: Thanks for replying. I m also thinking about using rules but I didn't find the conditions I need to use. Is there also a way to write custom conditions in rule. First of all I need to retrieve all customer who have bought the subscription of particular magazine. How Can I do that?
Comment: @Dipesh How have you currently set things up? How are you storing this data?
Comment: @Andy: Thanks.I didn't understand before. Now I think I need to write a custom action. For this site I set the product type as magazine. So the condition could be when the user creates a node of type magazine. I created the term for different magazine. So, in action First I need to retrieve the term associated with created node, then I need to find all the purchase of subscription and related customer from order. After that I need to send the email to the customer by retrieving its email. Can you guide little more about how should I write code? In drupal how to send mail writing code?
Comment: @Dipesh Sorry for the delay, been a bit busy. How do users subscribe to a magazine?
Comment: @Andy: Thanks for showing the way. I solved it by writing the sql query in the custom action and for mail I used the drupal_mail there. Now I m checking whether it works properly or not. Is drupal_mail good for sending a lot of email at a time? Since as the customer in the site increases no. of email to send also increases.
Comment: @Dipesh great! If you have a lot of emails to send it might be an idea to use [Queue Mail](http://drupal.org/project/queue_mail) or [MailQ](http://drupal.org/project/mailq)
Answer: You may try the Notify module. It allows users to subscribe and also unsubscribe (usefull feature) to your mass mailing. You can also setup multiple mass mailing. You can also mass mail everyone on your site.
Some more details about this module (from its project page):

The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.
Even if this feature is not configured for normal site users, it can be a useful feature for an administrator of a site to receive notification of new content submissions and comment posts.
The notifications are sent out in batches (digest style) at a frequency determined by the administrator. The administrator also decides what content type(s) to make available for notification subscriptions.
In the Drupal 7 version, ordinary users can turn notifications on and off, whether to receive just headlines, teasers, or complete nodes/comments, and what content types to subscribe to. (The Drupal 6 version only offer some of these options.)
Comment: Is there any way to add conditions on who gets the mail? I researched about messaging and notification module and I found that it doesn't support the conditions and notify module also seems doesn't support the conditions.
Answer: Maybe the Who Bought What|Ubercart module can be useful for your case.

This is for Ubercart. If you are using Ubercart to sell tickets or entries to an event or perhaps a race, it's very helpful to have a list, per item, of who bought what. For a competition, this will become an entry list. For a performance, this may become your will-call attendance list.

The Drupal 8 version has been created as separate project: Who Bought What (Ubercart).
Comment: Thanks for your reply. I checked that module earlier. It gives all the email list of the user how bought a particular product. which is what I wanted. but If I use this module I need to select the product and send email manually. Is there a way to do this automatically?
Answer: @Andy
I am using [Commerce Invoice/Reciept][1] module.
with a php code in main template file commerce-order-invoice-view.tpl.php something like below :

<code>   $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $order->commerce_line_items['und'][0]["line_item_id"]);
   $product_sku = $line_item_wrapper->commerce_product->sku->value();

    if($product_sku =="ONCE_OFF")
    {
      include 'commerce-order-invoice-once-off.php';
    }
    else
    {
      include 'commerce-order-invoice-recurring.php';
    }
</code>
After that you can create new files for emails.
FYI : $order object will be available in both files.
Hope this helps.
<code>  [1]: https://www.drupal.org/project/commerce_invoice_receipt
</code>


Doob's Martingale Decomposition -- Proving that the Martingale component is indeed a Martingale

Question: The Martingale-Part of the Doob decomposition for a stochastic process $(X_n)_n$ and filtration $(\mathcal F_n)_n$ is
$$M_n=X_0+\sum_{k=1}^n\bigl(X_k-\mathbb{E}[X_k\,|\,\mathcal{F}_{k-1}]\bigr)$$ (see e.g. here).
I want to prove that this is indeed a Martingale and suceeded by showing $$\mathbb E[M_n-M_{n-1}| \mathcal F_{n-1}] =0$$.
However, I failed to show  $\mathbb E[M_n| \mathcal F_{n-1}] =M_{n-1}$ and wanted to know where my mistake is.
My attempt is:
$$\mathbb E[M_n| \mathcal F_{n-1}] = X_0 + \sum_{k=1}^n(\mathbb E[X_k | \mathcal F_{n-1}] - \mathbb E\big[  \mathbb E[X_k | \mathcal F_{k-1}] | \mathcal F_{n-1}\big]) = (*).$$
Now, note that for $k<n$:
$$  \mathbb E\big[  \mathbb E[X_k | \mathcal F_{k-1}] | \mathcal F_{n-1}\big]) = \mathbb E[X_k | \mathcal F_{n-1}] = X_k,$$
and for $k=n$:
$$\mathbb E\big[  \mathbb E[X_k | \mathcal F_{k-1}] | \mathcal F_{n-1}\big]) = \mathbb E[X_n | \mathcal F_{n-1}],$$
so that all terms of the sum in $(*)$ are 0. Therefore, we get
$$(*) = X_0.$$
However, we should get $(*) = M_{n-1}$.
Where am I making my mistake?
Answer: When $k=n$, both terms become $X_n$, thus it is $X_n-X_n=0$. When $k<n$, it remains same. Therefore, you will have $M_{n-1}$.
Answer: To prove the martingale property (you also have to show $(\mathscr{F}_n)_{n \in \mathbb{N}_0}$-adaptedness and integrability) it is sufficient to notice that $M_n-M_{n-1}=X_n-E[X_n|\mathscr{F}_{n-1}]$ so that if you take the conditional expectation wrt $\mathscr{F}_{n-1}$ we get $E[M_n-M_{n-1}|\mathscr{F}_{n-1}]=0$ because $E[X_n|\mathscr{F}_{n-1}]$ is, of course, $\mathscr{F}_{n-1}$-measurable.
Your mistake lies into claiming $E[E[X_k|\mathscr{F}_{k-1}]|\mathscr{F}_{n-1}]\stackrel{(?)}{=}E[X_k|\mathscr{F}_{n-1}]$. This is not true: note that $k\leq n$ so all $E[X_k|\mathscr{F}_{k-1}]$ are $\mathscr{F}_{n-1}$-measurable. So the equality is in fact $E[E[X_k|\mathscr{F}_{k-1}]|\mathscr{F}_{n-1}]=E[X_k|\mathscr{F}_{k-1}]$. Also note that all $X_k,k\leq n-1$ are  $\mathscr{F}_{n-1}$-measurable, but $X_n$ is not. So we have
$$\begin{aligned}E[M_n|\mathscr{F}_{n-1}]&=X_0+(E[X_n|\mathscr{F}_{n-1}]-E[E[X_n|\mathscr{F}_{n-1}]|\mathscr{F}_{n-1}])+\sum_{k\leq n-1}(X_k-E[E[X_k|\mathscr{F}_{k-1}]|\mathscr{F}_{n-1}])=\\
&=X_0+0+\sum_{k\leq n-1}(X_k-E[X_k|\mathscr{F}_{k-1}])=\\
&=M_{n-1}\end{aligned}$$


Perform full-word substring replacement with pandas str.replace

Question: I have a sample data frame text column that contains strings including the word 'eng' and the word 'engine'.
ID  Text
1   eng is here
2   engine needs washing
3   eng is overheating

I want to replace the word 'eng' with the word 'engine'.  I use the code below:
df['Text'] = df['Text'].str.replace('eng', 'engine')

But this messes up my text in my second row.  The second row becomes
ID  Text
2   engineine needs washing

Is there a way to do the word replace so that it only replaces when the entire word says 'eng' only?
Answer: Wrap your keyword with the word boundary character \b:
df['Text'].str.replace(r'\beng\b', 'engine')

0           engine is here
1     engine needs washing
2    engine is overheating
Name: Text, dtype: object

If you have multiple keywords to replace in this manner, pass a dictionary to replace with the regex=True switch:
repl = {'eng' : 'engine'}
repl = {rf'\b{k}\b': v for k, v in repl.items()}

df['Text'].replace(repl, regex=True)

0           engine is here
1     engine needs washing
2    engine is overheating
Name: Text, dtype: object

Comment: Nice picture ! :-)
Comment: @W-B Thank you! New year, new profile :)
Comment: Good Pic with New Year Change! Bingo! Happy New Year.
Comment: @pygo tyvm, happy new year!
Comment: @W-B, which one :-)   coldspeed's pic ?
Answer: Adding a blank and fixed that problem from your own code
df['Text'].str.replace('eng ', 'engine ')
Out[736]:
0            engine is here
1      engine needs washing
2    engine is overheating
Name: Text, dtype: object

Update
df.Text.str.split(' ',expand=True).replace('eng','engine').fillna('').apply(' '.join,1)
Out[752]:
0           engine is here
1     engine needs washing
2    engine is overheating
dtype: object

Comment: Hmm, this will still match '`blaheng `', when it should match just `'eng'`.
Comment: @coldspeed yep you are right , and update ...I thought I should delete , but since many people already saw my fault I would like to correct it .
Comment: @pygo check the update
Comment: This must include word boundaries to match exact string.
Comment: and fail to match cases where the string ends with eng. its not a bad solution by any means if you know the edge cases, but it is not a very robust one.
Comment: @ParitoshSingh check the update and thank you for point it out
Comment: @W-B, thnx , Happy New year !
Comment: @pygo you too :> happy new year
Answer: You could try regular expressions like so:
import re
df['Text'] = df['Text'].map(lambda x: re.sub(r'\beng\b', 'engine', x))

The \b Tags in this given regular expression match "wordboundaries" so 'eng' will be forced to be surrounded by spaces for example.


Continuity of function with "internal" functions

Question: Suppose we have some $h:\mathbb{R}\to\mathbb{R}^2$ where $h(x)=(f(x),g(x))$ where $f,g:\mathbb{R}\to\mathbb{R}$. $h$ is continuous $\iff f,g$ are continuous. I'm not sure exactly what these sorts of functions are called, as they're not exactly multivariable functions.
I've been trying to prove this with the epsilon-delta method but it's a little tricky because I'm not sure exactly what epsilon is in the context of $\mathbb{R}^2$. Would this be an epsilon ball still, not a square? So $\epsilon = x^2+y^2$ for some $x,y$?
Moreover (this isn't the main question), I believe with an inductive argument we can prove that $\phi:\mathbb{R}\to\mathbb{R}^n$ where $\phi(x)=(\lambda_1(x),\dots,\lambda_n(x))$ and each $\lambda_i(x):\mathbb{R}\to\mathbb{R}$, $\phi$ is continuous $\iff$ each $\lambda_i$ is continuous.
Would appreciate any pointers in the right direction.
Best,
Adam
Answer: $f$ and $g$ are often called coordinate functions. $h$ is then called a curve.
Continuity for $h$ in some $x \in \mathbb{R}$ means that for every $\varepsilon > 0$ there is some $\delta > 0$ such that if $y \in \mathbb{R}$ and $\lvert x -y \rvert < \delta$ then $\lVert h(x) - h(y) \rVert := \sqrt{(f(x) - f(y))^2 + (g(x) - g(y))^2} < \varepsilon$.
Now let $f$ and $g$ be continuous in $x$ and $\varepsilon > 0$. Choose $\delta > 0$ such that $\lvert y - x \rvert < \delta$ implies
$$
\lvert f(x) - f(y) \rvert < \frac{\varepsilon^2}{2} \text{ and } \lvert g(x) - g(y) \rvert < \frac{\varepsilon^2}{2}.
$$
(You will get a different $\delta$ from $f$ and $g$, just take their $\min$.)
Then
$$
\sqrt{(f(x) - f(y))^2 + (g(x) - g(y))^2} < \sqrt{\frac{\varepsilon^2}{2} + \frac{\varepsilon^2}{2} }= \varepsilon.
$$
If $h$ is continuous in $x$, then note that for $\lvert x - y \rvert < \delta$ we have
$$
\lvert g(x) - g(y) \rvert = \sqrt{\lvert g(x) - g(y) \rvert^2} < \sqrt{\lvert g(x) - g(y) \rvert^2 + \lvert f(x) - f(y) \rvert^2} < \varepsilon.
$$
The continuity of $f$ you prove the same way.


Problems with Xamarin Essentials

Question: Im now working on my third beginner program in xamarin forms and want to programm an accelerometer
We know that the API Xamarin Essentials is doing the job with the calculation and all but when i insert something like Accelerometer.IsMonitoring it doesnt know about the IsMonitoring even it has to know about it what im doing wrong here is an eventhandler i defined in the xaml data and it doesnt recognize IsMonitoring and Start and gives me the error: the type or namespace name 'Start' doesnt exist in the namespace:Accelerometer
Here is the code:
private void ButtonStart_Clicked(object sender, EventArgs e)
    {
        if (Accelerometer.IsMonitoring)
            return;
        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        Accelerometer.Start(SensorSpeed.UI);
    }

 And this is the xaml code:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>

    </Grid.ColumnDefinitions>

    <Button Grid.Row="3" Grid.ColumnSpan="0" x:Name="ButtonStart" Text="Start" Clicked="ButtonStart_Clicked"/>
    <Button Grid.Row="3" Grid.ColumnSpan="1" x:Name="ButtonStop" Text="Stop" Clicked="ButtonStop_Clicked"/>

</Grid>

What im doing wrong or what is missing
Comment: as I already mentioned, if you will post your complete solution somewhere I can download it I will take a quick look
Comment: ok i will sent you a link to it
Comment: @Jason https://1drv.ms/u/s!AoZGfS0neKtLiRJJ21_xHKyebdIb?e=hSUPhb
Answer: because your project is named Accelerometer it cannot differentiate between your main App namespace and the Xamarin.Essentials Accelerometer class
You can fix this by renaming your project, or creating an alias for Xamarin Essentials, or fully qualifying the classname like this
private void ButtonStart_Clicked(object sender, EventArgs e)
    {
        if (Xamarin.Essentials.Accelerometer.IsMonitoring) return;

        Xamarin.Essentials.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        Xamarin.Essentials.Accelerometer.Start(SensorSpeed.UI);
    }

Problems with Xamarin Essentials


Como aplicar cor ao conteúdo de um elemento?

Question: Imaginando o cenário HTML:

    Cachorro

Leão

    Macaco
    Gaivota

Eu preciso aplicar um estilo específico para Macaco, sem afetar os elementos adjacentes ou precisar invalidar eles.
Atualmente, consigo o resultado desejado da seguinte forma:

div>* {
  color: initial;
}

div {
  color: red;
}

  Cachorro

Leão

  Macaco
  Gaivota

Mas não quero ter que reverter as alterações para elementos filhos de
 e sim aplicar exclusivamente em Macaco, sem ter que invalidar outros elementos no mesmo nível como a primeira regra do exemplo acima.
Como posso aplicar a cor vermelha exclusivamente ao Macaco, sem ter que colocar o mesmo dentro de um elemento e sem ter que selecionar elementos adjacentes, apenas utilizando CSS?
Comment: apenas para entender melhor, para quê precisa do texto? é que o CSS é usado para formatar o layout e não alterar, normalmente o conteúdo se altera com `javascript`, por isso fiquei curioso de entender.. aliás, por *"selecionar o texto do elemento"* você quer dizer, saber se tem o texto lá, ou para mudar o conteúdo?
Comment: Não existe, até tivemos documentado a implementação `:contains()`, ha um bom tempo atrás, mas não está mais disponível. Hoje o máximo que temos é o [`:empty`](https://developer.mozilla.org/en-US/docs/Web/CSS/:empty) e que não resolve.
Comment: Estou fugindo um pouco da pergunta, a qual já tem uma resposta bem satisfatória, mas por que haveria a necessidade de escrever _Macaco_ sem utilizar `tag`s?
Comment: @Heinrich, em documentos HTML produzido por autômatos, XLST, bibliotecas de conversão, programadores iniciantes ou testes empíricos, podem produzir conteúdo nas mais variadas formas. Então na criação de frameworks um parser de HTML embutido deve ser capaz de analisar qualquer entrada válida, mesmo que não seja trivial.
Comment: Se não entendi errado!!!... sim é possível, já vi algo assim no **front-end**  sem usar um elemento filho. acho que é chamado de **pseudo-classe**  ... se for isso é tbm  conhecida como **pseudo-elementos**
Comment: no css ficaria dessa forma `a::before {
    content: "Esse é um gato";

}`  ou   **a::before**       e no js teria essa sintaxe `document.querySelector("a").textContent `
Comment: Esse tal **pseudo-elementos**  é mais usados para adicionar algo antes ou depois do elemento que precisa e tbm usado para pegar um texto .
Answer: Não existe meio de selecionar textos com CSS, o máximo que temos (e que não atendem o caso) são os seletores:
::first-letter
Seleciona a primeira letra

.foobar::first-letter {
    font-size: 1.5rem;
    font-weight: bold;
    color: brown;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sagittis, odio non efficitur tristique, ipsum tortor semper urna, vel ultricies ipsum leo sit amet risus.

Curabitur finibus sagittis sapien nec tempus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi ultrices elit ac velit pellentesque egestas.

::first-line
Seleciona a primeira linha, se o texto tiver quebra automática o estilo só será aplicado até antes do texto quebrar

.foobar::first-line {
    font-size: 1.5rem;
    font-weight: bold;
    color: brown;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sagittis, odio non efficitur tristique, ipsum tortor semper urna, vel ultricies ipsum leo sit amet risus.

Curabitur finibus sagittis sapien nec tempus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi ultrices elit ac velit pellentesque egestas.

Então para concluir, até o momento nem sugestão de implementação para tal existe, o melhor mesmo é simplesmente criar um elemento inline (como span) com class ou id (depende do caso) e aplicar o estilo aonde desejar, simplesmente assim:

  Cachorro

Leão

  Macaco
  Gaivota

E não precisa de JavaScript para isso nem nada exagerado, a não ser que seja algo muito dinâmico mesmo, porque se for o caso, ai você poderia até aplicar um ... antes mesmo da página ser baixada, ou seja, no "back-end", mas isso seria um pouco mais além.
Answer: Creio que o que vc deseja é fazer isso

let element = document.getElementById("myElement");
let text = element.textContent;
console.log(text);
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

ESSE TEXTO

Comment: Com JS ok, mas acho que a pergunta é voltada somente para o CSS, sobre como atingir o resultado apenas com codigo CSS. Inclusive seu HTML nem representa a mesma ideia da pergunta.
Comment: Olá Christian. Boas-vindas ao site. As tags na pergunta indicam as tecnologias relevantes ao problema -> https://i.stack.imgur.com/L81FF.png, o autor da pergunta está solicitando [tag:css] e [tag:html5] -- Segue as instruções da Central De Ajuda do Stack Overflow em Português: https://pt.stackoverflow.com/help/tagging. *Agradecemos a compreensão*.
Comment: Ata, agora entendi, mas a sua pergunta está incompleta, você pede ajuda para acessar o texto mas não especifica se tem que ser obrigatoriamente com css
De qualquer forma, não tem como não. Para isso vc realmente tem que usar uma tag html.
Comment: Ata de boas então, peço perdão, não me atentei a isso.


React Interweave Library causing hydration error on runtime

Question: I am creating a react component where I am fetching some data from the array of strings where there is some html code. I am using interweave library when looping through that array to render my table. The problem is the it renders correctly but I am getting hydration error on runtime. How to fix it?
export const RewardsFromInvestments = [

  "The Net  Yield Farming  Rewards directly attributable to the Token Holder shall be calculated and distributed to the Token Holder's Account in Periodic Distributions using the following formula:",
  `For the purposes of clarity, the Yield Farming Rewards will comprise of profit generated from trading fees income and native token rewards income. The distribution of the Yield Farming Rewards are as follows:

      Trading Fee Income Allocated to Token Holders
      100%

      Trading Fee Income Allocated to ZaynFi
      0%

      Native Token Rewards Allocated to Token Holders
      80%

      Native Token Rewards Allocated to ZaynFi
      20%

`,

The code for creating the list dynamically:
 <ol
 className={`list-[lower-roman] font-normal text-[16px]  pl-5 outside ${styles.listTerms}`}
   >
 {RewardsFromInvestments.map((i) => (

{<Markup content={i} />}

   ))}

Error during runtime
Web output for the table
This runtime error goes away whenever I comment this line. It makes it clear that this is causing the problem. Please help me fix it.

{<Markup content={i} />}

Answer:
Interweave utilizes the DOM to parse and validate HTML, and as such, requires a polyfill for server-side rendering to work correctly. There are 2 options to solve this.

interweave-ssr - https://interweave.dev/docs/ssr/#interweave
JSDOM - https://interweave.dev/docs/ssr/#interweave


3-rd decimal digit has disappeared in the output

Question: I created a field, attached it to the entity: coefficient_to_second_side. Type in the  database is decimal(10,3). Then I added a value: 1.001. When I select this field manually from the database, the value is correct. In the edit form it is correct:

But when I output the field on the entity page:
field_attach_prepare_view('event', array($entity->id => $entity), 'full');
entity_prepare_view('event', array($entity->id => $entity));
$entity->content += field_attach_view('event', $entity, 'full');

I get this:
Coefficient to second side:
1.00

The third digit has disappeared. How to fix?
Answer: If you type of "Coefficient" is float, you can change scale in display options for your Content Type. (admin/structure/types/YOUR_CT/manage/display). By default it's 2.
Comment: I found it here: `/admin/structure/event/manage/display`. Thank you, sir :)


Separar JSX do componente - React Native

Question: Existe alguma forma de, no React Native, colocar todo o JSX em um arquivo separado sem ter risco de diminuir a performance do App?
Tipo o Angular que tem um arquivo para o HTML, outro para o CSS e outro pro Typescript.
Edit 1:
Esqueci de mencionar mas, o que eu quero é separar todo o JSX e poder utilizar o state, props e funções do componente mesmo assim.
Answer: Não faz muito sentido fazer isso pois o Angular tem uma estrutura de MVC e o react não, o maximo que você pode fazer é criar dois componentes. Um que apenas renderiza components apartir das props e outro que cuida do state e funções
Exemplo em React
Exemplo em React Native
function SomenteJSX(props) {
  return <View>{props.oQueVoceQuiser}</View>;
}

class SomenteStateProps extends React.Component {
  state = {
    oQueVoceQuiser: "hey"
  };

  algumaFuncao = () => console.log("oi");

  render() {
    return (
      <SomenteJSX
        algumaFuncao={this.state.algumaFuncao}
        oQueVoceQuiser={this.state.oQueVoceQuiser}
      />
    );
  }
}

Mas assim ainda vai ser dificil remover todo o JSX do componente.
Tentar transformar react em uma estrutura MVC não é recomendável. O que eu aconselho é sempre separar o arquivo css do componente.
Comment: Hmm, entendi. Vlw ae brother.


Redmine installation error

Question: I installed Redmine on my server.
When I run:
bundle install --without development test

I see an error, because I don't have PostgreSQL (and I don't use it). I want to run the bundler with parameter --without-pg, but I see this error:
root@localhost:/home/work/dev.redmine# bundle install --without-pg development test
Unknown switches '--without-pg'

Bundler version is
Bundler version 1.1.5
How can I fix this problem?
Comment: I found solution. I remove pg lib from Gemfile and everything is all right. Found answer here http://www.redmine.org/boards/1/topics/30204
Answer: I think that your command was wrong. You just need to remove the char - between without and pg
bundle install --without pg development test

Regards
Paul
Comment: Does not work with chilliproject (redmine fork) and bundler 1.1.4. Removing from gemfile is required.

Redmine installation error


Please explain these SQL statements

Question: Please explain me the below example
SELECT GROUP_CONCAT(COLUMN_NAME)
FROM information_schema.`COLUMNS` C
WHERE table_name = 'table_name'
  AND COLUMN_NAME =('columns_name') INTO @COLUMNS;

SET @table = 'table_name';

SET @s = CONCAT('SELECT ',@columns,' FROM ', @table);

PREPARE stmt FROM @s;

Comment: Above statements in the question meant, just selecting all the columns of a given table
Comment: generating dynamic sql with all the columns from the given sql
Comment: "_Explain me the below_"  Your question is broad can you clarify what you want?
Comment: have you read the manual for each statement you don't understand? Please clarify what exactly is puzzling you.
Answer: This pattern is all about creating dynamic (prepared in MySQL parlance) queries based on the names of columns in a particular table. INFORMATION_SCHEMA is a built-in database with read-only tables describing all the tables in all databases on the MySQL server.
The first query in your sequence retrieves a text string in the local variable @COLUMNS with a value like
      id,name,value,description

for a table named table_name with those four columns.
The third one retrieves a string in the local variable @s with a value containing a query like
      SELECT id,name,value,description FROM table_name

The fourth one, PREPARE, gets ready to do EXECUTE stmt, which runs the query. You can read about PREPARE and EXECUTE here.
The whole sequence of queries in your question does almost exactly the same thing as SELECT * FROM table_name.
There's a defect in your first query. You should add AND TABLE_SCHEMA = DATABASE() to its WHERE clause. Otherwise, you may pick up columns from tables named table_name in multiple databases.
Comment: I have another question..

i hav source table having 5 columns. i need to create mapping table for source . when we are trying to insert source data to another table with the help of mappng table.We need to write a dynamic query to insert the data to another table.

some times column increases to 7 in source table. we have to change only in the mapping table not in the sql query.. query should dynamically picks the data from source table and load it to target table.

Please explain these SQL statements


Display action sheet on OnBackButtonPressed

Question: I am creating xamarin form using PCL. I want to provide a feature when user press backbutton from mobile device hardware then i want to DispalyActionSheet. Is any option that i can do that. Below is my sample code.
    protected override bool OnBackButtonPressed()
    {
        base.OnBackButtonPressed();

        //new thread
        Device.BeginInvokeOnMainThread(async () =>
        {
              var action = await DisplayActionSheet("ActionSheet: Send to?", "Cancel", null, "Facebook", "twitter", "Instagram");

      //  Here i want to get  action  result for next step
        });

        return true; //
    }

Code update as per suggested by Martin Zikmund  : Feeling difficulty on redirect on different page after code execution
 protected override bool OnBackButtonPressed()
        {
            bool returnvalue = true;

            Device.BeginInvokeOnMainThread(async () =>
            {
              vawait DisplayActionSheet("ActionSheet: Send to?", "null", null, "Facebook", "twitter", "Instagram");
                    switch (action)
                    {
                        case "Facebook":
                         // My code
                CallPage();  Here i want to redirect on different page
               break;
                    }
            });
      }

 public async void CallPage()
    {
        try
        {
            await RetrunToPreviousPage();
        }
        catch (Exception ex)
        {

            //throw;
        }
    }

  public async Task<dynamic> RetrunToPreviousPage()
    {

            Navigation.InsertPageBefore(new InboundOrderList(), this);
            await Navigation.PopAsync();

        return true;
    }

Answer: If you want to handle the back button yourself, you will need to remove the call to base.OnBackButtonPressed.
protected override bool OnBackButtonPressed()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
          var action = await DisplayActionSheet(
            "ActionSheet: Send to?", "Cancel", null, "Facebook", "twitter", "Instagram");

          //your logic
    });

    return true; //you handled the back button press
}

When you actually want to navigate back within your logic, you will have to pop the page manually of the stack:
await this.Navigation.PopAsync();

Update
You still have to return true at the end of OnBackButtonPressed to mark it as handled. Additionally, ReturnToPreviousPage does not need any return true; and the return type can be a simple Task:
protected override bool OnBackButtonPressed()
    {
        bool returnvalue = true;

        Device.BeginInvokeOnMainThread(async () =>
        {
          vawait DisplayActionSheet("ActionSheet: Send to?", "null", null, "Facebook", "twitter", "Instagram");
                switch (action)
                {
                    case "Facebook":
                     // My code
            CallPage();  Here i want to redirect on different page
           break;
                }
        });
      return true; // always return true
  }

  ...

  public async Task RetrunToPreviousPage()
  {
      Navigation.InsertPageBefore(new InboundOrderList(), this);
      await Navigation.PopAsync();
  }

Comment: getting issue to redirect on page after //your logic   i create a function CallPage(); public   async void CallPage()
        {  await RetrunToPreviousPage(); }  and in public async Task RetrunToPreviousPage()
        {
Navigation.InsertPageBefore(new UserManifestInboundOrder(), this);
await Navigation.PopAsync();
       return true;
        }
Comment: what i am doing mistake
Comment: Please update the original update with the new code so I can see what is called where :-)
Comment: I have updated my answer, if that does not solve the issue you are having, please describe the problem :-)
Comment: Where you are calling the function RetrunToPreviousPage()
Comment: I meant you should keep `CallPage` method as it is.
Comment: i understand. Thanks for your help


How to manage billing with WSO 2 AM (2.0.0)

Question: I would like to combine WSO2 AM and DAS with billing function.
I tried to set it by referring to the following site, but the article did not correspond to WSO2 APIM(2.0.0).
http://wso2.com/library/articles/2016/07/article-enabling-monetization-of-apis-with-wso2-api-manager/
http://www.rukspot.com/Publishing_APIM_1100_Runtime_Statistics_to_DAS.html
I want to publish WSO 2 APIM(2.0.0) runtime statistics to DAS.
But,WSO2 AM(2.0.0) does not have admin-dashboard like WSO2 AM(1.10.X).
・Should I lower the WSO2 AM version?
・Is there a procedure / article based on WSO 2 AM (2.0.0)?
・Do you have my point should be noted?
Thanks a lot.
Comment: information was missing, I supplement it.WSO2 DAS 3.1.0
Answer: From 2.0.0 onwards, it's called admin portal, and the URL is https://localhost:9443/admin. However, analytics configurations are removed from Admin Portal UI. So you have to use api-manager.xml file to configure analytics.
Refer this doc to configure analytics in 2.0.0.
Answer: Also, note that online service based on API Manager - WSO2 API Cloud - has API monetization and billing integration available out-of-box - just configure your billing plans and bank account and start collecting money: https://docs.wso2.com/display/APICloud/Enable+Monetization
Answer: There´s a guide on the same blog that you linked
http://www.rukspot.com/configure_wso2_das_for_apim_analytics.html
This is for configuring DAS. If you only care about analytics data for apim I would recommend the new wso2am-analytics instead of the DAS. It's made specially for the apim and much easier to configure. See the guide that Bhatiya provided on how to configure wso2am-analytics.
Answer: The article is for APIM 1.10.0 and DAS 3.0.x. If you want to try this with APIM 2.0.0 you need to used the sample billing engine in this repo. checkout the tag am-2.0 and check.


Is this correct to assign value to string out of its allocated size in c++?

Question: char *str;
str = new char[1];
str[0]='1';
str[1]='2';
str[2]='>';
str[3]='\0';

This is what I want to do. Is it correct to assign values out of its allocated range.
Answer:
Is it correct to assign values out of its allocated range.

No. Doing so has undefined behaviour.
Answer: Two alternatives:
Appending to a string:
std::string s;
s += '1';
s += '2';
s += '>';
// s += '\0'; // not necessary as this is tracked for you

Using std::string's fill constructor if you want to specify a size:
std::string s(3, ' ');
s[0] = '1';
s[1] = '2';
s[2] = '>';


Does $ \int_{X}^{\infty} \int_{X}^{\infty} \min\left\{1, \frac{1}{|x_1 - x_2|}\right\} \frac{1}{(\max \{x_1, x_2\})^2} d x_1 d x_2 $ converge?

Question: Let $X>0$ be a fixed real positive number.
I am trying to figure out if the following integral converges or diverges.
$$
\int_{X}^{\infty} \int_{X}^{\infty} \min\left\{1, \frac{1}{|x_1 - x_2|}\right\}  \frac{1}{(\max \{x_1, x_2\})^2} d x_1 d x_2.
$$
Any input would be appreciated. Thank you!
Comment: Where does this integral come from?
Answer: The inner integral gives
$$
\int_X^\infty\dots\,\mathrm{d}x_1=
\begin{cases}
\frac{x_2 + \log(x_2 + 1) - X}{x_2^2} & X<x_2\leq 1+X\\
\frac{\log(x_2 + 1) + \log(x_2 - X) + 1}{x_2^2} & x_2>1+X
\end{cases}
$$
so then the outer integral converges.
Answer: i) Along the line $x=y$, the integrand is close to $\sum_{n=1}^\infty\ \frac{1}{n^2}$
ii) Consider a line $y=x-n$ so that $$
\frac{1}{|y-x|}=\frac{1}{n},\ \frac{1}{{\rm max}\ \{x,y=x-n=i\}^2}
=\frac{1}{(n+i)^2}$$
Hence $2\sum_{n=1}^\infty \frac{1}{n}\sum_{i=0}^\infty\
\frac{1}{(n+i)^2} =\ast $
Here $\int_n^\infty\ \frac{1}{x^2}\ dx =\frac{1}{n}$ so that
$\sum_{i=0}^\infty\ \frac{1}{(n+i)^2}$ is close to $\frac{1}{n}$. So
$\ast$ is convergent so that so is the given integral.
Answer: Since the integrand is symmetric WRT $x_1$ and $x_2,$ we can restrict to $X\leq x_2\leq x_1$ and then double it, so the integral is equal to:
$$\begin{align}I(X)&=2\int_{X}^{\infty}\int_{X}^{x_1}\min\left(1,\frac{1}{x_1-x_2}\right)\frac{1}{x_1^2}\,dx_2\,dx_1\\
&=2\int_{X}^{\infty}\frac{1}{x_1^2}\int_{0}^{x_1-X}\min\left(1,\frac{1}{u_2}\right)\,du_2 \,dx_1
\end{align}$$
where $u_2=x_1-x_2.$
Now, $$J(X,x_1)=\int_{0}^{x_1-X}\min\left(1,\frac{1}{u_2}\right)\,du_2=\begin{cases}x_1-X& X\leq x_1\leq X+1\\
1+\log(x_1-X)&x_1>X+1\end{cases}$$
So:
$$\begin{align}I(X)&=2\int_{X}^{\infty} \frac{J(X,x_1)}{x_1^2}\,dx_1\\
&=2\left(\int_{X}^{X+1}\frac{(x_1-X)}{x_1^2}\,dx_1 +\int_{X+1}^{\infty}\frac{1+\log(x_1-X)}{x_1^2}\,dx_1\right)\\
&=2\left(\log(X+1)-\log(X) +\frac{X}{X+1}-1+\frac{1}{X+1}+\int_{X+1}^{\infty}\frac{\log(x_1-X)}{x_1^2}\,dx_1\right)\\
&=2\left(\log(X+1)-\log(X) +\int_{X+1}^{\infty}\frac{\log(x_1-X)}{x_1^2}\,dx_1\right)
\end{align}$$
Letting $u=\log(x_1-X)$ and $dv=\frac{dx_1}{x_1^2}$ then $v=\frac{-1}{x_1}$ and $du=\frac{dx_1}{x_1-X}.$ Then:
$$\begin{align}\int_{X+1}^{\infty}\frac{\log(x_1-X)}{x_1^2}\,dx_1 &= \int_{X+1}^{\infty}\frac{dx_1}{x_1(x_1-X)}\\
&=\frac{1}{X}\int_{X+1}^{\infty}\left(\frac{1}{x_1-X}-\frac{1}{x_1}\right)\,dx_1\\
&=\frac{1}X \left(\log(X+1)\right)
\end{align}$$
So the final result is:
$$I(X)=2\left(\log(X+1)-\log(X)+\frac{\log(X+1)}{X}\right)$$


Convention over configuration

Question: I'm reading 'Building and testing with Gradle' book, and it talks a little about  Ant and Apache Ivy having little conventions.
Can someone please provide an example of how Ant or Ivy does not provide convention over configuration compared with Gradle?
Thank you.
Answer: For instance, with either Maven or Gradle, if you store your source files in src/main/java and your tests in src/test/java and then just build it, using a very minimal build script, it just knows to compile everything, run the unit tests, and produce a jar of the compiled classes (from src/main/java).
With Ant, you have to tell it specifically where all of your source is, exactly what tasks are in play, and how to package everything up.
The point is, Maven and Gradle assume reasonable conventions and defaults, and just do it, without you having to specify it. If you're using Ant, there may be reasonable conventions about how you SHOULD set up your build script, but you still have to do that work.

Convention over configuration


What, if anything, is known about Bach's interpretation of, or emphasis on, meter?

Question: The modern conventions for meter are, for example, that in 4/4 time, the metrical emphases are S-w+-s-w-, 3/4 is S-w-w, and so on.
Did Bach understand meter in these more-or-less strictly regulated ways, or were metrical emphases more fluid for him?
The question is particularly relevant in fugues, because the subject does not always enter on the same beat, particularly in stretto passages like the one below from Bach's fugue in C minor (WTC II, BWV 871), mm. 16–17. The subject appears first in the alto voice, beginning on the "and" of 1, and then enters in the soprano on the "and" of 3.

Image source: IMSLP (Hermann Keller, ed.; Peters)
Would Bach have expected

the subject maintains its "first-entry" stresses ("and" of 1) even when its metrical placement changes; that is, the soprano would put the main emphasis on the Eb in m. 17, b. 3,
the subject's stresses follow its actual metrical placement; meaning soprano emphasis on the G in m. 17, b. 1, or
Bach was agnostic about meter, so metric designations (time signatures) and bar lines were more notational convenience than performance instruction (so to speak)? The entire passage would be played with each beat being relatively equal.
Comment: I feel the question is splitting hair a bit. Difference between 1& and 3& is not so big. WTC were composed for instruments with no or limited dynamics, so differentiating between them would be even more difficult, especially at the rather not very fast tempo of the piece. Then, regarding point 3. this fugue, and other Bach pieces in general follow the meter consistently, there are no unexpected 2/4 or 6/4 measures between 4/4, which suggests that the whole composition is purposeful.
Comment: Interesting question.  There is quite a lot of material from the period about meter, and I suppose it's probably fairly safe to assume that Bach's view was in the mainstream (i.e., not 3), but I don't know whether he is on the record on this question. If he isn't directly, his son CPE probably had something to say about it in his famous "essay."
Comment: Great question. I don't have an answer (wondered about this a considerable amount myself), but what I would highlight is that many of Bach's pieces do give substantially more relevant instruction than just the meter: many of them are labelled by types of dance. A Sarabande will always have very different emphasis from a Menuett, though both are in 3/4.
Comment: @phoog Here's a promising-looking paper, but I can't read it just now: [Mid-Bar Downbeat in Bach's Keyboard Music](https://digitalcollections.lipscomb.edu/cgi/viewcontent.cgi?article=1061&context=jmtp). Both the journal and the author are of high repute.
Comment: @ToddWilcox and Aaron I doubt that Mozart's ideas about meter were all that different from Bach's -- at least I am fairly sure that they were more similar to Bach's than to Rachmaninoff's.  Certainly, if you look at the counterpoint in Mozart's Requiem, the main subject of the introit starts on either beat 2 or 4, and the Kyrie subject starts on 1 or 3.  I think the importance of multiple levels of metrical hierarchy is sometimes overstated: sometimes it's a useful concept but often it's not. This may have changed over time but it's not absolutely tied to period or style.
Comment: @user1079505 Excellent insight about the non-/limited dynamics of keyboard instruments. That might suggest that meter in Bach's keyboard works might not have been conceived in terms of metric pulses the way piano music often is.
Comment: @Aaron how could meter be anything other than metric pulses?  Meter is expressed rather differently in harpsichord and organ playing than it is in piano playing, most notably it is not expressed through volume, but that doesn't stop it from being pulses.  Besides, piano playing that expresses meter solely through volume is characteristic of beginning pianists.
Comment: @phoog Fair enough. I should have thought through my response to user1079505 more carefully.
Comment: @leftaroundabout excellent point.  A sarabande will also have a rather different tempo from a minuet.  In many cases (and as far as I've seen always in vocal works), Bach doesn't identify the dance form explicitly; rather, this is left to the performer who is assumed to know.
Comment: I've never done graduate level music studies, which I mention as a disclaimer related my understanding that the first paragraph describing the "modern conventions for meter" are not in any way "strictly regulated". I suppose the words "modern", "strictly", and "regulated" leave lots of room for interpretation. If "modern" means something like mid-20th century through today, then I'd retort that there is so much music with either implied or explicit stress that does not follow those patterns that the stress patterns mentioned are really more teaching tools than actual practice.
Comment: In light of my previous comment, I have noticed a change in notation maybe in the last 20 - 40 years of art/concert music that has a stress pattern that is not the one mentioned for 4/4 (for example) would be notated with a time signature in 8/8 and beaming of 8ths to clarify along with a notation like (3+3+2), for example (a tresillo rhythm) above the first bar of the 8/8 time sig. But not all notation follows this practice, and that only works when the "non-standard" rhythm is consistent, as opposed to something like rhythmic serialism (see Ligeti's *Musica Ricercata*).
Comment: @ToddWilcox Your points are well taken. "Modern" was probably a misleading choice of words on my part. What I really meant was "Modern compared to Bach," and I had in mind, say, Mozart through Rachmaninoff. Although meters open up significantly in the 20th century, it remains conventional that when one sees 4/4, the presumption is the classical stress pattern unless otherwise indicated.
Answer: This is a very interesting question, and I wish I had the time I would need to incorporate more source material into this answer.
Some thoughts:

in a passage such as the example, in 4/4 meter with only eighths and 16ths in the contrapuntal texture, the distinction between 1 and 3 is largely theoretical.  This will be true in any period.  The concept of good taste is always present in treatises of the baroque period.  If altering the articulation or phrasing of a fugue subject makes sense in some context, it should be considered, whether because the subject lies differently in the meter or for any other reason.  (This also means that different choices may be reasonable -- there may be incorrect choices, but that doesn't mean that there's only one correct choice.)

treatises that do talk about metrical considerations tend not to go much past a two-level hierarchy of "good" notes and "bad" notes, usually in the context of articulation: bowing of string instruments, tonguing of wind instruments, keyboard fingering, etc.  Similar to the previous point, beats 1 and 3 are certainly different if you are playing half notes, possibly different if you are playing quarter notes, and probably not so different if you are playing eighth notes or shorter.

while we could dispose of the example given in the question through the above points, there are probably more interesting examples to be found.  A few weeks ago I was looking at the Credo from the B-minor mass.  It is in 4/2 (notated as alla breve), and the theme enters mostly on beat one, a few times on beat 3, and once on beat 4.  But this example is also of limited use because the theme is in whole notes (with an initial breve), so when you start on beat 4, all of the notes start on a weak beat.  But what of the performance of those statements starting on 3 versus those starting on 1?  Since we have text here, the most likely is that they should be the same; otherwise we would sometimes have CRE-do IN u-NUM de-UM instead of CRE-do in U-num DE-um.

back to keyboard works, we have the first fugue of the Well-Tempered Clavier, where in measure 15 the tenor enters with the theme a beat after the alto.  Should the stress be different?  Probably not in general, but here the motion is in eighth notes, and even with text a rhetorical variation in stress could be desirable.  For example, suppose this were adapted into a choral fugue with the text wir danken dir:  There's no reason to avoid sometimes singing "we THANK you" and sometimes "we thank YOU'"; variety is the spice of life.  (In fact this theme is similar to the subject of BWV 29.2 on the text "wir danken dir, Gott"; that fugue appears twice in the B-minor mass, first as Amen and then as Dona nobis pacem.)

In summary, a strictly hierarchical approach to meter at multiple simultaneous levels is probably not indicated, nor is a strict approach to the application of meter to phrasing or articulation when a fugue subject or other melodic fragment lies differently in the meter compared to its initial statement.  As always, good taste prevails.
Answer: Bach's understanding of meter is good enough that his vocal works match word accents to musical accents (which makes for "singability") and you figure out an explicit stylistic exception like a hemiola out without the need for a meter change.


Who first used a bar graph of means?

Question: I've read a lot about Playfair and the history of graphics. However, I have not discovered who was the first to create the now popular yet information-poor bar graph of means. Anybody know?
Comment: An earlier use of the term _regression_ by Galton was Galton, F. 1885. Section H. Anthropology. Opening address by Francis Galton. _Nature_ 32: 507-510.  What precisely counts as the first use of regression is a deeper question as people were fitting lines and curves much earlier.
Comment: Yes, any bar graph or graphs showing means. I have looked at some very old psychology journals and don't see bar graphs of means. However, current issues are full of them. Recently there have been a number of articles saying they shouldn't be used but these articles don't seem to have any effect.
Comment: I am not sure that this is an appropriate question. It is hard to historically trace something to its first use. People even argue about the first use of regression.  Galton coined the term in the 1890s but maybe you could find in the literature someone who did it before him.
Comment: I agree,  but I would still be interested in the first use anyone can come up with.
Comment: "the ... bar graph of means" suggests that you have a specific design in mind. Is showing a set of different means by different bars sufficient?
Answer: I rather disagree that the bargraph, or specifically a bargraph of means, is information poor. Used in tandem with error bars, it can be equivalent to a forest plot to allow approximate inference and verification of consistency, as well as presenting the scale of effect so as to allow the viewer to compare effects both on a difference scale and on a log scale, depending on their perception. That's not to say that graphs cannot be used badly, and in ways I can't anticipate fully or even describe... but to name a few, 1) using truncation/omitting the origin, 2) omitting a y-axis or labeling it, and/or forgetting or using the wrong units 3) using superfluous dimensions like width, color, or 3-dimensions to obscure the effect of interest, 4) not mentioning how means and/or SEs are calculated and whether the error bar is 1 SE or 1.96 SEs. Those problems could be encountered in virtually any plot and serves as a reminder: it is not the tools, but their misuse, that contribute to a bad reputation. I would be interested to know how you might propose another general approach.
A very early example of bar graphs of means comes from Florence Nightengale who independently pioneered great dataviz tools. Here she presents death rates per 1,000 which, under a counting process like Poisson a rate is also a mean accounting for an person-year offset. This image dates to 1858. Seeing as there are no other answers, I'm almost certain an earlier verifiable source could be found, but this is one very early example to celebrate an influential figure in data visualization.

https://www.theguardian.com/news/datablog/2010/aug/13/florence-nightingale-graphics

Who first used a bar graph of means?


How to show thumbnail preview in node display for uploaded video in file field

Question: I am using a file field and media module in a custom content type to upload video files. The videos play fine.  The preview image for each video is a gray box.
How can I display a preview image or thumbnail for each video in place of the gray box in the node display?
Update: the preview image does not have to be auto-generated from the video; I would be OK with adding an field for an image to upload along with the video.
Comment: If you want a dynamic thumbnail generated from your uploaded video, it's quite complicated. We have to do this manually and it is almost +- 500 lines of code with file formatter, ffmpeg extension and custom functions.
Comment: Do you already have the thumbnails for the videos or are you not sure on how to generate them?
Comment: Generating and displaying them would be nice. But I would also go for snagging a frame outside of Drupal and just getting the display part working.
Comment: @mastoll the method I described should work for the latter.  For Generating them you need do use the ffmpeg plugin, which requires a lot more work.
Answer: Go to your content type >> MANAGE DISPLAY settings and set FORMAT as Rendered file and view mode: perview
Comment: This did not work for me. It displayed a film strip icon with no player controls.  The default view mode, on the other hand does work.  Preview now showing.
Answer: This depends on how you are displaying the video.  From your question I gather that it's from the node view.  The first comment from Djouuuuh is correct, but this is very time consuming and understandably may not be an option for you.  So I'll tell you how you can make it work in a smaller time frame with some templating.
First you need to make sure the video field and the thumbnail for the video are available to the display.  If you have a thumbnail field that gets populated automatically or uploaded to manually then all you have to do is add that to the display.
Go to admin/structure/types/type/manage/display and make sure the display you are trying to edit has both fields.  If your thumbnail field is on the video entity then all you would need is the video field.  Also, install and enable the devel module so you can test your displays.
In your node--type.tpl.php template you would need to first test that you have the data available to you, so write  at the top of the document, flush cache, flush browser cache, and reload the node page.  Click through the message printed at the top to make sure you have the data you need.
If the data is there, then you can start doing some templating to get the node to look how you want with the preview.  One quick solution I can think of is to utilize HTML5's  tag with the placeholder attribute.
Something like this:
<?php
  if (isset($content['video_field'])) { $video = $content['video_field']['und'][0]['link_to_video_file']; }
  if (isset($content['video_field']['und'][0]['thumbnail']['link_to_thumbnail_file'])) { $thumbnail = $content$content['video_field']['und'][0]['thumbnail']['link_to_thumbnail_file']; }
?>

  <video src="<?php if (isset($video)) { print $video; } ?>" poster="<?php if(isset($thumbnail)) { print $thumbnail; }?>"></video>

There are other attributes in addition to poster you can use with the  tag to embed controls, timers, multiple video file type sources, etc.


Is there a distance function so that $(\Bbb R,d') $ is compact?

Question: let $d(x,y):=|x-y|$ is there a distance function
$d'$ on $\Bbb R$ s.t. $d'(x,y) \geq d(x,y)$ so that $(\Bbb R, d')$ is compact ?
Answer: Hint. The condition $d'(x,y)\ge d(x,y)$ means that none of the finite-radius open balls around $0$ according to $d'$ is all of $\mathbb R$. But their union is, so together they form an open cover ...


"Server DNS address could not be found" error after adding subdomain in cPanel

Question: I'm trying to create a subdomain through cPanel. After adding the subdomain and visiting it in the browser, I get a This site can't be reached - server DNS address could not be found. Can anyone please advise?
Answer: You need to wait until the DNS cache get updated. also check you have added a correct CNAME for the sub domain and DNS configuration for the sub domain
Plz let me know if you have made any changes while creating a sub domain to help you better way
Comment: "also check you have added a correct CNAME for the sub domain and DNS configuration for the sub domain" - could you elaborate on this? For example, if the domain was example.com and the new subdomain is support.example.com.
Comment: check the primary domain cname and sub domain cname and check same with primary domain and sub domain DNS server name for the both. it should be same or added sub domain dns is working. plz help me with the screenshot or reference
Comment: it will take almost 24 hours to 48 hours


Ajax callback values not saved on submit

Question: I added an Ajax callback to Add to cart form on two fields : quantity and a date line item field, because I need customers to choose the product id depending on these values (see study case if you wish more details).
Everything works fine... except that Ajax values, especially product_id, aren't saved in cart on form submit :(
Relevant parts of code
Add to cart form alter
/**
* Implements hook_form_alter().
*/
function vts_commerce_form_alter(&$form, &$form_state, $form_id) {

  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    //line item field callback
    $form['line_item_fields']['field_date_de_d_part_line_item']['und'][0]['#ajax'] = array(
      'callback' => 'vts_commerce_liberte_addtocart',
     );
    //wrapping $form['product_id']
    $form['product_id']['#prefix']='
';
    $form['product_id']['#suffix']='
';

    // ... SOME CODE setting $options

    //overwriting native $form['quantity'] to have a select with specific options
    $form['quantity']= array(
      '#type' => 'select',
      '#title' => t('Number of participants'),
      '#default_value' =>  1,
      '#datatype'  => 'integer',
      '#size' =>  1,
      '#weight' => 45,
      '#prefix' => '
',
      '#suffix' => '
',
      '#options' => $options,
      '#ajax' => array(
        'callback' => 'vts_commerce_liberte_addtocart',
        'wrapper' => 'qty',
        'method' => 'replace',
      ),
    );
  }
}

Ajax callback
function vts_commerce_liberte_addtocart($form, &$form_state) {

  $commands = array();

  // ... SOME CODE setting $pid and other stuff, messages...

  //TRYING TO UPDATE PRODUCT ID with drupal_render
  $form['product_id'] = array(
    '#type' => 'select',
    '#options' => array(
       $pid => 'product title: '.$pid, // TODO retrieve product title
    ),
    '#default_value' => $pid,
    '#weight' => 0,
  );
  $commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

  //TRYING TO UPDATE PRODUCT ID with $form_state['values']
  $form_state['values']['product_id'] = $pid;
  $form_state['rebuild'] = TRUE;

  return array('#type' => 'ajax', '#commands' => $commands);
}

Either $form['product_id'] and $form_state['values']['product_id'] are changed by the callback, but when I submit the form, it takes the product id selected on page load instead of the one passed through  the callback.
With or without $form_state['rebuild'] = TRUE; in my callback doesn't changes anything...
As an alternative (or complement), I also noticed that product_id's callback is  commerce_cart_attributes_refresh_alter(), which updates the values given to cart, but I don't know how/where to call or trigger it in the ajax process ?
Answer: So, product_id was rendered but its value not passed to the commerce_cart_add_to_cart_form. This is how I solved it.
Add to Cart Form Alter
if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {

  $form['product_id']['#type']='hidden';
  $form['product_id']['#prefix']='
';
  $form['product_id']['#suffix']='
';
  //...

Ajax callback
$form['product_id']['#value'] = array(
  $pid,
);
$commands[] = ajax_command_replace('#liberte_pid', drupal_render($form['product_id']));

It's quite simple once you know it : before calling ajax_command_replace() you don't need to rebuild the full form element, just set the wanted attribute, and drupal_render($form['form_elt'])) will do the magic :)
Comment: Apart, I still don't know why rendering full $form['product_id'] via Ajax (with the code in the question) made it lose its name attribute, and so not updated in cart...?


A condition for a subset to be a subspace.

Question: Prove that if $S$ is a nonempty subset of a vector space $V$, then $S$ is a subspace of $V$ if and only if $\operatorname{Span}(S)=S$.
Comment: What is your definition of span?
Answer: By definition $span(S)$ is the minimal subspace (in the sense of inclusion) of $V$ that contains $S$. So if $S=span(S)$, then clearly $S$ is a subspace of $V$. For the other implication, since $S$ is a subspace of $V$ which trivially satisfies $S\subseteq S$, then $span(S)\subseteq S$, but also for definition $S\subseteq span(S)$, hence $S=span(S)$.
Answer: Let $S$ be a non empty subset of $V$.

Suppose we have $\text{span} (S) =S$. Let $v, w\in S$ and let $c, d$ be scalars. Since $\text{span} (S) =S$, we have $cv+dw\in S$. Therefore $S$ is a subspace of $V$.
Now suppose conversely that $S$ is a subspace of $V$. Suppose for the sake of contradiction we have $\text{span} (S) \neq S$. Since $S\subseteq \text {span} (S) $,  we must therefore have $\text{span} (S) \not\subseteq S$.  In other words,  there exists $v, w \in S$ and scalars $c, d$ such that $cv+dw\notin S $. But this contradicts the fact that $S$ is a subspace of $V$. Hence we must have $\text{span}(S) =S$.

From the above argument, we can conclude that if $S$ is non empty,  then $S$ is a subspace of $V$ if and only if $\text{span} (S) =S$.


How can I access a IPTV server programatically?

Question: My University is currently running an IPTV trial. To access the service, you are asked to install VLC Media Player, and run the files, downloaded from the University's intranet, each representing a channel, through it.
The files are of the format:
#EXTM3U
#EXTINF:0,ITV2
udp://@18.104.22.168:2001

Which I recognise as an M3U playlist file. Fortunately, the file species the IP address of the server hosting the service, the port to access it through, and the protocol, in this case the UDP.
My question is, how could I get access to the service programatically? Is there a specific handshake a client does with the server? Seeing as it's accessible so simply via VLC Media Player, surely accessing the data will be trivial as there is no proprietary protocol used?
I'm not too clued up on accessing the Internet programatically; I know in Java a Port can be constructed which models the UDP. I would appreciate the answers in Java, but any similar language is more than enough.
Thanks!
Answer: Their is a special handshake at the switch level, its telling the switch you are part of the multicast group so that you will also receive the packets.
Bellow is an example of registering and receiving on a UDP socket in java:
 // join a Multicast group and send the group salutations

 InetAddress group = InetAddress.getByName("220.127.116.11");
 MulticastSocket s = new MulticastSocket(6789);
 s.joinGroup(group);
 // get their responses!
 byte[] buf = new byte[1000];
 DatagramPacket recv = new DatagramPacket(buf, buf.length);
 s.receive(recv);
 ...
 // OK, I'm done talking - leave the group...
 s.leaveGroup(group);

Example from j2ee guide.
What you need to do is join the multicast group, then just receive the packets and write them to a file, then I would assume the MPEG2, MPEG4 or however the stream is sent will be a file on your machine that should be playable through another program.
Answer: You may want to look into VLC's Java bindings.  This will give you control of VLC through a Java programming interface.  You get all the greatness of VLC from Java!  Also, there are several other API bindings and interfaces you can use to play with VLC.