A problem in linear algebra about diagonalizable operators

Question:
Let $T$ be an operator in a vector space $V$ of finite dimension over $F$ such that
  $$(T−\lambda \cdot\text{Id}_V)^k=0$$ for some $λ∈F$ and $k>0.$
  Prove that $T$ is diagonalizable if and only if $T = \lambda \cdot\text{Id}_V $.

The proof of the inverse is trivial, but when we know $T$ is diagonalizable, how to get $T = \lambda \cdot\text{Id}_V$?
Use "$(T−\lambda \cdot\text{Id}_V)^k=0$"?
Answer: Let $n = \dim V$.  If $T$ is diagonalizable, then represent $T$ by the matrix
$$
\begin{pmatrix} \lambda_1 & 0 & \cdots & 0 \\ 0 & \lambda_2 & \cdots & 0 \\
\vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & \lambda_n \end{pmatrix}.
$$
Then what is the matrix that represents $T - \lambda \, \text{Id}$?  And so what is the matrix that represents $(T - \lambda \, \text{Id})^k$?  You can write this out very explicitly and then show that $(T - \lambda \, \text{Id})^k = 0$ implies that $\lambda_1 = \lambda_2 = \cdots = \lambda_n = \lambda$.
Comment: Wow,first k diagonal entries of (T- λ Idv)^k are (λ-λi)^k=0,so λi=0.Thanks I got it
Comment: Let me have a try.
Answer: More generally, suppose that $\displaystyle \sum_{n=0}^{n}a_n x^n=f(x)\in F[x]$. Then, there is a natural way to interpret $f(A)$ for $A\in\text{Mat}_n(A)$. Namely, $\displaystyle f(A)=\sum_{n=0}^{n}a_n A^n$ where, by convention, $A^0=I$. It is not hard to prove that if the eigenvalues of $A$ with multiplicity are $\lambda_1,\cdots,\lambda_n$ then the eigenvalues for $f(A)$ are $f(\lambda_1),\cdots,f(\lambda_n)$. This fact is absolutely invaluable, and will allow you to kill many problems.
For example, here you have the polynomial $f(x)=(x-\lambda)^k$ and you know that $0=f(T)=(T-\lambda I)^k$. Thus, applying the previous paragraph you know that if $\lambda_1,\cdots,\lambda_n$ are the eigenvalues of $T$ then $f(\lambda_1),\cdots,f(\lambda_n)$ since these are the eigenvalues of $f(T)$, which is the zero matrix. But, $f(\lambda_i)=(\lambda_i-\lambda)^k=0$ implies that $\lambda=\lambda_i$. Thus, we must necessarily have that $\lambda=\lambda_i$ for all $i$.
Here's where the second trick comes into play. Namely, the only matrix conjugate to a scalar matrix (a multiple of the identity) is that multiple of the identity. Indeed, if $A$ is conjugate to $\lambda I$ then $A=B\lambda IB^{-1}$ for some invertible $B$. But, $\lambda I$ commutes with every matrix in $\text{Mat}_n(F)$ and so $B\lambda IB^{-1}=\lambda I$ so that $A=\lambda I$.
Now, as Michael Joyce points out, if $T$ were invertible it would be conjugate to the matrix with the eigenvalues of $T$ on the diagonal. But, since every eigenvalue of $T$ is $\lambda$ this implies that $T$ would be conjugate to $\lambda I$ which implies, by what we have just said, that $T=\lambda I$!


Updating .PHTML Template Files Not Displaying Changes On Site

Question: I am attempting to make a minor edit to the list.phtml file in a custom theme for a Magento 1.9 site. Unfortunately even after turning on template-path hints, clearing and then disabling the caches I am not seeing my changes reflected on the site.
I have checked out Google and Stack Overflow for other people's encounters with this issue. I've toggled the template-path-hints to verify that I am indeed editing the correct file.
Essentially all I want to do is remove the "Read More" link from the template.
According to the template path hints the phtml file that I am looking to edit is at frontend/mycustomPackage/default/template/catalog/product/list.phtml
I edited the file on the server at that location and expected the changes to be reflected on the product catalog list page, but they haven't shown up. I have been spinning my cubic wheels on this.
Answer: Please check the following:
 1. Have you tried changing the theme?
 2. Try by creating a child theme of default to chek the changes.
 3. It can be a memcache issue also
 4. Make sure that the read more link is from that list.phtml. Sometimes,it shows the file but the data is retrieved either from block or module.
If these are not useful,you can share the Project details to my email-id.I will fix it for you.
Please vote if you find these links helpful.
Comment: Thank you for the reply, it turned to be a memcache issue!
Answer: If any third party caching is using then try to clear the cache from console.
Comment: Thank you it turned out to be a memcache issue.


How can I retrieve tenantId in a function triggered by onCreate in Google Cloud Functions

Question: UPDATE: Partially Solved! See Below
I've converted my Firebase application to multi-tenancy by upgrading to Identity Platform and I need to get tenantId in onCreate function.
// This is where it's defined;
exports.processSignUp = functions.auth.user().onCreate(events.signUp);

This is the function, I've tried various things to get tenantId.
  async function signUp(user, context) {
    let tenantId = user.tenantId; //context?.auth?.token?.firebase?.tenant;

    try {
      Logger.debug("USEROBJ", user);
      Logger.debug("USEROBJ-2", JSON.parse(JSON.stringify(user)));

      Logger.debug("CONTEXTOBJ", context);
      Logger.debug("CONTEXTOBJ-2", JSON.parse(JSON.stringify(context)));
      if (!tenantId) {
        Logger.error("TENANT ID IS EMPTY", "Assigned manually.");
        tenantId = "xxxx-xxxx";
      }
    } catch (error) {
      console.error(error);
    }

    //Set Custom Claims on Firebase
    return (
      _createUserClaims(user.uid, user.email)
        //Read claims from store & update user's claims.
        .then(() => _updateClaims(tenantId, user.uid))
    );
  }

Claims creating function
//Merge custom claims with default claims.
const createClaimsObject = (uid, additionalClaims) => {
  const defaultClaims = {
    "x-hasura-default-role": "user",
    "x-hasura-allowed-roles": ["user"],
    "x-hasura-user-id": uid,
  };

  const claims = {
    "https://hasura.io/jwt/claims": {
      ...defaultClaims,
      ...additionalClaims,
    },
  };

  return claims;
};

This function is supposed to update claims, but it fails.
function updateClaims(admin, firestore, tenantId, uid) {
  //
  return getClaims(firestore, uid)
    .then((doc) => checkClaims(uid, doc))
    .then((additionalClaims) => setClaims(admin, tenantId, uid, additionalClaims))
    .catch((err) => console.error(err));
}

This is checking Firestore for claim records.
//Check if claims exist.
const checkClaims = async (uid, doc) => {
  if (doc) {
    const data = doc.data();
    console.log(`${uid} has custom claims`, data);
    return data;
  }

  return {};
};

This is my claim setter function;
const setClaims = async (admin, tenantId, uid, additionalClaims) => {
  const claims = createClaimsObject(uid, additionalClaims);
  return admin
    .auth()
    .tenantManager()
    .authForTenant(tenantId)
    .setCustomUserClaims(uid, claims);
};

After setting it manually, setClaims return this; FirebaseAuthError: There is no user record corresponding to the provided identifier.
How can I retrieve the tenant id and, even if I set it manually, why does it fail with this error?

How it's solved?
I don't exactly know why it's solved but I'll explain here how it's solved.

admin.initializeApp(functions.config().firebase); this line updated with below
admin.initializeApp();
Another thing is when I log the user object there is no tenantId property but If I assign it to a value like const tenantId = user.tenantId
tenantId is there.
After signup, I was refreshing the token to get additional claims, but it wasn't there. It sometimes requires a second refresh, so adding
a timeout after the signup before fetching new token solves it.

This solves my problem but it's not clear exactly and not a valid solution, answers are still welcome.
Answer: Retrieve the tenantId in a function triggered by onCreate in Google Cloud Functions, you can access it through the context parameter of the onCreate function.
Define your Cloud Function for user creation:
exports.processSignUp = functions.auth.user().onCreate((user, context) => {
  const tenantId = context.auth.tenantId || "defaultTenantId";
  // In the logic of your function, use the tenantId.
  //...
});

Access the tenantId using context.auth.tenantId. If it's not available, you can provide a default value.
Use the tenantId in your function's logic for further processing or customization based on the tenant.
You may check this documentation about Cloud Function Event Context.
Comment: Ty, context.auth.teantId is not available in the object.
I need it to be dynamic, not static, but I've tried that as well, the error is written in the original post.
Answer: You can find it in context.auth.token.tenantId
Answer: For anyone still wrestling with this, I have solved it by upgrading the Firebase community builder to the latest version. From then on, the tenantId property was sent in the user parameter.
If you use another way for deploying your functions check if your firebase-admin version is up to date.


Can't figure out if OWIN is intercepting requests to api from client

Question: I have an Asp.net webapi with JWT authentication using OWIN middle ware.
My resource server and the authorization server are same. I am able to get the token from the token endpoint. ValidateClientAuthentication and GrantResourceOwnerCredentials methods are hit successfully.
However when I try to access a protected(with [Authorize]) api (with authorization header set to bearer token) I only get "Authorization has been denied for this request".
I have overridden ValidateAuthorizeRequest method just to see if it gets hit when the api call is made via Postman. However it is never hit.
I am trying to figure out a way to see if at all OWIN is intercepting calls to the api other than the calls to the token endpoint.
Is there any way or methods to override so that I can debug and see where in the pipeline the request is being rejected and why.
As of now I make the call via Postman and get an unauthorized response.
Any help would be greatly appreciated.
Comment: Two questions: 1. Do you bind the webapi config in the owin startup class? 2.Can you access the api without [Authorize]
Comment: 1) Yes I bind the webapi config in the owin startup class as shown in code posted in the other question.
2) Yes when I remove the [Authorize] attribute its accessible.
Comment: @MarcusH I made an update to the question based on the attempts I made since then. I have overridden MatchEndpoint method of OAuthAuthorizationServerProvider class. This method is called on every request to see if the request is on token endpoint or authorize endpoint. To my surprise IsTokenEndpoint comes true when i hit for token but IsAuthorizeEndpoint is never true for other requests which I guess it should be. Means its not detecting the call as being on authorize endpoint
Answer: this is difficult to answer without seeing what you've done.
I am wondering if you have wired things up correctly. Startup class is where you define your Provider and Token format and then you set your application to use those settings. Here is an example:
<code>public class Startup

    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            ConfigureOAuth(app);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            int accessTokenExpiresInSeconds = ConfigurationHelper.GetAppSetting("AccessTokenExpirationInSeconds").ToInt();
            var oAuthServerOptions = new OAuthAuthorizationServerOptions

            {
                AllowInsecureHttp = true,

                TokenEndpointPath = new PathString(ConfigurationHelper.GetAppSetting("TokenEndPoint")),

                AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(accessTokenExpiresInSeconds),

                Provider = new CustomOAuthProvider(),

                AccessTokenFormat = new CustomJwtFormat(ConfigurationHelper.GetAppSetting("TokenIssuer"))
            };

            app.UseOAuthAuthorizationServer(oAuthServerOptions);
        }
    }
