Deserializing complicated xml into objects - Problems creating the objects

Question: Ok so I am working on deserializing an xml document into objects.
Basically my xml document will look like this:
<?xml version="1.0"?>
<root>
    <eConnect CUSTNMBR="22222" DATE1="1900-01-01T00:00:00" TABLENAME="RM00101" DBNAME="BOLT" Requester_DOCTYPE="Customer" ACTION="0">
        <Customer>
            <CUSTNMBR>22222</CUSTNMBR>
            <ADDRESS1>123 ABC St</ADDRESS1>
            <ADDRESS2/>
            <ADDRESS3/>
            <ADRSCODE>PRIMARY</ADRSCODE>
            <CITY>Ann Arbor</CITY>
            <CNTCPRSN/>
            <COUNTRY>USA</COUNTRY>
            <CPRCSTNM/>
            <CURNCYID/>
            <CUSTCLAS/>
            <CUSTDISC>0</CUSTDISC>
            <CUSTNAME>Test Customer 2</CUSTNAME>
            <PHONE1>4165551234</PHONE1>
            <PHONE2/>
            <PHONE3/>
            <FAX/>
            <PYMTRMID/>
            <SALSTERR/>
            <SHIPMTHD/>
            <SLPRSNID/>
            <STATE>Micigan</STATE>
            <TAXSCHID/>
            <TXRGNNUM/>
            <UPSZONE/>
            <ZIP>45612</ZIP>
            <STMTNAME>Test Customer 2</STMTNAME>
            <SHRTNAME>Test Customer 2</SHRTNAME>
            <PRBTADCD>PRIMARY</PRBTADCD>
            <PRSTADCD>PRIMARY</PRSTADCD>
            <STADDRCD>PRIMARY</STADDRCD>
            <CHEKBKID/>
            <CRLMTTYP>0</CRLMTTYP>
            <CRLMTAMT>0.00000</CRLMTAMT>
            <CRLMTPER>0</CRLMTPER>
            <CRLMTPAM>0.00000</CRLMTPAM>
            <RATETPID/>
            <PRCLEVEL/>
            <MINPYTYP>0</MINPYTYP>
            <MINPYDLR>0.00000</MINPYDLR>
            <MINPYPCT>0</MINPYPCT>
            <FNCHATYP>0</FNCHATYP>
            <FNCHPCNT>0</FNCHPCNT>
            <FINCHDLR>0.00000</FINCHDLR>
            <MXWOFTYP>0</MXWOFTYP>
            <MXWROFAM>0.00000</MXWROFAM>
            <COMMENT1>test comment</COMMENT1>
            <COMMENT2>another test</COMMENT2>
            <USERDEF1/>
            <USERDEF2/>
            <TAXEXMT1/>
            <TAXEXMT2/>
            <BALNCTYP>0</BALNCTYP>
            <STMTCYCL>5</STMTCYCL>
            <BANKNAME/>
            <BNKBRNCH/>
            <FRSTINDT>1900-01-01T00:00:00</FRSTINDT>
            <INACTIVE>0</INACTIVE>
            <HOLD>0</HOLD>
            <CRCARDID/>
            <CRCRDNUM/>
            <CCRDXPDT>1900-01-01T00:00:00</CCRDXPDT>
            <KPDSTHST>1</KPDSTHST>
            <KPCALHST>1</KPCALHST>
            <KPERHIST>1</KPERHIST>
            <KPTRXHST>1</KPTRXHST>
            <CREATDDT>2015-11-27T00:00:00</CREATDDT>
            <MODIFDT>2015-11-27T00:00:00</MODIFDT>
            <Revalue_Customer>1</Revalue_Customer>
            <Post_Results_To>0</Post_Results_To>
            <FINCHID/>
            <GOVCRPID/>
            <GOVINDID/>
            <DISGRPER>0</DISGRPER>
            <DUEGRPER>0</DUEGRPER>
            <DOCFMTID/>
            <Send_Email_Statements>0</Send_Email_Statements>
            <GPSFOINTEGRATIONID/>
            <INTEGRATIONSOURCE>0</INTEGRATIONSOURCE>
            <INTEGRATIONID/>
            <Address>
                <CUSTNMBR>22222</CUSTNMBR>
                <ADRSCODE>PRIMARY</ADRSCODE>
                <SLPRSNID/>
                <UPSZONE/>
                <SHIPMTHD/>
                <TAXSCHID/>
                <CNTCPRSN/>
                <ADDRESS1>123 ABC St</ADDRESS1>
                <ADDRESS2/>
                <ADDRESS3/>
                <COUNTRY>USA</COUNTRY>
                <CITY>Ann Arbor</CITY>
                <STATE>Micigan</STATE>
                <ZIP>45612</ZIP>
                <PHONE1>4165551234</PHONE1>
                <PHONE2/>
                <PHONE3/>
                <FAX/>
                <GPSFOINTEGRATIONID/>
                <INTEGRATIONSOURCE>0</INTEGRATIONSOURCE>
                <INTEGRATIONID/>
                <Internet_Address/>
            </Address>
        </Customer>
    </eConnect>
</root>

When I try to deserialize this, I get an "Object reference not set to instance of an object" exception. My classes look like this:
    [XmlRoot("root")]
    public class eConnect
    {
        public Customer customer;
    }

    public class Customer
    {
        public string CUSTNMBR { get; set; }
        public string CUSTNAME { get; set; }

    }

Am I getting the exception because I have to have variables for all the nodes in the xml document? Is there a way to only use the nodes I need?
Also am I creating my classes the right way, because basically the xml will have a root node called root and the root can contain multiple eConnect nodes, but each eConnect node will only contain one customer node.
Comment: You'll want `public Customer customer` to be a property not a field.  Not sure if that's your only problem, however.
Comment: You have three layers of tags : root, eConnect, Customer, but your classes have only two layer : root, Customer.  The XMLRoot and class name should be the same.
Comment: Why didn't you use the technique outlined here: [Microsoft Dynamics GP EConnect: Deserializing a Transaction Requester document](https://learn.microsoft.com/en-us/previous-versions/dynamicsgp/developer/ff623173(v=msdn.10)?redirectedfrom=MSDN)?
Answer: Try adding the Serializable attribute on your classes and using the XmlElement tag inside your classes to define how the objects are mapped. I would also make a separate class for your root.
[XmlRoot("root")]
[Serializable]
public class Root
{
    public Root()
    {
        eConnects = new List<eConnect>();
    }

    [XmlElement("eConnect")]
    public List<eConnect> eConnects { get; set; }
}

[XmlRoot("eConnect")]
[Serializable]
public class eConnect
{
    [XmlElement("Customer")]
    public Customer customer { get; set; }
}

[XmlRoot("Customer")]
[Serializable]
public class Customer
{
    [XmlElement("CUSTNMBR")]
    public string CUSTNMBR { get; set; }
    [XmlElement("CUSTNAME")]
    public string CUSTNAME { get; set; }

}

Using the XmlElement tag also gives you the freedom to name your variables friendlier names. For example you could switch
[XmlElement("CUSTNAME")]
public string CUSTNAME { get; set; }

to
[XmlElement("CUSTNAME")]
public string CustomerName { get; set; }

Comment: I think you need a `public` on the `eConnects` property of the `Root` class (for the `XmlSerializer` anyway).
Comment: @steve16351 you are right, I just forgot to type it :) It's fixed now.
Comment: Thanks a lot, that fixed my problem!
Answer: Use Visual Studio's Paste XML as Classes feature.
To do this: Open Visual Studio > Edit Menu > Paste Special > Paste XML as Classes.
The resulting classes may need clean up (e.g. change type from ushort to int etc.). This feature handles the necessary attributes for serialization. Here is an example for your xml:
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class root
{

    private rootEConnect eConnectField;

    /// <remarks/>
    public rootEConnect eConnect
    {
        get
        {
            return this.eConnectField;
        }
        set
        {
            this.eConnectField = value;
        }
    }
}

// Intermediate Xml nodes ...

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class rootEConnectCustomer
{

    private ushort cUSTNMBRField;

    private string aDDRESS1Field;

    private object aDDRESS2Field;

    private object aDDRESS3Field;

    private string aDRSCODEField;

    // rest of class ...
}


How can I defer delivery of an email message with exim?

Question: I have previously used sendmail from the command line to send a large number of messages and used the -odd flag to defer delivery so that the program puts the emails into the queue quickly and returns to the user while messages are delivered in the background. This is described in the DeliveryMode portion of the man page:
http://www.sendmail.org/~ca/email/man/sendmail.html
The new server I am moving to is using exim and sendmail is aliased to exim, and is choking on the -odd flag. Is there a way to force exim to perform a deferred delivery on a message from the command line and put it into the queue instead of immediately trying to deliver it?
Comment: Thanks so much for this, I've been searching for sendmail command line options for delayed sending EVERYWHERE!
Answer: Have your tried/considered using exim supported -odq? (or exim specific -odqs)
Sendmail's -odd puts messages in queue like -odq and avoids doing any DNS loops.
The Exim command line

-odq  This option applies to all modes in which Exim accepts incoming messages, including the listening daemon. It specifies that the accepting process should not automatically start a delivery process for each message received. Messages are placed on the queue, and remain there until a subsequent queue runner process encounters them. There are several configuration options (such as queue_only) that can be used to queue incoming messages under certain conditions. This option overrides all of them and also -odqs. It always forces queueing.
Comment: If messages will be delivered to remote hosts also `-odqs` can be interesting.
Comment: They are actually only being delivered to remote hosts, so I think the distinction offered between odq and odqs is not too important for my use case, but thanks! Appreciate the response, Andrzej!


Music decreases fps in android 5.0 lolllipop version(nexus tab10) cocos2dx

Question: I am creating a game using cocos2d-x version 2.2.x, most of the part of this game has been completed and it is working well on all android devices except Nexus 10. The game was working well on nexus 10 before but now i have updated my nexus tab to android 5.0 (lollipop) . Now I have started encountering some issue related to audio.
The problem is that whenever my game plays any music file the frame from drops down 60 to 1, because of that all my animations stop. I am using ".mp3" format for all the sound files.
Comment: Test if this is related with your problem https://github.com/cocos2d/cocos2d-x/pull/9088/files
Comment: this does not work for me, this link is related to play background music,my game fps decreases in when i play effect
Comment: Can you try using .ogg files instead? I'm using XLD (http://tmkk.undo.jp/xld/index_e.html) to convert.
Comment: I tried .ogg format, but it also does not work
Answer: There is a problem with android 5.0 and the simpleAudioEngine
Google have altered the mediaplayer, which the simpleAudioEngine is using, some game ca not run at all on Android 5.0
luckily,  there is a much improved audio engine in v3.3, you can try to copy that audio engine into your v2.2.x
Comment: Thanx for reply, I tried to copy v3.3 audio engine into v2.2, but i failed, if you have any idea or solution please tell me
Answer: New AudioEngine in cocos2dx3.3 is work fine in Android 5.0.
A little differ between cocos2dx2.2 and cocos2dx3.3.
https://github.com/chenzepei/Cocos2dx2.2-AudioEngine


OpenVPN Access Server - How Do You Route All Client Traffic Through The VPN?

Question: I currently have an EC2 server with OpenVPN installed that I spun up using the official OpenVPN Access Server AMI.
I went through the OpenVPN setup process with all default values selected and I've been able to connect to my instance using the Windows client I downloaded from the VPN server.
My purpose is to use the VPN server to connect to the internet.  I will be going to a country where certain websites and services are blocked and need the VPN server to bypass the firewalls in place.  I do not plan on using the VPN server to access any private networks.
I have updated my OpenVPN Access Server settings to force it to route all internet traffic and to have its clients use the same DNS servers as the access server host:

