Phpmailer using own domain

Question: how i can use my email like firstname.lastname@example.com in phpmailer. because i always have an error even i have a correct credentials.
2020-05-14 09:21:24 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP e13sm1851788pfh.19 - gsmtp
2020-05-14 09:21:24 CLIENT -> SERVER: EHLO localhost
2020-05-14 09:21:24 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [188.8.131.52]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2020-05-14 09:21:25 CLIENT -> SERVER: AUTH LOGIN
2020-05-14 09:21:25 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2020-05-14 09:21:25 CLIENT -> SERVER: [credentials hidden]
2020-05-14 09:21:25 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2020-05-14 09:21:25 CLIENT -> SERVER: [credentials hidden]
2020-05-14 09:21:25 SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8  https://support.google.com/mail/?p=BadCredentials e13sm1851788pfh.19 - gsmtp
2020-05-14 09:21:25 SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8  https://support.google.com/mail/?p=BadCredentials e13sm1851788pfh.19 - gsmtp
SMTP Error: Could not authenticate.
2020-05-14 09:21:25 CLIENT -> SERVER: QUIT
2020-05-14 09:21:25 SERVER -> CLIENT: 221 2.0.0 closing connection e13sm1851788pfh.19 - gsmtp
SMTP Error: Could not authenticate.
this is my configuration:
<code>$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPAutoTLS = true;
$mail->Username = 'email@example.com';
$mail->Password = '';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
</code>
Comment: Is your domain set up to use gmail for email?
Comment: @Synchro my email domain was setup in GSuite.
Comment: In that case check out the gmail authentication issues covered in [the PHPMailer troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#gmail-oauth2-and-allow-less-secure-apps).
Answer: As per the logs that  I have read you need to turn your Less Secure Account On. Follow this steps below.
Help CenterCommunity
Setting up video conferencing for remote work? Set up Meet to help your team work remotely.
Control access to less secure apps
This article is for administrators. For actions users can take, go to Less secure apps & your Google Account.
You can block sign-in attempts from some apps or devices that are less secure. Apps that are less secure don't use modern security standards, such as OAuth. Using apps and devices that don't use modern security standards increases the risk of accounts being compromised. Blocking these apps and devices helps keep your users and data safe.
Examples of apps that don't support modern security standards include:
Native mail, contacts, and calendar sync applications on older versions of iOS and OSX
Some computer mail clients, such as older versions of Microsoft Outlook
Examples of apps that do support modern security standards are Gmail, Windows Mail, Office 365, Outlook for Mac, Instagram, PayPal, Amazon, Facebook, and Basecamp.
Transitioning to more secure app access to Google Accounts
Less secure apps can make it easier for hijackers to break into user accounts and devices. Blocking sign-ins from these apps helps keep accounts safe. For these reasons, Google is limiting password-based programmatic sign-ins to Google Accounts.
If you don't allow sign-ins from less secure apps
If you allow sign-ins from less secure apps
Notice of setting removal
Use alternatives to less secure apps
Manage access to less secure apps
You can allow users to turn on or off access by less secure apps or disable their ability to allow less secure apps.
Sign in to your Google Admin console.
Sign in using your administrator account (does not end in @gmail.com).
Go to the settings for Less secure apps:
From the Admin console Home page, go to Securityand thenLess secure apps.
To see Security on the Home page, you might have to click More controls at the bottom.
OR, if the "Less secure apps" option isn't visible:
From the Admin console Home page, go to Securityand thenBasic settings.
Then, under Less secure apps, click Go to settings for less secure apps.
Select the setting for less secure apps:
Disable access to less secure apps  (Recommended)
Users can't turn on access to less secure apps.
When you disable access to less secure apps while a less secure app has an open connection with a user account, the app will time out when it tries to refresh the connection. Timeout periods vary per app.
Allow users to manage their access to less secure apps
Users can turn on or turn off access to less secure apps.

Phpmailer using own domain


Odds ratio for continuous variable

Question: I have a question

How would you interpret the odds ratios for a continuous variable?
Comment: It might help if you clarified the context. It seems like you're talking about a continuous predictor in logistic regression (as I've assumed in the answer below) but more information would be helpful. I have the same comment regarding your interaction question - http://stats.stackexchange.com/questions/22036/interaction-terms-interpretation
Answer: It's not completely clear from your question, but I'm assuming you're talking about the situation where you have a single binary response $Y$ and a continuous predictor $X$ and fit a logistic regression model:
$$ \log \left( \frac{ P(Y_{i}=1|X_{i}) }{P(Y_{i}=0|X_{i})} \right) = \beta_{0} + \beta_{1} X_{i} $$
Then the odds ratio, $e^{\beta_{1}}$, is the odds ratio associated with a one unit increase in $X$.
Essentially you can think of it as the odds ratio between $Y$ and the dummy variable $B$ defined such that $B=1$ if $X=x+1$ and $B=0$ if $X=x$.
Note: The assumption underlying the logistic model is that this odds ratio does not depend on $x$.

Odds ratio for continuous variable


How many data points do we need for mixed effects longitudinal data?