</code>
If that's not the issue then you can use my own article on OAuth2 and JWT, I've got a full example on how to set everything up and the code is on GitHub. Hopefully it will guide you in the right direction:
https://eidand.com/2015/03/28/authorization-system-with-owin-web-api-json-web-tokens/
Comment: Here is the link to the actual question I posted. It contains the code. http://stackoverflow.com/questions/40019247/authorization-has-been-denied-for-this-request-using-jwt


Does the left and right eigenvector of a matrix corresponding to different eigenvalues ALWAYS  have  a zero dot product?

Question: Let $\mathcal{E} = \lbrace v^1 ,v^2, \dotsm, v^m \rbrace$ be the set of right
eigenvectors of $P$ and let $\mathcal{E^*} = \lbrace \omega^1 ,\omega^2,
\dotsm, \omega^m \rbrace$ be the set of left eigenvectors of $P.$ Given any two
vectors $v \in \mathcal{E}$ and $ \omega \in \mathcal{E^*}$ which correspond to
the eigenvalues $\lambda_1$ and $\lambda_2$ respectively. If $\lambda_1 \neq
\lambda_2$ then $\langle v, \omega^\tau\rangle = 0.$
Proof. For any eigenvector $v\in \mathcal{E}$ and $ \omega \in
\mathcal{E^*}$ which correspond to the eigenvalues $\lambda_1$ and $\lambda_2$
where $\lambda_1 \neq \lambda_2$ we have, \begin{equation*} \begin{split}\langle\omega,v\rangle = \frac{1}{\lambda_2}\langle \lambda_2 \omega, v\rangle = \frac{1}{\lambda_2} \langle P^ \tau \omega ,v\rangle = \frac{1}{\lambda_2}\langle\omega,P v\rangle = \frac{1}{\lambda_2} \langle  \omega,\lambda_1v\rangle = \frac{\lambda_1}{\lambda_2}\langle \omega,v\rangle .\end{split}
\end{equation*} This implies  $(\frac{\lambda_1}{\lambda_2} - 1)\langle\omega,v\rangle =
0.$ If $\lambda_1 \neq \lambda_2$ then $\langle \omega,v\rangle  = 0.$
My question: what if $ \lambda_2 = 0 \neq \lambda_1,$ how can I include this case in my proof.
Comment: $\LaTeX$ tip: don't use `<` and `>` for left and right angle brackets; $\LaTeX$ treats them like operators rather than delimiters, so the spacing is all wrong. Use `\langle` and `\rangle` instead.
Comment: Thanks Arturo for your suggestion. It was very useful.
Answer: Do not be afraid to use the formulation of the dot/inner product as a transpose/conjugate vector multiplied by actual vector. Recall that $v$ is a right eigenvector if and only if $Pv=\lambda_1 v$ and that $\omega$ is a left eigenvector if and only if $\omega^t P=\lambda_2\omega^t$.
Then $\left<\omega,v\right>=\omega^tv$. Sticking a $P$ in the middle and using associativity of matrix multiplication and commutativity of scalar multiplication we get
$$\lambda_2(\omega^tv)=(\lambda_2\omega^t)v=(\omega^tP)v=\omega^t(Pv)=\omega^t(\lambda_1v)=\lambda_1(\omega^tv)$$
Subtracting the far sides from each other we obtain $(\lambda_1-\lambda_2)(\omega^tv)=0$, and since the scalars $\lambda_1-\lambda_2$ and $\left<\omega,v\right>=\omega^tv$ belong to a field (which in particular has no zero-divisors other than $0$ itself) we must have either $\lambda_1=\lambda_2$ or $0=\omega^tv=\left<\omega,v\right>$.
Comment: Thanks. This was very helpful.
Answer: Let $Ax=\lambda x$ and $y^T A = \mu y^T$ with $\lambda \neq \mu$. Multiply $Ax=\lambda x$ from the left by $y^T$ and you get $\mu y^T x = \lambda y^T x$ or equivalently $(\lambda - \mu) y^T x =0$. Since $\lambda - \mu \neq 0$ this yields $y^T x=0$.
Note that i assumed that we can "cancel" $(\lambda - \mu)$. This is true as long as the set of our scalars forms an integral domain. For the purposes of standard linear algebra this is always true, since the scalars form a field, and a field is an integral domain.
If say $\lambda=0$, then the relation $(\lambda - \mu) y^T x =0$ becomes $\mu y^T x =0$. Since $\mu \neq 0$ (we assume $\lambda \neq \mu$), this yields $y^T x=0$.


How to access from node template a field added by module

Question: I have a content type that has a custom template. My content type is article and I have a node--article.tpl.php that displays the following.
<?php
    print render($content['field_image']);
    print render($content['body']);
?>

I have a module that adds a featured image to each node if it is made a featured node in its options. I believe this is the code in the module that is causing it but I'm not positive.
function featured_nodes_field_extra_fields() {
  $extra = array();
  // Get feature types from the database.
  $featured_node_types = db_select('featured_nodes_types', 't')
    ->fields('t')
    ->execute()
    ->fetchAllAssoc('machine_name');

  foreach($featured_node_types as $type => $feature) {
    foreach (node_type_get_names() as $name => $value) {
      $extra['node'][$name] = array(
        'display' => array(
          'featured_nodes_' . $type => array(
            'label' => $feature->label . ' - featured image',
            'description' => t('If this node is featured, display the associated image.'),
            'weight' => -10,
          )
        ),
      );
    }
  }
  return $extra;
}

function featured_nodes_node_view($node, $view_mode, $langcode) {
  if (!empty($node->featured_node)) {
    foreach ($node->featured_node as $delta => $values) {
      $node->content['featured_nodes_' . $values['feature_type']] = array(
        '#theme' => 'featured_node_image',
        '#node' => $node,
        '#view_mode' => $view_mode,
        '#db_values' => $values,
      );
    }
  }
}

Despite my attempts I have not been able to print the featured image from node--article.tpl.php but I believe I got close. When I added
print render($featured_node[0]['image']);

It displayed 10080. And a unique number on each featured node. Possibly the field's id. But I was still unable to produce the image. Any ideas?
Answer: I managed to figure it out. I found a location in the module with this code.
function theme_featured_node_image($variables) {
  $fid = $variables['element']['#db_values']['image'];
  $file = file_load($fid);
  $url = file_create_url($file->uri);
  return theme('image', array('attributes' => array(), 'path' => $url));
}

Then I wrote
$file = file_load($featured_node[0]['image']);
$url = file_create_url($file->uri);
print '';

Which allowed me to print the image.


What information can I gain from the fourier transform?

Question: I have acceleration data in 3D vectors (x,y,z).
For detecting certain patterns within the data stream, I use a fixed moving window to generate many statistic features, like mean, max, kurtosis,...
I use these feature vectors to detect key strokes.
My results are already quite ok, but I want to improve them.
And many papers in this field used the fourier transformation (or fft) to improve their results.
I never worked in the frequency domain, so I don't know what this is used for and what information I could gain from using fft.
Most articles I found on this topic are focused on audio stuff.
Here a sample plot of the data I capture (only the right graph):

These graphs correspond to the sequence of "0123034880". The spikes occur during a tap event
Can someone please give me a more general explanation of the fft and what information I can gain from it having a time series of data?
Comment: a) confused about keystrokes vs 3D acceleration. b) could you provide time series plots which will help knowledgeable FFT people give you a judgement on usefulness of FFT for your specific problem
Comment: Could you label the time series ie what keys does each time segment correspond to.
Comment: @seanv507 I just added a graph. and on the keystroke idea: https://www.researchgate.net/publication/256618651_On_the_Best_Sensor_for_Keystrokes_Inference_Attack_on_Android
Comment: I just added it. The spikes belong to tap events.
Answer: The FFT is used to analyse periodic data. You use the Short Time Fourier Transform ( basically the FT over small segments of the time series) to analyse how the frequencies change over time ( eg in music).
your plots are too low detail to zoom in, but I cannot imagine that a keystroke has any particular repetitive signal (eg that your fingers vibrate differently based on the key pressed) [ I have little imagination:) ].
I could imagine you look at frequency information to remove periodic noise (?you are on a train).
another possible use would be to identify typing frequency and maybe stretch your signal accordingly ( ie to standardise your signal across typing speeds)
Answer: Informally speaking frequency domain tells us "how fast things change". And the different "components" of you data.
You mentioned about audio data, which is a perfect example to understand frequency domain. The low frequency components can be the sound from base guitar, and the high frequency components can be sound from lead guitar. Suppose we want to know "how much work" has been done for two players. The "power spectrum on different frequency components" can tell you that. Also, suppose you want to practice lead and filter out the lead sound in original track. Frequency analysis can help to design a filter to do such task.
Back to your example of sensor data. Suppose you have some sensor on a person that can collect all the movement data. The data should be very complicated that contains slow movements (such as walk) and fast movements (such as heart beat).
Similar to the audio example, frequency analysis will give you different roles. Say, suppose you want to get the heart beat data only, a special filter can be derived and applied to your data to get that.
BTW, here is a related question from me. You can see if your data is periodic (as shown in your figure), using Fourier basis is better.
What's wrong to fit periodic data with polynomials?
Comment: "Similar to the audio example, frequency analysis will give you different roles. Say, suppose you want to get the heart beat data only, a special filter can be derived and applied to your data to get that." so, you'd suggest that I extract the same features, I so far extracted from m 3D polynomal interpolation, but for the fourier?
Answer: FFT will give you an idea of the dominant frequencies that are associated with the tap events you mention above. My guess is that you would see different spectral 'signatures' for each tap event (or for small sets of events like consecutive taps of the same number/button).
Comment: Well, assuming you can isolate each button press event, you could perform the FFT and extract features such as the dominant (peak) frequencies, etc. This post seems quite relevant too - http://stackoverflow.com/questions/27546476/what-fft-descriptors-should-be-used-as-feature-to-implement-classification-or-cl
Comment: so, in terms of extracting features from this, what could be a meaningful thing to derive from the FFT?


Blazor problem with updating bootstrap tooltip

Question: So, how can I use the bootstrap tooltip with Blazor?
I tried to use it like this:
MainLayout.razor:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await JsRuntime.InvokeVoidAsync("setTooltip");
}

setTooltip:
function setTooltip() {
    $('[data-toggle="tooltip"]').tooltip();
}