I have also enabled IP forwarding on my EC2 instance with the following command:
<code>echo 'net.ipv4.ip_forward=1' | sudo tee -a /etc/sysctl.d/99-sysctl.conf
</code>
With the above settings, I am unable to connect to the internet when I am connected to my VPN.  If I turn off Should client internet traffic be routed through the VPN, I can connect to the internet, but I would be connected through my original ISP IP address.
What else do you need to do here to enable OpenVPN to route all internet traffic?
Comment: Can you check after connecting to vpn server, if the client routing table get successfully updated? If you don't see a default route pointing to the vpn server, then there is a problem.
Comment: Any news on this? I have a same problem here. btw as @Bruce mentioned you need to disable "Change Source/Destination Check" on your instance.
Comment: Any updates?  I'm having the same issue.  Man, openvpn has poor, terse documentation!
Answer: On AWS Web Console, select your OpenVPN Access Server instance, then select "Actions", then select "Networking" then disable "Change Source/Destination Check"
Comment: Same problem here. Well that is an extra step that should be done, but even with disabling that option I can't connect to internet through my OpenVPN server.


POO em Java - Modelagem Copa do Mundo

Question: Estou adentrado ao universo de Orientação à Objetos e, movido pela curiosidade, decidi tentar simular a organização de uma Copa do Mundo através destes conceitos.
Bom, estou com algumas dificuldades com relação às classes e gostaria da ajuda de vocês para que, através da análise da Modelagem abaixo, pudessem me orientar.
Comment: Você já tentou implementar?
Answer: Um grupo contém seleções e não o contrário, então a composição deveria estar "invertida".
Um grupo também contém partidas, então está faltando uma agregação.
No mais, acho que você aplicou bem os conceitos.
Comment: Eu pensei nisso, porém acredito que dessa forma, não há relacionamento entre "Grupo" e "Partida" ao fim da Fase de Grupos. Por isso que considerei que uma Seleção disputa uma Partida pois, assim, as seleções classificadas continuam com o mesmo critério de partida.
Comment: Você pode fazer uma interface de partida e então implementá-la na fase de grupos, playoffs, semi-finais e tal também.

POO em Java - Modelagem Copa do Mundo


spark Dataframe string to Hive varchar

Question: I read data from Oracle via spark JDBC connection to a DataFrame. I have a column which is obviously StringType in dataframe.
Now I want to persist this in Hive, but as datatype Varchar(5). I know the string would be truncated but it is ok.
I tried using UDFs which didn't work since dataframe does not have varchar or char types. I also created a temporary view in Hive using:
val tv = df.createOrReplaceTempView("t_name")
val df = spark.sql("select cast(col_name as varchar(5)) from tv")

But then when i printSchema, i still see a string type.
How can I make I save it as a varchar column in Hive table ?
Comment: There is a `org.apache.spark.sql.types.VarcharType`. Did you try using that ?
Comment: yes, it says string cannot be casted to VarcharType
Answer: Try creating Hive table("dbName.tableName") with required schema (varchar(5) in this case) and insert into the table directly from Dataframe like below.
df.write.insertInto("dbName.tableName" ,overwrite = False)

spark Dataframe string to Hive varchar


Flagging a variable value

Question: I am trying to create a set of constraints that forces a binary variable $y$ to be set to a certain value when a variable $x$ is greater than or equal to zero. I have,
$-1 \leq x \leq 1, \qquad x \in {\rm I\!R}$
$y = \begin{cases}
1 & \text{if } x \geq 0\\
0 & \text{if } x  < 0
\end{cases}$
I believe the way to practically do this is as follows:
$x \leq My - \epsilon$
$-x \leq M(1-y)$
Note that $M$ is a very large number and $\epsilon$ is a very small number.
I am unsure if there is a better way to do this, let me know if there is. I don't like the fact that I need to use the $\epsilon$ value to separate from the $0$ boundary, but I may have no other choice.
Comment: It's not really clear what you are trying to do here. What do you mean by "constraints that flag when a variable is greater than or equal to zero"? Which variable are you trying to check? Why is there an $x$ and a $y$?
Comment: So when variable $x$ is greater than or equal to $0$ I need to force $y$ to become equal to $1$. On the contrary, when $x$ is less than $0$, I need to force $y$ to become equal to $0$.
Comment: Added this clarification to the question.
Answer: What you have is the standard modeling approach, and the $\epsilon$ is unavoidable unless you want the $x=0$ case to allow either value for $y$.  Because $x$ has bounds $[-1,1]$, you can (and should) replace $M$ with 1 in both places.
Comment: Thanks a bunch! Wanted to make sure. I'll be sure to set $M$ to $1$.

Flagging a variable value


Location module predictive textfield

Question: If you are familiar with the location module you would know that when creating a location the state/province textfield predicts options as you type. These options come from a file in the Location module.
I need to re-create that for the city field. Can you please point me in the right direction of how to accomplish this? I want to avoid user typos.
Do I need to create a module of my own or do I hack Location.module ???
Thanks
Answer: What this is is an autocomplete field. My guess is if you want to recreate it for another field within the same module then you will indeed need to hack Location module. You'll want to look at the autocomplete callback for the state/province field as well as the autocomplete properties set on the field itself.
However, this may be difficult to do with cities, which is probably why it hasn't been done in Location. If you want to an autocomplete field for cities that actually adheres to the cities wiin a state/province, or even if it doesn't adhere, it will require a full list of cities within each state/province. That's a pretty hefty task if you ask me, but it certainly isn't impossible. I would check around the Location issue queue to see if this has been discussed before. Maybe you can gain information on why it was never done and what the drawbacks may be to developing this.

Location module predictive textfield


Automatically downloading attachments from outlook

Question: Following site. Created this code into a modul:
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment

For Each objAtt In itm.Attachments
    objAtt.SaveAsFile "C:\Data\" & objAtt.DisplayName
    Set objAtt = Nothing
Next
End Sub