Question: I am collecting longitudinal data using for 4 time waves.  Although the survey is administrated to the same population, different individuals may decide to complete it at each time point. As a result there are a number of individuals that only completed it once, others that completed it twice, some that completed it three times and others who participated in all four waves. For example at the moment there are about 2000 participants in time 1 and 1900 for time 2 but only 1200 that participated in both time 1 and time 2 (at the moment i am still collecting data for time 3 so i don't know yet what the final matched sample will be).
The data are from different organizations so I would like to model this with using mixed effects with the lmer in R. e.g.
<code>
lmer(outcome~"some repeated variables"+"organization level variables"+timewave+(timewave|subject)+(1|organizations))
</code>
My questions are

 Do i need to remove individuals who completed it only once or twice to use a random slope for time?
 Is it meaningful to also try to fit a quadratic effect for time given that there are only 4 waves? (and would i need to remove subjects that have not participated in all four?)

Many thanks,
George
Comment: Are you interested in studying possible attrition effect or do you only want to assess the overall trend?
Comment: I am not interested in the attrition effect. Only want to assess the trend
Answer:
No, you don't need to remove individuals with data for only only one (or only a limited number) of timepoints. You're right to think that individuals with only one timepoint contribute nothing to estimation of the slope but they contribute to estimation of the intercept and you want to estimate both jointly. The maths and the algorithm deal with this  so you don't need to worry about it, and you're more likely to make errors than the programmers of lmer if you try to second-guess things by dropping observations you don't think will contribute.
Yes, you could fit a quadratic effect for time with 4 timepoints. In fact, if you designed an experiment to look for a quadratic effect, you might well choose to have 4 timepoints. (3 would  in principle maximise your power, but 4 allows 1 d.f. to test for fit of the quadratic curve). Clearly you need at least some people to participate in at least 3 waves. But as above, don't remove subjects that didn't.


Solve $3^{1-x}=2$

Question: I've been trying to solve a problem:
$3^{1-x}=2$
I converted this to a log as:
$\log_{3}{2} = (1-x)$
But I couldn't see how to progress from there. Having put it into a solving team, it suggests that it can be translated to:
$\left(1-x\right)\ln \left(3\right)=\ln \left(2\right)$
...but I can't see why this makes sense. Could anyone point me in the right direction?
Comment: "But I couldn't see how to progress from there". You have an equation with one unknown, namely $x$. Re-arrange to make $x$ the subject of the equation [ Hint: the brackets don't serve a purpose in the equation:$log_{3}{2} = (1-x)\ $]
Comment: @AdamRubinson Thanks - I'll do that, appreciate the useful advice on how to reach the solution
Answer: This is due to the change of base formula, $$\log_{b}x = \frac{\ln x}{\ln b}.$$
This is because if you have $\log_{b}x = a$, then you can rewrite it as $x = b^{a}$.  Taking the natural logarithm of each side gives you $\ln x = \ln (b^a)$, which can be rewritten as $\ln x = a\ln b$, which upon dividing both sides by $\ln b$ gives you $a = \frac{\ln x}{\ln b}$.  Hence, you have $$\log_{b}x = a = \frac{\ln x}{\ln b}.$$
Comment: Fantastic, thank you - I will look this up
Answer: Use the property of logarithms that $\log_b x=\dfrac {\log_e x}{\log_e b}$.
Comment: Fantastic, thank you - I will look this up
Comment: @user133935: This answer is wrong for $e=1$.
Comment: The base of natural logarithms $e\ne1$
Answer: If you mean to find the value of $x$ you almos have it. Another option is to write $3^{(1-x)}=2$ as $\frac{3}{3^x}=2$ which is equivalent to $\frac{3}{2}=3^x$ and using $log_3$ the value of $x$ is $log_3\frac{3}{2}$.

Solve $3^{1-x}=2$


Cant create play 2 template in intellij : java play framework

Question: I am new to java play 2 framework in IntelliJ, I can run the server without any issue. But I can't create a new play 2 templates. Can someone tell me what's the issue here?
I searched in jetbrains support page.
It says the issue is with intellij ide, but I tried the same thing with the latest version 2017.3, and the same issue prevails
click here:
How it should be
click here:
But how it looks
Note: I am following these video tutorials
Comment: OK GREAT, i got the solution for my issue, it would be useful for other beginners:  INTELLIJ COMMUNITY EDITION DOESN'T GIVE THE OPTION TO CREATE THE PLAY 2 TEMPLATE (IF YOUR A STUDENT YOU CAN PURCHASE THE STUDENT LICENSE FOR FREE AND GET THAT OPTION), or else you can do the following in the community edition: select file from options and enter filename with .scala.html extension. for example you want to create index file, then you have to select file option and enter index.scala.html file name and then click on create file
Comment: i was using play 2.6, which was the latest version, but latter i changed to version 2.5 where i could fix one issue.THE PROBLEM IS; the IDE doesn't gives any option to create PLAY 2 TEMPLATE.the issue is discussed in this page (https://intellij-support.jetbrains.com/hc/en-us/community/posts/205998049-Subfolder-in-views-play-framework-not-see-templates- )
Answer: OK GREAT, i got the solution for my issue, it would be useful for other beginners: INTELLIJ COMMUNITY EDITION DOESN'T GIVE THE OPTION TO CREATE THE PLAY 2 TEMPLATE (IF YOUR A STUDENT YOU CAN PURCHASE THE STUDENT LICENSE FOR FREE AND GET THAT OPTION), or else you can do the following in the community edition: select file from options and enter filename with .scala.html extension. for example you want to create index file, then you have to select file option and enter index.scala.html file name and then click on create file – Mohamed Sajjadh Dec 29 '17 at 8:56
Comment: one more think I want to add is that do not forget to use sbt clean compile from terminal so that it will create template file of your  index.scala.html page in target->twirl->main->view.html directory


What does it mean that a spanning set can form a plane?

Question: From what I know, If you have $3$ linearly independent vectors and the vectors have a spanning set of $\mathbb{R}^3$. Then you will form a basis. However, it is not always the case that you will have $3$ independent vectors, so it will not have a spanning set of $\mathbb{R}^3$.
Sometimes the "spanning set can form a plane or a line in $\mathbb{R}^3$". I have no idea what this means, has it got something to do with the dimensionality of the vector space? Can you explain it to me assuming I am a beginner at this.
Thank you
Comment: $\text{span} \{u\}$ is the set of all linear combinations of $u$, i.e. $2u, -5u$. It is a linear space, can you see it forms a line determined by $u?$
Comment: Take the vectors $i,j,k$. They span all of $R^3$, right? Now take the vectors $i,j,i+j$. What subspace of $R^3$ do they span?
Comment: If $u,v$ are any two vectors in $R^3$, the span of $\{u,v\}$ is not all of $R^3$. The span will be $\{0\}$ if $u=v=0$, or a line through the origin if $u,v$ are linearly dependent, but not both zero, or a plane through the origin if $u,v$ are linearly independent.
Answer: Consider how many coordinates it takes to uniquely define a point in a plane, or a line for that matter. For a plane it's $2$, for a line it's $1$.
Thus given two linearly independent vectors in $\mathbb{R^3}$: $u$, $v$; we can define a plane where the coordinates $(a,b)$ are defined as $au + bv$, and the subspace in which the points lie is the plane containing the vectors $u$ and $v$. Conversely, any point that lies in that plane can be written as a linear combination of $u$ and $v$, and that is what is meant by "$u$ and $v$ span the plane"
Same for a single vector w in $\mathbb{R^3}$, the coordinate (c) can be defined as $cw$, and hence the the subspace this defines is the line that passes through the origin and $cw$. Likewise, any point in that line can be written as a scalar multiple of $w$. That is what is meant by "$w$ spans the line"
Since the dimension of a vector space is equal to the greater number of linearly independent vectors in that space, the plane (which has a maximum of two independent vectors) has dimension 2, and a line (which has at most one independent vector) has dimension 1.


Given a real vector space $V$, each element of the complexification has the form $v+iw$?

Question: Notation: Let $W$ be some complex vector space, then $\widetilde W$ is the associated real vector space.
Question:
Let $V$ be a real vector space and $(V_\mathrm c,I)$ a complexification of $V$, i.e. $V_\mathrm c$ is a complex vector space and $I\in L(V,\widetilde{V_\mathrm c})$ such that for each complex vector space $W$ the function
\begin{align}
L(V_\mathrm c,W)&\to L(V,\widetilde{W})\\
A&\mapsto A\circ I
\end{align}
is bijective. I want to show that
\begin{align}
\Phi:V\times V&\to V_\mathrm c\\
(v,w)&\mapsto Iv+iIw
\end{align}
is bijective.
Comment: I don't understand what you have to prove
Comment: are you sure? You wrote that you assume that the map is bijective
Comment: okay, I delete it
Answer: I think I finally solved the problem (of course your feedback would be appreciated):

Let $W$ be the complex vector space obtained by taking  the real vector space $V\oplus V$ and extending the scalar multiplication by$$i(v,w)=(-w,v).$$
In addition, consider $J\in L(V,\widetilde W)$ defined by $Jv=(v,0)$. I claim that $(W,J)$ is another complexification of $V$.
Clearly $I=\Phi\circ J$, i.e. $\Phi$ is the extension of $I$ w.r.t. $J$ and thus $\Phi\in L(W,V_\mathrm c)$ is the natural isomorphism from $(W,J)$ to $(V_\mathrm c,I)$.


How to play given notes on the guitar

Question: I'm sorry, if my question is not too generic, but I'm having trouble playing instrumental acoustic peace and would appreciate if you could help me out.
Here are the notes I have (sorry for scan quality):

But I cannot figure out how to play them on guitar. C note should be heard throughout the bar and you should be able to hammer-on or pull-of from E to D. Can anyone think of a tab for this notation puzzle?
Answer: Here are two possible solutions.
Option 1 - starting with the third finger on the 6th string, 8th fret. (that last B could be played with the first finger depending on where you want to go next.)  Generally in the fret 5 - fret 9 area.

Option 2 2 - solidly in the 7th position.  Starting with the second finger on the 6th string, 8th fret.  (You have to slide your first finger back one fret to get the last note.)  Feels a little easier to play (to me).

I'm sure there are other possibilities.  Of course, the solution you choose will depend on what came before and what is coming after this measure.
Comment: I used http://lilypond.org/ Yes it can do Roman Numerals for positions. I think circled strings are possible, but may require jumping through some hoops.  Lilypond isn't for everyone as you must use text markup to produce the notation - however, I think there is a GUI front for it.
Comment: What tool did you use for your images? Can it do Roman Numerals for positions? Circled numbers for strings?

How to play given notes on the guitar


How to reconnect to the backend with HAProxy

Question: I'm new in working with HAProxy.
I couldn't figure out how to make HAProxy to reconnect to backend that was down and started up back again.
I have a configuration of two backend servers. When they are running and I start HAProxy all works OK. The handshake is passed. Then I stop one of the backend and the traffic correctly goes to the server that is  keep running. But then, when I start up the stopped server again HAProhy does not recognize that. Only after HAProxy service restart it can again connect.
How to fix this behavior?
Answer: You can use HAProxy backend health checking mechanism:
<code>backend farm1
   server s1 192.168.1.10:80 check
   server s2 192.168.1.11:80 check
</code>
More info:
http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#check
Comment: If the backend went down the health check fail. That's OK, but if the backend is up again the health check still fail until HAProxy is restarted.
Comment: try (for each server):
`server s1 192.168.1.10:80 check inter 2000 fall 3 rise 2`
Comment: Thank you for your help! Did not work for me. When the backend is down only restart or refresh makes it status up again in HAProxy.
I do the refresh with
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid)


Is it safe to configure SSL on nginx and keep apache untouch?

Question: I have nginx as the front proxy server, All traffics go through that, and on the same machine I need to run PHP so the quick easy way was running apache.
I only enabled SSL on nginx so things are running with HTTPS, is it safe? Having both running on SSL seems odd, resource inefficient.
Comment: Yes, but nginx can serve as the origin server and run PHP perfectly well (many of us would say better than Apache). You can probably safely eliminate Apache with an nginx + php-fpm setup.
Answer: Having SSL running on only Nginx is a safe way to do things. To intercept traffic the attacker would need to have access to your local machine.
Running SSL on both Nginx and Apache is a waste of resources, it's no point in encrypting traffic between load balancer and your application server that in this case are Apahce.
Answer:
I only enabled SSL on nginx so things are running with HTTPS, is it
  safe?

Yes, it is perfectly safe to run nginx as an SSL-terminator in front of Apache.
However, both Apache and nginx are able to run HTTPS and PHP, so for simplicity you can either move the HTTPS to Apache or PHP to nginx if you'd like.


What is the meaning of _T("xyz")?

Question: I wanted to understand the use of _T("xyz") in the code below:
#include<CString.h>
int main()
{
   uint32_t xyz = 15;
   LPCSTR Desc = "xyz value is : ";
   CString Value;
   Value = (LPCSTR)Desc + _T("xyz");
}

Will the above code display:
xyz value is : 15

or
xyz value is : xyz

How to display -
xyz value is : 15
Comment: do you want to know what or why? for what, you just need to run the code, no?
Comment: Don't use `CString.h`, it's an ancient non-portable hack from times when C++ didn't have a usable string class.
Comment: @Jabberwocky agree, maybe it was even a post like that that made OP think they need it for their case
Comment: Read this: https://msdn.microsoft.com/en-us/library/dybsewaf.aspx. Using `_T` in this case it totally wrong.
Comment: ... and `Value = (LPCSTR)Desc + _T("xyz");` is totally wrong too.
Comment: I want to display xyz value is : 15..
Comment: I suggest you start reading your C++ text book.
Comment: I'm not sure the duplicate is helpful here. Voted for repopening
Comment: whats wrong with `std::cout << "xyz value is " << xyz;` ? Do you **have** to use `CString.h` ?
Answer: The _T macro is used to simplify transporting code for international uses.
See https://msdn.microsoft.com/en-us/library/c426s321.aspx for more information.
Comment: ... at least that's what Microsoft would have developers believe.
Answer: You probably want this:
uint32_t xyz = 15;
LPCWSTR Desc = L"xyz value is : %d";
CString Value;
Value.Format(Desc, xyz);

Forget about the _T macro. What makes you think you should use it?
Or maybe you need this:
uint32_t xyz = 15;                // integer variable containing the number 15
CString stxyz;                    // CString variable
stxyz.Format(L"%d", xyz);          // stxyz contains "15" now

LPCWSTR Desc = L"xyz value is : ";  // Desc points to the string literal "15"

CString Value = Desc + stxyz;     // Value contains concatenation of Desc and stxyz

Comment: I have two string for which I need to concatenate
Comment: @CAAnusha OK, so you need to transform `xyz` into string first. BTW `"XYZ"` is a string literal, its content is in no way related to the identifier `xyz`.
Comment: I thought that is used to convert any non-string value to string
Comment: _I thought that is used to convert any non-string value to string_: absolutely not. You need to learn at least the basics of C++ to understand why my answers work.
Comment: I am using a user defined datatype basically a union instead of uint32_t ..
How should I store in string then?
Comment: I am getting below error
Severity Code Description Project File Line Suppression State
Error C2664 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *'
Comment: Replace `LPCSTR` with `LPCWSTR` and replace `"xyz value is : "` with `L"xyz value is : "`.

What is the meaning of _T("xyz")?


Javascript Json

Question: Olá pessoal preciso montar um objeto deste tipo:
{y: "2017-8", a: 0, b: 0, c: 2, d: 0, …}

As letras vão até h, mas pode variar de um usuário pra outro, estou montando um grafico linha Morris.Line.
O meu servidor me retorna um array:
["a: 0", "b: 1", "c: 0", "d: 0"]

Se eu colocar isso com toString() obtenho:
console.log(x);
a: 0,b: 1,c: 0,d: 0

Aparentemente perfeito mas, não resolve meu problema pois se eu colocar dentro do objeto que preciso inicializar pra fazer meu gráfico obtenho:
console.log({y: data, x});
{y: "2017-8", x: "a: 0,b: 1,c: 0,d: 0"}

Se eu colocar o array direto também não fica como preciso; Obtenho:
console.log({y: data, x});
{y: "2017-8", x: Array(4)}

Bom galera como faço pra obter aquilo que coloquei lá no começo ?
Answer: Seria algo assim:
a = ["a: 0", "b: 1", "c: 0", "d: 0"];
obj = {};
obj['y'] = '2017-8';
a.forEach(function(el, i){
    var arr = el.split(': ');
    obj[arr[0]] = arr[1];
});
console.log(obj);

{y: "2017-8", a: "0", b: "1", c: "0", d: "0"}

Comment: valeu guerreiro!
Comment: Por nada, qual lib você está usando para gerar o gráfico @AbnerPassosMagalhaes ?
Comment: https://morrisjs.github.io/morris.js/lines.html
Answer: Pra fins de "code golfing" :D
let arrayDoServer = ["a: 0", "b: 1", "c: 0", "d: 0"];
let jsonDeSaida   = JSON.parse('{"' + arrayDoServer.join('","').replace(/: /g, '":"') + '"}');
console.log(jsonDeSaida);

Javascript Json


React Native property 'ref' does not exist on type 'intrinsicattributes & flatlistprops'.ts(2322)

Question: This is my component:
import React, {memo} from 'react';
import {FlatList as RNFlatList, FlatListProps} from 'react-native';

// interface IFlatList<ItemT> extends FlatListProps<ItemT> {}

function FlatList<ItemT = any>(props: FlatListProps<ItemT>) {
  return (
    <RNFlatList
      {...props}
      nestedScrollEnabled
      showsVerticalScrollIndicator={false}
      showsHorizontalScrollIndicator={false}
      // Performance settings
      removeClippedSubviews={true} // Unmount components when outside of window
      initialNumToRender={20} // Reduce initial render amount
      maxToRenderPerBatch={20} // Reduce number in each render batch
      updateCellsBatchingPeriod={100} // Increase time between renders
      windowSize={10} // Reduce the window size
    />
  );
}

export default memo(FlatList);

when I call it:
<FlatList
    ref={flatListRef}
    // others props
/>

and it shows warning as title then I cannot use the ref.
I try to add
interface ClassAttributes<T> extends Attributes {
    ref?: LegacyRef<T> | undefined;
}

but I still can't find a solution to add it into props.
So where is the right way that I can customize my component and using all the default props of React Native's component?
Answer: I'm not sure about the practical use cases of a "Custom FlatList", because it doesn't affect the style at all. You already can style each item using renderItem, so there's no need for a "Custom FlatList".
But if you REALLY want to, you should understand ref in React itself first before writing any custom component, then get to know useRef, useImperativeHandle. You have to pass the ref to FlatList itself using forwardRef.
Here's an example:
import React, { forwardRef, useRef } from 'react';
import {
  FlatList,
  FlatListProps,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

interface CustomFlatListProps<T> extends FlatListProps<T> {}

export const CustomFlatList = forwardRef<FlatList, CustomFlatListProps<any>>(
  (props, ref) => {
    return <FlatList ref={ref} {...props} />;
  }
);

interface ItemData {
  id: string;
  title: string;
}

const demoData: ItemData[] = [
  { id: '1', title: 'something 1' },
  { id: '2', title: 'something 2' },
  { id: '3', title: 'something 3' },
];

export function DemoUsingCustomFlatList() {
  const flatListRef = useRef<FlatList>(null);

  function _renderItem({ item }: { item: ItemData }) {
    return <Text>{item.title}</Text>;
  }

  return (
    <View>
      <CustomFlatList
        ref={flatListRef}
        data={demoData}
        renderItem={_renderItem}
        keyExtractor={(item) => item.id}
      />

      <TouchableOpacity onPress={() => flatListRef.current?.scrollToEnd()}>
        <Text>Click to scroll to end</Text>
      </TouchableOpacity>
    </View>
  );
}


WPF ListBox MouseDoubleClick

Question: I have a ListBox in a WPF application and I use the event MouseDoubleClick:
private void listBoxMain_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        try
        {
            textBoxDateiName.Text = listBoxMain.SelectedItem.ToString();
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
    }

Question 1: why I get the error message "Object reference not set to an instance of an object"?
Question 2: how can a display in a TextBox the selected item of the ListBox with a simple click and not with DoubleClick?
Thank you for helping
Filippo
Answer: You can do it directly in your xaml, you must bind TextBox to the SelectedItem of ListBox like this :
<ListBox x:Name="MyListBox">
   //...
</ListBox>
<TextBlock Text="{Binding ElementName=MyListBox, Path=SelectedItem}"/>

If the SelectedItem is an object, you must specify the property to show
<ListBox x:Name="MyListBox">
   //...
</ListBox>
<TextBlock Text="{Binding ElementName=MyListBox, Path=SelectedItem.Property}"/>

WPF ListBox MouseDoubleClick


JavaScript: How to set a property for a function?

Question: I'm testing one of my functions, and I want to test whether a specific function is called with the right argument from that code.
For that reason, I overwrite the original function like this:
var oldSort = sort;
sort = function(array) {
    this.arrayToSort = array;
}

Then I execute it and check that the property sort.arrayToSort is set to the value I passed in and reassign the original function:
sort(myArray);
deepEqual(myArray, sort.arrayToSort);
sort = oldSort;

However, I can't access sort.arrayToSort like that. How can I set a property of the function to make that possible? Right now, I'm declaring a variable above the sort function and have it set that, but I'd rather have it as a property of the function to keep its scope small. Is that possible?
Comment: Is that your own deepEqual function or are you using some javascript library?  What Line is causing problem?  Could you include the full javascript instead of theses two snippets.
Comment: I'm using QUnit and this is a test case. I wrote this snippet to reproduce a problem I'm having in our production system whose code I cannot release.
Answer: Sounds like you want arguments.callee, which refers to the function itself, rather than the object it was bound to.
var oldSort = sort;
sort = function(array) {
    arguments.callee.arrayToSort = array;
}

Comment: Great, this works! But it does look a little obscure - would you recommend doing it this way in my case?
Comment: The other way to do it would be to reference sort directly (sort.arrayToSort = array). arguments.callee is the only way to do it on an anonymous function.
Comment: I don't know if there's a JS mocking library that supports mocking global functions, but that's basically what you're trying to do. If you can find a way to use a mock library, that's what I would recommend.
Comment: Yeah, I'm trying to mock a global function here, but I'm not sure about adding a 3rd party mocking framework.
Comment: I guess I'll either keep it the way it is or introduce Sinon.JS, seems to work well with QUnit. Anyway, you answered my question so I'll accept :)
Answer: you cant access the function properties if you don't create it with new keyword.
mysort = new sort(array);
alert(mysort.arrayToSort);

you can use custom comparator function in original sort. like this
array.sort(sortfunction)

function sortfunction(a, b){
   //Compare "a" and "b" in some fashion, and return -1, 0, or 1
}

Comment: Works as well, but similarly obscure. As I asked Austin: Would you recommend doing this in my case?
Comment: I just don't understand why override the original sort? you can write your own sort function and pass it to sort as argument. I'll update my post to make it clear.
Comment: Sorry, I guess the example was pretty bad, I'm assuming the sort function was defined by me.


How to update one table with data from the other, based on condition from the first

Question: I have:

The goal is to update table A with groupID from the table B, with the rule:

if A._groupID = 1, get first B.groupID of the same subjectID and write the value to A.groupID
if A._groupID = 2, get second B.groupID of the same subjectID and write the value to A.groupID

(Explanation: in table A groups were numbered from 1-20 for each subject, but with app upgrade it is necessary to store group data to another table and assign them a proper primary key ID (b.groupID), because of that this pairing is needed).
What I tried:
UPDATE A
    JOIN    B
        ON  B.subjectID = A.subjectID
SET A.groupID = B.groupID
ORDER BY A.groupID ASC

This results with (always writes the first result from table B):

Efficiency is not a concern because this query will be executed only once..
How to make this query work?

the subjects also have multiple types (like lecture, exercise, practice), so group counting should take a Type into a consideration when counting.
fiddle with working example without a Type consideration: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=172109270f3f83f8e763f7d4daffb26f
Result:

Can you please advise on how to modify the update query to fix the error?
Answer: If you can use analytic functions (Mysql 8) this is a breeze with row_number()
This works by first creating a derived table for tableB (another CTE could also be used). This then uses row_number to add numbers (in this case just 1 or 2) according to the ordering of groupId which matches the _groupId in tableA. Then it's just a simple join on both columns to assign the right value.
update a
join (
  select *,
    row_number() over(partition by subjectid order by groupid) _groupid
  from b
)b on a.subjectid=b.subjectid and a._groupid=b._groupid
set a.groupid=b.groupid

working Fiddle
Comment: This query works, I have no idea how, but it works :) , except maybe in some edge cases where a.groupID is null or 0, but I will sort that out.. Can you please explain a bit more what this query and used functions do? Thank you
Comment: Sure have added an additional paragraph.