It's fine when the content is updated on MainLayout, but if the child component has been updated, it does obviously nothing.
How i can dynamically update a tooltip with no other code in childs?
Comment: Since you are on the javascript side, the onchange event of document might help you out here, have a look: https://stackoverflow.com/a/35966779/3936440
Answer: Consider using the HxTooltip or take a look at HxTooltip's source-code where this is covered.


The admin toolbar is messing up the sticky position set with fundation

Question: i am using the sticky component from foundation to render a sidebar element sticky.
It does work when unconnected but when connected the toolbar cover the sticky element.
How could i fix this ?
fundation sticky component

a table of content

Answer: i used then the fundation data-margin-top attribute


Metric spaces, compactness, how to solve this with the open covering property?

Question: I have an excercise I am supposed to solve with the open covering property. I am not able to do that, but I can solve it with another method. I have two questions.
1. Is my method of solving it correct?
2. Can you please tell me how to solve it using that the open covering property is equivalent with compactness?
excercise:

Let $K_{n}$ be a decreasing sequence (i.e., $K_{n+1} \subseteq K_{n}$
  for all $n \in \mathbb{N}$) of nonempty, compact sets. Show that
   $\bigcap_{n \in N}K_{n} \ne \emptyset. $

solution without using open-covering property:

For each $K_{n}$ choose an element in $K_{n}$. Since the higher sets
  are contained in each other, all of these elements will be a sequence
  $\{x_{n}\}$ in $K_{1}$. Since $K_{1}$ is compact there will be a
  subsequence $\{x_{n_{k}}\}$ converging to a point $a$ in $K_{1}$.
Assume for contradiction that $a \not\in \cap_{n \in N}K_{n}$. Then for a
  large anough N, $a$ will not be an element in
  $K_{N},K_{N+1},K_{N+1}....$. Since $K_{N}$ is compact and $d(x_{n},a)$
  is continuous, by the extreme value theorem $d(x_{n},a)$ will be
  bigger than  $min\{d(x,a): x \in K_{N}\}$ for all $n \ge N=M>0$. And
  this distance can not be zero since a is not in this set. Hence the subsequence can not converge
  to a as assumed.

Is my sollution correct, and how can it be done with the open covering property instead?
Answer: My knowledge on sequences is minimal but I can tell you how to solve it using the open covering method.
Consider the sequence of sets $F_n = (K_n)^c$. If the intersection is empty then there is no common point in the sequence $\{K_n\}$ and hence the union $\bigcup_{n \in \Bbb N} F_n$ contains $K_1$. Now since each $K_n$ is compact they are alsoo closed. Hence $F_n$ is open and $\bigcup F_n$ is an open covering of $K_1$ which is compact.
Therefore, there is a finite subsequence, $F_{i_1}, F_{i_2}, .. F_{i_m}$ of $F_n$ which is also a covering of $K_1$. Now if $M = \text{Max} \ \{ i_n \}$ then since each $F_n$ increases in size, $F_{i_1} \subseteq F_{i_2} \subseteq, .. F_{i_m} \subseteq F_M$. Therefore $F_M$ contains $K_1$.
But $K_M \subseteq K_1 \implies K_M \cap K_1 = K_M$. Since $K_1 \cap F_M = K_1$ we have $K_M \cap (K_1 \cap F_M) = K_M \implies (K_M \cap F_M) \cap K_1 = K_M \implies \emptyset = K_M$ which is a contradiction since every member of $K_n$ is non-empty.
Therefore the sequence has a common point and hence the intersection is non-empty.
Comment: @user119615: Anytime..
Answer: It looks pretty good to me.
I think that you lose the plot a little when you start talking about the continuity of the distance function, but not in any serious way.  Your contradiction argument will work in a simpler way: Once you have an $N$ such that $a\notin K_N$, the contradiction is immediate since all but finitely many terms of the convergent subsequence are contained in the closed set $K_{N}$. QED
The open covering property approach is pretty simple.  Let $U_n$ be the complement of $K_n$.  Then if the intersection is empty, these sets form an open cover for each compact set $K_n$.  A contradiction follows from there - I'll let you finish it yourself.
Comment: Thank you very much for your time and help.
Answer: You can prove something more general, if you want.

Claim Let $\mathscr F=\{K_\alpha:\alpha\in A\}$ be a family of centered compact sets in a Hausdorff space, that is, any finite intersection of elements of $\mathscr F$ is nonempty. Then $\bigcap \mathscr F$ is nonempty.

Proof Suppose not. Then there exists some $K_0\in \mathscr F$ such that  for each $x\in K_0$ there is $K_{\alpha_x}$ with $x\notin K_{\alpha_x}$. Since the space is Hausdorff, our compact sets are also closed, so the sets $V_{\alpha_x}=K_{\alpha_x}^c$ are an open cover of $K_0$. This means there exists a finite subcover $V_1,\ldots,V_n$ such that $K_0\subseteq \bigcup_{i=1}^n V_i$ that is $$K_0 \cap (K_1\cap\cdots\cap K_n)=\varnothing$$
which contradicts $\mathscr F$ is centered. $\blacktriangleleft$


Proving that a sequence is not Cauchy

Question: I'm trying to prove that the sequence $\left(\frac{1}{2},\frac{1}{3},\frac{2}{3},\frac{1}{4},\frac{2}{4},\frac{3}{4},\frac{1}{5},\frac{2}{5},\frac{3}{5},\frac{4}{5},\cdots\right)$ is not a Cauchy sequence.
I know that a sequence of real numbers is not Cauchy if there exists an $\epsilon>0$ such that, for all $N\in\mathbb{N}$, there exists $m,n>N$ such that $|x_{m}-x_{n}|\geq\epsilon$. It intuitively makes sense to me that the sequence cannot be Cauchy, as the distance between points where the denominator changes (like $\cdots\frac{99}{101},\frac{100}{101},\frac{1}{102},\cdots$) keeps growing larger. However, I'm not sure how to find indices $m$ and $n$ in general with $|x_{m}-x_{n}|\geq\epsilon$. Thanks in advance for any help!
Answer: Let $(a_n)_{n\in\mathbb N}$ be your sequence. Take $\varepsilon=\frac12$. Given $N\in\mathbb N$, take $n\geqslant N$ such that $a_n$ is of the form $\frac k{k+1}$ for some $k\in\mathbb N$ and let $m=n+1$. Then $a_m=\frac1{k+2}$. Therefore,$$\left\lvert a_m-a_n\right\rvert=\frac k{k+1}-\frac1{k+2}\geqslant\frac12=\varepsilon.$$