But nothing happens when I set up a rule which calls the script everytime a mail comes in.
Answer: what your doing looks correct..
Are you sure there are attachments attached to your email ?
and if so have you tried debugging to make sure this sub is being called ?
if it is then have you checked its actually fetching the attachments from the email ?
or is it returning an empty collection of attachments ?
also you can simplify your for each like so -
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
        For Each objAtt As Outlook.Attachment In itm.Attachments
            objAtt.SaveAsFile("C:\Data\" & objAtt.DisplayName)
        Next
    End Sub

Comment: yes, there are attachments. how can i debug it since it has an argument in the function?
Comment: run the program in debug and put a breakpoint on the for each, hover over itm.Attachments and see if there any attachments in that collection, if there aren't then there's an issue fetching the attachments, if there are then there's more than likely an issue with saving them
Comment: A method of debugging is [here](https://stackoverflow.com/questions/5029141/debugging-an-outlook-2007-script-fired-by-a-rule).


Solve the phase plane equation to obtain the integral curves for the system:

Question: Solve the phase plane equation to obtain the integral curves for the system:
$$\begin{align*}\frac{\mathrm dx}{\mathrm dt}&=2y-x\\\frac{\mathrm dy}{\mathrm dt}&=e^x+y\end{align*}$$
It's for a 200 level paper; differential equations. What is important with this question is that it is non-linear. So he can't use linear methods. He will try a Jacobian matrix and see if that gives anything useful. His textbook also says he could maybe change it into polar coordinates, but that doesn't seem to be helping.
Comment: http://www.sosmath.com/diffeq/system/nonlinear/linearization/linearization.html
Comment: The references to "him" no longer make sense after you edited out your boyfriend.
Answer: The phase plane equation for the integral curves is
$$\def\part#1#2{\frac{\mathrm d#1}{\mathrm d#2}}
\part yx=\frac{\part yt}{\part xt}=\frac{\mathrm e^x+y}{2y-x}\;.$$
To get a grip on this, it helps to expand around the equilibrium. At equilibrium, $\part xt=2y-x=0$, and thus $y=x/2$, so we can write $y=x/2+z$, with $y'=1/2+z'$. Substituting this into the differential equation for $y$ yields
$$
\begin{align}
\frac12+z'
&=\frac{\mathrm e^x+\frac x2+z}{2(\frac x2 + z)-x}\\
&=\frac{\mathrm e^x+\frac x2+z}{2z}\;,\\
z'
&=\frac{\mathrm e^x+\frac x2}{2z}\;,\\
2zz'
&=\mathrm e^x+\frac x2\;,\\
z^2
&=\mathrm e^x+\frac {x^2}4+C\;,\\
z
&=\pm\sqrt{\mathrm e^x+\frac {x^2}4+C}\;,\\
y
&=\frac x2\pm\sqrt{\mathrm e^x+\frac {x^2}4+C}\;.
\end{align}$$
Comment: I follow until your last sentence. What is the resulting differential equation for $z$? (More specifically, how do we see $e^x+y$ solely as a function of $z$?)
Comment: @anon: I'd written this out but then removed it because I saw the question is on homework; I'll write it out again.
Comment: Oh, of course. For some reason I was thinking we had to get it autonomous in $z$, not sure why I thought that. Moment of brain seepage.
Comment: Thanks.
This was posted by my gf on my behalf. This is exactly what i needed. Knew it would be something simple!


How can I calculate a sample size for a ranked list of items across a population?

Question: I have a population - in this case they are phone calls into a call center.
Each call can be one of approximately 200 'Problems'.  (an example of a Problem is 'I cannot connect to the internet').
I would like to predict the top 10 most common problems across the entire population based on analysis of a sample set of phone calls.  How many phone calls do I need to categorize in order to generate this list with different confidence levels and population sizes?
Ideally I would like to find a formula which allows me to derive sample size from population size, problem set size and confidence level.
Disclosure:
- I am a programmer, not a mathematician - I hope I have asked this question in the correct manner!
- I have done reading prior to asking this question, most content I can find is about estimating p(x) in a population, my problem has more dimensions.  Sorry if this is a duplicate and I am just not smart enough to realize!
Comment: apologies - I did not even know that SE existed.
Comment: No need to apologize! I have flagged the qn to the moderator for migrating to stats.SE.
Comment: Perhaps, my [answer](http://stats.stackexchange.com/a/19142/7199) to "[Sample size for a variable number of answers](http://stats.stackexchange.com/q/19120/7199)" is relevant.
Answer: The Chernoff Bound looks to be out of my league, and for all I know it may be out of yours.  A more manageable method would use chi-square tests or tests of the difference between proportions.  If you specified the size of a difference you wanted to test, and if you specified the confidence level at which you wanted to get results, you could use various software packages (including the open-source GPower) or online power calculators to accomplish your goal of estimating the needed sample size.
Example:  is item 1's % statistically significantly different from item 2's?  You have %'s of 20 and 9, respectively.  You want to see if they are significantly different at the .05 level (95% confidence).  You plug those numbers into the calculator and you'll obtain a required sample size that at least applies for those who choose items 1 or 2.
Now here's the part that purists are likely to question:  you repeat the process to compare item 2 with item 3, and so on.  The fact that you'll be doing multiple tests, each partly dependent on the previous, makes this a rough workaround rather than an ideal method.  But it may be good enough for government work.
Answer: I think you can use the Chernoff Bound


mapping properties of $(1−z)^i$

Question: There is a question on the complex analysis of Conway "Functions of one complex variable" (pg.$57\ \#28$) about the mapping properties of $(1−z)^i$. Can anyone describe me what does the exponent '$i$' mean? What does it do to $(1−z)$? I am confused. Can i write in the following way?
$$(1−z)^i=e^{i\cdot\log(1−z)}=\cos(\log(1−z))+i\sin(\log(1−z))$$
Comment: Yes, but take care, as $1-z$ is not necessarily (positive) real, $\log(1-z)$ will take complex value(s!). So, you'd rather keep the $e^{i\cdot\log(1-z)}$ form.
Comment: @Berci
Could you please describe the mapping properties.Thanks in advance for any help you may able to provide.
Comment: FYI, this looks identical to the following older problem: [mapping properties of $(1-z)^i$](http://math.stackexchange.com/questions/552604/). That one doesn't have an answer, so this isn't a duplicate; in fact, if this iteration receives an answer, I'd advocate marking the other as a duplicate.
Answer: As you mentioned, $(1-z)^i = \exp(i \log(1-z))$. However, $\log$ is a multi-valued function, and different branches of $\log$ will give you different branches of $(1-z)^i$.  I'll assume we're using the principal branch of the logarithm, i.e. the one with imaginary part in $(-\pi, \pi]$.
For any complex $z$,  $\log(1-z)$ is thus in the horizontal strip with imaginary part in $(-\pi, \pi]$.  Multiply it by $i$, and you get the vertical strip with real part in $(-\pi, \pi]$.  The exponential function maps this into the annulus
$\{w: e^{-\pi} < |w| \le e^\pi\}$.  However, this mapping is not one-to-one,
as $\exp$ is periodic with period $2 \pi i$.  $\exp$ will map
 each of the rectangles $R_k = \{x+iy: -\pi < x \le \pi, 2k\pi < y \le 2(k+1)\pi\}$
one-to-one onto the annulus.  Now $ i \log(1-z) \in R_k$ iff $\text{Re}(\log(1-z)) \in (2k\pi, 2(k+1)\pi]$, and since $\text{Re}(\log(1-z)) = \log |1-z|$
this says $2k\pi < \log |1-z| \le 2(k+1)\pi$, or $e^{2k\pi} < |1-z| \le e^{2(k+1)\pi}$.
Thus one answer is that $(1-z)^i$ maps each annulus $e^{2k\pi} < |1-z| \le e^{2(k+1)\pi}$ one-to-one onto the annulus $e^{-\pi} < |w| \le e^{\pi}$.

mapping properties of $(1−z)^i$


Find $m$ if $f(x)=x^m\sin\frac{1}{x}$ is continuous and is not differentiable

Question: If $f(x)=\begin{cases}
x^m\sin\dfrac{1}{x}, & x\ne 0 \\
0, & x=0
\end{cases}$.
Find $m$ if $f(x)$ is continuous and is not differentiable
My attempt is as follows:-
Let's find the condition of continuity
$$\lim_{x\to0^{+}}x^m\sin\dfrac{1}{x}$$
As $x\rightarrow 0^{+}, \dfrac{1}{x}\rightarrow \infty,\sin\dfrac{1}{x} \text { oscillates in }  [-1,1]$
$$m>0$$
$$\lim_{x\to0^{-}}x^m\sin\dfrac{1}{x}$$
As we have the negative base
$$m>0 \cap m\notin \left\{\dfrac{p}{q} | p,q \text { are coprime and } q \text { is even }\right\}\tag{1}$$
Let's find the condition of non-differentiability
$\lim_{h\to 0}\dfrac{h^m\sin\dfrac{1}{h}}{h}$ should not exist
$$\lim_{h\to 0^{+}}h^{m-1}\sin\dfrac{1}{h}$$
$$m\le0$$
$$\lim_{h\to 0^{-}}h^{m-1}\sin\dfrac{1}{h}$$
$$m-1\le 0 \cup m-1\in\left\{\dfrac{p}{q} | p,q \text { are coprime and } q \text { is even }\right\}$$
$$m\le 1 \cup m\in\left\{\dfrac{p+q}{q} | p,q \text { are coprime and } q \text { is even }\right\}\tag{2}$$
Taking intersection of equations $(1)$ and $(2)$
$$\left(m\in(0,1] \cap m\notin \left\{\dfrac{p}{q} | p,q \text { are coprime and } q \text { is even }\right\}\right) \cup  \left(m>0 \cap m\notin \left\{\dfrac{p}{q} | p,q \text { are coprime and } q \text { is even }\right\} \cap m\in\left\{\dfrac{p+q}{q} | p,q \text { are coprime and } q \text { is even }\right\}\right)$$
But actual answer is simply $m\in(0,1]$
Comment: What does that $x\in0$ mean in the definition of $f$?
Comment: I have corrected, it is "not equal to "
Answer: I have to admit I cannot really understand what you are trying to do, and how you come with your conditions for $p$ and $q$.
The first condition is that you need
$$
\lim_{x\to0} x^m\sin\frac1x=0.
$$
Since the sine is bounded, when $m>0$ we have $\left|x^m\sin\frac1x\right|\leq|x|^m$, so the limit is $0$ and the function is continuous. When $m\leq0$ the function oscilates at $0$ (unboundedly if $m<0$ so the limit doesn't exist).

So far: continuity when $m>0$.

For differentiability, we look at the limit at $0$ of
$$
\frac {x^m\sin\frac1x}{x}=x^{m-1}\sin\frac1x.
$$
If $m>1$, the limit is zero and so $f$ will be differentiable. When $m<1$, let $x_k=\frac2{\pi(2k+1)}$. Then
$$
x_k^{m-1}\sin\frac1{x_k}=\left(\frac{\pi(2k+1)}{2}\right)^{1-m}\xrightarrow[k\to\infty]{}\infty
$$
since $m<1$ so $1-m>0$. And when $m=1$ the limit is $1$ we can also choose a sequence so that the limit doesn't exist.
Thus $f$ is differentiable precisely when $m>1$. So,

$f$ is continuous but not differentiable when $0<m\leq 1$.
Comment: see I will explain you in simple terms, suppose we are considering left hand limit, ok? $\lim_{x\to 0^{-}}x^m\sin \dfrac{1}{x}$, so you can see $x$ is just less than $0$, ok?

Now if m is $\dfrac{1}{2}$, left hand limit will become undefined right? now you got my point. Because square root of negative doesn't exist, right?
Comment: Yeah, with very few exceptions, your function is not defined when $x<0$. The reasonable thing when considering arbitrary powers of a real number is to assume that the number is non-negative.
Answer: I'd do cases: clearly $\;m>0\;$, otherwise you have $\;\frac1{x^n}\sin\frac1x\;$ , with positive $\;n\;$ , and thus the limit doesn't exist as
$$\;\frac1{x^n}\xrightarrow[x\to 0^\pm]{}\pm\infty\;\;\text{and}\;\;\lim_{x\to 0}\sin\frac1x\;\;\text{doesn't exist}$$
Now, for $\;0\le m\le1\;$ , we get that
$$\lim_{x\to0} x^m\sin\frac1x=0\;\;\text{since sine is bounded, but}\;\;f'(0)=\lim_{x\to0}\frac{x^m\sin\frac1x}x=\lim_{x\to0}x^{m-1}\sin\frac1x$$
and this last limit doesn't exist by the reasons above as $\;m-1\le0\;$.
Thus, it must be $\;m>1\;$ , and then
$$f'(0)=\lim_{x\to0}x^{m-1}\sin\frac1x=0\;,\;\;\text{ since}\;\;m-1>0$$
Comment: can you tell me what's wrong in my approach and you have not considered when x is negative and m is like $\dfrac{1}{2}$
Comment: Why would the sign of $\;x\;$ be important at all?! All that matters is that $\;x\to0\;$ and the limit of a function converging to zero times a bounded one is zero.
Comment: As your approach is way to messy and it seems to deal with rationals in reduced form and other things that I can't understand how are relevant here.
Comment: if function needs to be continuous, left hand limit and right hand limit both should exist
Comment: @user3290550 Exactly! And that's what the above approach shows in case $\;00\;$ no matter whether $\;x<0\;$ or not...I don't really understand your insistence in this...
Comment: see if $x$ is just less than zero, ok? it means $x$ is negative, right?
now m is
Comment: BTW, what does "$\;x\in0\;$" mean? Is it "different from zero" or $\;x>0\;$ ?
Comment: see I will explain you in simple terms, suppose we are considering left hand limit, ok? $\lim_{x\to 0^{-}}x^m\sin \dfrac{1}{x}$, so you can see $x$ is just less than $0$, ok?

Now if m is $\dfrac{1}{2}$, left hand limit will become undefined right? now you got my point. Because square root of negative doesn't exist, right?
Comment: @user3290550 Indeed so, and thus it is way easier: your function is undefined on any left neighborhood of zero ad thus it must be defined on the positive real numbers, and thus the question must be only about right continuity and right differentiability.
Comment: let me make some cases in general:- Case 1: only one of right hand limit or left hand limit is defined and the other one is undefined, does it means limit exist? Case 2: none of right hand limit or left hand limit is defined, can we say limit exists?
Answer: The funcion $f$ is differentiable at $0$ if and only if the limit$$\lim_{x\to0}\frac{f(x)-f(0)}x\tag1$$exists. But, since $f(0)=0$, the assertion that the limit $(1)$ exists is equivalent to the assertion that the limit$$\lim_{x\to0}x^{m-1}\sin\left(\frac1x\right)$$exists. And this happens if and only if $m-1>0$.
Comment: can you tell me what's wrong in my approach and you have not considered when x is negative and m is like $\dfrac{1}{2}$
Comment: When $m<0$, it is clear that $f$ isn't even continuous.
Comment: Besides, the behaviour of the limit is the same when $h$ goes to $0$ from above and from below.
Comment: see I will explain you in simple terms, suppose we are considering left hand limit, ok? $\lim_{x\to 0^{-}}x^m\sin \dfrac{1}{x}$, so you can see $x$ is just less than $0$, ok?

Now if m is $\dfrac{1}{2}$, left hand limit will become undefined right? now you got my point. Because square root of negative doesn't exist, right?
Comment: Right. Then $f$ is actually *undefined* when $x<0$.
Comment: so $\lim_{x\to 0}x^m\sin \dfrac{1}{x}$ will not exist right? for such values of $m$ $\dfrac{1}{2},\dfrac{3}{2}\cdots\cdots$ as left hand limit is getting undefined
Comment: @user3290550 It is moot to ask about that limit as the function doesn't exist when $\;x<0\;$ unless $\;m=0\;$...and thus it isn't even continuous. The question thus must be about right continuity and differentiability at zero.
Comment: Yes, the limit exists. For instance, the limit $\lim_{x\to0}\sqrt x$ exists; it is equal to $0$.
Comment: @JoséCarlosSantos That's been discussed several times in the past, and it all depends on definitions. You seem to take $\;\lim\limits_{x\to0}\sqrt x\;$ as the limit **within the definition domain** of the function...and that's fine. but not all oblige by the same and things must be made clear.
Comment: let me make some cases in general:-

Case $1$: only one of right hand limit or left hand limit is defined and the other one is undefined,  does it means limit exist?

Case $2$: none of right hand limit or  left hand limit is defined,  can we say limit exists?
Comment: @DonAntonio I have never been exposed to another possibility.
Comment: @JoséCarlosSantos I have and it is not a universal thing. Read some comments and answer here, for example: https://math.stackexchange.com/questions/637280/limit-of-sqrt-x-as-x-approaches-0
Answer: Your approach in correct in all aspects except your considering fractional powers with even denominators as base. The original question does not imply any condition to the domain of the function, it asks you to define a function. The domain is defined after you define the function. Here, you need not necessarily take the domain as $\Bbb R$.
In those functions with $m\in \left\{\dfrac{p}{q} | p,q \text { are coprime and } q \text { is even }\right\}$, the domain would be simply defined as $\Bbb R^{+}\cup \{0\}$ , and in that case continuity and differentiability would be checked from the right side. See:- for limit at end point of domain.
And those functions will not pose any problem to the conditions given question.


Exact power of prime that divides an (unrelated) number

Question: I am trying to understand a paper where a numerical algorithm is described.  I do not understand the point where the expression "exact power of a prime that divides a number" is used.  Here is the text with all related context and the exact point in bold:

Let $n_0$ be a fixed (small) positive integer, and $n≥4n_0$ (...)
Let $m$ be a positive integer

Compute the prime factors $p_1$, . . . , $p_l$ of $m$
For index $j$, $1≤j≤k$, perform the following operations :

Assign $a = n − j + 1$ and $b =j$.
Decompose $a$ and $b$ with the powers of $p_i$, in the form
  $$a=a^{*}×p_1^{α_1}...p_l^{α_l}, b=b^{∗}×p_1^{β_1}...p_l^{β_l}$$
  For each $i$, $p_i^{α_i}$ is the exact power of $p_i$ that divides $a$, $p_i^{β_i}$ is the exact power of $p_i$ that divides $b$, so that $a^∗$ and $b^∗$ do not have one of the $p_i$ as a prime factor.

What I am struggling to understand is that the $p$ prime number is a factor of $m$ but not necessarily of $a$. The definition of $p_i^{\alpha_i}$ calls for an exact division of $a$, not the largest power that is not greater than $a$.
For instance
$$ n_0 = 2 \rightarrow n = 4n_0 = 8 \\
   m = 21 \rightarrow p_1 = 3; p_2 = 7 \\
   j = 1 \rightarrow a = 8 - 1 + 1 = 8; b = 1 \\
   p_1^{\alpha_1} = 8 / 3^{\alpha}
$$
where the last expression does not seem to have an exact (integer) solution.
Am I misunderstanding the definition of "exact division"? Or am I missing something in the algorithm steps leading to this point?
Any help is appreciated.
Answer: The exact power here means the maximal power that divides the number.
So the exact power of $5$ that divides $50$ is $2$ as $5^2$ divides $50$ while $5^3$ does not.
If a primes does not divide a number the exact power that divides it is the $0$-th power.
Comment: Yes, I started to suspect this was the case as soon as I finished writing the question :)  Just for clarification: is this a conventional meaning of "exact division"?  I found an [unrelated definition in Wikipedia](http://en.wikipedia.org/wiki/Exact_division) and [my initial assumption in a mathematical software library](https://gmplib.org/manual/Exact-Division.html)
Comment: I would *not* say it is a usage of "exact division." The phrase is "the exact power of [something] that divides" in that usage it is somewhat common. A notation is $p^a||n$ (so twice the symbol for division). Yet I would consider variations on the phrase like say "we have $5^2$ divides $50$ exactly" or "the divsion of $50$ by $5^2$ is exact" as confusing precisely for the reason you mention (the second usage).
Comment: After re-reading the whole context, it seems the operation is in fact focused on "weeding out" prime factors, and not finding exact powers that may not exist.  So, I'm accepting your answer.  Thanks!
Comment: You are welcome. Yes, the point is to factor out *all* instances of $p$ that are present, so that the co-factor is not divisible by $p$.


PHP: Conditionals Security with $_POST

Question: I am editing someone else's PHP, and they have an 'authentication' system in which they are directly using post data in a conditional in code that looks like this:
if($database_password == $_POST['password']){
//access granted
}else{
//access denied
}

This doesn't look right, first of all, the password is stored in plaintext, but I am wondering whether the $_POST['password'] part is secure. I don't know if it is possible, but can't someone simply write '' OR 1==1 or something to gain access into the site? I am asking because I have to spend a significant amount of time in order to convince them that I need to introduce password rules and force every single user on the intranet to change their password to follow the new rules, especially when my task isn't supposed to involve editing this part of the code or the database.
Thanks!
Answer: As we can't see the rest of your code, all I can do is guess. If you are putting any sort of user generated content into a query (in this case, $_POST['password'] or a username perhaps), always use mysql_real_escape_string(). This will escape quotes so your input is safe.
If you're comparing variables in if() statements, you don't need to escape your input.
You should always encrypt your passwords. Always. Apart from being against the law in some places, it's incredibly insecure. You could even use SHA1 in MySQL queries if you don't want to do a lot of PHP.
Answer: No that is not possible. A variable is an atomic unit and unlike for example in SQL it is not evaluated to a String and then executed.
Your example would simply be evaluated to the following which (in most cases) is false:
if ($database_password == " OR 1==1")

Comment: This does not make any difference in this example.
Answer: Extremeley insecure...
Bad intended persons can become authenticated with: a boolean TRUE, or integer 0.
Source: http://php.net/manual/en/types.comparisons.php
Comment: So you are saying `("password" == TRUE)` or `("password" == 0)` will evaluate to true? That's wrong. The second one would evaluate to `true` if the password is empty, but as $_POST always are Strings this is not possible in the example.
Comment: also note that your example is bad coding, for a simple security system try using SHA-512 (with keystretching, ignore this if they dont know how to correctly implement keystretching)
Comment: It is not *my* example, I just evaluated a string in it (if by "you" you meant me). Please tell me, what exactly you intend with "a boolean TRUE, or integer 0".
Comment: that comment was not intended as comment on your comment but as a comment on my answer. and yes you are right with your first comment on my answer, however on the size of fail in the given example (from David) it would be wise to note the fact of loose comparison vs strict comparison for his "intranet-developers"
Answer: No, with string comparison there is no danger of injection. But the "security" system is obviously to be rewritten.
Comment: Yes, I understand that. I just never trust any user data, it's a lesson that I learned early on. I have an object with lots of miscellaneous string stripping functions, and I always use those on ANY user input, so seeing someone else using unfiltered user input right there, in a simple conditional, in that particular manner, was just disturbing. I just wanted to have a clear conscience if I leave it there.
Answer: It is ok, since it's a string comparison. But generally, its just terrible.
<?php
if($database_password == true){
    echo "ACCESS";
}else{
   //access denied
}

Returns true.
Use the  === operator to improve that code.
if("rd" === true){
    echo 3;
}else{
   //access denied
}

This would be false.
Answer: it's secure, the password is only passed to the conditional if-else, not included to the Query.
it will be in danger if you do this
mysql_query("SELECT user_id FROM table WHERE password='".$_POST['password']."'");

Comment: this example is not safe, its not a strict comparison! see my post
Answer: Like people have said, there is no scope for SQL injection in here because there is no SQL in this code. For passwords, the one way I did sometime ago was to convert into an md5 hash by using md5() function before storing in the DB, and then during login convert the password to md5 and compare the two hashes. May be not the best way, but certainly more secure than this one.

PHP: Conditionals Security with $_POST


Given $X,Y\sim i.i.U[0,1]$, what is $P(X<Y)$?

Question: Let a, b be real numbers randomly selected independently and uniformly from the range of (0,1).
What is P(a < b)?
The problem here is that a can be equal to b, so is
P(a < b)  ≈   0.5 or
P(a < b)  →   0.5 formally correct? Or anything else?
What I'm looking for here is a correct formal way to write this probability down.
Comment: @Riko, it is best to edit these facts into the question rather than leave them in the comments, since not everybody will read the comments and comments may eventually be deleted. I have done this for you in this case.
Comment: All the following material has appeared elsewhere on this site (search if you need details): Making *no* assumptions about the distribution, it is trivial that $\Pr(a\lt b)=\Pr(b\lt a)$. It is axiomatic that $1=\Pr(a\lt b) + \Pr(a=b) + \Pr(a \gt b)$. Algebra implies $\Pr(a\lt b) = (1-\Pr(a=b))/2.$ Any distribution for which $\Pr(a=b)=0$ is *non-discrete.* Such distributions include all continuous distributions, such as the Uniform$(0,1)$ distribution.
Comment: The probability of having a single value is zero, if the the probability density is $f(x)$ then the probability that the outcome is equal to $a$ is $\int_a^a f(x)dx=0$ because the lower and upper limit are the same.
Comment: "random real numbers between 0 and 1" does not contain enough information to determine $p(a<b)$ (though it can be guessed that  independence and uniform distribution were intended).
Comment: @JuhoKokkala correct
Comment: @fcop  does it mean that in my case, p(a < b) = 0.5 and p(a = b) = 0?
Comment: Would the probability not be: $\int_{0}^{b} f(x) dx$ - $\int_{0}^{a} f(x) dx$? This is assuming that $b \geq a$. Now, if $a = b$ then this becomes $\int_{0}^{b} f(x) dx$ - $\int_{0}^{b} f(x) dx = 0$.
Comment: thanks @Silverfish I thought that random selection automatically  assumes independent and uniform distribution. Wouldn't it be semi-random otherwise? Sorry, but I still can't find a clear answer to what is p(a<b) eual to in these comments
Comment: The uniform distribution is not the only way to select two numbers between zero and one at random - see e.g. the [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution). And just because two numbers are chosen uniformly on (0,1) doesn't mean they are independent: e.g. if $X \sim \mathrm{Uniform}(0,1)$ then so is $Y=1-X$, but clearly $X$ and $Y$ are dependent.
Answer: If $a$ and $b$ are independent and identically distributed as $U[0,1]$, then $P(a \lt b) = 0.5$. It is also true that $P(a \le b) = 0.5$, because $P(a = b) = 0.$
In fact, if $a$ and $b$ are independent and identically distributed from any continuous distribution on the real numbers, then $P(a \lt b) = 0.5$, $P(a \le b) = 0.5$, and $P(a = b) = 0.$
Comment: They dont even need to be independent, exchangeable is enough
Answer: For independent continuous $U(0,1)$ random variables we have (taking into account that their density is constant and equal to $1$)
$$P(a<b) =P(a\leq b)= \int_0^1 \int_0^b da\,db = \int_0^1(b-0)\, db $$
$$=\int_0^1b\, db = \frac 12 b^2 \big|^1_0 = \frac 12\cdot1^2 - \frac 12\cdot 0^2 = \frac 12$$
Answer: If we start with an infinitely-large ordered set and we pick two elements from the set, we know that one (and only one) of the following situations can be correct:

a < b
a = b
a > b

We can state:

P( a = b ) = 0 (assuming selection from an infinite set of values)
P( a < b ) = P ( a > b ) (because a and b are independently selected)

Therefore P( a < b ) = 0.5.
Your example refer to independent selection from the set of all real numbers in the range (0, 1), so this result applies.
Comment: **Your first statement does not follow from the assumptions.**  For instance, let the underlying distribution be [geometric](https://en.wikipedia.org/wiki/Geometric_distribution) with parameter $p$, $0\lt p\lt 1$, where the probability associated with a natural number $n$ is $(1-p)^n p$.  Although the natural numbers are infinite and ordered, $$\Pr(a=b)=\sum_{n=0}^\infty ((1-p)^n p)^2 = \frac{p}{2-p}\ne 0.$$


A Question about an example in Durrett's Probability textbook

Question: I was reading an example in Durrett's book: Probability : Theory and Example, 4th edition (pdf verison) (Example 3.4.7, p.112)
The scenario is as follows:

Define $Y_1,Y_2...$ be independent random variables with $P(Y_m=1) = 1/m$ and $P(Y_m=0) = 1 - 1/m$, and then we can compute the mean and variance as
  $$EY_m=1/m; \;\; var(Y_m)=1/m-1/m^2$$
  and the author also mentioned that $var(S_n) \sim \log(n)$;

Here are my questions:

I'm not very clear about the notation "$\sim$" above, what does this notation means?? and why $var(S_n) \sim \log(n)$
I also wonder why $var(Y_m) = 1/m - 1/m^2$? I mean
$$var(Y_m) = E(Y_m^2) - (E(Y_m))^2 = E(Y_m^2) - 1/m^2 $$
but how to make $E(Y_m^2)= 1/m?$

Thanks.
Answer:
the notation is: $a_n \sim b_n \iff \frac{a_n}{b_n}\to 1$. Here, using comparison with an integral you get that $$\sum_{k=1}^n \frac1k \sim \log n$$
$$\begin{align}\text{var } Y_m &= EY_m^2 - (EY_m)^2
 \\&= (1/m\times 1^2 + (1-1/m)\times 0^2) - (1/m\times 1 + (1-1/m)\times 0)^2 \\&= 1/m - 1/m^2\end{align}$$
Comment: Thanks for reply; @mookid ; For question 2, can I think this way: $E(Y_m^2)=1\cdot P(Y_m^2 =1) + 0 \cdot P(Y_m^2=0) = P(Y_m^2=1)$ and since $P(Y_m =1) = P(Y_m^2 = 1) = 1/m$ so we get $E(Y_m^2)=1\cdot P(Y_m^2 =1) = 1/m?$
Comment: this is correct!


SSRS - Display a tablix across a single page

Question: I am using Report Builder 3 to create a simple report. My report is formatted to be printed in Landscape mode on letter sized paper.
I have a single 3 column tablix, that returns about 100 results from a dataset. Instead of breaking to a new page, I want the data to continue displaying in a new set of columns across the page, so that it all fits on a single page. I'm not sure how to accomplish this.
Answer: add three tablix on the one page then divided the data on it..
Comment: That's the part I'm not sure how to do. How do you get the other two tablix to be repeating grids for the first one.
Comment: drag and drop tablix  from the toolbox in SSMS project in BIDS. How are you developing your report?
Comment: I am developing it in MS Report Builder 3.0
Comment: I use Buss Iinteligent Deveplment Studio.  I am sure that you can do this. simply copy and paste the tablix object.


Can you fit a Markov chain transition matrix to a series of vectors?

Question: Given a set of column vectors $v_1, v_2,...,v_t$ is there a way to calculate a unique transition matrix?
In other words, is there one and only one matrix $A$ such that $Av_{i} = v_{i+1}$?
Additionally, is it possible to find the "transition matrix of best fit" for $v_1, v_2,...v_t$?  In other words, the matrix $A$ that minimizes the error between a predicted vector and the actual?
I'm asking because I'm trying to use Markov chains to predict a series of column vectors and I'm curious if there's a more "vectorized" (i.e. linear algebra based) implementation of calculating the transition matrix.
Comment: I'm assuming you actually want $Av_i = v_{i+1}$, and not just $Av_1 = v_2$. It depends on the $v_i$; for a trivial example, if $v_i=\mathbf{0}$ but $v_{i+1}\neq\mathbf{0}$, then no matrix $A$ with $Av_i=v_{i+1}$ exists. More generally, if $v_i\in\mathrm{span}(v_1,\ldots,v_{i-1})$, $v_i=\alpha_1v_1+\cdots+\alpha_{i-1}v_{i-1}$, then the relations $Av_1=v_2$, $Av_2=v_3$, etc. force $v_{i+1}=Av_i = \alpha_1v_2+\cdots+\alpha_{i-1}v_i$. These conditions are necessary; if the $v_i$ satisfy the conditions, then $A$ exists; uniqueness only follows if the $v_i$ span the vector space.
Comment: If I misread your problem and you actually want just $Av_1=v_2$, then if $v_1\neq\mathbf{0}$ there are generally *lots* of matrices $A$: complete $\{v_1\}$ to a basis $v_1,u_2,\ldots,u_n$, pick your favorite vectors $w_2,\ldots,w_n$; then there is a matrix $A$ such that $Av_1=v_2$ and $Au_j=w_j$ for $j=2,\ldots,n$. Clearly, this gives lots of liberty in choosing $A$ if you only subject it to the condition $Av_1=v_2$.
Comment: Yep, that was a typo, thanks.  What you said about span makes sense, however, for my particular dataset I can't guarantee that will be true.
Answer: I can't (yet) describe the theory behind it, but I wrote an article on fitting Leslie matrices to data: http://arxiv.org/abs/1203.2313
The above article references the method as presented in Caswell's book on matrix population models, and only really works for a specific format of transition matrix.  The method can actually be made quite general and should be framed in terms of Kronecker products and the columnize-ing vec operator. I am working on that article currently, and will post a draft if you ask me to.
To get you started consider a data matrix $D$ at time t being the result of multiplication by an unknown transition matrix $X$:
$D_{t+1}=XD_{t}$
This is equivalent to the following with $I$ a conformable identity matrix:
$D_{t+1}=IXD_{t}$ (1)
Now you can use the following formula (from various textbooks):
$vec(ABC)=(C^{T}\otimes A)vec(B)$
For our case, B is the unknown transition matrix, A is the identity matrix, C is the data matrix. Take $vec()$ of both sides of (1):
$vec(D_{t+1}) = vec(IXD_{t}) = (D_{t} \otimes I)vec(X) $
This is a standard matrix equation.  Rewrite as
$ (D_{t} \otimes I)^{-1} vec(D_{t+1}) = vec(X)$
and solve if possible.  It is unlikely that there is a single solution to this (see textbooks etc), but you can minimize the following
$|| (D_{t} \otimes I)^{-1} vec(D_{t+1}) - vec(X) ||_2$ (2)
Then you de-vec $vec(X)$ to get the original transition matrix.
Caveats:  So far I have found that you need to constrain the heck out of X to make it usable and enforce sparsity, and you also probably want to minimize the norm of (2) for an underdetermined solution.  I do the following in the paper, and I am working on articulating how to do the latter with SVD now.
If you are using this, please cite me, and feel free to IM or ask questions here.


Evaluate $\int_{C}\dfrac{e^{z}}{(z-1)(z-2)}dz$ if C is a circle of radius 3 with centered at the origin

Question: Note, i know that this question can be solved easily by residue theorem, however i want to solve it using Cauchy integral method.
Here is how i approached it, i tried to use partial fractions and get to the step $\int_{C}\dfrac{e^{z}}{(z-1)(z-2)}dz = \int_{C}\dfrac{-e}{z-1}dz + \int_{C}\dfrac{e^{2}}{z-2}dz$ and then i applied the CIF formula where i claim that $-e$ and $e^{2}$ is analytic everywhere on the circle $C$. Somehow i got the answer as needed, however i realized that i am not sure if a constant function can be analytic on the circle or not. So i think my approach may be flawed.
Here is the second approach which i do not understand, the answer decomposed to become $\int_{C}\dfrac{e^{z}}{(z-1)(z-2)}dz = \int_{C1}\dfrac{e^{z}}{(z-1)(z-2)}dz + \int_{C2}\dfrac{e^{z}}{(z-1)(z-2)}dz$ where he claimed $C1$ is the circle centered at 1 with radius 0.5 and $C2$ is the circle centered at 2 with radius 0.5. I do not know how this decomposition came about. Can anyone enlighten me?
Answer: let $f(z) = \frac{e^z}{(z-1)(z-2)}$, then we have $$\int_{C}f(z) = 2\pi i\sum_{k=1}^{n}Res_{z=z_k}f(z)$$
here $n=2, z_1=1,z_2=2$. and each pole is 1-order.
$$Res_{z=z_1}f(z) = \lim_{z \to 1}\frac{1}{(1-1)!}\frac{d^{1-1}(z-1)^1f(z)}{dz^{1-1}} = \lim_{z \to 1}\frac{e^z}{z-2} = -e$$
$$Res_{z=z_2}f(z) = \lim_{z \to 2}\frac{1}{(1-1)!}\frac{d^{1-1}(z-2)^1f(z)}{dz^{1-1}} = \lim_{z \to 2}\frac{e^z}{z-1} = e^2$$
so $$\int_{C}f(z) = 2\pi i\sum_{k=1}^{n}Res_{z=z_k}f(z) = 2\pi i(-e+e^2)$$
Comment: Hi would Like to mention that I wish not to use residue theorem here
Comment: Notice the first line in the question.
Comment: sorry, try again. let $C_1 := |z-1|=\varepsilon, C_2 := |z-2|=\varepsilon$. $f_1(z) = \frac{e^z}{z-2},a_1=1, f_2(z)=\frac{e^z}{z-1},a_2=2$. then $f_1(z)$ is analytic on $C_1$, $f_2(z)$ is analytic on $C_2$. by Cauchy ,$$\frac{1}{2\pi i}\int_{C_1}\frac{e^z}{(z-1)(z-2)}dz=\frac{1}{2\pi i}\int_{C_1}\frac{f_1(z)}{z-a_1}dz = f_1(a_1)=-e$$, $\frac{1}{2\pi i}\int_{C_2}\frac{e^z}{(z-1)(z-2)}dz=e^2$.
Comment: @xunitc i do not understand why C1 + C2 gets you the C
Comment: @ilovewt by Cauchy-Goursat theorem, https://en.wikipedia.org/wiki/Cauchy%27s_integral_theorem maybe we need attention the direction of $C, C_1, C_2$.


How to implement deleting multiple rows in a database at once via datagridview

Question: I have a c# application with a connected database. The data is stored in a datagridview. How do I implement the removal of several selected rows from the datagridview and, accordingly, from the database.
here's what I tried, but in this code the last selected line is deleted:
private void button2_Click(object sender, EventArgs e) {
  String cell = dataGridviewl.SelectedRows[0].Cells[0].value.ToString();
  FbCommand cmd = new FbCommand();
  foreach(DataGridViewRow item in this.dataGridView1.SelectedRows) {
    cmd = new FbCommand("delete from " + nameTable + " where id=" + cell, connection);
  }
  cmd.ExecuteNonQuery();
  Update();
}
}

Comment: You can build query with "id IN (id1,... idN)"
Answer: You have only one FbCommand instance executed - the last one, you should either

Add several FbCommand instances into collection and then execute all of them in cycle (also change cell variable every time) -

foreach(DataGridViewRow item in this.dataGridView1.SelectedRows) {
    cell = item.Cells[0].value.ToString();
    cmd = new FbCommand("delete from " + nameTable + " where id=" + cell, connection);
    //add to collection
  }
//execute every FbCommand

Execute every FbCommand when you create it

foreach(DataGridViewRow item in this.dataGridView1.SelectedRows) {
    cell = item.Cells[0].value.ToString();
    cmd = new FbCommand("delete from " + nameTable + " where id=" + cell, connection);
    //execute every FbCommand
  }

Build query with "id IN (id1,... idN)" and then create FbCommand outside your cycle, and execute it only once.

foreach(DataGridViewRow item in this.dataGridView1.SelectedRows) {
    cell = item.Cells[0].value.ToString();
    //build query
  }
FbCommand cmd = new (query, connection);
cmd.ExecuteNonQuery();


$f : \mathbb{R} \to \mathbb{R}$ (Lipschitz) continuous implies $f(A)$ is Borel for all Borel $A$.

Question: Full question:
Let $(\mathbb{R}, \mathfrak{M}, m)$ denote the measure space $\mathbb{R}$ equipped with the Borel $\sigma$-algebra and the Lebesgue measure. Suppose $f : \mathbb{R} \to \mathbb{R}$ is Lipschitz continuous with Lipschitz constant $L$. Show $f(A) \in \mathfrak{M}$ and $m(f(A)) \le L m(A)$ for all $A \in \mathfrak{M}$.
This is a question from an old preliminary exam. I feel quite comfortable, after assuming measurability of $f(A)$, in showing that $m(f(A)) \le L m(A)$ for all $A \in \mathfrak{M}$. I have found similar questions on this site, but none that do not assume $f$ is either one-to-one or onto, as well as the closest one to my question having an accepted answer that says the question is wrong.
My progress (aka simple cases):
If $A \subset \mathbb{R}$ is connected, we know that $A$ is either a point, or an interval (possibly infinite, and can be open, closed, or half-open). However, since $f$ is continuous, the set $f(A)$ must also be connected, so $f(A)$ is also a point, or an interval. In particular, if $A$ is connected, then $f(A)$ is either an $F_{\sigma}$ or a $G_{\delta}$ set (countable union of closed sets and countable intersection of open sets respectively).
If $A \subset \mathbb{R}$ is open, due to the separability of $\mathbb{R}$, it must be a countable union of open intervals, so $A = \cup_{i=1}^{\infty} I_{i}$ for intervals $I_{i}$ and consequently $f(A) = \cup_{i=1}^{\infty} f(I_{i})$ is an $F_{\sigma}$ or $G_{\sigma \delta}$ set (the latter being countable unions of $G_{\delta}$ sets).
If $A \subset \mathbb{R}$ is compact, then $f(A)$ is compact, and hence closed. If $A \subset \mathbb{R}$ is closed but not compact, we can write $A = \cup_{n = 1}^{\infty} A \cap [-n,n]$, and consequently, $f(A) = \cup_{n=1}^{\infty} f(A \cap [-n,n])$ is the countable union of compact sets, and hence a $G_{\sigma}$ set.
My issue:
I know that the Borel hierarchy continues on for an uncountable number of steps. So, I cannot use induction to try to finish the proof based off of these simple cases.
So far unsuccessful, but yet a promising idea:
I'm tempted to appeal to the monotone class lemma, (see Folland's Real Analysis page 66, Lemma 2.35) by showing that the sets from my simple case combined with some sets that involve $\mathbb{R} \setminus f(A)$ form an algebra and a monotone class, and consequently their $\sigma$-algebra is the same $\sigma$-algebra that is generated by the sets from the simple cases (which I believe is the Borel $\sigma$-algebra).
The big guns:
There's a remark (2.2.13) on the bottom of page 69 and top of page 70 in Federer's "Geometric Measure Theory" that says:
If $f : X \to Y$ is continuous, $X$ is a complete, separable metric space, $Y$ is a Hausdorff space, $\mu$ measures $Y$, and every closed subset of $Y$ is $\mu$-measurable, then the $f$ image of every Borel subset of $X$ is $\mu$-measurable.
This remark seems to imply the problem is true. However, this remark follows from two sections of Federer's GMT that are far beyond the expected knowledge for the prelim I'm studying for, and the sections are too terse for me to yet understand. Moreover, Federer goes through the process of defining Suslin sets, and considering the image of Borel sets as projections of Suslin sets. Again, none of this seems like "prelim-level" material. However, since Lebesgue originally thought he'd proved something along these lines (the error in his proof was found by Suslin) I'd be surprised if there's a more elementary proof. Maybe some of the restrictions in this specific problem make it possible.
Thanks for reading. Cheers.
Comment: Note: the "big guns" says $\mu$-measurable, not Borel measurable. In your context, $\mu$-measurable is Lebesgue measurable, not Borel measurable.
Comment: Where did you take this problem from?
Comment: So the claim is: a Lipschitz function maps Borel to Borel.  Certainly false for metric spaces (or even $\mathbb R^2$ to $\mathbb R$), but what about $\mathbb R$ to $\mathbb R$?
Comment: It's false.${}{}$
Answer: It's false; $f(A)$ need not be Borel.
Let $C$ be the middle-thirds Cantor set. Define $\pi_1:C\times C\to C$ by $\pi_1(x,y)=x$.
True Fact There exists a Borel set $B\subset C\times C$ such that $\pi_1(B)$ is not Borel.
Hand Waving Well, that's well known with $\Bbb R$ in place of $C$. There simply cannot be any difference between $\Bbb R$ and $C$ in this regard, qed. Indeed it seems likely that the construction is going to be simpler for $C$. Look for instance at the sketch here. The sorts of codings needed there can certainly be done just as well with $C$ in place of $\Bbb R$. In fact when I think about natural ways to code well-orders, etc., as reals what I actually get are codings as elements of a Cantor set! For example, a natural way to code $R\subset\Bbb N\times \Bbb N$ as a real is $$R\mapsto\sum_{(n,m)\in R}3^{-2^n3^m},$$and that does map $R$ to an element of a certain Cantor set.
If someone who knows that stuff is inclined to confirm the true fact that would be fine.
Recall that $C$ is the set of all sums $$x=\sum_{j=1}^\infty x_j3^{-j}$$where each $x_j$ is $0$ or $2$. In defining various maps it will be convenient to write as though $$x=(x_1,x_2,\dots).$$Various inequalities below will be clear if you note that if $x,y\in C$ with $x\ne y$ then
$$|x-y|\sim 3^{-n},\quad n=\min\{j:x_j\ne y_j\}.$$
We begin. Let $h:C\to C\times C$ be the obvious bijection $$h(x)=((x_1,x_3,\dots),(x_2,x_4,\dots)).$$Note that $$|h(x)-h(y)|\le c|x-y|^{1/2}.$$Suppose $B\subset C\times C$ is a Borel set such that $\pi_1(B)$ is not Borel, and let $$A=h^{-1}(B).$$Let $$g=\pi_1\circ h.$$Now $g:C\to C$ is continuous, $A\subset C$ is Borel but $g(A)$ is not Borel.
But $g$ is not Lipschitz; we have just $|g(x)-g(y)|\le c|x-y|^{1/2}$. Here's the part that works for $C$ but not for $\Bbb R$: Define $s:C\to C$ by $$s(x)=(x_1,0,x_2,0,\dots).$$Then $s$ is injective, in particular $s$ is a homeomorphism from $C$ onto $s(C)$, and $s$ satisfies $$|s(x)-s(y)|\le c|x-y|^2.$$(Exercise: Show that if $\phi:\Bbb R\to\Bbb R$ satisifes $|\phi(x)-\phi(y)|\le c|x-y|^2$ then $\phi$ is constant. Figure out why that argument does not apply here.)
So we define $f:C\to C$ by $f=s\circ g$; then $f$ is Lipchitz but $f(A)$ is not Borel.
Finally, any Lipschitz $f:C\to C$ can easily be extended to a Lipschitz map $f:\Bbb R\to\Bbb R$. For example, define $f$ to be constant on $(-\infty,0]$, constant on $[1,\infty)$, and if $(a,b)$ is a bounded component of $\Bbb R\setminus C$ define $f$ to be linear on $[a,b]$.
Comment: @bookend Thanks for the reference. If you had a reference for the True Fact in the new improved version that would be great.
Answer:
Conjecture: Suppose that $E\in\mathfrak M$ and $f(E)\in\mathfrak M$. Then, $f(E^{\mathsf c})\in\mathfrak M$.

If this conjecture is true, then the claim easily follows, since $$\mathfrak S\equiv\{E\in\mathfrak M\,|\,f(E)\in\mathfrak M\}$$ would then be a $\sigma$-algebra containing the open sets.
I do not know whether this conjecture is true, but if it is, then its proof ought to rely on the special properties of $\mathbb R$ (as opposed to higher-dimensional Euclidean spaces, in which the claim apparently fails) and Lipschitz continuity.


Qt Designer - Using High Resolution. Need Low Resolution version

Question: I designed a rather large GUI using QT designer on a high resolution screen. I am needing a version to deploy on low resolution screens. In the post: PyQt GUI size on high resolution screens I found a solution for converting from low resolution to high resolution by doing this:
# Handle high resolution displays:
    if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)

However, in my case, I need the exact opposite. I need a way to handle a GUI that was designed for a high resolution screen to scale down to low resolution.
Comment: So when you tested your code on a normal resolution screen, what specific problem(s) did you encounter?
Comment: The GUI is too big on a "normal" resolution screen.
Answer: According to High DPI Displays documentation, the first attribute, AA_EnableHighDpiScaling should automatically scale your application for all displays. Documentation for all attributes is found here.
I'm assuming you've already tried something like this, where you have a boolean flag (highres) for whether the application is high resolution:
# use AA_EnableHighDpiScaling for both high and low res app versions:
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)

if highres:
    if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
else:
    if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, False)

I'm also guessing this does not give the desired result because you made your layout on a  high res screen and it's just too big to fit. You can try some trickery with Style Sheets
For your QMainWindow, you can set global values for all widgets. Assuming your main app is a QMainWindow and you drop this in init or setupUI:
if highres == False:
    style = '''QWidget {
                   fontsize: 6pt;
                   icon-size: 15px;
               }

               QWidget::indicator {
                   width: 10px;
                   height: 10px;
               }
            '''
    self.setStyleSheet(stylesheet)

Comment: Thanks. I ended up using the solution below before I saw your post. It worked quite well.
Answer: I ended up writing a small program to change the ratio within the ui file that was generated by Qt Designer. There are only four tags that I changed , , , and . This got it pretty close so that now I am able to tweak it with designer. I hope this helps someone else.
old_file = "old.ui"
new_file = "new.ui"
#Old resolution
oldx = 3840.0
oldy = 2160.0
#New resolution
newx = 1360.0
newy = 768.0

ratiox = newx / oldx
ratioy = newy / oldy

def find_between( s, first, last ):
    start = s.index( first ) + len( first )
    end = s.index( last, start )
    return s[start:end]

with open(old_file, 'r') as f:
    for line in f:
        if "<width>" in line:
            num = float(find_between(line, "<width>", "</width>"))
            #Fix resolution
            old_size = str(int(num))
            new_size = str(int(num * ratiox))
            w = line.replace(old_size, new_size)
        elif "<height>" in line:
            num = float(find_between(line, "<height>", "</height>"))
            #Fix resolution
            old_size = str(int(num))
            new_size = str(int(num * ratioy))
            w = line.replace(old_size, new_size)
        elif "<x>" in line:
            num = float(find_between(line, "<x>", "</x>"))
            #Fix resolution
            old_size = str(int(num))
            new_size = str(int(num * ratiox))
            w = line.replace(old_size, new_size)
        elif "<y>" in line:
            num = float(find_between(line, "<y>", "</y>"))
            #Fix resolution
            old_size = str(int(num))
            new_size = str(int(num * ratioy))
            w = line.replace(old_size, new_size)
        else:
            w = line
        with open('new_file.ui', 'a') as g:
            g.write(w)


Objective C Dependency Management w/ Static Libs

Question: I'm looking for a solution to dependency management for a large Objective C (iOS) project. Right now we have multiple static libs built, which have to be pulled down from git by each developer, the code added as a submodule and compiled along with the project.  I've looked through a lot of posts, but haven't found exactly what I want.
Ideally, I'm looking for something similar to Maven 2 for Java. A tool that:
a) Manages dependencies of a project or static lib
b) Can handle multiple versions (proj A -> lib 1.0, proj B -> lib 1.1, etc)
c) Pulls down only the static lib endstates (.a) if possible.
I realize item c might not be possible as the .h files are needed to define the API, but wanted to put that out there in case there's some magic about static libs that I'm not aware of.
I've looked at CocoaPods and VendorKit, but both are doing something similar to what we have now.
Answer: (Author of CocoaPods here.)
I think I'm missing the part that makes CocoaPods not a suitable solution for your problem, could you elaborate?
In case you don't want the dependency resolution etc of CocoaPods, you might be able to use just the part which modifies/creates Xcode projects to do just what you need.
Comment: sorry, somehow I missed your response until now. Part c was my main question.  I can build the project with CocoaPods so it pulls in all the .h and .m's (in order to build the libPods.a) but I'd like to not have to build that entire group of .m's all the time.  I'd rather just have the .a and the headers pulled in, link against those, and go.