SwiftUI Control flow build elements

Question: I recently started playing with SwiftUI and though there are some good things too it, so far I am very disappointed. Especially by the fact that it makes it really easy to create large, messy looking code and reminds me of XML ( or HTML ) structure of sorts.
Anyhow, I am running into the following problem that I can't find a solution for anywhere.
I need to draw certain rectangles ( or shapes ) at run time, think about it as generating a horizontal bar-chart in a way. Because the number of rects is dynamic, I need to generate this in a method, however I am getting an error from the compiler with any method I've tried so far.
Whenever I try and use some sort of flow control, like 'for' or 'while' in order to generate elements inside the:
struct ContentView: View {

or :
 var body: some View {

I either get:
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

or
Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

What would be a better approach for drawing dynamic elements with SwiftUI.
I've seen a ton of examples on dynamic lists, even though that was covered by Apple already on day 1, but nothing that would be about custom elements or if you wanted to create a dynamically set number of HStack or Vstack, that are not formatted as a List.
Thank you!
Answer: ViewBuilders are special things and you cannot use certain control flow statements in them.
You can call out to separate (private) functions to do the appropriate control flow and produce the appropriate views.
See this blog post by John Sundell on the Swift 5.1 features that power SwiftUI: https://www.swiftbysundell.com/articles/the-swift-51-features-that-power-swiftuis-api/

SwiftUI Control flow build elements


how to change the property of the first form while using a second form?

Question: I'm using two forms and I disable the first one when the second form shows up. I couldn't find a way to enable the first form when the second one is closed.
Passing a parameter could be a solution but I bet there is a simpler way.
First I thought of enabling the first form on the destructor of the second but could not do it.
Anyone have any suggestions?
Comment: Please run a search on StackOverflow, this question has come up *a lot.* Your second form needs a reference to the first form, on which it can either call a method or change a property.
Comment: @codesparkle you are right, there are many topics on this. looks like creating custom events and delegates are the right track.
Comment: Why not just open the second form as modal? That will automatically handle suspending execution of the first form while the second one is open.
Comment: @codesparkle You don't *need* to pass a reference to the first form.  In fact, it's not even considered the best approach.  The accepted practice here is to use events.
Comment: @Servy indeed, that would probably be the cleanest way to do it. @Bora you may not need to create a delegate; check out [`EventHandler`](http://msdn.microsoft.com/en-us/library/db0etb8x.aspx) or the various versions of [`Action`](http://msdn.microsoft.com/en-us/library/system.action).
Comment: @codesparkle In this case you won't be creating an event at all, just using the existing events that `Form` implements, which means you will be using an already defined delegate, not creating one.  If you needed to add your own event, rather than use one that has already been created, you can use one of those delegates, yes.
Answer: You can show second form with ShowDialog() - form will be shown as modal, first form will be enabled only when second will be closed.
For future problems you can have a field in second form to have instance of first one, and use that instance, if you need, for example you can use custom constructor:
class SecondForm: Form
{
   FirstForm _parentForm;

   public SeconForm(FirstForm form)
   {
      InitializeComponent();
      _parentForm = form;
   }

   void DoSomethingWithParent()
   {
      _parentForm.DoSomesting();
   }
}

Comment: It worked as I expected. This solves my answer, but still looking for an answer for future similar problems!
Answer: As has been mentioned, in this specific case it probably makes sense to use a modal dialog for opening the second form.
To cover the case when that isn't applicable, the accepted best practice would be to subscribe to the FormClosing event of the second form from the first, and in the event handler you could enable "yourself" and do anything else that you might want to do as a result of the other form being closed.  Here is a simple example:
public partial class ParentForm : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
        ChildForm child = new ChildForm();

        child.FormClosing += new FormClosingEventHandler(child_FormClosing);
        Hide();
        child.Show();
    }

    private void child_FormClosing(object sender, FormClosingEventArgs e)
    {
        Show();
    }
}

Comment: `child.FormClosing += child_FormClosing;` would suffice if you are using an up-to-date version of .NET
Comment: @codesparkle Yes, it would, but VS code completion generates this code automatically, so it's actually more work to change it to that sorter version.  If I was typing this all out in notepad without code completion there are actually several additional changes I would make.  (I'd use a lambda rather than a new method, for example.)