Or you can say that your sequence diverges, since the subsequence$$\frac12,\frac13,\frac14,\ldots$$converges to $0$, whereas the subsequence$$\frac12,\frac23,\frac34,\ldots$$converges to $1$. So, the sequence diverges and therefore it is not a Cauchy sequence.
Answer: You only need such an $\epsilon$ to exist, so you can choose a convenient value.
Then you need to show that there are gaps bigger than $\epsilon$ between elements of the sequence as far a=out as you care to go - that gaps as big as $\epsilon$ don't fade out and disappear in the tail of the sequence.
Well you have identified some chunky gaps which persist (you don't need every gap to be big). What $\epsilon$ would work for the gaps you have identified?
Answer: Cauchy sequence: $$\forall\varepsilon>0\exists N\forall n,m\quad n,m>N\implies|a_n-a_m|<\varepsilon$$
We want to show the negative:$$\exists\varepsilon>0\forall N\exists n,m\quad n,m>N\land |a_n-a_m|\ge\varepsilon$$
Take $\varepsilon=1/10$, and then, for all $N$ take $n=\sum_{i=1}^{N+1} i=\frac{(N+1)^2+N+1}{2}, m=n+1$ and you have $a_n$ an element in the form of $\frac{k}{k+1}$ and $a_m$ in the form of $\frac{1}{k+2}$

Proving that a sequence is not Cauchy


Loss of references between service and controller data in Angular.js

Question: We encountered a problem when working with references between service and controller data
// We have a service that we use to store id and some other data
app.service('testService', function ($http, serverURL) {
    var self = this;
    self.data = {
        id: null,
        token: null,
        ....
    };
    self.initMe = function () {
        return $http({
            method: 'GET',
            url: serverURL + '/initMe/' + '?token=' + self.data.token
        });
    };
    return self;
});
meModule.controller('MeCtrl', function (testService, ...) {
    $scope.me = testService.data; // we make a connection between the scope and the controller

    $rootScope.$on('initMe', function (e, data) {
        testService.initMe().success(function (data, status, headers, config) {
            // typeof(data.result) === 'object'
            // $scope.me = data.result;         // Doesn't work
            // OR
            // testService.data = data.result;    // Doesn't work

            testService.data = data.result; //
            $scope.me = testService.data;   // It works, but we have to recover
                                            // the references between scope and service
        });
    });
}

Questions

Why we loose the connection between scope and service in $scope.me =
data.result or meService.data = data.result;?
Maybe there are other, nicer ways to update the data in a sevice
from an external API (Get requests)?
Comment: Try changing `var self = this;` to `var self = {};`
Answer: That's just how JavaScript works. Consider the following example:
> first = { data: null }
{ data: null }
> second = { data: first.data }
{ data: null }
> first.data = "something"
'something'
> second.data
null

There is an incorrect assertion on this line:
$scope.me = testService.data; // we make a connection ...

There is no actual connection between the scope and the service; you're just copying the simple value over. However, if you store off a reference to an object, you can update that object in place and the "connection" will be kept. Consider this example:
> first = { data: {} }
{ data: {} }
> second = { data: first.data }
{ data: {} }
> first.data['something'] = 'stuff'
'stuff'
> second.data
{ something: 'stuff' }

Comment: So which path should I choose? According to your answer I see two possiblities:
1. Change the structure of the testService.data object and bind to object  'o':
`self.data = {
 o: {
  id: null,
        token: null,
        ....
 }
}`
2. When assigning service data to scope  use for..in for the object and assign every property separatly.

Am I right or there is a better solution here?
Answer: Service is like a constructor function. You do not do return on the constructor function.
I am not sure about what you mean by loosing connection. But the object data that you create on the service should not get reassigned anytime within the service. You are currently updating the data in the controller. The same can be done in service.
Also the asignment that you have highlighted $scope.me = data.result; will cause a controller to point to a different instance of data than what the service has.
The overall problem is with reference that the service and controller point to.


ZFS configuration opinions

Question: Currently, I'm tasked with progressively building a ZFS store.  IOPS are not the priority, data security and capacity are.
In essence what we have is one brute of a machine, that contains an OS (FreeBSD most likely but OmniOS is a possible), 2 RAID-1 OS disks, and 4 SSDs, for caching and ZILs.  RAM will start of at 16GB but I can go all the way up to 128GB if need be (and if accounting doesn't suffer a stroke).  That in turn is connected to a JBOD chassis that can handle upto 45 drives.  Each drive is 4TB.
I was considering incrementing by 9 drives, using a RAID-Z2 schema and then as needed, creating a new vDEV of another 9 drives until the 45 drive capacity is fulfilled, after which we would add another chassis that also handles another 45 drives.  There is a limit of 3 or 4 connected chassis before a new similar configuration would need to be created.
Another possible option is to go up in 7s (RAID-Z2) and once we hit the 42 drive mark, we can slot in 3 drives to be used at any moment by any of the vdevs if a drive pushes up the daisies.
The Architecture is something as follows:
<code>                                Storage Server
                                       |
                                       |
                                       |
               ------------------------------------------------
              |                       |                       |
             JBOD 1       ...        JBOD 2                   JBOD 3
            -vdev 1.1 (9 drives)    -vdev 2.1 (9 drives)     -vdev 3.1 (9 drives)
            -vdev 1.2 (9 drives)    -vdev 2.2 (9 drives)     -vdev 3.2 (9 drives)
            -vdev 1.3 (9 drives)    -vdev 2.3 (9 drives)     -vdev 3.3 (9 drives)
            -vdev 1.4 (9 drives)    -vdev 2.4 (9 drives)     -vdev 3.4 (9 drives)
            -vdev 1.5 (9 drives)    -vdev 2.5 (9 drives)     -vdev 3.5 (9 drives)
</code>
On a side note, I'd also highly appreciate any input on FreeBSD vs Illumian vs OmniOS with respect to ZFS.  I'm fairly fluent on FreeBSD and I've played a bit with OmniOS but no working knowledge on Illumian.
TIA
[edit]
Referencing Nex7's blog post point 9, we're building our VDEV's on 9 disks, 2 are for parity, so we're still in the clear, but we could I believe exchange that for a 15 vdev with 2 for parity since we're using RAIDZ2.
Point made on the SATA drives, switching to SAS will not be a problem.  The SSD drives are Intel server drives, but I'll be checking.  In all, because we have a few dozen boxes running 100% on the same hardware, I'm not worried about compatibility being an issue.
The reason we did not got with Linux is because we're not 100% certain of how decent and stable the implementation is.  If it were stable...
What advantage does OpenIndiana have over FreeBSD for ZFS? What is the advantage of Napp-it?
How would you suggest we deal with the storage head HA issue?
Thanks
Comment: Please, don't ask for opinions on [SF]. We only want questions that are answerable by facts. For more infos, see the [FAQ]. A valid question would be of the form  "I have requirement A and plan configuration B. Does this meet A?".
Comment: Just a word of warning: What you plan looks fine in theory, but realize that ZFS on FreeBSD is not well tested on systems with so many disks. After research & discussions with FreeBSD devs, we realized that there are very few FreeBSD contributers who actually have a ZFS system with more then 30-40 disks. The developers, many who work for free, simply don't have systems to test large configurations like that. You will be in uncharted territory and will mostly be on your own. If you do choose the FreeBSD/ZFS route, get a support contract to support it, such as IXsystems (Maintainers of FreeNAS).
Comment: Interesting.  So what OS actually does have ZFS systems with more than 40 disks?  Illumian? OpenIndiana? OmniOS?
Comment: That, my friend, is the million dollar question. The answer may be "Solaris", or use traditional hardware-based storage appliances. Neither Illumian & OpenIndiana seemed mature enough when I last looked 6 months ago. zfsonlinux looks really cool and the latest stable release sounds good for scientific computing workloads, but I'm waiting for some time to test it.
Comment: Wow, we're running some really large loads on OpenIndiana for our Node.js installations (aka the farm) and it is ROCK solid.  This started before I showed up there because the previous SA was a Solaris buff.  I'm more the FreeBSD guy, but even on the ZFS channel, no one seemed surprised at the number of disks, but many have validly commented on the difficulty of backing that up.
Answer: What's your question? I don't see a question mark in your post... :)

If you're asking if this will work... Yes, this will work under any ZFS-compatible OS. If you don't like one, you can move your ZFS data to another OS with ease.
If you're asking if it will perform well... It depends... But really, no, It probably won't. SATA is bad news for what you're proposing.
Are you considering your cabling design? A 45-disk JBOD is going to have an onboard expander. Will SAS cabling become a bottleneck?
If you're asking if this is the best way to achieve scale-out storage... Probably not. Your design has no storage-head high-availbility. What happens if your "brute" of a server has a motherboard failure? You'd lose access to EVERYTHING until it's repaired.
If you're asking if the hardware is supported... It depends. You didn't provide any hardware or component specifications. Really. What server, what controllers, which disks, which SSD manufacturer?
If you're asking if there are best-practices for what you're trying to do, yes, there are. (I'd be rethinking the number of disks in each vddv if I were you)
If you're asking which OS to use, I'd say none of them... but that's subjective. I'd suggest NexentaStor, OpenIndiana (with Napp-It?) or just plain Linux these days.

Are those the questions you wanted answered? Does that answer them?
Comment: Wow... That burst my cozy little bubble. Check the edits

ZFS configuration opinions


Interaction for dummies

Question: I used an OLS regression to find correlation between wage gaps and skill similarity in a paired combinations data (ie. A|B, A|C, B|C).
To expand the analysis, I included workplace gender distribution for A, B, C.
I compiled the distribution into dummy form (ie. where Wom >= 50.0)
After a little experimenting, I also compiled the distribution into a similarity measure. (ie. 100 = where distribution is A = B)
I went ahead to construct an variable interaction of a dummy variable and continuous, which looked pretty good to me (ie. where OLS is 'Gap ~ skillSim + Wom:distributionSim')
Question, Is this Ok?
Answer: Including interaction terms(s) between continuous and categorical (special case: dummy) variables is common practice in Regression.
Check out https://www.theanalysisfactor.com/interactions-categorical-and-continuous-variables/ for more info

Interaction for dummies


Application request routing and load balancing

Question: I use Application request routing in my farm environnement.
I got 2 ARR server and 2 IIS server in my farm. I configure my routing to load balance request even to my iis server, but when i look worker process in my farm server, only one server receive all the request and the other server is idle.
Could someone tell my if i am rigth or not but ARR suppose to load balance the request even on all my farm server if i configure it to do that rigth ?
My load balance configuration is Weigthed total traffic,(even distribution).
My server affinity is set to Client affinity, Use host name, ignore subdomain
Comment: In your server farm, double click Load Balance.  What algorithm are you using?
Comment: Actually is Least response time
Answer: I could make a rather long post, detailing all the possibilities causing this, or I could give you an extremely useful link that walks one through the entire process.  I'll do the second thing!
Link
If you find that you cannot solve your problem with the steps listed in this article then feel free to respond with what problems still plague you.
Answer: Try "Weighted round robin" and fire at least 2 requests then check whether your servers receive the requests or not.


react-native scrollview doesn't scroll

Question: I can't seem to figure out why a screen in my Android app doesn't scroll at all in the Android emulator.  Here's my code:
import React, { Component } from 'react';
import Dimensions from 'Dimensions';

import {
  Text,
  ScrollView,
  View,
  TouchableHighlight,
  StyleSheet
} from 'react-native';

const win = Dimensions.get('window');

class DeficiencyItem extends Component {

    render() {
        const touchable = {
                width:win.width/2-20,
                height:230,
                backgroundColor:'red',
              };
        return (
            <TouchableHighlight style={touchable}>
                <View>
                    <Text>Item Here</Text>
                </View>
            </TouchableHighlight>
        );
  }
}

export default class Items extends Component {
  static navigationOptions = {title:'hey'};

    constructor(props)
    {
        super(props);
    }

    render() {

        let deficiencies = [];
        for(let x = 0; x<12;x++)
        {
            let row = <DeficiencyItem key={x} />;
            deficiencies.push(row);
        }
        return (
            <View style={{flex:1}}>
              <ScrollView style={{
                margin:5,
                flexWrap: 'wrap',
                flexDirection:'row',
              }}>
               {deficiencies}
              </ScrollView>
            </View>
        );
  }
}

There are items exceeding the bottom limit of the view port.  But touch drag to scroll in the emulator does nothing.  What did I do wrong?
Comment: Tell me how can i also install react native
Answer: if there is no view outside scrollview than remove View element and add flex:1 to scrollview.
Scrollview should be parent view,
<ScrollView style={styles.container}>
  <View style={{flex:1}}>
    {deficiencies}
  </View>
</ScrollView>

container: {
    flex: 1,
  }

Comment: This doesn't work for me. Could you take a look here? https://stackoverflow.com/questions/63437251/unable-to-scroll-in-scrollview
Answer: My ScrollView is nested in two other views. The issue was solved by providing a height to the scrollview. It's not necessary on iOS so, after adding Platform and Dimensions to react native imports, I do this:
 const { height } = Dimensions.get("screen");
 const styles = StyleSheet.create({
 scrollView: {
   // my outer views have flex:1 so no flex needed here
   alignItems: "center",
   justifyContent: "center", // or whatever you want
   width: "100%,
   height: Platform.OS === "android" ? height * 1.3 : height,
   // if it was just "height", there would be no extra space to scroll on android
 },

 // lots of other styles and stuff

 });

Comment: What should we use as the height? The screen height? I tried adding  ```height: '50%' ```but it didn't work for me. Could you take a look here? https://stackoverflow.com/questions/63437251/unable-to-scroll-in-scrollview
Comment: This messes up with the height of the screen in different devices :(

react-native scrollview doesn't scroll


metrical structure - levels of metrical grouping

Question: In Music, Mind and Brain: The Neuropsychology of Music they use a technique to find the most "salient" level of grouping.
Link to passage text here
This is important in musicology for making observations on the metrical structure of a piece.

Row 0 refers to eighth notes, 1 to quarter notes, etc. What I can't understand is what they shows exactly. There are dots marked on row 0 regardless of whether a note coincides with that particular beat or not, and there are extra dots on row 4 for the start of the second bar yet I don't see why.
How do I read this and what can I infer from this?
Answer: Let's talk about the music before we talk about the metric breakdown. The piece is in cut time (2/2) and the first measure is a pickup and starts from the second beat. In cut time you would count this meter as 1 - 2 where beat 1 would be felt as a stronger beat.
What this is showing in a very round about way is the note hierarchy and how it lines up with the meter and a measure. By doing this you also see the importance of each beat and its divisions in the meter. It also seem that the 5th dot seen in the first full more is to indicate the start of the section.
In this example, every place where you see 4 dots you have the first beat which is the strong beat. Every place where you see 3 dots is the second beat of the measure which is weaker than the strong beat. Every place where you see 2 dots is the up beat of that beat. Every place where you see 1 dot is between the up beat and down beat.
Another way to represent this and how it is typically represented in this meter is through counting the meter like this 1 - e - + - a - 2 - e - + - a.  If you look at the analysis you have you'll notice the 1 is represented by the four dots, the 2 is  represented by the three dots, the + is represented by the  two dots, and the e and a are represented by the single dot.
Comment: I see the pattern. but I don't see how it's possible to read the music notation and infer, for example, 2nd bar row 4 should have a dot vs 3rd bar row 4 should not. Would they not be equally weighed given they indicate the beginning of a measure? Or is this something external to the piece? Sorry if I am not clear. This subject is new to me.
Comment: @user3168961 they are equally weighted. The  extra dot in the second measure means its the start of a grouping of measures.
Comment: @user3168961 indeed, Dom is correct. I would argue that the second full measure should have the dot in row four rather than the first full measure, but whatever grouping of measures one chooses, it is not expressed in the notation. Row 4 therefore represents an interpretation. Rows zero through three, on the other hand, are unambiguously expressed by the notation.
Comment: @phoog the second notated bar here is the first full bar, so is seen as the first in a group of 4 (or could be 2, or 8) bars. As such, it is a "strong beat of level three" (according to the parlance of the OP's linked text) and *is* weighted more strongly than the first beat of the third notated bar, which is a 'weak beat of level three'. From the text: "a beat of L is strong if it is also the beat of a larger metrical level' (level four here).
Comment: @topomorto I am trying to say that the beat with the b in the melody should be stronger than the beat with the d. This is in keeping with the concept of end weight, and with the structure of the piece starting on a weak beat. In other words, I think that the linked text has interpreted the metrical structure incorrectly.
Comment: @phoog aha - I was more just commenting that (as pictured) the two aren't to be seen as equally 'weighted' (if that's the right word).


What is the meaning of model selection and model assessement?

Question: I think in model selection one has to look for the best tuning parameter. But what is the tuning parameter? Is this the k in the k-fold cross validation? And is the model assessment just the estimation of the expected test mean squared error?
Answer: The tuning parameters are ones that cannot be estimated from fitting and it kind of control how your model behaves. Every model would have its own set of tuning paratmers and usually packages would provide a list of these, for example scikit-learn and caret.
For example, let's take k nearest neighbour. When you train a knn model, you need to define k, and you predict the value of an observation based on either the label or mean of its k nearest neighbors. The question is which k to use to make this effective? This is a tuning parameter. But if we go to another model, for example ridge regression, then the question becomes how to penalize large / many coefficients and for this we set lambda (or shrinkage penalty, see for a guided example).
From the two examples above, you can see it is not the k in k-fold cross validation. The k in fold cross validation refers to how many folds of cross validation to perform, and this is something you decide when training the model, to find the optimal parameters, as briefly discussed above.
For regression machine learning RMSE is commonly used, but you can also use R square, Mean square error (MSE), Mean absolute error (MAE)


Matched cox proportional hazard models

Question: I have a dataset in which we follow a cohort of healthy individuals at recruitment, and when an individual experiences the event we assign four matched controls to it by age, sex, and recruitment center (this is how the study was designed, I have no control over it). I'm looking for biomarkers associated with the outcome. This is all the information I have.
My advisor who seems to think that we can't do a survival analysis because when a case is identified both the case and the matched controls are censored at the time of matching even though the controls are still in the study.
Is this right? in my opinion, his assumption is not correct.
I understand there may be biases, but please focus on whether or not the cases and controls are really both censored at the time of matching.
Thanks
Comment: Some types of case-control studies can introduce bias, so please say more about the design and purpose of the study. Are you, for example, looking for a relationship between some biomarker and outcome? Are cases defined by their having had an event, or by some status at entry into the study? Why are the matching criteria limited to age, sex, and center and not including other characteristics potentially related to outcome? Is there some risk of a survivorship bias in identifying controls? The more details you can provide the better a response can be.
Comment: I've tried to address as much as possible but is the idea of censoring both cases and controls at the time the case experiences the event true?
Answer: Quoting from Leung et al, Annual Review of Public Health 18: 83-104, 1997:

Censoring occurs when incomplete information is available about the survival time of some individuals.

So ask yourself: what does survival time mean in this study, and is that information incomplete about some individuals?
If survival time is being defined for an individual as the time between recruitment into the study and the time of an event, then any case (defined in your study as having had an event) clearly has complete information about survival time and should not be considered censored.
It's possible, however, for a study to be interested in some starting time for survival before recruitment into the study. For example, Therneau and Grambsch (page 75) describe a study at a tertiary referral center, for which survival was calculated from the date of original diagnosis. If an individual's diagnosis was made elsewhere before entry into the study at the referral center, then that individual was not at risk for an observable death until entry into the study, and the survival time would be considered left truncated at the time of study entry. If survival time is calculated from some unknown time before study entry, the survival time is left censored. This paper describes some of the issues that arise in these cases.
Whether controls are considered censored depends on their follow-up. Provided that survival time is calculated from study-entry date (putting aside the possibility of left censoring or truncation), if any control individual is followed until the time of an event, then that individual's survival time is by definition not censored. If the event hasn't happened by the time of last follow-up for some individual, then that individual's survival time is right censored at the last follow-up time. So if you do an early analysis of the data most or all controls might have right-censored survival times, but at later analysis times (assuming follow-up continues) some of those might have defined event times.

Matched cox proportional hazard models


How Can i pass js value to sql

Question: function muIo($val){
    var val = $val;

    <?php $result = mysql_query("UPDATE category SET category_active=1 WHERE category_id=" +  val + "");?>

}

Comment: Please don't use the `mysql_*` function library, it is deprecated. Use `mysqli_*` and query parameters to avoid SQL injection attacks. http://php.net/manual/en/book.mysqli.php
Comment: thank you about your advice, i will work on it
Answer: You have to make a POST request to the server where PHP will then grab that value.
PHP and MySQL are server side while JS is client side.
Check these questions out:
send data to MySQL with AJAX + jQuery + PHP
Javascript function post and call php script
Comment: sorry i didn't get it. can you send me some exmple?
Answer: Javascript is client side. In order to run PHP and execute SQL Queries you need to have this code on your server setup.
Once you have this server script set up, in order to pass javascript values to this script you need to send a POST or GET request to PHP.
A simple way to do this for a beginner would probably be to use JQuery to use their simple POST functionality.
See Here

How Can i pass js value to sql


Syntax Error: "]," invalid syntax - Dash Graph Building

Question: I am new to Dash and I have to build a web application where I print some data read from a microphone and an accelerometer.
Now I am trying to understand how to setup various graph and information. I am following the example given in the Dash User guide.
The error is at line 23 that is the line where I set data and layout. It seems he doesn't like the ], but honestly I don't know how I can fix it.
import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__,external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''Dash: A web application framework for Python.'''),

    dcc.Graph(id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name':
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name':
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Syntax Error:
File "app.py", line 23
],
^
SyntaxError: invalid syntax

Why is it giving this kind of error?
P.s.: User guide (first example) -> https://dash.plot.ly/getting-started
Comment: your `'data'` element are missing closing curly braces`'}'` have you copied and pasted incorrectly here? there is no value for `'name'` for both your rows unlike in the linked example
Comment: That's still invalid, you've added a key `'name'` with no value, look carefully at the example in the link
Comment: U mean to do like this:
data:[
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name':}
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name':}], ?? Because now it doesen't like the { at the beginning and yes i copied the code correctly
Comment: Also, what is the value for 'name'  in both lines?
Comment: Not dash-specific, this problem is just a regular Python syntax error; you'd get the same error just taking the `{` from `figure={` up to the closing `}` and evaluating it in any Python repl.
Comment: Thanks to all. I've fix it.
I am sorry for the stupid question but i come from C world and all that stuff are useless.. Thanks !!! :)
Comment: No problem @Giulio, Happy to help :)
Answer: Try this:
import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__,external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''Dash: A web application framework for Python.'''),

    dcc.Graph(id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name':'a'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name':'b'}
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Output
Running on http://127.0.0.1:8050/
Debugger PIN: 201-392-957
 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
Running on http://127.0.0.1:8050/
Debugger PIN: 906-971-228


Add header to Google Cloud Endpoint in Android

Question: I have the following approach for getting instance of my endpoint. I want to add a header to it. How do I do that? Please modify my code following, to include the header bit. Thanks.
<code>public class RemoteServiceEndpointReference {
    private static final boolean USING_LOCAL_SERVER = false;
    private static final String LOCAL_SERVER_PATH = "…";

    private static RemoteService service;

    public static RemoteService getRemoteServiceEndpoint() {
        if (null != service) {
            return service;
        }

        RemoteService.Builder builder = new RemoteService.Builder(
                AndroidHttp.newCompatibleTransport(),
                new AndroidJsonFactory(),
                null
        );
        forLocalServer(builder);
        service = builder.build();
        return service;
    }

    private static void forLocalServer(AbstractGoogleJsonClient.Builder builder) {
        if (USING_LOCAL_SERVER) {
            builder.setRootUrl(LOCAL_SERVER_PATH)
                   .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                       @Override
                       public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
                           request.setDisableGZipContent(true);
                       }
                   });
        }
    }
}
</code>
Answer: You should be able to do something like this:
<code>@Override
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
    HttpHeaders yourHeaders = new HttpHeaders();
    header.set("yourHeader", value);
    // ...

    request.setDisableGZipContent(true);
    request.setRequestHeaders(yourHeaders); // setting the headers
}
</code>