Is it possible to pull the .a endstates and headers from a repo? If so, is there a good example out there? Thanks for creating the project BTW - very cool.
Comment: I think this is what I'm looking for: https://github.com/CocoaPods/CocoaPods/issues/98  I'll do some more investigation on that thread.  Thanks!


A first order non-homogeneous initial value problem

Question: Does $\frac{\text{d}y}{\text{d}x}=-y+\sin(x^2)$ has a unique and well defined solution in $y\in[0,\infty)$ for any $y(0)\in\mathbb{R}$? For a unique solution to exists, do we need $\sin(x^2)$ to be locally Lebesgue integrable on $[0,\infty)$?
Comment: this equation has no soluution in the known elementary functions!
Comment: What do you mean by y(0)? Do you mean that both y and x are parameterized by some other variable, and the value of y when this variable is zero is known? Do you mean that the value of y when x is zero is known?
Comment: I am looking for an argument for existence and uniqueness of the solution. Is $\sin(x^2)$ locally Lebesgue intergrable? If that is true then we have guarantees that a solution exists and is unique.
Comment: @user85310520 You do not need to mess with Lebesgue stuff here. This is a standard existence and uniqueness application. I left an elaboration down below.
Answer: Hint : This is a classic example of elaborating an existence and uniqueness case by Piccard's or Peano's Theorem and via Lipschitz continuity. I'll provide a general elaboration down below.