Estimating incidence rate for subpopulation from test calibrated on whole population

Question: Formal problem:
I'm given random variables $X\in\{0, 1\}$, $T \in \mathbb{R}$ and $S \in \{0, 1\}$ such that
1) $S$ and $T$ are independent given $X$, i.e. for both $x\in\{0, 1\}$:
$$P(S\text{ and }T\in\mathcal{T}|X=x) = P(S|X=x) \cdot P(T\in\mathcal{T}|X=x) \text{ for all sets }\mathcal{T}\subseteq\mathbb{R}$$
Assume I know
2) the joint distribution of $P(X = 1 | T)$ and of $S$, i.e. for all $\mathcal{T}\subseteq\mathbb{R}$, I am given the probabilities
$$P(X \text{ and }S | T \in\mathcal{T} ), P(X \text{ and }\bar{S} | T \in\mathcal{T} ), P(\bar{X} \text{ and }S | T \in\mathcal{T} ), P(\bar{X} \text{ and }\bar{S} | T \in\mathcal{T} )$$
I'm interested to know (or estimate, or at least get some rough idea of)
3) $P(X|S)$
I thought it should be easy enough, but I've been banging my head against a wall with this. I'd be grateful for any help.
Context example:
There's a standard test that predicts the chance to have a rare condition X. I notice that people of a small sub-population S appear to have an above average chance for X. I'm interested in estimating that chance using the test that's been calibrated on the whole population.
A first pass would be to take the average of the test predictions for P(X). However, this is likely to underestimate the true incidence rate for X in S:
As X is a rare condition and the test is far from perfect, the test heavily hedges its bets by never predicting a very high probability for X, just like even after a positive HIV test, the chance for a false positive used to be still higher than for a true positive. However, if you measure individuals from the sub-population again and again, and always get the most positive result the test is willing to predict, it's starting to appear quite likely that they probably are all positive.
At least if you assume that the high values of the test are due to some actual marker of X that should be independent of the subpopulation (or the higher results could just be because the test identified the subpopulation). This assumption is expressed in condition 1.
Comment: I understand 1) to mean p(S,T|X) = p(S|X) p(T|X). I'm not sure I understand 2). When you say "joint distribution" do you mean you know something about p(X,S|T)? If not, then what do you mean?
Comment: Thanks for your comment. I'll edit my question to be clearer.

Yes, this is what I meant with 1), and with 2), I meant that I assume as a given the joint distribution of P(X = 1|T) (which is a T-measurable random variable) and S.
Answer: Here's the answer I've arrived at myself in the meantime.
For any event $\mathcal{T}\subseteq\mathbb{R}$ where the denominator is not 0, the desired expression computes as
$$P(X|S) = \frac{P(\mathcal{T}|S) - P(\mathcal{T}|\bar{X})}{P(\mathcal{T}|X) - P(\mathcal{T}|\bar{X})}$$
There always is such an event $\mathcal{T}$ provided that $T$ and $X$ are not independent. If they are independent, there is no hope of using $T$ to get at $P(X|S)$ anyways (in the context example, that would mean the test for X is just useless).


Adicionar marcador em mapa ANDROID

Question: Boa noite,
tenho uma aplicação com um mapa num separador de swipe, mas pretendo que o mapa marque um ponto no mapa e inicie nesse ponto.
obrigado desde já.
Junto envio o JAVA:
public class Mapa extends Fragment {

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

    View android = inflater.inflate(R.layout.mapa_3, container, false);

    return android;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    Fragment f = getFragmentManager().findFragmentById(R.id.mapFragment);
    if (f != null)
        getFragmentManager().beginTransaction().remove(f).commit();
}

}
e o layout:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map_container"
    tools:context=".Mapa" >

    <fragment
        android:id="@+id/mapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

Comment: Como está fazendo a manipulação da instância do `GoogleMap`? Para criar um marker é só criar um `MarkerOptions` e depois passá-lo ao `GoogleMap.createMarker`.
Comment: Mas isso é feito no java?
Comment: Isso mesmo, no `onCreate` da `Activity` ou do  `onCreateView` do `Fragment`. De uma olhada na primeira resposta dessa pergunta do SO EN: http://stackoverflow.com/questions/19353255/how-to-put-google-maps-v2-on-a-fragment-using-viewpager.
Answer: Tenta isso
private void initilizeMap() {
        googleMap = ((SupportMapFragment) getFragmentManager()
                .findFragmentById(R.id. mapFragment)).getMap();

            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setRotateGesturesEnabled(true);
            googleMap.getUiSettings().setZoomControlsEnabled(false);

            createMarkers();
    }

private void createMarkers() {
MarkerOptions marker = new MarkerOptions().position(
                new LatLng(lat, lon)).icon(
                BitmapDescriptorFactory
                        .fromResource(R.drawable.pin_localizacao));
        googleMap.addMarker(marker);

 }

Adicionar marcador em mapa ANDROID


Combining multiple probabilities

Question: I've searched for a while now but didn't find anything that would answer my question precisely, so I've decided to post.
Suppose we have symptoms of various diseases, and after a day the actual diagnosis is 100% known. We have studied numerous past cases and want to make a probabilistic diagnosis for new patients coming in.
(The data is made up to illustrate the problem)
Possible diseases:
D1 = Common cold
D2 = Strep throat
D3 = Malaria
Of all the past cases studied,
Symptom 1 - vomiting:
10% of common cold (D1) patients were vomiting.
40% of strep throat (D2) patients were vomiting.
70% of malaria (D3) patients were vomiting.
Symptom 2 - elevated body temperature:
For common cold (D1), 20% had normal temperature, 70% had slightly elevated temp, 10% had very high temp.
For strep throad (D2), 60% had normal temp, 10% had slightly elevated temp, 30% had very high temp.
For malaria (D3), 10% had normal temp, 20% had slightly elevated temp, 70% had very high temp.
Symptom 3 - dhiarhea:
For common cold (D1), 80% had no dhiarhea, 10% had mild dhiarhea, 10% had bad dhiarhea with dehidration.
For strep throad (D2), 60% had no dhiarhea, 30% had mild dhiarhea, 10% had bad dhiarhea with dehidration.
For malaria (D3), 10% had no dhiarhea, 20% had mild dhiarhea, 70% bad dhiarhea with dehidration.
Now that we know these probabilities, a doctor accepts a patient, for who we can see that he isn't vomiting, has very high body temperature, and mild dhiearhea.
What are the chances for this person of the three different diseases?
(The chances of all three diseases of course should sum up to 100%).
(Not a homework assignment, just trying to figure out for a hobby project)
Comment: You can't really say anything without also specifying the prevalence of the three diseases among the numerous past cases.  (E.g., if malaria is extremely rare, as it is in the U.S., it's unlikely to be the diagnosis no matter what the symptoms.)  Once you've done that, you can bring Bayes Theorem to bear.
Answer: Here's how I think you need to go about it:
You have $18$ possible combinations of symptoms: vomit/novomit, low/med/high temp, no/mild/severe diarrhea.
When you multiply out the probabilities of each combination of symptoms, you therefore end up with $18$ probabilities (for each disease).  The probability of a cold sufferer displaying "vomit, no temp, no diarrhea", for example, is $0.1\times 0.2 \times 0.8 = 0.016 = 1.6\%$. (When you add up the probabilities of each of the $18$ combinations, you get $100\%$.)
Since there are three diseases in play, you have $3$ different probabilities for each combination of symptoms.  As seen above, the chance that someone with a cold has "vomit, no temp, no diarrhea" is $1.6\%$, the chance that someone with strep has those symptoms is $14.4\%$, and the chance that someone with malaria has those symptoms is $0.7\%$.  So, when someone with those symptoms shows up, there is a $\dfrac{1.6}{1.6+14.4+0.7} = 9.58\%$ likelihood that they have a cold; similarly, an $86.23\%$ chance of strep, and a $4.19\%$ chance of malaria.

Combining multiple probabilities


Dynamically generate multiple tasks based on output dictionary from task in Airflow

Question: I have a task in which the output is a dictionary with a list value in each key
@task(task_id="gen_dict")
def generate_dict():
   ...
   return output_dict # output look like this {"A" : ["aa","bb", "cc"], "B" : ["dd","ee", "ff"]}

# my dag (Not mention the part of generating DAG and its properties)
start = DummyOperator(task_id="st")
end = DummyOperator(task_id="ed")
output = generate_dict()
for keys, values in output.items():
   for v in values:
      dm = DummyOperator(task_id=f"dm_{keys}_{v}")
      dm >> end

start >> output

For this sample output above, it should create 6 dummy tasks which are dm_A_aa, dm_A_bb, dm_A_cc, dm_B_dd, dm_B_ee, dm_B_ff
But right now I'm facing the import error
AttributeError: 'XComArg' object has no attribute 'items'

Is it possible to do what I aim to do? If not, is it possible to do it using a list like ["aa", "bb", "cc", "dd", "ee", "ff"] instead?
Answer: The code in the question won't work as-is because the loop shown would run when the dag is parsed (happens when the scheduler starts up and periodically thereafter), but the data that it would loop over is not known until the task that generates it is actually run.
There are ways to do something similar though.
AIP-42 added the ability to map list data into task kwargs in airflow 2.3:
@task
def generate_lists():
    # presumably the data below would come from a query executed at runtime
    return [["aa", "bb", "cc"], ["dd", "ee", "ff"]]

@task
def use_list(the_list):
    for item in the_list:
        print(item)

with DAG(...) as dag:
    use_list.expand(the_list=generate_lists())

The code above will create two tasks with output:
aa
bb
cc

dd
ee
ff

In 2.4 the expand_kwargs function was added. It's an alternative to expand (shown above) which operates on dicts instead.
It takes an XComArg referencing a list of dicts whose keys are the names of the arguments that you're mapping the data into. So the following code...
@task
def generate_dicts():
    # presumably the data below would come from a query made at runtime
    return [{"foo":6, "bar":7}, {"foo":8, "bar":9}]

@task
def two_things(foo, bar):
    print(foo, bar)

with DAG(...) as dag:
    two_things.expand_kwargs(generate_dicts())

... gives two tasks with output:
6 7

...and...
8 9