How to make td tags move when clicked to available cells?

Question: This is my current table:

Each cell can only move if it has a white cell next to it, and proceed to switch positions with that white cell. (I'm trying to do the Parking Lot puzzle game).
I'm not sure if using a table is the right choice, is there an easier way to do this?
Here is what I have so far:

Comment: I wouldn't use a table. I would use canvas
Answer: With using tables, this will get messy very fast. This is because, like you illustrated, will have to make use of the colspan and rowspan properties, and these properties will have to change for multiple cells at the same time with some complex logic. Also, possibly animations of the cells switching are a bit harder too. Therefore, this method of using tables is not recommended.
Possible other solutions would be the use of div's with absolute positioning, or even better the use of a canvas.


Criar coluna baseada em outro dataframe

Question: Boa noite!
Tenho dois dataframes ex8_alunos e ex8_cursos
ex8_alunos

ex8_cursos

Eu gostaria de criar uma coluna no ex8_alunos chamada CO_UF
Para alimentar essa coluna eu precisaria cruzar os dados dos dois dataframes citados acima
No ex8_cursos usar o CO_IES e o CO_UF para criar no ex8_alunos a coluna CO_UF e com os respectivos Códigos do UF de cada faculdade.
Eu tentei o seguinte método, sem resultado:
ex8_alunos['CO_UF'] = 0
for i in range (0, ex8_alunos.shape[0]):
    if ex8_alunos.at[i, "CO_IES"] == ex8_cursos["CO_IES"]:
        ex8_alunos['CO_UF'] = ex8_alunos['CO_UF'].append(ex8_cursos["CO_IES"].loc[[i]])

Alguém pode me ajudar?
Desde já agradeço!
Comment: pode disponibilizar os dados ou fazer um MWE?
Comment: Estou providenciando!
Comment: Isto responde à sua pergunta? [Pegar valores de uma coluna de um dataframe e criar uma coluna em outro com os valores correspondentes](https://pt.stackoverflow.com/questions/435498/pegar-valores-de-uma-coluna-de-um-dataframe-e-criar-uma-coluna-em-outro-com-os-v)
Comment: [ex8_alunos](https://drive.google.com/file/d/16qLPsPlefqi12bJzV6FR0GIRdtMsjNxo/view?usp=sharing)
[ex8_cursos](https://drive.google.com/file/d/1vxzdmL5Srjc8WICEOKXBI43O4IHR78ul/view?usp=sharing)
Comment: `ex8_alunos['CO_UF'] = 0`
`ex8_alunos['CO_UF'] = ex8_alunos.merge(ex8_cursos, on='CO_UF', how='left')`
Não deu certo
Answer: A solução é fazer o merge de forma diferente do que está no comentário
Segue exemplo:
Criando Dataframes Testes
>>> import pandas as pd
>>> df1 = pd.DataFrame({"A": [1, 2, 2, 3, 4, 3, 3, 2, 1, 5]})
>>> df2 = pd.DataFrame({"B": [1, 2, 3, 4, 5], "C": ["a", "b", "c", "d", "e"]})

O conteúdo dos dataframes:
>>> df1
   A
0  1
1  2
2  2
3  3
4  4
5  3
6  3
7  2
8  1
9  5

>>> df2
   B  C
0  1  a
1  2  b
2  3  c
3  4  d
4  5  e

Fazendo o merge
>>> df3 = pd.merge(df1, df2, left_on='A', right_on='B')

Conteúdo de df3
>>> df3
   A  B  C
0  1  1  a
1  1  1  a
2  2  2  b
3  2  2  b
4  2  2  b
5  3  3  c
6  3  3  c
7  3  3  c
8  4  4  d
9  5  5  e

Para maiores detalhes veja a documentação

Criar coluna baseada em outro dataframe


Field filter in Views, filter by TID, not name

Question: I have a content type, books, with a field Category, based on a taxonomy.
I have a View of books, and can filter by author, date, and also by field category.
Everything works right, but when I try to add several subcategories (nested taxonomy), I have the problem that I cannot let the filter exactly as it is, as I can have two family names exactly equal, namely "offers". For example:
<code> http://www.example.com/books/science/offers
 http://www.example.com/books/sports/offers
</code>
As I am using arg(3) for retrieving "offers", I have the same name for two different taxonomies with different tid's.
How can I alter the SQL in ´MYMODULE_views_pre_view´ so I can filter by tid instead of name? I can programmaticaly get the tid from the URL and inject it directly into the SQL, but don't know how to alter this SQL accordingly.
Comment: Add contextual filter of  Has taxonomy term ID >> select provide default value >> select Taxonomy ID from url.
Answer: @no-sssweat' answer is what you want as long as views can figure out the right tid from the url.  In cases where it can't but you know how to, you can do an argument replacement in a custom module.  Here is some code I have that is doing that:
<code>/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    $views_to_process = array(
        'view_name1' => array(
            'display_name1',
            'display_name2',
            'display_name3',
        ),
        'view_name2' => array(
            'display_name1',
        )
    );
    if (!in_array($view->name, array_keys($views_to_process))) { return; }
    if (!in_array($view->current_display, $views_to_process[$view->name])) { return; }
    if (!empty($args[0]) && !_MYMODULE_isInteger($args[0])) {
        $tid = _MYMODULE_get_tid_for_top_level_term($args[0], 'area');
        if ($tid) {
            $args[0] = $tid;
        }
    }

}

/**
 * Helper function to determine whether a value is an integer or not.
 *
 * Sourced from http://php.net/manual/en/function.is-int.php#82857
 */
function _MYMODULE_isInteger($input){
    return(ctype_digit(strval($input)));
}
</code>
The `$views_to_process is a tree of views and displays that this should be applied to and the first two ifs just ignore this hook if the display isn't in $views_to_process.  I then check to make sure there is an argument of some kind in place and that it isn't already an integer (helper function included for that), and then it loads a tid based on the current argument.  It then replaces that argument with the tid.  If you replaced _MYMODULE_get_tid_for_top_level_term with your helper function for loading up the tid, you can then use the tid as a contextual filter value.  I hope that helps!
note: I currently have a question open on that very view, and while I don't think this solution has anything to do with the issue I'm having, there is a chance.


Can we override Drupal includes files?

Question: I want to modify the menu.inc file that is in the Drupal "includes" folder, but I want to create an overriding file for it, so that we can easily package only our custom theme.
Comment: There's no in-built mechanism to override a whole system file, no. Drupal has a hook system that allows you to alter pretty much anything...what exactly do you need to change?
Answer: Generally Clive is right. Don't touch core. But sometimes you are forced to do a core patch or it's just much easier to solve your requirements.
If you must: I'd recommend to put your whole project into git. This gives you the possibility to have a clean core version in one branch and the patched one in an other. Everytime a new core version is published you can merge it in a clean way.

Can we override Drupal includes files?


SQL code to project how many clients will reach age 55 each month for a year

Question: I am trying to get the number of clients who are currently >= age 55, which I've managed, but next I want to find out how many people will be >= 55 in a month's time, then in 2 month's time etc up to 12 months.
Here is what I have so far, but I'm not sure how to go about the next bit. Any help greatly appreciated! Thanks.
SELECT
    SUM(CASE
        WHEN [C].[BirthDate] > dateadd(year, -54, getdate()) AND [E].[MfChk4] = '0'
        THEN 0
        ELSE 1
    END) AS [Age Eligible]
FROM
    [dbo].[CR_Entity] [E]
    LEFT OUTER JOIN [dbo].[CR_RefMaster] [RM]
        ON  [RM].[EntCode] = [E].[EntClient]
        AND [RM].[Status] = '0'
    LEFT OUTER JOIN [dbo].[Compliance] [C]
        ON  [C].[AddrCode] = [RM].[RefCode]

The result I want for the next bit will be something like...
Answer: You would have to write multiple case statements like:
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+1, getdate())
    AND [E].[MfChk4] = '0'
             THEN 0 ELSE 1 END) AS Month1,
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+2, getdate())
    AND [E].[MfChk4] = '0'
             THEN 0 ELSE 1 END) AS Month2,
.
.
.
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+12, getdate())
    AND [E].[MfChk4] = '0'
             THEN 0 ELSE 1 END) AS Month12

Comment: Yay that worked, thanks!  Probably a stupid question but is there any way to get the alias to show the actual month? Can you make the alias effectively (dateadd(month,1,getdate()) so the column names are Feb-20, Mar-20 etc?
Comment: Case _expressions_.
Answer: To create the Naming convention you are looking, for you would have to use Dynamic SQL. You might have to change the query a bit, but the basics of it is:
--Declaring and calculating the Column Names

declare @test1 nvarchar(max),
        @test2 nvarchar(max),
        @test12 nvarchar(max)
set @test1='['+CAST(FORMAT(DATEADD(month,1,GETDATE()),'MMM-yy') as Varchar(20))+']'
set @test2='['+CAST(FORMAT(DATEADD(month,2,GETDATE()),'MMM-yy') as Varchar(20))+']'
.
.
.
set @test12='['+CAST(FORMAT(DATEADD(month,12,GETDATE()),'MMM-yy') as Varchar(20))+']'

--Writing the Dynamic Sql text

DECLARE @sql nvarchar(max)
SELECT @sql = N'SELECT SUM (CASE WHEN [C].[BirthDate] > dateadd(year, -54, getdate())
    AND [E].[MfChk4] = ''0''
             THEN 0 ELSE 1 END) AS [Age Eligible],
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+1, getdate())
    AND [E].[MfChk4] = ''0''
             THEN 0 ELSE 1 END) AS' + @test1 + ',
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+2, getdate())
    AND [E].[MfChk4] = ''0''
             THEN 0 ELSE 1 END) AS' + @test2 + ',
.
.
.
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+12, getdate())
    AND [E].[MfChk4] = ''0''
             THEN 0 ELSE 1 END) AS' + @test12 + '
FROM [dbo].[CR_Entity] [E]
    LEFT OUTER JOIN [dbo].[CR_RefMaster] [RM] ON [RM].[EntCode] = [E].[EntClient] AND [RM].[Status] = ''0''
    LEFT OUTER JOIN [dbo].[Compliance] [C] ON [C].[AddrCode] = [RM].[RefCode]'

--Executing the Dynamic Sql query

EXEC sp_executesql @sql

You might want to start with one case statement to understand how it works and then implement it for the entire data.
Comment: Thanks so much, really helpful


Can I use linear regression to find the strongest predictor?

Question: I have 3 different techniques for measuring an effect, which is my independent variable. The value produced by each technique is different. Thus I want to find out which one of these 3 techniques is the strongest predictor of my dependent variable.
Can I use multiple linear regression to find this out? If so, what does the $R^2$ value in this case mean?
As I understand, if I use multiple linear regression in the form
Predictor = Constant + Beta1*Technique1 Beta2*Technique2+Beta3*Technique3 + error
the $R^2$ value indicates the variance explained by all the three variables. However, I have only one variable, which in this case has been measured in 3 different ways.
Comment: +1 and welcome to Cross Validated! Is your goal to assess which model gets the tightest fit to your data? What kind of independent variable do you have? There are a bunch of ways to make this assessment, depending on what your independent variable is and what you value in a prediction (such as missing high being much worse than missing low).
Comment: There will always be an apparently strongest predictor.   The question is do the data have enough information to be confident in the "winner".  A method that fully exposes the difficulty of the task, especially when there are collinearities among $X$s, is to bootstrap th ranks of predictor importance (partial $R^2$ or any other measure you choose).  An example is given here: https://hbiostat.org/rmsc/validate.html#sec-val-bootrank
Comment: What do you mean by stronger predictor? Can you give an example of the 3 techniques? If it's about which one seems to have the most important effect, you could just compare betas of your linear regression after standardizing your variables.
Answer: What do you mean by stronger predictor? Can you give an example of the 3 techniques? If it's about which one seems to have the most important effect, you could just compare betas of your linear regression after standardizing your variables.
Comment: *Pace* the flag, this post *does* constitute an answer: it proposes using standardized parameter estimates. (Whether that's good or appropriate is another matter, but that's also indicated in the first line of this answer.)
Comment: @whuber I see this more as a comment than an answer, since it starts asking for clarification, but maybe you are right.
Comment: @utobi Yes, it's on the borderline and would benefit from some elaboration.  However, I think we should favor keeping answers up in such cases rather than deleting them.


Estimating IRT item parameters when ability and response are know

Question: I have 500,000 students dichotomy responses for a 45 item test. I know the ability of the this students, that this ability was calculated from this responses  using 3PL model by Expected a Posteriori (EAP) and I know the prior mean and standard deviation used. Having this information it's possible in R to know or at least get a approximation of the 3 parameters of each items that were used to calculated the students ability?
I am not interested in recalculating the value of the parameters, but rather to know the values of the parameters used by those who prepared the test.
Answer: I don't think there is an easy way to calculate them. You can only estimate them.
Assuming that the $\theta$ is known, you can write a function to optimize the loglikelihood function for a given response vector of each item.


Como validar um campo que depende de outro para ser obrigatório no Symfony?

Question: No Laravel existe uma validação required_if, nela eu digo que um campo vai ser obrigatório somente se outro campo for informado. Preciso fazer o mesmo tipo de validação utilizando o FormType do Symfony mas não encontrei nada na documentação que funcione parecido. Eu consigo validar isso no Controller mas queria deixar essa responsabilidade para o meu FormType já que todas as outras validações estão nele.
Alguém já fez algo parecido no Symfony que possa me ajudar?

Versão do Symfony: 3.4
Answer: Encontrei a resposta no stackoverflow em inglês.
Segue o link para a resposta: https://stackoverflow.com/questions/30206854/conditional-validation-of-fields-based-on-other-field-value-in-symfony2


Dealing with pointers that may not point to anything

Question: I have a set of objects in a vector of pointers to their baseclass held inside a manager:
std::vector<object*> objectVec;

Classes may wish to spawn one of these objects using the Add() method in the manager. The problem is that they then subsequently need to set or update these objects themselves. I've decided to have Add() return a pointer to the object itself, which is stored in whatever class has decided to spawn one. The problem is dealing with the case where the object behind that pointer may have been deleted.
Add looks like this:
object* ObjectManager::Add(object* obj)
{
   objectVec.push_back(obj);
   return objectVec.back();
}

and used like this:
objectptr = ObjectManager::OMan()->Add(new object());

Where objectptr is a member of whatever class has called the function. So should that particular object be deleted, the pointer returned by Add would point to rubbish.
Is it my responsibility to ensure that whateverclass::objectptr is always set to NULL if this object is deleted? Or can this be dealt with using some sort of smart pointer? The problem being that I don't need to use a smart pointer to deal with the possibility of a memory leak, but to deal with the case where the stored pointer has become invalid.
Please let me know if i've been unclear, or if the question is badly formed.
Any help would be greatly appreciated.
Comment: You might want to revise your design altogether. You shouldn't need neither base class for all objects nor any manager thingy for them. Especially if it's going to be a singleton. Also use pointers when you absolutely need them, and cannot do with values and references.
Comment: The baseclass is in this case specifically for a type of object that has subtypes (lights), i've just generalised it to an object class for the question. My problem is needing access an object stored in a manager for setting values quickly, which rules out iterating through a vector until I find it by ID. I am entirely open to other suggestions!
Comment: @jgf: Other suggestions include "pointing to the desired object directly".  Isn't dereferencing a pointer the fastest look-up operation?
Answer: Yes, you can store smart ptr's instead of raw ptr's in your vector. In this case if somebody releases an object, it's not deleted until the last reference is not released (the one held in vector in your case). You can use boost::shared_ptr or std::shared_ptr (C++11).
If this is not what you want, you can use boost::weak_ptr to store references in your vector. weak_ptr doesn't increment reference counter so if somebody releases an object, it's get deleted, but reference (weak_ptr) stored in your vector allows you to check this.
Answer: You likely want weak_ptr and shared_ptr. shared_ptr is a general smart pointer class.  weak_ptr is an observer of shared_ptr.  When all the references of the shared_ptr go away, instances of weak_ptr "become null" and are easier to deal with than a pointer to a deleted object.
These classes come with Boost.
http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm
http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/weak_ptr.htm
And if I'm not mistaken, there are equivalents built into std namespace on compilers that implement newer C++0x standards.  Visual C++ keeps has this built in.
http://blogs.msdn.com/b/vcblog/archive/2011/02/16/10128357.aspx
Oh shoot, looks like everyone else beat me to the answer...
Comment: A weak_ptr observing shared_ptrs is exactly what i'm looking for. Thanks.
Answer: Best is to forget this "manager" idea, but if you do or if you don't, the solution to shared ownership is the same as always, use boost::shared_ptr.
Or, with relatively new compiler, use std::shared_ptr.
Considering that with shared_ptr the ownership issue is taken care of already, then ask yourself, what is it that the "manager" manages?
Cheers & hth.,
Comment: @jgf: don't forget this "central" object manager idea is just a fancy way of organizing (or a fancy syntax for) global variables.  Global state always makes it harder to test applications and verify correctness, as functions relying on that state yield different results at different times.  Global variables are never *really* convenient.  They just *seem* so at first.
Comment: In this case, it's Lights - which needs to be drawn to a specific buffer, and with specific blending settings - so it's convenient for them to be centralised.
Comment: I'm intending to completely rewrite this program after i've had an attempt at implementing the various features i'm after, as i've read similar things to what you've mentioned, so the question was generalised a bit, as really i'm just after the best way to deal with dangling pointers that need to be set to NULL!
Comment: @jgf: in this case, the need to set pointers to `0` is a symptom of your design, hence Alf's recommendation.  The structure of your application causes you to allocate memory using `new` and manage pointers although it can probably avoid it.  Consider writing a proper copy constructor for your `Light` class and storing the different "light" instances as `std::vector`.
Answer:
Is it my responsibility to ensure that whateverclass::objectptr is always set to NULL if this object is deleted?

You're writing the class, so it's up to you to decide.  This is a design decision and either choice is admissible, provided that you document it:

design the application
write the documentation/specification
write the code to matches the specification

Or can this be dealt with using some sort of smart pointer?

Using a smart pointer (strong or weak version) will help achieve whatever behavior you chose for the class.  However, it will also strongly affect the client code.  In the following code:
class Scene
{
      // can't use this object in a call to `ObjectManager::Add()`,
      // assuming it uses a smart pointer to deal with object lifetimes.
    Object myLight;
};

The use cases for the ObjectManager class should be taken into consideration, on top of simplicity of implementation.  Think "write once, use a lot".
Answer: Dangling pointers and memory leaks are two different issues, but a proper shared pointer can protect from both.  For this particular case, I'd suggest boost::shared_ptr.
Use std::vector<boost::shared_ptr<BaseType>> for the vector type and also have the objects that hold the bare pointers now hold instead a boost::shared_ptr<BaseType>.  This will ensure that the pointers will stay valid in the vector and in the objects as long as one of those objects still exist.
If you have differing requirements, you can use a boost::weak_ptr in one of the places holding the pointer (either the vector or the object).
Also, the object can hold a derived type instead of a base type (boost::shared_ptr<DerivedType>) and you can convert between them using boost::shared_static_cast.
Here is the documentation for all of these concepts.
Comment: Hit the enter key a little early?
Comment: My proxy flaked out, and when it came back only part of my answer was saved :(


Automatically reload cached objects after varnish xkey.softpurge()

Question: I need to automatically refresh/fetch again objects I invalidated with xkey.softpurge() so that varnish always has a cached version in memory. How is this possible?
I am doing a restart in vcl_purge but this does not seem to be executed when doing an xkey purge.
sub vcl_purge {
    set req.method = "GET";
    return(restart);
}

Answer: A single xkey (soft)purge operation will quick from the storage an undefined number of objets. It's not possible to trigger threads to refresh each kicked object.
This is similar to normal purges, but usually purging a URL kicks a single object from the storage. That's why the restart works as expected. In any case, a single purge could kick multiple objects (e.g. Vary responses) and the restart will only refresh one of the variants.


Subsequences and convergence. Do all subsequences have to converge to the same limit for the sequence to be convergent?

Question: I was asked this question:
Prove that $a_n$ converges if and only if:
$a_{2n},a_{2n+1},a_{3n}$ all converge
I thought this was an easy generic question until I read the hint which said:
Note: It is not required that the three sub-sequences have the same limit. This needs to be shown
This is what is confusing me because I have found two sources stating something different:
Proposition 4.2. A sequence an converges to L ∈ R if and only if every subsequence converges to L.
and
Let $a_n$ be a real sequence. If the subsequence $a_{2n}$ converges to a real number L and the subsequence $a_{2n+1}$ converges to the same number L, then $a_n$ converges to L as well.
So my question is: for a sequence $a_n$ to converge does it's subsequences have to converge to the same limit? (I suspect not) and if the answer is no can you help me prove why?
Thanks in advance
Comment: If a sequence converges its subsequences must converge to the same limit. This follows directly from the definition of the limit of a sequence.
Answer: If a sequence has two subsequences that do not both converge to the same limit, then the sequence does not converge.

This can be proven using the $\epsilon-\delta$ definition of convergence:

Let $a_n$ converge to $L$, and let $\{a_{n_k}\}_{k\to\infty}$  be a subsequence of $a_n$.
Let $\epsilon > 0$.
Then, because $a_n$ converges to $L$, there exists some $N$ such that if $n>N$, then $|a_n - L|<\epsilon$.
Because $n_k$ is an increasing sequence of integers (by definition of a subsequence), there exists such $K$ that $n_K > N$.
Then, if $k > K$, we have $n_k > n_K > N$, and from the previous point, we get that $|a_{n_k} - L|<\epsilon$, meaning that $a_{n_k}$ converges to $L$.

However, your case is special in that there is an overlap of sequences, for example $a_6$ is in the first and third sequence, and $a_9$ is in the second and third sequence. In fact, the third sequence alternates between the first two sequences, and you can use this to prove all three limits must be equal.
Comment: Ok so for $a_{2n}$ and $a_{2n+1}$ I can say we are either in the odd or the even case and then $a_{3n}$ goes between the two cases.
Comment: @babylon Yup. And that, forces the sequences to converge to the same number. Then you need to prove that the whole sequence also converges to the same number.
Answer: I think the word "required" in the hint is confusing. Focus instead on the last sentence:

Note: It is not required that the three sub-sequences have the same limit. This needs to be shown

In other words, you need to show that as a result of the given hypotheses, the three sub-sequences do have the same limit. You need to do that precisely because it is a necessary condition for $a_n$ to converge.


C++ Arabic numbers to Roman Numeral's & vice versa

Question: I am writing a C++ program that converts between Arabic and Roman numbering systems. I wrote one program that converts Arabic to Roman and have another program that converts Roman to Arabic.
The problem is that I can't figure out how to merge them into one single program so that the user can input an Arabic or Roman number and as a result, the program would convert said number to the other.
My question is HOW can I merge these two programs into one?
Code for Roman to Arabic
#include <iostream>
using namespace std;
int main()
{
    char roman_Numeral;
    int arabic_Numeral = 0;

    cout << "Enter the Roman Numeral in Capital letters (e.g. CCXIX) : ";
    while (cin.get(roman_Numeral))
    {

        if (arabic_Numeral > 100)
        {
            cout << "\nInvalid Value. Number must be  between I and C" << endl;
            return 0;
        }

        else if (roman_Numeral == 'C')
        {
            roman_Numeral = cin.peek();
            if (roman_Numeral == 'M' || roman_Numeral == 'D')
            {
                arabic_Numeral = arabic_Numeral - 100;
            }
            else
            {
                arabic_Numeral = arabic_Numeral + 100;
            }

        }

        else if (roman_Numeral == 'L')
        {
            roman_Numeral = cin.peek();
            if (roman_Numeral == 'M' || roman_Numeral == 'D'
                    || roman_Numeral == 'C')
            {
                arabic_Numeral = arabic_Numeral - 50;
                continue;
            }
            else
            {
                arabic_Numeral = arabic_Numeral + 50;
                continue;
            }
        }

        else if (roman_Numeral == 'X')
        {
            roman_Numeral = cin.peek();
            if (roman_Numeral == 'M' || roman_Numeral == 'D'
                    || roman_Numeral == 'C' || roman_Numeral == 'L')
            {
                arabic_Numeral = arabic_Numeral - 10;
                continue;
            }
            else
            {
                arabic_Numeral = arabic_Numeral + 10;
                continue;
            }
        }

        else if (roman_Numeral == 'V')
        {
            roman_Numeral = cin.peek();
            if (roman_Numeral == 'M' || roman_Numeral == 'D'
                    || roman_Numeral == 'C' || roman_Numeral == 'L'
                    || roman_Numeral == 'X')
            {
                arabic_Numeral = arabic_Numeral - 5;
                continue;
            }
            else
            {
                arabic_Numeral = arabic_Numeral + 5;
                continue;
            }
        }

        else if (roman_Numeral == 'I')
        {
            roman_Numeral = cin.peek();
            if (roman_Numeral == 'M' || roman_Numeral == 'D'
                    || roman_Numeral == 'C' || roman_Numeral == 'L'
                    || roman_Numeral == 'X' || roman_Numeral == 'V')
            {
                arabic_Numeral = arabic_Numeral - 1;
                continue;
            }
            else
            {
                arabic_Numeral = arabic_Numeral + 1;
                continue;
            }
        }

        else
            break;
    }
    cout << arabic_Numeral << endl;
    return 0;
}

Code for Arabic to Roman
#include <iostream>
#include <string>

#include <iomanip>
using namespace std;

#define MAX_INPUT 100 // These constants hold high and low integer numbers,
#define MIN_INPUT 1
#define ARRAY_SIZE 4   // and the array size declarator.

string convert(int digit, string low, string mid, string high);

int main()
{
    string answers[ARRAY_SIZE] = { "", "", "", "" }; //An  array of string to hold the output from the convert function.
    int accumulator = 0; // Variable to hold number of arabic numbers converted.
    int userNum = 0;
    string strUserNum;

    do
    {
        cout << "";
        cout << "Enter an arabic number between 1 and 100: ";
        cin >> strUserNum;

        userNum = std::stoi(strUserNum);

        if (userNum == 0 || userNum > MAX_INPUT)
        {
            cout << "\nInvalid Value. Number must be between 1 and 100" << endl;
            return 0;
        }
        else if (userNum == 'end')
        {
            cout << "Exiting program:";
            break;
        }

        int thous = userNum / 1000;

        int hund = userNum % 1000 / 100;

        int tens = userNum % 100 / 10;

        int ones = userNum % 10 / 1;

        answers[0] = convert(thous, "M", "M", "M");
        answers[1] = convert(hund, "C", "D", "M");

        answers[2] = convert(tens, "X", "L", "C");
        answers[3] = convert(ones, "I", "V", "X");

        cout << answers[0] << answers[1] << answers[2];
        cout << answers[3] << endl;
        cout << endl;
        break;

    } while (userNum != 'end');

    system("PAUSE");
    return 0;

}
string convert(int digit, string low, string mid, string high)
{

    if (digit == 1)
    {
        return low;
    }
    if (digit == 2)
    {
        return low + low;
    }
    if (digit == 3)
    {
        return low + low + low;
    }
    if (digit == 4)
    {
        return low + mid;
    }
    if (digit == 5)
    {
        return mid;
    }
    if (digit == 6)
    {
        return mid + low;
    }
    if (digit == 7)
    {
        return mid + low + low;
    }
    if (digit == 8)
    {
        return mid + low + low + low;
    }
    if (digit == 9)
    {
        return low + high;
    }
    if (digit == 0)
    {
        return "";
    }
}

Comment: Merge them by creating two functions. One to do arabic_to_roman() and the other to do roman_to_arabic(), then call either of the functions from `main` as needed.
Comment: What is your question?
Comment: @JesperJuhl I have included the code
Comment: Do these programs work?  I'm concerned about `while (userNum != 'end')`, given that `userNum` is an `int`.
Comment: Show us your code and ask a specific question.
Comment: @DrewDormann My question is how can I merge these two programs into one single working program
Comment: @DrewDormann yes both programs work
Comment: Try this tactic: 1. Detect which conversion the user wants, roman-to-arabic or arabic-to-roman. 2. Run the desired conversion. It would be natural and straightforward to express each conversion as a separate function. It is desirable to have conversion functions that can detect invalid input and report the failure, in which case the tactic could be slightly different: 1. read the input. 2. try conversion one. if successful, output the result; otherwise, try conversion two and print the result (or an error message).
Answer: Put code (that inside the main block) for Roman to Arabic into void procedureRomanToArabic()
The same for Roman to Arabic. Put it into void procedureArabicToRoman().
Remove remove ArabicToRoman do-while and move it to main.
void procedureRomanToArabic(){
    char roman_Numeral;
    int arabic_Numeral = 0;

    //...

    cout << arabic_Numeral << endl;
}

void procedureArabicToRoman()
{
    string answers[ARRAY_SIZE] = { "", "", "", "" }; //An  array of string to hold the output from the convert function.
    int accumulator = 0; // Variable to hold number of arabic numbers converted.
    int userNum = 0;
    string strUserNum;

    //remove do while here
    cout << "";
    cout << "Enter an arabic number between 1 and 100: ";
    cin >> strUserNum;

    //...

    answers[2] = convert(tens, "X", "L", "C");
    answers[3] = convert(ones, "I", "V", "X");

    cout << answers[0] << answers[1] << answers[2];
    cout << answers[3] << endl;
    cout << endl;
}

int main(){
  char type;
  do{

    cout<<"2 for Arabic to Roman, 1 for Roman to Arabic, or anything else for exit";
    cin>>type;
    if(type=='1')
        procedureArabicToRoman();
    else if(type =='2')
        procedureRomanToArabic();
    else break; //end program
  } while(true);

}


Synths as Audio Sound interface

Question: I have an Analog Four MK1 connected directly to the computer and to the speakers and used as an Audio Interface in Ableton.
I will get now an Elektron Analog Rytm MKII. and I wonder if I can play both or I should add an Audio Interface like Focusrite Scarlett 2i2 (2nd Gen)
Answer: When you route the audio already through the computer this should be easy with OB2.
Or when you don't want to use OB2 yet, you can also connect the main outs of AR to the inputs of the A4 so you can mix it in.
You can route the rytm through the analog four inputs and do it that way. just turn on the volume (FX track + OSC1 /Ext In).

Synths as Audio Sound interface


ssl using php pn apache

Question: i want about ssl, and the request response between server and client. am developing in php on apache
How do i do ssl on localhost using php; curl?
How do i do it on a php enabled live server?.
thanks
Comment: You really need to explain what you mean if you want an answer.
Answer: Wikipedia knows how to do ssl and this is the first google hit for 'apache ssl'. More specific questions may lead to more specific answers.

ssl using php pn apache


Integrating exponential pdf for mgf

Question: I would like to integrate the following function but unfortunately I am  not getting to the right outcome
$$\int_0^{\infty} e^{tx}\frac 16\left(e ^{-\frac x2}+xe^{-\frac x2}\right)$$
Comment: what do we know about $t$?
Comment: What have you already tried to do?
Answer: Consider $h(t)=\int_{0}^{\infty}e^{tx}e^{-\frac{x}{2}}\mathrm{d}x$, then
$$
h(t)
=\int_{0}^{\infty}e^{-x\left(\frac{1}{2}-t\right)}\mathrm{d}x
=\frac{2}{1-2t}
$$
Now observe that
$\int_{0}^{\infty}xe^{tx}e^{-\frac{x}{2}}\mathrm{d}x=h'(t)=\frac{4}{(1-2t)^{2}}$
and so the integral you seek equals $\frac{1}{3}\left(\frac{1}{1-2t}+\frac{2}{(1-2t)^{2}}\right)$

Integrating exponential pdf for mgf


Custom content type and views field rendering

Question: I have a template views-view-fields--services.tpl.php
I don't want to iterate over the array of fields as I know which each of them are in this case.
I want to simply:

  <?php echo $row->title; ?>

  <?php echo $row->image; ?>

Doesn't appear to be a higher level template which might have this context of data???
UPDATED CODE SAMPLE:
views-view--services.tpl.php:

  <?php print $rows; ?>

views-view-unformatted--services.tpl.php:
<?php foreach ($rows as $id => $row): ?>
  <alex>
    <?php print $row; ?>
  </alex>
<?php endforeach; ?>

views-view-fields--services.tpl.php:
<?php foreach ($fields as $id => $field): ?>

  <?php /*print $field->class;*/ ?>
  <?php print $field->content; ?>

<?php endforeach; ?>

Results in:

    <alex>

    Entry #1

Briefly describe which problems we can help with.

  </alex>
  <alex>

    Entry #2

Quickly describe the services we offer or how our services can help?

  </alex>

Comment: Where is the markup between the  tags coming from??? I want just the raw field data in a per-row context so I can simply write my required markup and echo each field (custom fields but I know what they are
Comment: In your view you probably need to strip the html tags as they are rendered by default in the view.
Answer: Have a look at views-view-field.tpl.php. It' not used by default views, but available as a template override.
Edit: In views-view-fields.tpl.php you can also use $fields['my_field_name']->content; to access individual fields, but this will give you the fields default markup as well. The raw values can be accessed with $fields['my_field_name']->raw but those values must be proper sanitized before printing.
Comment: I've tried that but VIEWS are still producing markup?!?! I've update my post with templates and code
Comment: @Alex Did you see the slight difference? I'm not relating to [views-view-fields.tpl.php](https://api.drupal.org/api/views/theme!views-view-field.tpl.php/7)
Comment: I think I did but both fields and field are called once for each field...I want to use a template one step higher and basically output all 4 or five fields at once in the grid markup I have in place, if that makes any sense?
Comment: @Alex I have updated the answer, does this help now?
Comment: Yes it might...I dumped the $row variable in the context of views-view-field.tpl.php and this has all the info but if I can use $fields['name']->content thats even better :)