Let the differential equation problem of the specific problem of an initial value, be :
$$y' = -y + \sin(x^2), \quad y(x_0)=y_0 $$
Consider the function :
$$f(x,y) = -y + \sin(x^2)$$
Then, it's obvious that $D_f = \mathbb R^2$ and that the function $f$ is continuous over $\mathbb R^2$.
Then, following from Piccard's Theorem of Existence (or Peano's respectively), the given initial value problem has a solution because $f$ is continuous, or in other words, $f$ is continuous on an interval of the form :
$$D = \{ (x,y) \in \mathbb R^2 : |x-x_0|<a, \space |y-y_0| < b\}, \space \text{where} \space a,b>0$$
This means that a solution for the IVP exists in $D$ and is well defined in it.
To proceed about the uniqueness, you need to show that $f_y$ is bounded, or in other words $f$ is Lipschitz continuous.
The derivative of $f$ with respect to $y$ is :
$$f_y = \frac{\partial (-y + \sin(x^2))}{\partial y} -1$$
which clearly yields a bounded/surrounded case, as for :
$$\lim_{y\to \pm \infty} f_y=-1$$
This means that the solution is unique.
Note 1 : Manipulating the case for $x_0 = 0$ and a specific initial value will yield more specific results, as for the existence and uniqueness in $[0,\infty)$.
Note 2: Take into account that the existence and the uniqueness of a solution to a given IVP does not necessarily mean that one can find the solution in terms of standard functions.
Comment: @KingTut You could take a brief look [here](https://faculty.math.illinois.edu/~tyson/existence.pdf) .
Comment: Sorry I ask, where is all this taught? Is it real analysis
Comment: @KingTut A complete elaboration of existence and uniqueness theorems are provided with their applications and proofs in classes as : Ordinary Differential Equations, Partial Differential Equations, Dynamical Systems, Control Theory etc. The differential problems are considered a category of analysis.
Comment: Thank you a lot, will look into ode in detail.
Comment: Rebellos, can you give a reference text for that covers the existence and uniqueness of $y'=-y+f(x)$? what kind of general condition we need to require on f(x) to guarantee uniqueness and existence of the results?
Comment: @user85310520 The text I gave you mentions the case for the IVP : $$x'=f(t,x), \quad x(t_0) = x_0$$ This is the same as the case here : $$y'=f(x,y), \quad y(x_0) = y_0$$ The symbols are just not the same, this doesn't mean anything. Instead of $y$ you could have $z$ and instead of $x$ you could have $w$. My elaboration on the answer also considers the same case scenario. Don't get confused by different variables :)
Comment: Actually the reference text I mentioned in the comment above is for the case : $$y' = f(x,y), \quad y(x_0) = y_0$$ Did you read it ? This is exactly the case for : $$y' = -y + g(x)$$ since you can let $$f(x,y) = -y + g(x)$$. The case of $f(x,y)$ covers everything possible.
Comment: Thank you Rebellos. What I meant was a text book, so, I can read more on the subject.
Comment: @user85310520 No problem ! Well, I guess "Elementary Differential Equations" by Boyce - Diprima is a commonly known book. I am Greek though and most of my strict knowledge about differential problems came on my dynamical system course in which we used a Greek book + textbooks, which I guess 1) you cannot find them 2) you probably aren't Greek.
Comment: I also wonder what is the least restrictive condition on $g(x)$ so that $y'=-y+g(x)$ is guaranteed to have a unique and well defined solution in $[0,\infty)$. I think it is that g(x) should be locally Lebesgue integrable. Lebesgue integrable functions do not have to be continuous.
Answer: In fact it's much easier than using general theorems about existence annd uniqueness. In a first-semester DE course one learns a method of solving first-order linear equations, and, unlike a lot of things one learns in that course, the algorithm essentially contains a proof that it's correct.