expand only lets you create tasks from the Cartesian product of the input lists, expand_kwargs lets you do the associating of data to kwargs at runtime.
Comment: Should be the accepted answer. Amazing stuff. Thank you for linking the confluence task API-42 as well. It was exactly what I needed to see how to make this work with my `DockerOperatorTemplated`. Pretty amazing feeling when you start using a tool and that feature you need was just added!
Comment: Thanks for the feedback. Now that it's released I made some edits. You might be interested in the new stuff in 2.4 as well. I find `expand_kwargs` to be more flexible than `expand`.


Calculate the volume (double or triple integral) with boundaries

Question: Suppose we have the following boundaries:
$x^2+y^2 \le a^2$
$x \ge 0$
$y \ge 0$
$0 \le z \le \sqrt{x^2+y^2}$
I need to calculate the volume of the figure which is bounded by these conditions. So I know that the most obvious way would be to use a triple integral with the following boundaries:
$$ \int_{0}^{a}\int_{0}^{\sqrt{a^2-x^2}}\int_{0}^{\sqrt{x^2+y^2}}{dzdydx}$$
However, after solving the first integral I get $$\int_{0}^{a}\int_{0}^{\sqrt{a^2-x^2}}{\sqrt{x^2+y^2}dydx}$$
but the next integral seems kinda hard to solve which makes me wonder if the volume should be calculated by another method (for example a substitution).
Can anyone help? Thanks!
Comment: Have you considered cylindrical coordinates?
Answer: It can be done that way, but it's hard. It's better to do it in cylindrical coordinates, in which case your integral becomes$$\int_0^{\pi/2}\int_0^a\int_0^rr\,\mathrm dz\,\mathrm dr\,\mathrm d\theta=\frac{\pi a^3}6.$$
Comment: I did but I have trouble with the boundaries. For example, if $x=rcos{\theta}$, $y=rsin{\theta}$, $z=z$, $ 0 \le \theta \le 2\pi$, if I plugged this in I would get:
$r \le a^2$, $\cos{\theta} \ge 0$ and $\sin{\theta} \ge 0 $ which is the first quadrant.

thus I don't know how your boundaries for $\theta$ are $0$ and $r$, and the same goes for $z$! My $z$ boundaries are $0, r$
Comment: Since $r\cos(\theta)=x\geqslant0$ and $r\sin(\theta)=y\geqslant0$, $\theta\in\left[0,\frac\pi2\right]$. Asserting that $x^2+y^2\leqslant a^2$ is the same thing as asserting that $r\leqslant a$. Finally, asserting that $0\leqslant z\leqslant\sqrt{x^2+y^2}$ is the same thing as asserting that $0\leqslant z\leqslant r$.
Comment: Sorry my mistake. Thanks!


Unable to browse virtual host with WAMP

Question: I am working on a site that will eventually be hosted on a Linux box. I have decided to use WAMP as my development server so that I can be sure all my Angular.js routing, etc. works properly.
I have WAMP up and running (nice green tray icon).The vhosts module is selected. I have added the following to httpd-vhosts.conf:
# mergable.local
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    DocumentRoot "D:/Main/source/mergable"
    ServerName mergable.local
    ServerAlias www.mergable.local
    ErrorLog "logs/mergable.local-error.log"
    CustomLog "logs/mergable.local-access.log" common
    <Directory "/">
        Deny from all
        Allow from 127.0.0.1
    </Directory>
</VirtualHost>

I also added the following to my hosts file:
127.0.0.1       localhost
127.0.0.1       mergable.local
127.0.0.1   www.mergable.local

When I browse to http://www.mergable.local I get the WAMP configuration page. Any ideas on what I did wrong?
Comment: This line `` should be `` or you are giving access to the root of `D:` to anyone that hacks your site.
Comment: And if you are using Apache 2.4.? `Deny from all Allow from 127.0.0.1` should be `Require local`
Comment: This line in the `hosts` file is also not needed
Answer: Check your apache\conf\httpd.conf file for
#LoadModule vhost_alias_module modules/mod_vhost_alias.so

and for
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf

If you have the # before the LoadModule and Include remove it so the virtual hosts config file will run.
Comment: OK, so now I get a different error. It now says "Forbidden

You don't have permission to access /index.html on this server."

I am betting this has something to do with the empty .htaccess file in that website folder? What SHOULD be in the .htaccess file anyway?
Comment: Do you have the file index.html in there, "D:/Main/source/mergable" ?
Comment: Yes the index.html file is in d:/Main/source/mergable
Comment: I had to change the DIRECTORY portion of the httpd-vhosts.conf file to:

``
  `Options Indexes FollowSymLinks Includes ExecCGI`
  `AllowOverride All`
  `Require all granted`
  `Deny from all`
  `Allow from 127.0.0.1`
 ``
Comment: .htaccess is used for configuration directives, more about it https://code.tutsplus.com/tutorials/the-ultimate-guide-to-htaccess-files--net-4757
Comment: `mod_vhost_alias` is not actually required to run simple virtual hosts

Unable to browse virtual host with WAMP


What is meant by a formal statement in mathematics/computer science

Question: While reading books in Mathematics and Theoretical Computer Science, usually the term Formal Statement props up. What is meant by that?
Comment: This is a second repetition of a statement that was previously made informally, i.e. imprecisely.
Comment: See http://en.wikipedia.org/wiki/First-order_logic#Formation_rules..
Comment: better if you gave a longer excerpt from a mathematics book you have in mind.
Answer: It's a tricky question because "formal" can mean two different exactly opposite things depending on the context. Sometimes an author will carry out "formal manipulations", meaning manipulations that look reasonable or intuitive but are not rigorous. On the other hand, formal can also mean extra rigorous in some contexts, such as "formal systems" in logic.
Can you post an example of where formal is used that is confusing, along with the context?
Answer: What is formal depends on who you ask.  Something that is formal to someone who studies "applied" mathematics may seem quite informal to someone who studies mathematics for mathematics sake.  Formal is usually used to mean "meeting some standard of rigor".
An informal proof that $x^3 \in \mathbb O (x^4)$ might simply say "because $x^3$ is smaller than $x^4$". Someone might call $(\forall x > 1)\, x^4 > x^3 \rightarrow x^3 \in \mathbb O (x^4)$ a more formal statement.
Some (myself included) only use "formal" to mean a mathematical statement that is part of a (usually electronic computer) proof engine, and use the word "rigorous" for anything less.


Direct proof of Alexander's Subbasis Theorem from Propositional Compactness

Question: Alexander's Subbasis Theorem (AST) is the following statement:

A topological space $X$ is compact if and only if there is a subbasis $\mathcal{S}$ for the topology such that every cover of $X$ by elements of $\mathcal{S}$ has a finite subcover.

I can prove the following (over $\mathsf{ZF}$):

AST $\Rightarrow$ Tychonoff's Theorem for compact Hausdorff spaces $\Rightarrow$ Propositional compactness (PC).

PC $\Rightarrow$ Boolean Prime Ideal Theorem (eq. Ultrafilter Theorem) $\Rightarrow$ AST.

I know how to show AST $\Rightarrow$ PC more directly, by appropriately topologizing the set $X$ of all valuations of propositional formulas ($X$ will be homeomorphic to $\{0,1\}^{|L|}$), showing that $X$ is compact iff PC holds, and then applying AST to show that $X$ is a compact space.
However, is there a direct proof of PC $\Rightarrow$ AST? That is, by directly defining an appropriate set of propositional formulas encoding the conclusion of AST.
Answer: Yes, you can use exactly the same strategy I showed you in my answer to your previous question on Tychonoff's Theorem. Since it seems you had some lingering questions about that answer, I'll write out the details again for you.
One direction of AST is trivial. Suppose $X$ is compact. Taking $\mathcal{S}$ to be the subbasis consisting of all open sets, every cover of $X$ by elements of $\mathcal{S}$ has a finite subcover.
For the non-trivial direction, suppose $\mathcal{S}$ is a subbasis for the topology on $X$ such that every cover of $X$ by elements of $\mathcal{S}$ has a finite subcover. Let $\mathcal{B}$ be the basis generated by $\mathcal{S}$ (so $\mathcal{B}$ is the set of all finite intersections of sets from $\mathcal{S}$). To show $X$ is compact, it suffices to show that every cover of $X$ by elements of $\mathcal{B}$ has a finite subcover. Equivalently, it suffices to show that if $(U_i)_{i\in I}$ is a family of basic open sets from $\mathcal{B}$ such that no finite subfamily covers $X$, then $(U_i)_{i\in I}$ does not cover $X$.
So fix $(U_i)_{i\in I}$ such that no finite subfamily covers $X$. For each $i\in I$, write $U_i = S_i^1\cap\dots\cap S_i^{k_i}$ with each $S_i^j\in \mathcal{S}$. Consider the propositional language consisting of one proposition symbol $P_S$ for each set $S\in \mathcal{S}$, and the propositional theory $T$ consisting of the following two axiom schemes:

Whenever $S_1,\dots,S_n\in \mathcal{S}$ and cover $X$, include the axiom $\varphi_{S_1,\dots,S_n}\colon \bigvee_{j=1}^n \lnot P_{S_j}$.
For each $i\in I$, include the axiom $\psi_{U_i}\colon \bigvee_{j=1}^{k_i} P_{S_i^j}$.

Claim 1: For any point $x\in X$, define a valuation $v_x$ by $$v_x(P_S) = \begin{cases} \top& \text{if }x\notin S\\
\bot&\text{if }x\in S.\end{cases}$$
Then $v_x$ satisfies all axioms from scheme 1, and if $x\notin U_i$, then $v_x$ satisfies axiom $\psi_{U_i}$ from scheme 2.
Proof of Claim 1: For scheme 1, suppose $S_1,\dots,S_n\in S$ and cover $X$. Then $x\in S_j$ for some $1\leq j \leq n$, so $v_x(P_{S_j}) = \bot$, and $v_X$ satisfies $\varphi_{S_1,\dots,S_n}$. For scheme 2, suppose $x\notin U_i = S_i^1\cap\dots\cap S_i^{k_i}$. Then there exists $1\leq j\leq k_i$ such that $x\notin S_i^j$, so $v_x(P_{S_i^j}) = \top$, and $v_X$ satisfies $\psi_{U_i}$. $\square$
Claim 2: Let $v$ be a valuation which satisfies all axioms from scheme 1. Then there is a point $x\in X$ such that for all $S\in \mathcal{S}$, if $v(P_S) = \top$, then $x\notin S$. Further, if $v$ satisfies axiom $\psi_{U_i}$ from scheme 2, then $x\notin U_i$.
Proof of Claim 2: Let $\mathcal{F} = \{S\in \mathcal{S}\mid v(P_S) = \top\}$. Let $S_1,\dots,S_n\in \mathcal{F}$. If $S_1,\dots,S_n$ cover $X$, then $v$ satisfies $\varphi_{S_1,\dots,S_n}$, so there is some $1\leq j\leq n$ such that $v(P_{S_j}) = \bot$. This contradicts the fact that each $S_j\in \mathcal{F}$. So no finite subfamily of $\mathcal{F}$ covers $X$. By our hypothesis on $\mathcal{S}$, $\mathcal{F}$ fails to cover $X$, so there is some $x\in X\setminus \bigcup_{S\in \mathcal{F}} S$. Thus, for all $S\in \mathcal{S}$ such that $v(P_S) = \top$, $x\notin S$. Now suppose $v$ satisfies the axiom $\psi_{U_i}$. Then for some $1\leq j\leq k_i$, $v(P_{S_i^j}) = \top$, so $x\notin S_i^j$, and hence $x\notin U_i$. $\square$
To finish the proof of AST, I claim that the theory $T$ is consistent. A finite subset $\Delta\subseteq T$ includes only finitely many axioms $\psi_{U_{i_1}},\dots,\psi_{U_{i_m}}$ from scheme $2$. By our assumption, $U_{i_1},\dots,U_{i_m}$ does not cover $X$, so there is some point $x$ which is not in any $U_{i_j}$. By Claim 1, the valuation $v_x$ satisfies $\Delta$.
By compactness, $T$ is consistent. Let $v$ be a valuation satisfying $T$. By Claim 2, there is a point $x\in X$ such that $x\notin U_i$ for all $i\in I$. Thus $(U_i)_{i\in I}$ does not cover $X$, as was to be shown.
Comment: Thank you very much for your very detailed answer. Also, last week I carefully read your past answer to the Tychonoff Theorem question, and I thought I had resolved my lingering issues. However, in reading your answer to the Alexander Subbase Theorem I see that the way you think about these types of problems is a bit different than mine, so I decided to post my answer (re-worked via open covers) to the Tychonoff Theorem question. If my "how to" approach to define what's needed is flawed, I would certainly welcome a correction, if you have the time to read it.


newFixedThreadPool in asynchronous web services Jersey

Question: Hello I tried to create a async web services following a tutorial.
I'm not understand this statement:
service = MoreExecutors.listeningDecorator ( Executors.newFixedThreadPool (10) ) ;
What does that mean ? I can have 10 simultaneous requests ?
because I wanted to know when they get so many simultaneous requests as he works async web services ? there is a queue ?
Answer: Yes, you understand correctly, it means that there is a pool of 10 parallel threads that handles the requests.
Usually there is 1 acceptor that takes the request and forward it to a handler (one of the 10 threads).
But, it doesnt mean that if you will have 100 requests they will be rejected. it just will take longer since they will go into the ThreadPool queue and wait untill there is a free thread to handle them


nginx - How to... DirectoryIndex to a folder

Question: I want to set a initial page inside a folder, besides the common index.htm
I want to change index.htm to /folder/file.htm
Is it possible using nginx?
In my Apache server all I have to do is config the htaccess file, putting this:
DirectoryIndex /folder/file.htm
PS: I tried to do that with RegEx, but I really preffer with DirectoryIndex
Thanks a lot in advance!!!
Comment: The equivalent directive for nginx is [`index`](http://wiki.nginx.org/HttpIndexModule#index). You can specify multiple files, and/or an absolute path that will result in an internal redirect.
Comment: @cyberx86 Why not post that as an answer?
Answer: Nginx has a directive, index, that is equivalent to Apache's DirectoryIndex. As per the documentation:

index
  Syntax:   index file ...
  Default:  index.html
  Context:   http, server, location
Sets the default file to serve if a directory is requested by the
  client. Multiple files can be specified. If the first file isn't
  found, the second will be used and so on. If the last entry begins
  with a /, and none of the earlier files are found, nginx will perform
  an internal redirect to this uri.
e.g.  index index.html index.php /index.php;

As indicated from the above, you can specify multiple files, each of which will be tried in sequence, and can also specify an full path if the file you wish to use is not under the current directory.
Comment: Thanks a lot cyberx86, I will try this and let you know if worked.
Comment: I have a special php file that lists directories and wanted all directories without their own index files to be rewritten to that file - using an absolute path with this directive as the last parameter did just that. Works fine, thanks!


Which wildcard SSL cert vendors allow you to set up the same cert on multiple servers?

Question: We are looking to set up a service where multiple boxes, in different data centers, would allow HTTPS access. We are looking to set to buy a wildcard SSL cert to handle any number of vanity sub domains.
We are primarily looking at goDaddy's wildcard SSL cert. Has anyone set up anything similar to this? We have looked at Digicert's offering but we want to look for cheaper options.
Comment: Certs aren't tied to servers, what you do with them is your own business (within reason).
Comment: Believe it or not, there are CAs that make you execute a licensing agreement that limits the number of servers you can use the certificate on. Strange but true.
Answer: You can create your own wildcard cert also.  You don't get the "brand name" and insurance that goes along with it, but its just as secure.  If the SSL connections aren't used by the general public, and only for your own use, i'd recommend that to save money.
Here is a rough draft of the process (using a Keystore) that you have to hack for your own use.  You'd have to learn how to do it yourself using the following as a "hint" :
<code>:: create authority
openssl req -config %OPENSSL_HOME%\openssl.cfg -new -x509 -extensions v3_ca -keyout %OPENSSL_HOME%\..\demoCA\private\cakey.pem -out %OPENSSL_HOME%\..\demoCA\cacert.pem -days 1096

:: create wildcard cert in keystore, cn name *.site.com
keytool -genkey -alias wildcard -keyalg RSA -keystore %OPENSSL_HOME%\..\myCerts\keystore.kdb

:: generate CSR
keytool -certreq -alias wildcard -keystore %OPENSSL_HOME%\..\myCerts\keystore.kdb -file %OPENSSL_HOME%\..\myCerts\wildcard.csr

:: import CA from previous step into keystore
keytool -import -alias root -keystore %OPENSSL_HOME%\..\myCerts\keystore.kdb -trustcacerts -file %OPENSSL_HOME%\..\demoCA\cacert.pem

:: sign CSR with CA and convert to DER format
openssl ca -config %OPENSSL_HOME%\openssl.cfg -policy policy_anything -out %OPENSSL_HOME%\..\myCerts\wildcard.crt -infiles %OPENSSL_HOME%\..\myCerts\wildcard.csr
openssl x509 -in %OPENSSL_HOME%\..\myCerts\wildcard.crt -inform PEM -out %OPENSSL_HOME%\..\myCerts\wildcard.der -outform DER

:: import chain of wildcard cert
keytool -import -alias wildcard -keystore %OPENSSL_HOME%\..\myCerts\keystore.kdb -trustcacerts -file %OPENSSL_HOME%\..\myCerts\wildcard.der
</code>
Answer: http://www.digicert.com has very flexible licensing including unlimited installs within your domain for UC and Wildcards. We use their UC on Exchange and are shifting from Verisign and Thawte to Digicert for other systems as well due to both the pricing and license flexibility. They also provide a 30 day trial, in which they issue a certificate that has a 30 day validity period, for testing with your systems. So far they've been great for us.
Comment: +1 for Digicert! They've been great to us as well; very professional, excellent technical support, reasonable pricing, and flexible licensing. UCC certs are are useful in many circumstances, not just Exchange 2007, and can be more cost-effective than wildcard certs in most instances. Even their standard certs utilize the Subject Alternate Name field to protect both www.example.com and example.com with a single cert (and license fee).
Comment: +1 Digicert - they are a great company to work with. They're really flexible and helpful on working with you to make sure your cert problems are solved, and really good on fees in my book.
Comment: +1 Digicert - I've had nothing but excellent support from DigiCert.  They're really on the ball.
Answer: We use GoDaddy's wild card certs for most of our sites.  All our sites are hosted by multiple servers.  After you install the cert on the server that creates the CSR export the cert to a PFX file and import it to the other server.  The clients won't know the difference.
GoDaddy knows we do this, and they haven't ever questioned us about it.
Comment: I'm not sure what you're implying here; certs+key are not linked to a server (unlike, say, ssh's known_hosts+server keys) but to a domain name and possibly IP. Needless to say, if said domain name is served by 100 servers, each of them gets a copy of the private key.
Comment: or just the proxy/load-balancer gets the private key and the 100 servers behind it can be just http
Answer: SSL certificates are issued based upon their domain, rather than which server hosts them. All that matters from a client's perspective is that the domain used to access the certificate matches the domain on the certificate itself.
For your needs, I expect any wildcard certificate should work. I'd be interested to see if anyone can provide evidence to the contrary?
Comment: You are correct; there are no technical limitations preventing the installation / use of a wildcard cert on multiple hosts.  It *is*, however, a violation of the contract with the SSL vendor in almost all cases.  I know I've encountered a couple that do explicitly allow installing the cert on multiple hosts, but unfortunately I can't remember which ones...
Comment: Just a follow up, we had contacted goDaddy and they said they support wildcards on multiple servers. So that is the direction we went. Thank you all.
Comment: Not all SSL vendors have the same policies, for instance "Comodo Premium Wildcard" certs have an extra fee per server you want to install the cert on.
Comment: Interesting; didn't know about this. That's a bizarre requirement.
Comment: It is a money thing, Veri$ign makes big profits selling the same tiny file to you multiple times.
Comment: When we upgraded a web server I asked Thawte about moving the cert from the old server to the new server.  They didn't require extra payment in this case, and were very helpful.
Answer: The cheapest one I have found is the one from StartSSL. They only charge for yearly verification and you can have as many wildcard certificates for different domains as you want.
Comment: Important caveat: This method requires that you be the owner of your mail server, or at least have the authority in your company to request that emails to firstname.lastname@example.com  be forwarded to yourself.  So, if you can afford a domain name and mail server, then this is a lot cheaper than other SSL alternatives.
Answer: Maybe a bit too late, but
"GlobalSign SSL Certificates are provided with licensing for an unlimited number of servers included in the standard price."
Comment: At over $500/year even with all discounts, that's not a very good deal.


How do I view java log files in Eclipse

Question: I am running some JUnit tests in Eclipse, and my code is generating an XML log file using the java logging APIs. (java.util.logging). Is there an easy way to view this XML log output in Eclipse, other than reading the raw XML? Specifically I want to be able to easily see what threads different log messages have come from.
Answer: I've been using the SLF4J logging API coupled with the Logback logging implementation.  SLF4J can be configured to map log messages in the java.util.logging, log4j, jakarta commons logging, and SLF4j APIs into a common intermediate form.  On the other side, the messages can be generated via java.util.logging, log4j, or Logback.  It's a flexible approach that works well, especially when you have components that use different logging APIs.
One nice thing about Logback is that you can configure it to send a copy of the log messages to a an Eclipse plug-in.  The plug-in and lets you view and filter the log file in a variety of ways.  Messages contain the thread that generated them, so it sounds like something you should check out.
Comment: True, although there is ongoing work on a new and improved version.
Answer: I think you were looking for the same thing I was looking for. I found UtilLogger4E, but I started my own project (EDevTools LogViewer), because it has some missing features and is not opensource.
It has the abilities to read Java Util Logging XML logs from a file or a configurable socket, display them colored by level in a table and it can show more than one log at a time (through multiple view instances).
Java Util Logging has a built-in feature to send logs to a socket (SocketHandler), it must only be set by the configuration file.
You can take a look at LogViewer at: http://sourceforge.net/projects/edevtools/
Answer: If you want to use log viewer which is not based on eclipse, I recommend you OtrosLogViewer. I can import java.util.logging XML format and SimpleFormat.
Disclaimer: I am the author of OtrosLogViewer
Answer: I was always hoping to find something like Apache Chainsaw for the java.util.logging/Eclipse combination, i.e. a log viewer in Eclipse that listens to a port and a java.util.logging.Handler implementation writing directly to that. But I haven't found such thing yet and didn't get around writing one either. So far I just use a suitable plain-text format to log to the console. Not elegant and no handy filtering options, but it does the job. Writing your own custom formatter is not hard at all.
There is some support for analyzing log files in Eclipse's Test and Performance Tools Platform Project (the name being even worse than the acronym). I never tried that, but it might be useful for you.
Comment: Peter, see my note on SLF4J/Logback.  It does just this, although Thorbjørn points out that there is a bug when using the current release of logback (Ceki says they're working on a solution).
Comment: I'd much prefer something that does not add dependencies into my production code. Particularly SLF4J has burned me already with making incompatible API changes between point releases, causing issues as indirect dependencies of one of my Maven based projects. java.util.logging might not be perfect, but I still don't see a justification for the added costs and risks introduced by the alternatives.
Answer: Just on the side, an excellent tool for viewing log files in real-time is baretail (essentially a tail -f on Windows), but can be set up to highlight certain patterns in colour which can really help. You can find a free version here.
Answer: Depending on exactly what you're trying to do you might just need a good logging setup for your logging sub sys?
A framework I've been using recently uses slf4j to log, by providing the following log4j config I get to see which threads output what:
log4j.rootLogger = trace, default
log4j.appender.default = org.apache.log4j.ConsoleAppender
log4j.appender.default.layout = org.apache.log4j.PatternLayout
log4j.appender.default.layout.ConversionPattern = %-4r [%t] %-5p %c %x - %m%n

In my case I get output similar to the following in the Console tab in eclipse when I run my junit tests.
0    [pool-1-thread-1] INFO  com.example.BaseTest  - Server listening on port 9090
35   [NioProcessor-6] INFO  org.apache.mina.filter.logging.LoggingFilter  - CREATED
35   [NioProcessor-1] INFO  org.apache.mina.filter.logging.LoggingFilter  - CREATED

Answer: I don't see how Eclipse can know about your threads.  If it's XML, you need to write a parser that can find your thread messages using XPath and print them out.  But that's up to you - Eclipse can't read your mind.
You'll have to find an XSL-T stylesheet that can take the XML stream produced by log4j and pull out the threads that you want.
Comment: The thread is part of the java.util.logging output. See http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html#2.4

How do I view java log files in Eclipse


Como usar RNCryptor e Firebase?

Question: Estive pesquisando formas de criptografar os dados de usuário de um aplicativo Android que utiliza Firebase. Neste artigo é recomendado o RNCryptor, porém sem detalhes da implementação. Encontrei esta pergunta sobre o uso para iOS. Como fazer o mesmo para Android?
(Também aceito sugestões de outras formas de criptografia, pois não tenho experiência com isso).
Answer: Você pode tentar usar a Base64 do próprio android.
import android.util.Base64;
private String CodificarBase64(String texto){
        return Base64.encodeToString(texto.getBytes(), Base64.DEFAULT).replaceAll("(\n|\r)", "");
    }
private String DecodificarBase64(String textoCod){
        return new String(Base64.decode(textoCod, Base64.DEFAULT));
    }

Como usar RNCryptor e Firebase?


If differentials aren't supposed to be treated like fractions, how come we do just that in Differential Equations?

Question: For years I've heard that differentials aren't fractions and multiplying $\frac {d y}{d x} $ with $d x$ to "cancel out the denominator" isn't the right view, yet I've never been shown this "right view" and in my ODE class we always do exactly what we were told was wrong.
What exactly are the properties and proper usages of differentials? How come we're told they don't technically "cancel out" in fractions, yet nearly everything we've been exposed to counters that?
Comment: Related, possibly duplicates: http://math.stackexchange.com/questions/1252405/is-it-mathematically-valid-to-separate-variables-in-a-differential-equation and http://math.stackexchange.com/questions/27425/what-am-i-doing-when-i-separate-the-variables-of-a-differential-equation
Comment: Also: http://math.stackexchange.com/q/1356981/34930
Answer: Consider the following example
\begin{align}
\frac{dy}{dx} = xy
\end{align}
which is a separable differential equation. In particular, it is taught in most ODE courses that you could rewrite the equation as
\begin{align}
\frac{1}{y}dy = xdx
\end{align}
then integrate both sides accordingly and everything will workout. However, a more rigorous way is to view as follow
\begin{align}
\int \frac{1}{y}\frac{dy}{dx}\ dx = \int x\ dx
\end{align}
then by the change of variable formula we get that
\begin{align}
\int\frac{1}{y} \frac{dy}{dx}\ dx = \int \frac{1}{y}\ dy.
\end{align}
So by treating the ordinary derivative as a fraction, you simply save the step for justifying the change of variable.
Comment: Your use of the word "then" in "then by the change of variables formula" is confusing: it suggests, or at least could suggest, the equation that follows is *deduced from* the previous equation, but it's not. (I would have said "but the change of variables formula says the lefthand side is $\int\frac{1}{y}\,dy$.")
Comment: Is this always the case though? Is there a case where treating differentials as fractions could bring about errors in calculation?
Comment: Remember, $\frac{dy}{dx} \approx \frac{\Delta y}{\Delta x}$ which is a fraction. However the only difference is that there is also a limit involved in the definition of derivative which means that you might have infinity over infinity as a fraction.
Comment: @AndrewTawfeek : Yes, there are restrictions on the substitution that the "short way" may occlude: The substitution is only valid on monotone branches of the substitution function, i.e., where it is bijective. Any extension beyond must be justified and may require the adjustment of integration constants
Answer: Given Co-Ordinate projections in ${\mathbb{R}^2}$
\begin{gathered}
  x:{\mathbb{R}^2} \to \mathbb{R},x\left( p \right) = u \hfill \\
  y:{\mathbb{R}^2} \to \mathbb{R},y\left( p \right) = v \hfill \\
\end{gathered}
point $p \in {\mathbb{R}^2}$ can now be written like
$$p = \left( {u,v} \right)$$.
Differentials from these Co-Ordinate functions at point $p$
\begin{gathered}
  d{x_p} = {T_p}{\mathbb{R}^2} \to \mathbb{R} \hfill \\
  d{y_p} = {T_p}{\mathbb{R}^2} \to \mathbb{R} \hfill \\
\end{gathered}
are Co-Vectors, that means $d{x_p},d{y_p} \in T_p^*{\mathbb{R}^2}$.
For every Tangent-Vector like $\xi  \in {T_p}{\mathbb{R}^2}$, we have
$$\xi  = a\frac{\partial }{{\partial x}} + b\frac{\partial }{{\partial y}}$$
$a,b \in \mathbb{R}$. Now
$$d{x_p}\left( \xi  \right) = d{x_p}\left( {a\frac{\partial }{{\partial x}} + b\frac{\partial }{{\partial y}}} \right) = d{x_p}\left( {a\frac{\partial }{{\partial x}}} \right) + d{x_p}\left( {b\frac{\partial }{{\partial y}}} \right) = a\frac{{\partial x}}{{\partial x}} + b\frac{{\partial x}}{{\partial y}} = a$$
$$d{y_p}\left( \xi  \right) = d{y_p}\left( {a\frac{\partial }{{\partial x}} + b\frac{\partial }{{\partial y}}} \right) = d{y_p}\left( {a\frac{\partial }{{\partial x}}} \right) + d{y_p}\left( {b\frac{\partial }{{\partial y}}} \right) = a\frac{{\partial y}}{{\partial x}} + b\frac{{\partial y}}{{\partial y}} = b$$.
That is: $d{x_p},d{y_p} \in T_p^*{\mathbb{R}^2}$ are linear real-valued functions. And from this point of view we are calculating with real numbers.
So we can divide them like $\frac{{d{y_p}}}{{d{x_p}}}$ and there is nothing to
worry about. If $f:{\mathbb{R}^2} \to \mathbb{R},y = f\left( x \right)$
for a differentiable function, we have
$$\frac{{d{y_p}}}{{d{x_p}}} = f'\left( p \right)$$
Nothing, but a real number.


Series comparisons and logarithms?

Question: Prove the convergence of
$$
\sum_{n = 1}^{\infty}
{\sqrt{\, 2n - 1\,}\,\ln\left(4n + 1\right) \over n\left(n+1\right)}
$$
I've been struggling for hours on this. By the textbook we have the limit test, comparison test, asymptotic test and integral test. When I use the asymptotic test my quotient ends up as $0$ or $\infty$, and I cannot prove anything. Since I am self studying, I have no one to turn to. The rest of the questions were easy, but I cant figure this out. Please help!
Answer: The two problems yield to basically the same technique. We look at the first one, which is somewhat harder.
First let us argue informally. Note that $\sqrt{2n-1}$ in the long run behaves like $\sqrt{2}\sqrt{n}$. Since we won't worry about constants, let us say it behaves like $\sqrt{n}$.
The bottom behaves like $n^2$, so $\frac{\sqrt{2n-1}}{n(n+1)}$ behaves like $\frac{1}{n^{3/2}}$.
The term $\ln(4n+1)$, in the long run, grows very slowly, more slowly than any power of $n$. So in the long run, in particular, it grows more slowly than $n^{1/4}$. Thus, in the long run, our original expression goes to $0$ faster than $\frac{1}{n^{5/4}}$.
But $\sum_1^\infty \frac{1}{n^{5/4}}$ converges. It follows that our original series converges.
In essence, in $\frac{1}{n^{3/2}}$, the exponent $3/2$ is plenty big enough to ensure convergence. So we grab an $n^{1/4}$ from it to "kill" the $\ln(4n+1)$ term. That leaves us with $\frac{1}{n^{5/4}}$, which still goes to $0$ fast enough.
Now it is time to turn the above into a more formal argument, say by using the Limit Comparison Test. Let $a_n$ be the $n$-th term of our series. We show that
$$\lim_{n\to\infty} \frac{a_n}{\frac{1}{n^{5/4}}}=0.$$
Since $n^{5/4}=n^{3/2}/n^{1/4}$, we want to show that
$$\lim_{n\to\infty} \frac{\sqrt{2n-1}\,n^{3/2}}{n(n+1)}\frac{\ln(4n+1)}{n^{1/4}}=0.$$
We can use L'Hospital's Rule to show that $\lim_{n\to\infty}\frac{\ln(4n+1)}{n^{1/4}}=0$.
Standard techniques show that
$$\lim_{n\to\infty}\frac{\sqrt{2n-1}\,n^{3/2}}{n(n+1)}=\sqrt{2}.$$
This completes the Limit Comparison argument.
Comment: This technique also works. I think this is what the book was getting at. Thanks!
Comment: You are welcome. You will see that exactly the same idea will work for your second problem. We need not have grabbed $n^{1/4}$ to kill the $\ln(4n+1)$ term. for example, $n^{0.1}$, or $n^{0.4}$, would have worked. But $n^{0.5}$ would not, since it takes away too much from $n^{3/2}$.
Answer: I would suggest you start with some rough hand-wavy approximations and then make it rigorous. For example, when $n$ is large,
$$\frac {\sqrt{2n-1}}{n(n+1)}\approx \frac {\sqrt {2n}}{n^2}=\sqrt 2 n^{-3/2}$$
and $\ln (4n+1) \sim \ln n$.
Let's try integrating
$$\int x^{-3/2} \ln x \,dx.$$
Let $u = \ln x$, $du = \frac 1 x dx$, $dv = x^{-3/2}$, $v=-2 x^{-1/2}$.
This gives an integral of
\begin{align*}
-2x^{-1/2}\ln x - \int -2x^{-3/2}\,dx
&=-2x^{-1/2}\ln x-4x^{-1/2} +C\\
&=-2\frac{\ln x}{\sqrt x}-4\frac{1}{\sqrt x}+C.
\end{align*}
So the integral from, say, $1$ to $+\infty$ of this thing is quite clearly finite.
Comment: I've tried that. Ended up with $\frac{{1}/{n^(1/2)}}$ which doesn't converge, while the textbook says it does.
Comment: @Haresh, I think you made a mistake somewhere along the way. I suggest you try it again. What you end up with is the result of approximating $\ln n$ by something proportional to $n$, which would be a terrible approximation.
Comment: Okay, I think the I mixed up my work with my second question, which I removed to meet guidelines, and the problem is that the textbook does not tell us why  $\frac{\ln n}{n^p}}$, for p greater than 1 converges. How would I prove this? Both of the problems boil down to this series.
Comment: @Haresh, check out http://www.math.uconn.edu/~kconrad/blurbs/analysis/growth.pdf
Comment: Thanks so much, I now see that I had to use integration by parts. I would never have figured this out!
Comment: @Haresh, André's approach doesn't use integration at all. I was just using one of the very few convergence tests I actually remember!
Answer: $\ln n$ grows much, much, much more slowly than any positive power of $n$.  So for $n$ large enough,
$$ \frac{\sqrt{2n-1}\ln(4n+2)}{n(n+1)} < \frac{\sqrt{2n}*n^{1/10}}{n^2}<\frac{2}{n^{14/10}}.$$
Use the Comparison Test (then the Integral Test).  You may have to justify the first inequality, depending on who's asking.

Series comparisons and logarithms?


Find the principal value of $\big[\frac{e}{2}(-1-\sqrt3i)\big]^{3\pi i}$

Question: I have been asked to find the principal value of: $\big[\frac{e}{2}(-1-\sqrt3i)\big]^{3\pi i}$
The textbook Complex Variables with Applications by A. David Wunsch only provides answers to the odd questions and I have found myself at a loss. All examples I have found have been much simpler in nature. any help would be appreciated.
Comment: is the $i$ under the radical, or does it, in fact, belong outside?
Comment: Write the complex number $\frac{e}{2}(-1-\sqrt{3}i)$ in polar form, and then raise it to the power $3\pi i$.
Comment: You are correct that is my mistype, the i does belong outside - I will correct.
Answer: \begin{align}
  & \left(\frac e2(-1-\sqrt{3}i)\right)^{3\pi i} \\
= & e^{3\pi i}\cdot\left(-\frac12-\frac{\sqrt3}2i\right)^{3\pi i} \\
= & (e^{\pi i})^3\cdot\left(e^{\tfrac{-2\pi i}3}\right)^{3\pi i} \\
= & (-1)^3\cdot e^{\tfrac{-2\pi i}3\cdot3\pi i} \\
= & -e^{2\pi^2} \\
\end{align}
Answer: $1+i\sqrt 3 = 2 (\frac 12 + i \frac {\sqrt {3}}{2}) = 2(\cos \frac {\pi}{3} + i\sin \frac {\pi}{3}) = 2e^{\frac {\pi}{3}i}$
$\left((\frac {e}{2})(2e^{\frac {\pi}{3}i})\right)^{3\pi i}\\
\left(e^{\frac {\pi}{3}i+1}\right)^{3\pi i}\\
e^{(\frac {\pi}{3}i+1)\cdot (3\pi i)}\\
(e^{-\pi^2}e^{3\pi i})\\
e^{3\pi i} = -1\\
-e^{-\pi^2}\\
$
Comment: The question asks for $-1 - i\sqrt{3}$, perhaps you may write the angle as $\frac{-2 \pi}{3}$ to correct it?


Add 15 minutes to current time then determine whether new time went past midnight

Question: I want to:

Get the current time
Add 15 minutes
Display the new time in H:i:s
Know whether the new time went past midnight

Some examples:
Now is 12:00:00
$plus15 is 12:15:00
$pastmidnight = 0

Now is 23:55:00
$plus15 is 00:10:00
$pastmidnight = 1

I'd like to use DateTime, but this attempt gives unexpected results:
$now = new DateTime(date('H:i:s'));
$now2 = new DateTime(date('H:i:s'));
$now->modify('+15 minutes'); // try "+23 hours", doesn't set $pastmidnight to 1
if($now < $now2){
    $pastmidnight = 1;
}else{
    $pastmidnight = 0;
}
echo $pastmidnight . "->" . $now->format('H:i:s') . "\n";

Comment: Your `$now < $now2` condition will **always** be `false`
Answer: You have the right idea, but $now will never be less than $now2, so your conditional will never trigger. Even if you added the 15 minutes to $now2 the logic wouldn't hold, as it would always trigger.
To correct this, I would recommend comparing against strtotime('today midnight'):
$now = new DateTime(date('H:i:s'));
$now->modify('+15 minutes');
$midnight = new DateTime(strtotime('today midnight'));
if ($now > $midnight) {
  $pastmidnight = 1;
}

Or set the time of the DateTime to midnight with setTime(0,0):
$now = new DateTime(date('H:i:s'));
$now->modify('+15 minutes');
$midnight = new DateTime(date('H:i:s'));
$midnight = $now->setTime(0,0);
if ($now > $midnight) {
    $pastmidnight = 1;
}
else{
    $pastmidnight = 0;
}

Comment: Don't think you need `strtotime`. I think `DateTime` can handle the same strings
Comment: Neither of those 2 work for me. I tried with '+23 hours' to get past midnight, but $pastmidnight is always 0
Comment: I got it with @Phil's suggestion: if(!(date_format(new DateTime(date('H:i:s')), 'Y-m-d') == date_format($time, 'Y-m-d'))){


IPHONE: UIAlertView called twice in a custom function/IBAction

Question: i have an IBAction which does some processing and within will have a few UIAlertViews (to show alerts). However it seems that the FIRST alert in the paragraph is being called TWICE (once immediately after i clicked and another time after all the other alerts has occured). Additionally, the first time the alert appears, the alert automatically closes even though i have an OK button and the user has not clicked on it. The 2nd time the alert appears, it will require the user to click on OK.
I tried moving the paragraph out from IBAction into its own function but still the problem occurs.
all the alerts in my IBAction/function are the same:
<code> UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"blah" message:@"blah" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];
   [alert show];
   [alert release];
</code>
but the other alerts function normally.
the code looks like this ("blah" is the one being called twice):
<code>-(void)function {
  if (......) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"blah" message:@"blah" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];
         [alert show];
         [alert release];
     for (int i=0; i<2; i++) {
    if (.....) {
          //do stuff
    } else {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"blah2" message:@"blah2" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];
         [alert2 show];
         [alert2 release];
    }
     }
   } else {
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"blah3" message:@"blah3" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil,nil];
         [alert3 show];
         [alert3 release];
}
}
</code>
please help!
Comment: its a straight forward code, nothing fancy.
Answer: First of all, we need more code to diagnose your problem. What you provide is not sufficient.
Second, I once encountered a similar problem: when a compose an email action is triggered by the user who didn't set up her email account on that device, I asked my app to show an UIAlertView. However, when I tested my code on a real device with such a scenario, two consecutive UIAlertViews showed, one after another, both of which are about the email account not set up issue.
I finally figured out that the iOS system will automatically show an UIAlertView when the email account is not set up while a user tries to compose an email, which is why two UIAlertViews showed up when I only expected one.
Hope that helps.
Comment: well the problem is my code is rather long. and its mostly just if else and for loop statements doing stuff (which works fine as i have tested) but its the uialertview that's behaving oddly.
Comment: so i guess i am asking if anyone else had experienced this issue before where uialertview is called twice and the first time it is called, the uialertview will auto close (no one press the OK button) whereas the 2nd time it appears it requires a click to close it.
Comment: or could it be because i created the program as a view app but i  have never used the view (in interfacebuilder) and i created a window and all the action is being done on the window?