If $g$ is continuous then $y'+y=g$, $y(0)=a$ has a unique solution.

Proof: Since $e^t\ne0$, $y'+y=g$ is equivalent to $$e^{t}y'+e^ty=e^tg(t),$$or $$(e^tg(t))'=e^tg(t).$$
But since $e^tg(t)$ is continuous, elementary calculus show there is a unique function $f$ such that $$f'(t)=e^tg(t),\quad f(0)=a.$$
(Existence: Let $f(t)=a+\int_0^t e^sg(s)\,ds$. Uniqueness: If $f_1$ and $f_2$ are two solutions then $(f_a-f_2)'=0$, so $f_1-f_2$ is constant. But $f_1(0)-f_2(0)=0$.)


$('html, body').stop().animate" not animating

Question: I am trying to animate my HTML page so it will scroll to a  tag, so I used this code
$(document).ready(function(){
   $('#button a').click(function( e ){
      e.preventDefault();
      var el = $( this.getAttribute('href') );
      var offs = el.offset();
      $('html, body').stop().animate({ scrollTop: offs.top-100 },500);
   });
});

HTML

More Info

And it will actually scroll to the desired , but it doesn't do the animation, it will only scroll without any cool transition like it should.
Thanks in advance.
Comment: which "cool transition" do you expect?
Comment: The one that should do, all the body moving down, to the div.
Answer: This should work better for you. There is no need to specify "#button". You can smooth scroll to ANY ID in your markup by writing the function the way I've shown below.  I tested my code and it works:
$(document).ready(function(){
  $('a[href^="#"]').click(function(e) {
  e.preventDefault();

  var target = this.hash,
  $target = $(target);

  $('html, body').stop().animate({
      'scrollTop': $target.offset().top-100
  }, 500, function () {
      window.location.hash = target;
  });
 });
});


In modal counterpoint for more than two parts, should every pair of voices be in "good" two-part counterpoint?

Question: When checking my own three- and four-part modal exercises, I regularly run into questions like the following: if the bass has the CF, the alto is in 2nd species and the soprano in 3rd species, how exactly should I evaluate the counterpoint between the alto and the soprano? Is this just a version of two-part 2nd species in halved note values, or should I allow myself more leeway? If the latter, how much leeway?
Of course there are going to be obvious exceptions. Such as that the interval of the perfect fourth is allowable between the upper voices in a chord of the sixth. But other than such modifications, which rules should I abide by when evaluating the counterpoint between the upper voices?
Comment: The extreme counterexample is the constant doubling of a voice at the octave in some modern, amateur fugues I've listened to and read the scores of.
Answer: Yes. Otherwise one loses the feel of 3 independent parts.
Answer: Yes.
Elaborating on ttw's to-the-point answer:  one of counterpoint's general aims is how to write voices that keep the listener's attention engaged over a sustained passage of time, by avoiding redundancy or "cheating," particularly the redundancy encoded in two-species rules.  Those rules apply at all time scales, to all pairs of voices.  It's tedious to check all those pairs, but after a while you just learn not to break those rules in the first place.
Eventually, organists can even improvise four-part textures on the fly, without breaking those rules.  Remember that J.S. Bach, whom we regard as the master contrapuntalist, in his day was esteemed instead for his improvisational prowess.  (Which might explain his compositional volume: from modern examination of sketchbooks we see that he didn't hit the backspace key nearly as much as, say, Beethoven.)


$\limsup$ and $\liminf$ in Extended Reals

Question: Is it true that any sequence $X_n$ converges to $x$ in the extended real number system if and only if $\limsup X_n \le \liminf X_n$?
Comment: Yes; or equivalently, $\limsup X_n=\liminf X_n$.
Comment: @JohnGriffin Why is it true?
Comment: Which direction are you not sure about?
Comment: Both, but if you can explain the forward direction, I'll try to work out the other way
Answer: Strictly speaking, what you wrote is not quite true. Indeed, consider the constant sequence $x_n=0$ and set $x:=1$. Then $\liminf x_n=0=\limsup x_n$, but $x_n\not\to x$. However, it's clear that you meant to ask:

If $(x_n)$ is a sequence of real numbers, then $(x_n)$ converges to an extended real number $x$ iff $\limsup x_n \le \liminf x_n$.

Let $(x_n)$ be a sequence of real numbers.
It's easiest to think of $\liminf x_n$ and $\limsup x_n$ as the infimum and supremum, respectively, of all subsequential limits of $(x_n)$.
If this isn't something you've seen before, it's a good exercise to work through. The wikipedia page may also be helpful.
From this definition, or the others, it should be clear that $\liminf x_n \le \limsup x_n$.
With these two remarks in mind, suppose $(x_n)$ converges to some extended real number $x$.
Then every subsequence of $(x_n)$ must also converge to $x$, so by the above characterization, we have $\liminf x_n=\limsup x_n$.
Conversely suppose $\limsup x_n \le \liminf x_n$. Hence $\liminf x_n=\limsup x_n$. We aim to show that if $x:=\liminf x_n$, then $x_n\to x$. Suppose by contradiction that $x_n\not\to x$. Then there exists a neighborhood $U$ of $x$ for which infinitely many terms of the sequence $(x_n)$ lie outside $U$. This gives a subsequence $(y_n)$ of $(x_n)$ such that $y_n\not\in U$ for every $n$. Then any convergent subsequence of $(y_n)$ will not converge to $x$, and thus contradict the assumption $\liminf x_n=\limsup x_n = x$.
It only remains to see that $(y_n)$ has a convergent subsequence. If it is bounded, then this is given to us by the Bolzano-Weierstrass theorem. On the other hand, if it is unbounded, then it has a subsequence which converges to either $\pm\infty$. This completes the proof.
Comment: Why are you able to say "Hence $\liminf x_n=\limsup x_n$"?
Comment: @user23899 It's always true that $\liminf x_n \le \limsup x_n$, so if we additionally assume $\limsup x_n \le \liminf x_n$, then we must have that the two are equal.


Remote access to network share via FTP?

Question: This may be a very simple question, but I'm not sure what the best solution would be. Thanks in advance for your help!
We have a couple of users in our domain that need to access network shares (remotely. We don't have a VPN set up, and in the past this had been accomplished via FTP. Would FTP be the most effective way to go about doing this? The users need to be able to read and make changes to files and folders within whatever share they're accessing, and it needs to be secure - so that nobody accesses anyone else's files.
Thanks,
Anthony
Answer: FTP is fairly clunky by today's standards, but it certainly works. The main problem with FTP is that passwords cross the wire in cleartext (anybody monitoring networks between the client and the server can obtain the user's FTP password). You can run FTP over SSL, but client support for FTP over SSL isn't as ubiquitous as plain ol' FTP. FTP can be a pain to get working through some (typically low-end) firewalls.
You don't mention what your server and client OS's are, but the phrase "network share" makes me think yu're talking about Windows. Using WebDAV over SSL can provide a better user experience than FTP. You can "map" a "drive" to a WebDAV over SSL share from the client. On the server-side, the same old NTFS permissions that are used to control access still apply, since IIS will "impersonate" the authenticated user when accessing their files.
Here's a resource for configuring WebDAV on recent versions of Windows Server: http://learn.iis.net/page.aspx/350/installing-and-configuring-webdav-on-iis-7/

Remote access to network share via FTP?


Utilizando laços com PDO em PHP

Question: Estou tentando criar um laço com PDO aonde eu possa escolher o campo desejado para posicioná-lo na página. Porém o código que eu estou usando está trazendo todos os campos de uma só vez.
Meu código está assim:
include("libraries/conn.php");
$sql = "SELECT
   content.id_content,
   content.img,
   content.titulo,
   povos.pv,
   cat.categoria,
   content.inicio,
   content.fim,
   content.content,
   regiao.reg,
   regiao.wmap
FROM cat
INNER JOIN regiao
INNER JOIN povos
INNER JOIN content ON povos.id_povos = content.civ
AND regiao.id_regiao = povos.regiao
AND cat.id_cat = content.clas
ORDER BY rand()";

$result = $PDO->query( $sql );
$rows = $result->fetchAll(PDO::FETCH_ASSOC);

print_r( $rows );

O resultado está vindo assim:

Array ( [0] => Array ( [id_content] => 31 [img] => paleozoica.jpg [titulo] => Era Paleozoica [pv] => Indefinido [categoria] => Arquitetura e Habitação [inicio] => -550000000 [fim] => -250000000 [content] => A era Paleozoica prevaleceu de 550 a 250 milhões de anos atrás. Nesse período a superfície terrestre passou por grandes transformações, entre eles estão o surgimento de conjuntos montanhosos como os Alpes Escandinavos (Europa). Essa era geológica também se caracteriza mpela ocorrência de rochas sedimentares e metamórficas, formação de grandes florestas, glaciações, surgimento dos primeiros insetos e répteis. [reg] => Mundo [wmap] => mundo.jpg )
Comment: Trouxe todas as colunas que você selecionou. Qual seria o resultado que esperava obter?
Answer: Para acessar alguma informação dentro da variável $rows, faça desta forma:
$rows->titulo
$rows->categoria
$rows->inicio
$rows->fim
...

Desta forma poderá acessar os registros dentro do array e posicioná-los onde gostaria em qualquer parte da página, sendo que eles estejam dentro do laço.
Comment: Obrigado pela resposta Rhuan, porém ainda não estou conseguindo o efeito desejado. Meu código ficou assim:
print_r( $rows->titulo );  e o navegador está retornando a mensagem "Notice: Trying to get property of non-object in D:\xampp\htdocs\n_archaeus\index.php on line 14"
Answer: Observe que o array $rows possue uma chave 0 com o valor sendo um outro array:
Array ( [0] =>
    Array (
        [id_content] => 31
        [img] => paleozoica.jpg
        [titulo] => Era Paleozoica
        [pv] => Indefinido
        ...

Então para filtrar o resultado, para cada chave, você tem um array com os dados, ou seja, temos um laço foreach() ai, para cada $rows vamos separar sua chave e o array com os valores que você precisa:
foreach ($rows as $key => $eachRow) {
    echo $eachRow['id_content'];
    echo "
";
    echo $eachRow['img'];
    echo "
";
    echo $eachRow['titulo'];
}

Como você usou a constante FETCH_ASSOC para trazer os resultados, o array $rows tem como conteúdo um outro array, assim $eachRow['id_content'], $eachRow['img'], etc, mas se fosse utilizado FETCH_OBJ, por exemplo, o array $rows teria um objeto como conteúdo, e poderia ser expressado dentro do laço foreach() assim $eachRow->id_content, $eachRow->img, etc.

Utilizando laços com PDO em PHP


What is this operator ::== called and how does it work?

Question: I'm learning program analysis and separation logic to create formulas expressing correctness of computer programs and I encountered these equations:

Is it wrong to interpret ::== as "Membership assignment"?
Answer: The symbol you are talking about is almost equal to the symbol $:=$ in mathematics. It means "is defined as". You can see a further explanation of the concept behind here Stack overflow question on BNF. It means that the items on the LHS are defined as what is on the RHS for a programming language. More specifically, the term | then works as a comma, so for example you will have that objects such as basic proposition could be either A (atomic propositions in your image), or !A


Centering float:left thing vertically

Question: I can't figure it out how to center float:left object vertically.
I imagine that I could set the position of this menu bar vertically (The height of Y-axis) I think that would be the answer

// html part

One

Two

//css
.menu_simple ul {
        float:left;
            margin: 0;
            padding: 0;
            width:100px;
            list-style-type: none;
            box-shadow: 5px 8px 5px #888888;

        }

        .menu_simple ul li a {
            border: 1px solid #0066cc;
            text-decoration: none;
            color: white;
            padding: 10.5px 11px;
            background-color: #3b3b3b;
            display:block;
        }

        .menu_simple ul li a:visited {
            color: white;
        }

        .menu_simple ul li a:hover, .menu_simple ul li .current {
            color: white;
            background-color: #5FD367;
        }

Answer: Fiddle example
First you set position: absolute for the menu div, then set top to 50% and the transform option to -50%.
Source: https://css-tricks.com/centering-css-complete-guide/
Hope this helps
Answer: Use the CSS position property.
Set the page hold, in your case the  to position: relative; and the part you wish to move, in your case; .menu_simple to the following:
.menu_simple {
    position: absolute;
    top: 50%;
    left: 0;
}

Answer: Flexbox works nicely for this type of thing:
http://codepen.io/simply-simpy/pen/rVwXyz
menu_simple {
  display:flex;
  justify-content: flex-start;
  align-items: center;
  height: 500px;
  border: 1px solid red;
}

Centering float:left thing vertically


Unable to programmatically render webform with supplied default values

Question: I have a block that is rendering a webform programmatically however I want to change a field based on the node that it's appearing on. I'm performing this like so.
<code>    $webform_id = 'contact';
    $current_node = \Drupal::routeMatch()->getParameter('node');
    $contact_form = \Drupal\webform\Entity\Webform::load($webform_id);
    $values = ['data' => ['contact_email' => $current_node->field_email->value, 'message' => 'test']];
    $contact_form->getSubmissionForm($values);
    $contact_form_render = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($contact_form);
    return $contact_form_render;
</code>
It is able to render the webform just fine, however the supplied values for the contact_email field and the message field do not appear, even though they were supplied as a parameter for getSubmissionForm. I've used https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform as an example but I don't seem to see any discrepancies between my code and theirs.
Is there something wrong with how I'm supplying the values to the programmatically rendered webform?
UPDATE: I tried doing things in a more manual manner
<code>$form_storage = \Drupal::entityTypeManager()->getStorage('webform');
$webform_submission = $form_storage
      ->create(['webform_id'=>'contact', 'data' => ['contact_email' => $current_node->field_email->value],'message' => 'testing']);

$contact_form_render = \Drupal::entityManager()
      ->getViewBuilder('webform')
      ->view($webform_submission);
</code>
However I get the error

Exception: Webform id (webform_id) is required to create a webform
  submission. in Drupal\webform\Entity\WebformSubmission::preCreate()
  (line 586 of
  modules/contrib/webform/src/Entity/WebformSubmission.php).

Even though I'm explicitly setting the webform_id.
Answer: Did you try using the Webform render element documented at the bottom of https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform.
<code>return [
  '#type' => 'webform',
  '#webform' => 'your_form_id',
  '#default_data' => ['name' => 'Custom Name'],
];
</code>
Comment: @Matt, jrockowitz is right, building a render array is always the best option in D8. While doing this don't forget to add a cache tag for the node and a cache context, otherwise the block won't update when viewing different nodes: `'#cache' => ['contexts' => ['url.path']],`
Comment: Yep that worked. Would be kind of nice to know why the other way didn't work though.
Comment: The recipe can be updated and the first example should be removed.
Comment: I like to render two forms at the same page. Any idee how to return the render array?


Error in simplenews when send the node more than one

Question: I am using module simplenews and when I send node more than one. Its show me this:-

This newsletter has been sent.

Why and how can I solve this and don't want to show me again.
Answer: This is by design. Why would you want to send the same newsletter twice?
If you want to test your newsletter, choose the option "Send test newsletter". This can be done multiple times before sending out the newsletter to all subscribers.
EDIT: I just saw your other question (you should maybe combine both) and if you want to send a newsletter containing a View on a regular basis, see my answer to the other question or my documentation on drupal.org.
Comment: no no, my problem is when send the node more than once. its show me that message
Comment: Yes, and that is by design. Simplenews only allows to send each newsletter once (to avoid spam presumably). So there's no real solution as there is no real error. Everything as expected.


$0 \leq a \leq b \implies \sqrt{a}\leq \sqrt{b}$ in $C^*$-algebras

Question: Let $a,b$ self-adjoint elements in a unital $C^*$-algebra. I'm trying to show that
$$0 \leq a \le b \implies \sqrt{a} \le \sqrt{b}$$ (these square roots are defined via functional calculus).
The hint I was given said to prove it first if $b$ is invertible, and I managed to do that.
Next, I attempted the case that $b$ is non-invertible. Fix $\epsilon > 0$. A standard argument using Gelfand's theorem shows that $b + \epsilon$ is invertible, and we have $a \le b + \epsilon$,so the former case applies and we get
$$\forall \epsilon > 0: \sqrt{a} \leq \sqrt{b+ \epsilon}$$
Next, choose a sequence $\epsilon_n \searrow 0$. I want to show that
$$\sqrt{b+ \epsilon_n} \to \sqrt{b} \quad\quad (*)$$
Maybe this follows because $f_n \to f$ uniformly where $f_n(x) = \sqrt{x+\epsilon_n}$ and $f(x) = \sqrt{x}$ (via functional calculus)?
If I can deduce this, then from $$\forall n : \sqrt{a} \leq \sqrt{b+\epsilon_n}$$
we would obtain $\sqrt{a} \leq \sqrt{b}$ where implicitely was used that the positive elements are norm-closed.
So how can I justify $(*)$. Is the reason I said a good one?
Answer: The reason is that functional calculus is a $*$-homomorphism. Concretely, let $\Gamma:C(\sigma(b))\to C^*(b)$ be the Gelfand transform. Then
$$
\|f(b)-g(b)\|=\|\Gamma(f)-\Gamma(g)\|=\|\Gamma(f-g)\|\leq\|f-g\|.
$$
Comment: You have $$\sigma(f(b))=f(\sigma(b)).$$ If $f$ is not zero on $\sigma(b)$, then $f(b)$ is invertible.
Comment: Ah yes, I believe it is even an isometry!
Comment: Does the above approach work though? Or is something wrong with it?
Comment: Yes. I answered to the part of your proof that contains the word "maybe".
Comment: Alright. Thanks. One more follow up question. Write $\Gamma_b$ for the functional calculus map w.r.t. the element $b$. In fact, I proved that if $c$ is invertible, then $\Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_c(x \mapsto \sqrt{x})$. Thus I applied this to get $\Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_{b+\epsilon_n}(x \mapsto \sqrt{x})$. Would it be correct to say that $\Gamma_{b + \epsilon_n}(x) = \Gamma_{b}(x \mapsto \sqrt{x+\epsilon_n})$ because functional calculus respects the composition and then the above applies?
Comment: I guess what I am asking is if 'functional calculus respects composition' is implicitely used.
Comment: The elements $(b+\epsilon_n)^{1/2}$ are in $C^*(b)$ (if you consider it unital, which is the case here). So you are using a single $\Gamma$.
Comment: I don't quite understand, I proved $\Gamma_a( x \mapsto \sqrt{x}) \leq \Gamma_b( x \mapsto \sqrt{x})$ if $b$ is invertible. I apply this with the invertible elements $b+ \epsilon_n$, so I would obtain $\Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_{b+\epsilon_n}(x \mapsto \sqrt{x})$. Then I still need to use that functional calculus respects composition to get it to $\Gamma_b$, right?
Comment: No. You have two functions, and you are evaluating both at $b$. There is no composition.
Comment: But how do I know that $\Gamma_b(x \mapsto \sqrt{x + \epsilon_n})$ is invertible then? This I don't know.
Comment: I'm really sorry, I still don't understand. Let me try to rewrite because I don't see how that helps. I proved $a \leq b \implies \Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_b(x \mapsto \sqrt{x})$ IF $b$ is invertible. Now, assume the general case. Choose a sequence $0 < \epsilon_n \to 0$. Then I know that $b + \epsilon_n$ is invertible. Applying the result above $\Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_{b+\epsilon_n}(x \mapsto \sqrt{x}) = \Gamma_{b}(x \mapsto \sqrt{x+\epsilon_n})$.
Comment: Letting $n \to \infty$ and using that positive elements are norm closed, we get $\Gamma_a(x \mapsto \sqrt{x}) \leq \Gamma_b(x \mapsto \sqrt{b})$. I really don't see why we don't need the maps $\Gamma_{b+\epsilon_n}$
Comment: Neither do I. You wrote $\Gamma_{b+\epsilon_n}$, 49 minutes ago.
Comment: I'm very confused by your response. How would you write this proof in terms of the maps $\Gamma_b$, avoiding the maps $\Gamma_{b+\epsilon_n}$?
Comment: Call $g_n(t)=\sqrt{t+\varepsilon_n}$, $g(t)=\sqrt t$. Then $$\|g_n(b)-g(b)\|=\|\Gamma(g_n)-\Gamma(g)\|=\|g_n-g\|.$$
Comment: I agree with this. And how would you deduce that $\sqrt{a} \leq \Gamma(g_n) = \Gamma_b(g_n)$ from what I already proved?
Comment: I don't follow. You said you knew how to show that $a\leq b$ implies $a^{1/2}\leq (b+\varepsilon_n)^{1/2}$, and now you can take limit. What's the problem now?
Comment: No! I know how to show that $a \leq b \implies \Gamma_a(g) \leq \Gamma_b(g)$ when $b$ is invertible.
Comment: How can I conclude that $\Gamma_a(g) \leq \Gamma_b(g_n)$ from this? Strictly applying what I already know, I can see that $\Gamma_a(g) \leq \Gamma_{b+\epsilon_n}(g)$. But you said that we don't need that functional calculus respects composition.
Comment: You have $a\leq b\leq b+\varepsilon_n$, so (as you said) you know how to show that $a^{1/2}\leq (b+\varepsilon)^{1/2}$. As you showed in your OP, you know how to show that the right-hand-side converges to $b^{1/2}$. At this stage I cannot possibly imagine what you are looking for.
Comment: I have $a \leq b \implies \Gamma_a(g) \leq \Gamma_b(g)$ when $b$ is invertible. Now, $b+ \epsilon_n$ is invertible, so I can deduce that $\Gamma_a(g) \leq \Gamma_{b+\epsilon_n}(g)$. You seem to suggest that we can immediately say: $\Gamma_a(g) \leq \Gamma_b(g_n)$. Why is that so? To justify $\Gamma_{b+\epsilon_n}(g) = \Gamma_b(g_n)$ we need that functional calculus respects composition right?
Comment: I understand if you don't want to continue the discussion. Thanks for your time anyways!
Comment: I don't mind. And you are right, if you want to be precise you are using that $\Gamma$ is a homomorphism. It's just that it's usually not worth sweating about it.
Comment: Alright. I just wanted to write it out in extreme detail so next time I won't have to! Thanks for the help.
Answer: Look at this from Arveson's book on Spectral Theorem. You can deduce what you want from his elegant approach.
Comment: I'm sorry but am I misunderstanding an answer? I want to show an inequality not show there is a square root.
Comment: @user745578 : You can deduce what you from the explicit form of the series, and the fact that the $c_n > 0$. This is an elementary approach. Knowing this approach is also useful for abstract $C^*$ algebra theory, where it allows you to build up the GNS construction. This is pre-Gelfand, and it is needed to build to GNS.