Error: Undeclared identifier: 'OutputDebugString'

Question: I use OutputDebugString in my Delphi Code, but I receive the error:

Error: Undeclared identifier: 'OutputDebugString'

Which package is this OutputDebugString in?
Comment: Useful tip in future; In a unit that has it working, Ctrl-Click and it will find the unit containing the symbol. And in Delphi recent versions, F1 on OutputDebugString might get you some help too.
Comment: ...or hover your mouse cursor over the symbol and see the help insight (in a unit that has it working).
Comment: Instead of Ctrl-Cick, I prefer to use "Find definition" from the context menu (or is it "Find declaration"?). I keep forgetting all those key-key and key-mouse combinations.
Comment: Personally I prefer Windows Search 4. At the beginning you just need to explain it that pas-files are "plain text" and point it to directories which should be indexed.
Comment: @Torbins - I prefer source searching too, because some classes are defined in more than one namespace - for instance TBitmap; it's in [Graphics.pas](http://docwiki.embarcadero.com/VCL/en/Graphics.TBitmap) as well as in [Windows.pas](http://msdn.microsoft.com/en-us/library/dd183371%28v=vs.85%29.aspx) but they mean totally different thing. There I wouldn't rely on the methods mentioned above; even if they are much more faster than this searching. But hey, isn't there some tool, some class explorer for this, something in CnPack or another IDE extension ?
Comment: If not it would be fine to create one. As a starting version would be enough to search *.pas (*.inc and whatever) files in predefined directories for `TClassYoureLookingFor =`
Comment: Windows Search 4 is extremely fast. I never had a need of something faster.
Answer: It's declared in the Windows unit.
Answer: In windows unit in Winapi namespace:
uses
   Winapi.Windows;

How to find the unit of a specific command:

Through Find Definition command in the context menu
Through Help Insight information invoked by hovering the mouse
Or just use Windows Search or a popular search tool


Convert rgb images to grayscale images

Question: I have a numpy array of rgb images as shown below
print(train_frames.shape) #(100, 40, 120, 140, 3)

which means 100 rows each of 40 frames contains an image of 120x140.
I need to convert that into gray scale images i.e,
print(train_frames.shape) #(100, 40, 120, 140, 1)

How to convert that ?
Answer: If you want to do that in batch, one way is to use numpy.mean
numpy.mean(train_frames, axis=-1)

axis=-1 means the 3 rgb channels.
If you want to get a better conversion, I guess you will need to convert image by image with opencv cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Comment: When I am using that cv2.cvtColor thing, I am getting array shape of only (100, 40, 120, 160) instead of (100, 40, 120, 160, 1)
Comment: To use cvtColor you must iterate on the (100, 40) matrix with 120x160x3 images. Each image should be converted to a 120x160x1. Got it?

Convert rgb images to grayscale images