Finding Streamlines: How to solve this ODE? Is there a easier way?

Question: I was given the velocity vector field $\mathbf{\vec{v}}(x, y, z)$ and was asked to find the streamlines $\mathbf{\vec{r}}(t)$ in my exam:
$$\mathbf{\vec{v}}(x, y, z) = -\dfrac yx \hat i + 4x \hat j + 0 \hat k$$
This is what I did:
$$z(t) = \int 0 dt = C_1$$
$$\dfrac{dx}{dt} = -\dfrac {y(t)}{x(t)};\; \dfrac{dy}{dt} = 4x(t)$$
But these two equations are coupled. So, I tried to decouple them like this:
$$y = -x\dfrac{dx}{dt}$$
$$\implies \dfrac{dy}{dt} = -\left(\frac{dx}{dt}\right)^2 - x\dfrac{d^2x}{dt^2}$$
$$\implies x\dfrac{d^2x}{dt^2} + \left(\frac{dx}{dt}\right)^2 + 4x = 0$$
Now, what do I do? Is there a easier way?
Comment: Small note, we call such equations *coupled* and we look to decouple them, not entangled/disentangled.
Comment: @Tony S.F. Thnx
Answer: setting $$u(x)=\frac{dx(t)}{dt}$$
so we get $$4x+u(x)^2+x\frac{du(x)}{dx}u(x)=0$$ or
$$x\frac{du(x)}{dx}u(x)+u(x)^2=-4x$$
and we substitute $$u(x)=v(x)^2$$ with $$\frac{du(x)}{dx}=2v(x)\frac{dv(x)}{dx}$$
and we get
$$\frac{dv(x)}{dx}+2\frac{v(x)}{x}=-8$$ with the integrating factorn $$\mu(x)=x^2$$
$$x^2\frac{dv(x)}{dx}+2xv(x)=-8x^2$$
and we have $$\int \frac{d}{dx}(x^2v(x))dx=\int -8x^2dx$$
and we get $$x^2v(x)=-\frac{8}{3}x^3+C_1$$
i think now it is right!
Comment: i have corrected my post, sorry for that
Comment: Are there any missing steps? Am sorry I have to ask again coz I am not able to follow all the steps. Thnx in advance :)
Comment: which step is not clear?
Comment: First, how $u \dfrac{du}{dx} = \dfrac{d^2x}{dt^2}$
Comment: it is $$\frac {d^2x(t)}{dt^2}=\frac {d}{dx}\left(\frac {x(t)}{dt}\right)=\frac{du(x)}{dt}=\frac{dx}{dt}\frac{du(x)}{dx}=u(x)\frac{du(x)}{dx}$$
Comment: and now your next question
Comment: How does $\dfrac{du(x)}{dx} = 2 v(x) \dfrac{dv(x)}{dx}$ follow from $x \dfrac{du(x)}{dx} u(x) + u(x)^2 = −4x$, $u(x) = v(x)^2$ and $\dfrac{du(x)}{dx} = 2 v(x) \dfrac{dv(x)}{dx}$?
Comment: this is the chain rule $$u'(x)=2v(x)v'(x)$$
Comment: Sorry, I meant to ask how $\dfrac{dv(x)}{dx} + 2 \dfrac{v(x)}{x} = −8$ follows from those things.
Comment: Can you explain how $\dfrac{dv(x)}{dx} + 2 \dfrac{v(x)}{x} = −8$ follows from $x\dfrac{du(x)}{dx}u(x) + u(x)^2 = −4x$, $u(x) = v(x)^2$ and $\dfrac{du(x)}{dx} = 2v(x)\dfrac{dv(x)}{dx}$
Comment: This is what I am getting: $$2x v(x)^3 \dfrac{dv(x)}{dx} + v(x)^4 = -4x$$ implies $$\dfrac{dv(x)}{dx} + \dfrac{v(x)}{2x} = \dfrac{-2}{v(x)^3}$$ not $$\dfrac{dv(x)}{dx} + 2 \dfrac{v(x)}{x} = −8$$
Answer: In $2$ dimensions you can transform a system
$$\dot x=-{y\over x},\quad \dot y=4x$$
directly into a $(x,y)$-ODE for the stream lines: Write
$$y'={\dot y\over\dot x}=-{4x^2\over y}$$
and obtain
$$(y^2)'=-8x^2\ .$$
It follows that the stream lines are given by
$$y^2+{8\over3}x^3=C\ .$$
Of course the information about the time dependence is lost in this process.
Comment: Thanx. I guess I should have done that. But I thought I couldn't find the functions that way. But it does specify the streamlines


Prevent Spring from Failing if One Bean Fails

Question: We have an application that creates beans on startup using Spring's AnnotationConfigApplicationContext. What we're trying to do is not have Spring destroy all the beans created and thus cause the app fail on startup if creation of one of the beans fails. Is there any native Spring config or way to accomplish this?
I tried overriding the AnnotationConfigApplicationContext with my own Custom AnnotationConfigApplicationContext and catching exceptions within there. What was happening though is when an exception was thrown, all remaining beans were not created.
We're using Spring 4.3.0.
Comment: Why? When an exception occurs that basically means your application (configuration) is wrong, hence it cannot/will not start. So why do you need this, generally this happens when using the framework in weird/wrong ways.
Comment: Out app is an API with different endpoints, where each bean represents an endpoint to our API. If one bean, or endpoint fails, we still want the rest of the API to startup and have some active endpoints, if that makes any sense.
Answer: easy way to deal with this is by lazy initialization of bean using attribute lazy-init="true" in your bean declaration


How Do I Program The Mode On Python 3.3.0

Question: I need help trying to program the mode in python 3.3
I've been trying for about 2 hours and it's bugging me.
Because I'm using 3.3, so we have no statistics module, which is normally how I would get around this and I can't update as its on school computers. My program Is Supposed to Calculate the Average, Median, Mode And Also Quit. They All Work Except The mode.
Anyone Have Any Ideas? It Would Help!
All I Have so Far is
lists = [1, 2, 3, 4, 5]
print("Hello! What Is Your Name?")
name = input()
func = ["Average", "Median", "Quit", "Mode"]
print("Please Enter 5 Numbers")
lists[0] = input()
lists[1] = input()
lists[2] = input()
lists[3] = input()
lists[4] = input()
print("Hello " + name + ", Would You Like " + func[0] + ", " + func[1] + ", " + func[2] + " Or, Would You Like to " + func[3])
func1 = input()
if func1 == "Average" :
    total = int(lists[0]) + int(lists[1]) + int(lists[2]) + int(lists[3])
    total1 = total / 4
     print("Your Average is " + str(total1))
elif func1 == "Median" :
    lists.sort()
    print("Your Median Is " + lists[2] + "!")
elif func1 == "Quit":
    print("Thank You")
elif func1 == "Mode":

Comment: See [Finding the mode of a list](http://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list)
Comment: You have an unexpected space in your line `print("Your Average is " + str(total1))`. Average function doesn't work, change to  `total1 = total / 4.`
Comment: If you have been trying for two hours, why don't you show some of your efforts? The above code doesn't even try to compute a mode.
Comment: Possible duplicate of [Finding the mode of a list](http://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list)
Comment: Homework question?
Comment: @cz it's for computer science coursework
Comment: @Nuageux What Do You Mean? The space is needed for reasons to do with concatenation. The change you've mentioned is already in the code
Comment: @Jack Space at the beginning of your line. It is not indented well.
Comment: @Nuageux I see thanks!
Answer: You can do the following without any additional library:
lists = [1, 2, 2, 4, 4, 5, 7]
print(max(set(lists), key=lists.count))

Comment: I have just tried to do this however, it has come up as 'Invalid Syntax' And highlights max, any way around this?
Comment: oops my bad, `print` in python3 requires `()`. I have edited the answer.
Comment: Thanks Bro! This Works!
Answer: Have a look at collections.Counter() and its method most_common():
>>> from collections import Counter
>>> lists = [1, 2, 2, 4, 4, 5, 7]
>>> mode = Counter(lists).most_common(1)
>>> mode
[(2, 2)]


Escaping strings from AppleScript for sqlite3

Question: I want to collect some data from e-mail messages in Mac Mail, using AppleScript, then write this data into a sqlite3 database using "do shell script". The problem is, one of the things I want to write is data from the message body, which can contain all manner of special characters that could choke the process of passing the data to sqlite3.
What's the best way of escaping this data? Or is there a better way to do this than using "do shell script" within AppleScript?
Answer: Without example problematic data I'm assuming quoting is the only issue where as fully binary safe would require more code.

on sqlite_quote(subject)
    set OLD_TID to AppleScript's text item delimiters
    try
        set AppleScript's text item delimiters to "\\'"
        set subject to subject's quoted form's text items
        set AppleScript's text item delimiters to ""
        set subject to subject as string

        set AppleScript's text item delimiters to OLD_TID
    on error error_message number error_number from error_source partial result error_result to error_class
        set AppleScript's text item delimiters to OLD_TID

        error error_message number error_number from error_source partial result error_result to error_class
    end try

    subject
end sqlite_quote
on sqlite_quotes(subjects)
    set subjects to {} & subjects
    repeat with subject in subjects
        set subject's contents to sqlite_quote(subject)
    end repeat
    subjects
end sqlite_quotes
on sqlite_fields_quote(sources)
    my list2string(",", sqlite_quotes(sources))
end sqlite_fields_quote

on sqlite_stmnt_create_table_ifnexists(table, columns)
    "create table if not exists " & sqlite_quote(table) & "(" & sqlite_fields_quote(columns) & ")"
end sqlite_stmnt_create_table_ifnexists
on sqlite_stmnt_drop_table_ifexists(table)
    "drop table if exists " & sqlite_quote(table)
end sqlite_stmnt_drop_table_ifexists
on sqlite_stmnt_insert_into(table, values)
    "insert into " & sqlite_quote(table) & " values(" & sqlite_fields_quote(values) & ")"
end sqlite_stmnt_insert_into

on list2string(delimiter, source) -- general utility
    try
        set {|applescript's text item delimiters|, AppleScript's text item delimiters} to {AppleScript's text item delimiters, delimiter}
        set |result| to source as string
        set AppleScript's text item delimiters to |applescript's text item delimiters|
    on error error_message number error_number from error_source partial result error_result to error_class
        set AppleScript's text item delimiters to |applescript's text item delimiters|
        error error_message number error_number from error_source partial result error_result to error_class
    end try
    |result|
end list2string

property executable : "sqlite3"
property db_path : "/tmp/test.sqlite"

on run argv
    set {table, values} to {"table", {"example with CRLF: " & («data TEXT0D0A» as text) & " using applescript's TIDs on this string's quoted form"}} -- example

    set {stmnts, test_ins, test_drp, debug} to {{}, true, false, false}

    if test_drp then set stmnts's end to sqlite_stmnt_drop_table_ifexists(table)
    if test_ins then set stmnts's end to sqlite_stmnt_create_table_ifnexists(table, "text")

    set stmnts's end to sqlite_stmnt_insert_into(table, values)

    if test_ins then set stmnts's end to "select * from " & sqlite_quote(table)

    set |script| to executable & space & db_path's quoted form & space & my list2string(";", stmnts)'s quoted form

    if debug then set |script| to "echo >&2 " & |script|'s quoted form & ";" & |script| & "|xxd"

    do shell script |script|
end run


Can I get rid of postfix if i am not sending email from server?

Question: I am not a sysadmin, just managing a a dedicated server, I get a high load due to Postfix, i shut it down it was the only way to not hang the server.
Comment: If you get a high load due to postfix something pretty bad is going on on your dedicated server, such as it has been compromised and is sending spam.
Comment: you are right, in my case, /dev/root was full due to bad logging file management. I suppose Postfix had dificulties for this reason.
Answer: As above, but I would just set up your server so the postfix service isn't started. (rc.conf on FreeBSD for example). The idea here is postfix and a mail server in general is a huge amount of work to set up. I wouldn't start uninstalling files. You would probably want to make sure none of the email related programs are started. That would be postfix, dovecot, spamd, amavisd-new and probably a few others. Sendmail should already be disabled.
So you would change the config file for the services and also kill them by hand, or just change the config file and boot. You didn't mention the OS, so I cant comment more.
Comment: Hi, it's centos 6.thanks for the input.


Recursively search xml by entry

Question: I have a feed of XML from Google, about 300 entries in all. It looks like this:
<?xml version="1.0"?>
-<ns0:feed ns1:etag="W/"LIESANDCRAPfyt7I2A9WhHERE."" xmlns:ns4="http://www.w3.org/2007/app" xmlns:ns3="http://schemas.google.com/contact/2008" xmlns:ns2="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:ns1="http://schemas.google.com/g/2005" xmlns:ns0="http://www.w3.org/2005/Atom">
    <ns0:updated>2012-01-25T14:52:12.867Z</ns0:updated>
    <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
    <ns0:id>domain.com</ns0:id>
    <ns0:generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</ns0:generator>
    <ns0:author>
        <ns0:name>domain.com</ns0:name>
    </ns0:author>
    <ns0:link type="text/html" rel="alternate" href="http://www.google.com/"/>
    <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#feed" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full"/>
    <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#batch" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/batch"/>
    <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full?max-results=300"/>
    <ns2:startIndex>1</ns2:startIndex>
    <ns2:itemsPerPage>300</ns2:itemsPerPage>
    <ns0:entry ns1:etag=""CRAPQR4KTit7I2A4"">
        <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
        <ns0:id>http://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson</ns0:id>
        <ns1:name>
            <ns1:familyName>Person</ns1:familyName>
            <ns1:fullName>Name Person</ns1:fullName>
            <ns1:givenName>Name</ns1:givenName>
        </ns1:name>
        <ns0:updated>2012-01-25T14:52:13.081Z</ns0:updated>
        <ns1:organization rel="http://schemas.google.com/g/2005#work" primary="true">
            <ns1:orgTitle>JobField</ns1:orgTitle>
            <ns1:orgDepartment>DepartmentField</ns1:orgDepartment>
            <ns1:orgName>CompanyField</ns1:orgName>
        </ns1:organization>
        <ns3:status indexed="true"/>
        <ns0:title>Name Person</ns0:title>
        <ns0:link type="image/*" rel="http://schemas.google.com/contacts/2008/rel#photo" href="https://www.google.com/m8/feeds/photos/profile/domain.com/nperson"/>
        <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
        <ns0:link type="application/atom+xml" rel="edit" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
        <ns1:email rel="http://schemas.google.com/g/2005#other" address="email@example.com"/>
        <ns1:email rel="http://schemas.google.com/g/2005#other" primary="true" address="firstname.lastname@example.com"/>
        <ns4:edited>2012-01-25T14:52:13.081Z</ns4:edited>
    </ns0:entry>
    <ns0:title>domain.com's Profiles</ns0:title>
</ns0:feed>

i am able to pull the data form the name, organization and email fields with beautifulstonesoup with this code:
profiles_feed = gd_client.GetProfilesFeed('https://www.google.com/m8/feeds/profiles/domain/domain.com/full?max-results=300')

soup = BeautifulSoup(str(profiles_feed))

for tag in soup.findAll('ns1:name'):
    print tag.find('ns1:familyname').text
    print tag.find('ns1:fullname').text
    print tag.find('ns1:givenname').text

for tag in soup.findAll('ns1:organization'):
    print tag.find('ns1:orgtitle').text
    print tag.find('ns1:orgdepartment').text
    print tag.find('ns1:orgname').text

for tag in soup.findAll('ns1:email',address=True):
    print tag['address']

I want to be able to grab the data group together from every ns0:entry node, so it would output a line like: family name, given name, org title, org name, email
I have tried using:
for tag in soup('ns0:entry'):
    print tag.name.familyName.text

But it treats it as an attribute
I thought about using xpath, but I couldn't find any docs pertaining to beautifulstonesoup and xpath, so I am not sure it supports it native. So, how could i search each entry node and return all the data specific for the entry, instead of all of it grouped by tag.
Answer: >>> from BeautifulSoup import BeautifulStoneSoup
>>> xml = """<ns0:feed ns1:etag="W/"LIESANDCRAPfyt7I2A9WhHERE."" xmlns:ns4="http://www.w3.org/2007/app" xmlns:ns3="http://schemas.google.com/contact/2008" xmlns:ns2="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:ns1="http://schemas.google.com/g/2005" xmlns:ns0="http://www.w3.org/2005/Atom">
...             <ns0:updated>2012-01-25T14:52:12.867Z</ns0:updated>
...             <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
...             <ns0:id>domain.com</ns0:id>
...             <ns0:generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</ns0:generator>
...             <ns0:author>
...                 <ns0:name>domain.com</ns0:name>
...             </ns0:author>
...             <ns0:link type="text/html" rel="alternate" href="http://www.google.com/"/>
...             <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#feed" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full"/>
...             <ns0:link type="application/atom+xml" rel="http://schemas.google.com/g/2005#batch" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/batch"/>
...             <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full?max-results=300"/>
...             <ns2:startIndex>1</ns2:startIndex>
...             <ns2:itemsPerPage>300</ns2:itemsPerPage>
...             <ns0:entry ns1:etag=""CRAPQR4KTit7I2A4"">
...                 <ns0:category term="http://schemas.google.com/contact/2008#profile" scheme="http://schemas.google.com/g/2005#kind"/>
...                 <ns0:id>http://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson</ns0:id>
...                 <ns1:name>
...                     <ns1:familyName>Person</ns1:familyName>
...                     <ns1:fullName>Name Person</ns1:fullName>
...                     <ns1:givenName>Name</ns1:givenName>
...                 </ns1:name>
...                 <ns0:updated>2012-01-25T14:52:13.081Z</ns0:updated>
...                 <ns1:organization rel="http://schemas.google.com/g/2005#work" primary="true">
...                     <ns1:orgTitle>JobField</ns1:orgTitle>
...                     <ns1:orgDepartment>DepartmentField</ns1:orgDepartment>
...                     <ns1:orgName>CompanyField</ns1:orgName>
...                 </ns1:organization>
...                 <ns3:status indexed="true"/>
...                 <ns0:title>Name Person</ns0:title>
...                 <ns0:link type="image/*" rel="http://schemas.google.com/contacts/2008/rel#photo" href="https://www.google.com/m8/feeds/photos/profile/domain.com/nperson"/>
...                 <ns0:link type="application/atom+xml" rel="self" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
...                 <ns0:link type="application/atom+xml" rel="edit" href="https://www.google.com/m8/feeds/profiles/domain/domain.com/full/nperson"/>
...                 <ns1:email rel="http://schemas.google.com/g/2005#other" address="firstname.lastname@example.com"/>
...                 <ns1:email rel="http://schemas.google.com/g/2005#other" primary="true" address="firstname.lastname@example.com"/>
...                 <ns4:edited>2012-01-25T14:52:13.081Z</ns4:edited>
...             </ns0:entry>
...             <ns0:title>domain.com's Profiles</ns0:title>
...         </ns0:feed>"""

Note from the docs (http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing XML):

The most common shortcoming of BeautifulStoneSoup is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can tell BeautifulStoneSoup that certain tags are self-closing by passing in their names as the selfClosingTags argument to the constructor:

>>> soup = BeautifulStoneSoup(xml, selfClosingTags=['ns0:category','ns3:status', 'ns0:link','ns1:email'])
>>> a = soup.findAll('ns0:entry')
>>> a[0].find('ns1:familyname')
<ns1:familyname>Person</ns1:familyname>
>>> a[0].find('ns1:familyname').text
u'Person'
>>> a[0].find('ns1:givenname')
<ns1:givenname>Name</ns1:givenname>
>>> a[0].find('ns1:givenname').text
u'Name'
>>> for entry in a:
...     print ', '.join([entry.find('ns1:familyname').text, entry.find('ns1:givenname').text, entry.find('ns1:orgtitle').text, entry.find('ns1:orgname').text, entry.find('ns1:email')['address']])
...
Person, Name, JobField, CompanyField, email@example.com

Hopefully this helps.
Comment: this works perfectly, thanks for helping me clear this up. Just one question; The parser stops when it find an empty attrib, I couldn't find anything in the docs for this, do you know if there is a flag to ignore empty attribs and tags?
Comment: `entry.find('ns1:email').get('address','No-address-found')` you can alter the `'No-address-found'` to be any string you want. See: http://docs.python.org/library/stdtypes.html#dict.get
Comment: I am sorry, i should have been more specific, if a text field is blank, the attrib to an address field would most likely not be blank in the xml I would be using, but the text fields in something like orgname might.
Comment: You can check if find returns None, if it doesn't do something with `text`: `if a[0].find('ns1:familyname') != None: print a[0].find('ns1:familyname').text`
Comment: I have been trying for a week to get this to work, but I cannot seem to get the parser to skip over NoneType. I have it written like this for entry in a:
 writer.writerow([entry.find('ns1:familyname').text + ',' + entry.find('ns1:givenname').text + ',' + entry.find('ns1:fullname').text + ',' + entry.find('ns1:orgtitle').text + ',' + entry.find('ns1:orgdepartment').text + ',' + entry.find('ns1:orgname').text + ',' + entry.find('ns1:email',primary=True)['address']]) and it works fine, but if I try to add and condionals, it breaks. What am I missing?

Recursively search xml by entry


Dense subset of $L^{2}$ such that $x^{-1/2}f \in L^{1}$ and $\int_{[0, 1]}x^{-1/2}f\, dx = 0$

Question: Does there exist a dense set of functions $f \in L^{2}([0, 1])$ such that $x^{-1/2}f(x) \in L^{1}([0, 1])$ and $\int_{0}^{1}x^{-1/2}f(x)\, dx = 0$?
I've noticed that $\int_{0}^{1}x^{-1/2}f(x)\, dx = 2\int_{0}^{1}f(x^{2})\, dx$ and so perhaps I should work with $f(x^{2})$ instead. So I tried $f(x) = e^{2\pi i n\sqrt{x}}$, but then I noticed that $x^{-1/2}f(x) \not\in L^{1}$.
Answer: If $g\in L^2[0,1]$, with $x^{-1/2}g(x)\in L^1[0,1]$ and $\int_0^1x^{-1/2}g(x)\,dx=1$,
Take $f\in L^2[0,1]$, then for every $\varepsilon>0$, there exists a $g\in C[0,1]$, with
$$
\|f-g\|_{L^2}<\varepsilon.
$$
Next, there is a $\tau\in (0,1)$, such that, is $h=g\cdot\chi_{[\tau,1]}$,
$$
\|g-h\|_{L^2}<\varepsilon.
$$
Let $a=\int_\tau^1 x^{-1/2}h(x)\,dx$. Set $w(x)=\beta\chi_{[\delta,\tau]}x^{-1/2+\eta}$.
Then, for suitably small $\eta$ and $\delta$ and suitable $\beta$, we obtain that
$$
\int_0^1 x^{-1/2}\big(h(x)+w(x)\big)\,dx=0,
$$
while $\|w\|_{L^2}<\varepsilon$.


What is the most efficient PHP accelerator for a shared hosting environment?

Question: Just wondering if theres any performance benefits for using something like APC over eAccelerator (for PHP) on a shared environment.
Answer: Not sure about in replacement of eAccelerator, but generally APC is better to use than eAccelerator as it is more actively developed than the latter and has a much better release cycle.  Also it's probably worth pointing out that APC will be integrated as part of the core of PHP with the forthcoming PHP6 (though you'll still have to explicitly enable it in the php.ini file.) which fairly biases my mind towards it as well.
Answer: It's difficult to quantise the benefit that opcode caching will bring you without knowing much about your environment and code. Generally speaking though, you will see a performance increase of somewhere between a little and a lot, for what is very trouble on your part. So give it a go and observe your metrics.
There is a pretty good statistical comparison of opcode caches over at Stackoverflow. As you'll see from the results; APC is often pipped to the post by eAccelerator in terms of performance. However performance isn't everything. APC is easy to install, configure and has good future backing - frequent releases and adoption into the PHP codebase.
Personally I use APC wherever possible.


dropdownlist postback in MVC3

Question: The scenario is I have got 2 dropdown list and a table in which i am displaying my data.
The requirement is second dropdown is filled depending upon the first dropdown and the table data is also reloaded.so how can i post my page and reload entire data in MVC3.
I wanted to post my page onchange of first dropdown and second dropdown also.
I have tried using the following in view:
<code><%= Html.DropDownList("SectorDropDown",
        (IEnumerable<SelectListItem>)ViewData["SectorDropDown"],
        new { onchange = "this.form.action='/Screener/Screener.aspx';this.form.submit;"           }
) %>
</code>
Komal
Answer: Are you posting back to a different Action to the Submit button? If not, you don't need to specify the action in the onchange handler. Your submit is missing the parentheses and should be:
<code> this.form.submit();
</code>
Comment: I was missing the parenthesis part so the page couldnt be posted.
Comment: Could you mark the question answered then? Thanks

dropdownlist postback in MVC3


Rounding off a double

Question: @State var value1 = 25.8711
@State var value2 = 30.6234
@State var value3 = 90.2534
@State var value4 = 87.3232
@State var value5 = 87.2334

var body: some View
{
    let finalGrade = (value1 + value2 + value3 + value4 + value5) / 5

    Section(header: Text("Average Grade")){
                    Text("\(finalGrade)")

                        .foregroundColor(.blue)
                }

            }

            .navigationTitle("Grade Calculator")
}

In this block of code how would I get so that finalGrade variable is rounded off into two decimals, and outputs ie: 92.80 versus 92.801232 in the Text() box. The variables 'value' obviously do not calculate to that number but that is just an example.
Comment: Does this answer your question? https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift
Answer: You can use a text specifier when needing to display to a certain decimal place. I prefer this for more accurate calculations with the variables themselves and then it cuts off the decimals only for displaying within Text(). For instance, to show as 2 decimals use
specifier: "%.2f"
Answer: The modern way is
Text(finalGrade.formatted(.number.precision(.fractionLength(2))))

which rounds up 90.2554 to 90.26. If you want always to round down use
Text(finalGrade.formatted(.number.rounded(rule: .down).precision(.fractionLength(2))))

Rounding off a double


Basic page template

Question: I am using Drupal 7 to create a page and a custom template for that page.
I created a page from Content >> Add Content >> Page.
In my theme /template folder I have created a file called page--my-test-page.tpl.php. In that template, I have a test echo which just displays hello world, which isn't displayed.
Where am I going wrong?
Answer: Theme suggestions like that do not work on node titles, out of the box.  You could theoretically add your own suggestions based on node title, but it seems like a very bad idea to me because editors can change titles at will, which will immediately break the correspondance to the templates in your file system.
If you really want to target an individual node, page--node--1.tpl.php should work, where 1 is the node ID of your "My test page" content.  But to be honest that is probably not a great idea either, because node IDs can also change very easily, especially between environments, whereas template filenames do not.  For example you may create page--node--57.tpl.php because your custom page in question is node 57, but if the editor deletes it and then recreates it, even with the same name and same path, it will suddenly be node 109 and not match.
Ultimately, trying to target an arbitrary specific page with custom HTML is somewhat counter to the entire notion of a CMS.  I'm not trying to sound preachy here, just explaining that you are inevitably going to be "swimming uphill" a bit here.  The CMS "wants" you to do your templating based on categories and types - news stories vs events and so on - and not on the actual contents of the content, because editors can change all that on a whim.
So, you could for example solve this by writing a custom hook.  See for example this example fragment which adds page.tpl suggestions based on content type.  It's just PHP, so you're free to do whatever.  So you can do:
if ($variables['node']->title == "My custom page")) {
   // the file name will be "page--customoverride.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__customoverride';
}

and you've got a dedicated page template for that item, but you still haven't really solved your problem, because if the editor changes title you're still back to square one.
You could of course add some extra field to your content types, like a "Use special styling" checkbox, and use that as the criteria to alter the theme suggestions.  It's still possible for editors to change, but at least it's a dedicated, clearly labelled thing they won't change accidentally without realising that doing so has associated consequences to the templating.
So, hard to say what the best way to tackle this is.  Depending on the scope of your site and how many staff you have, etc, it could be as simple as agreeing "Don't change the title of that page, guys!"  Or you may feel obliged to create a bespoke content type purely for this one-off page, or a custom module to control this one-off page, or whatever other more complicated technical solution.
Comment: I think I follow, what is the best way of doing it then? I come from a WordPress world so have gotten myself really confused
Comment: Sorry, disregard that last (now deleted) comment, I didn't read the docs carefully enough.  I'll have a think and come back with a better one.
Comment: Comment boxes are too short, so I expanded my original answer.  Unfortunately I haven't any wordpress knowledge so I can't draw analogies with how that works

Basic page template


Determining a group given some elements

Question: Say we have a group G and we know some of the elements (but not all). How does one determine the order and list all the elements of the group in an intuitive way?
In this case G is the smallest subgroup of $S_4$, and it contains the permutations $\tau_1 = (2,3,4)$, $\tau_2 = (1,3,4)$, $\tau_3 = (1,2,4)$, $\tau_4 = (1,2,3)$, and $\mu_{12}=(1,2)(3,4)$, $\mu_{13}=(1,3)(2,4)$, $\mu_{14}=(1,4)(2,3)$.
What i want to do: find the order of G and list all the elements of G by using the symbols above and give the corresponding permutations.
My thought process so far:
$S_4$ has $4! = 24$ which means that G's order must be a divisor (possibilities are 8, 12, 24 ignoring 1,2,3,4 and 6). Since G is a group, it must contain the identity element, the inverses for all elements mentioned above, and all possible products of the elements*.

is where I get stuck, because one has many possibilities? Hence why i think i am missing something. How does one go about this?
Comment: Since there is no odd permutation in the given list, $G$ is a subgroup of $A_4$. Then $|G|$ divides $12$ and since $8\leq |G|$ we have the equality. Since you are asking a much more general question (most probably which does not have an answer) I leave this as a comment.
Comment: For me the most intuitive way would be, denoting the list of elements you start with by $x_1,...,x_n$, to consider successively the subgroups $\langle x_1\rangle$, $\langle x_1,x_2\rangle$ and so on.

In this case @Levent has a more efficient solution
Answer: In this particular case, you may note that all listed permutation are even, so you are within $A_{4}$, of order $12$. Your group has at least $8$ elements, but then it has elements of order $3$, so it cannot have $8$ elements.
You may finish noting that
$$
V = \{ 1, (1,2)(3,4), (1,3)(2,4), (1,4)(2,3) \}
$$
is a (normal) subgroup of $A_{4}$, and the elements of $A_{4}$ outside $V$ have all order $3$.
To obtain all the elements of order $2$ from the given elements, try conjugating $(123)$ and $(234)$ by the elements of $V$. For instance
$$
(123)^{(12)(34)} = (214).
$$
Comment: @clueless it does not because as Andreas stated in the first lines $G$ must be a subgroup of $A_4$ hence its order must divide $12$ and so it cannot be $24$.
Comment: So one eliminates 8 because 8 is not divisible by 3, but one still has to decide if G has order 12 or 24?
Comment: Nice. I have one stupid question:  So. when listing all the elements of the group there are 4 'unknown' elements (because the identity element and the 7 permutations are given), one finds the inverse element for each permutation ? And then since we only can have 4 extra elements, these inverse elements are either included in G as one of the initial 7?
Comment: The identity, and the products of two disjoint two-cycles, are their own inverses. Then the group will contain all the three-cycles, and the inverse of the three-cyclke $(abc)$ is the three-cycle $(cba)$.

Determining a group given some elements


PHP Wordpress error - Site not working

Question: Seem to be having this error when uploading the new theme onto my wordpress website.
The error is as follows.

Fatal error: Can't use function return value in write context in
  /home/squatz1/public_html/justserviceofny.com/wp-content/themes/justserviceofny
  - NEW SITE/front-page.php on line 16

Here is the entire code if this helps.
 <?php

/**
 * Home Page template
 *
 * @package WordPress
 * @subpackage JustServiceOfNewYork
 * @since JustServiceOfNewYork 1.0
 */

get_header();

?>

<div class="home-banner" style="background: url('<?= ot_get_option('home-banner'); ?>');
  <?= !empty(ot_get_option('home-banner-height')) ? 'height:' . ot_get_option('home-banner-height') . 'px;' : ''; ?>"
>

    <?php
    // Start the loop.
    while ( have_posts() ) : the_post();
      get_template_part( 'template-parts/content', 'home' );
    endwhile; // End the loop.
    ?>

  <?php if ( vct_get_sidebar_class() ) : ?>
    <?php get_sidebar(); ?>
  <?php endif; ?>

<?php get_footer();

Comment: You've problem in your if else shorthand.
Comment: You've to `echo` it.
Answer: Update code
<?php $hb = ot_get_option('home-banner'); ?>
<div class="home-banner" style="background: url('<?= echo $hb; ?>');"
<?= $hbh = ot_get_option('home-banner-height');
echo !empty($hbh) ? 'height:' . $hbh . 'px;' : ''; ?>>

Comment: Some explanation of what you have changed and why it helps solve the problem would improve this answer.
Answer: Most probably thats because you are using empty() on a function return, in following line:
!empty(ot_get_option('home-banner-height')) ? 'height:' ....

change this line to
ot_get_option('home-banner-height') ? 'height:'...

just remove the !empty()
Answer: Replace your code:
<div class="home-banner" style="background: url('<?= ot_get_option('home-banner'); ?>');
<?= !empty(ot_get_option('home-banner-height')) ? 'height:' . ot_get_option('home-banner-height') . 'px;' : ''; ?>">

With
<div class="home-banner" style="background: url('<?= ot_get_option('home-banner'); ?>');
<?= echo !empty(ot_get_option('home-banner-height')) ? 'height:' . ot_get_option('home-banner-height') . 'px;' : ' '; ?>">

Because, you're echoing the height. But as your code it isn't echoing any thing.

PHP Wordpress error - Site not working


Custom query in Views?

Question: At some point I found the need to modify an SQL query generated by Views, in the end I overrode views_pre_execute and changed the query for that specific view.
This feels like an ugly hack to me and I wonder if there is a more elegant and maintainable way to do that. Ideal would be a way that would allow me to directly modify the query from the Views UI.
Comment: It depends on how you wanted to modify that query. What exactly were you trying to accomplish?
Comment: @Jason I posted the question to SO at that time: http://stackoverflow.com/questions/3147916/drupal-display-only-specific-nodereferrer-field-in-views But that problem is solved now, I'm just looking for an elegant way to modify any Views query if I have to.
Comment: I'm not convinced that you can't accomplish what you were trying to do in the other thread just using views. That said, there's far more than one way to skin this cat.
Comment: If any of the answers below are what you were looking for, you should accept one (click the check mark below the vote count)
Comment: hook_views_pre_execute may not be the most elegant, but it does have its place for complex query overrides (see [Custom Views 3 queries in Drupal 7](http://techatitsbest.com/blog/custom-views-3-queries-drupal-7))
Comment: The [#1 answer](https://drupal.stackexchange.com/a/160/88044) should be accepted.
Answer: You can also use hook_views_query_alter() to alter the query before it's run. I think this is similar to hook_views_pre_execute, but makes it easier to modify the query. You basically get access to each part of the query through a keyed array. I haven't found much official documentation, but there's a pretty good example of it at https://www.appnovation.com/blog/using-hook-views-query-alter. This is also the approach I had to use to fix a date bug in the Calendar module.
Comment: I have confirmed that this works in Views-3.
Comment: @Fabian you should accept this answer if it was useful for you, or comment on why it wasn't so we can make it better
Comment: Will this work with Views-3 as well?
Comment: @markdorison I believe so, but haven't confirmed that
Comment: Another example reference for [Custom Views 3 queries in Drupal 7](http://techatitsbest.com/blog/custom-views-3-queries-drupal-7) using `hook_views_pre_execute()` in a simple custom module.
Answer: In general this depends on your use case.
If you want to have a field/filter/argument which should behave in a certain way, it is recommended to write a handler for it.
See advanced help of views for more information.
If you want to change some parts of the query you can also use hook_views_query_alter().
The bad thing about hook_views_query_alter() is that you can't really reuse the code there.
This is the example code shown from the documentation. It gives an example of what the hook can do.
function mymodule_views_query_alter(&$view, &$query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->name == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

Answer: I have used the hook_views_query_alter() to alter a views mysql query. The following example is tested under Drupal 7 with 7.x-3.0, it adds a custom ORDER BY clause to the query:
 function MYTHEME_views_query_alter(&$view, &$query) {
   // check so it's the correct view
   if($view->name == 'product_view') {
     // set a custom 'ORDER BY' clause in the query
     $query->orderby[0] = array(
       'field' => 'SUBSTR(taxonomy_term_data_name,3,4)',
       'direction' => 'ASC'
     );
     $query->orderby[1] = array(
       'field' => 'SUBSTR(taxonomy_term_data_name,1,2)',
       'direction' => 'ASC'
     );
   }
 }

Answer: I don't know if you can directly change the sql, but you could write your own field handler and craft your own query.

Custom query in Views?


Can we create virtual keyboard for a specific app?

Question: Is it possible to create a virtual keyboard for a specific application....I have gone through this example virtual keyboard but it is replacing the system keyboard not for a specific application....How can i achieve virtual keyboard for a specific application....please suggest any valuable posts or links
Thanks
Comment: This is a duplicate of http://stackoverflow.com/questions/5890071/view-specific-ime
Comment: http://www.addictivetips.com/mobile/create-your-own-custom-keyboard-for-android-devices/ check it.
Comment: I didnt find correct solution for my problem
Answer: Follow the link and you'll get your answer
android app specific soft keyboard


Need this code simplified please

Question: so i just started learning python and found this 2 lines of code for finding multiple indexes of letters in strings/lists.
I'd love if some of you guys can simplify the 2nd line for me,
text= 'Allowed Hello Hollow'
print [n for n in xrange(len(text)) if text.find('ll', n) == n]

I don't know if it's just a shortcut style writing or something, but I'd like it simplified, thanks :D
Comment: Maybe try deconstructing the list comprehension (the `[n for n in ...]` part) into a `for` loop and see how it goes?
Comment: `l = [];
for n in xrange(len(text)):
      if text.find('ll', n) == n:
             l.append(n);` then `print l`
Comment: You should seriously consider learning Python 3, Python 2 will reach its official End Of Life in 2020.
Answer: Here's the "simplified" version
myList = []
for n in xrange(len(text)) :
    if(text.find('ll', n) == n) :
        list.append(n)
print myList

This answer explains the syntax
Comment: I think you have an error. `xrange` is for python 2 but `print()` is for python 3. Make the code for python 2 or 3, but not something hybrid.
Comment: @EnderLook You can use parentheses with the `print` statement.
Comment: @cᴏʟᴅsᴘᴇᴇᴅ, oh, I didn't know that.
Comment: @cᴏʟᴅsᴘᴇᴇᴅ Yes, you can use parentheses with the `print` statement, but it makes the code confusing, since the `print` _statement_ with parentheses prints a tuple, so it's rather different to calling the `print` _function_. However, in Python 2.6+ the `print` function is available via a future import: just put `from __future__ import print_function` as the first `import` statement of the script.
Comment: BTW, you shouldn't use `list` as a variable name because that shadows the built-in `list` type. And you shouldn't do `print(some_stuff)` unless you're actually calling the print _function_.

Need this code simplified please


About Rigid Matrices

Question: I want to know the meaning of Rigid matrices and Rigidity of matrices contained in this definition "The rigidity of a matrix A for target rank r is the minimum number of entries of A that must be changed to ensure that the rank of the altered matrix is at most r".
  What is the change that is doing to the elements? with an example
Comment: It is unclear what you're asking.  Perhaps it would be helpful to provide a reference (link or book title) for the *"rigidity of a matrix"*.
Comment: Not sure what is meant by "What is the change that is doing to the elements? with an example"
Comment: https://arxiv.org/pdf/0910.5301.pdf What is the meaning of the Definition 1 and What is the change that is doing to the elements?
Answer: Let's try a random-ish example.
$$ A = \pmatrix{0 & 0 & 1\cr 1 & -1 & -3\cr 1 & -2 & -1\cr}\ \text{over}\ \mathbb C$$
Its rank is $3$.  The most obvious way to make the rank $2$ is by changing the
top right $1$ to $0$, but you could change any of the entries $a_{ij}$ except $a_{23}$ and $a_{33}$ to make the rank $2$.  On the other hand, to make the rank $0$ will require changing all seven nonzero entries to $0$.  To make the rank $1$ will require changing at least $3$ entries, I think.  For example, you could change $a_{13}$ to $0$, $a_{23}$ to $-1$ and $a_{32}$ to $-1$.
So $\text{Rig}(A,3) = 0$, $\text{Rig}(A, 2) = 1$, $\text{Rig}(A,1) = 3$, $\text{Rig}(A,0) = 7$.
Comment: This means that the matrix has changed and becomes another one?
Comment: Yes, of course.  To get a different rank it must change.
Comment: When solving equations $A.X=B$ we calculate the rank of the constants matrix $[A|B]$ to get equivalent equations to simplify the solution.
Do we get another equivalent equations when we calculate the rigidity of the constants matrix? and therefore we get more simplified solution?

About Rigid Matrices


PHP 5.3, Ampersand in URL passing not working

Question: I have code that works fine for anything before 5.3, and now this code won't work in php 5.3:
    foreach($_GET as $key => $value) {
    $params .= "&";
    $params .= $key."=".$value;
}

$fields = array(
    'mode'=>urlencode('native'),
    'cookie_file'=>urlencode($data['cookie_file']),
    'full_status'=>urlencode('1'),
    'remove_cookies'=>urlencode('1'),
    'url'=>urlencode("http://www.domainblocked.com/blocked_name.php?" . $params)
);

//url-ify the data for the POST
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');

//open connection
$ch = curl_init();

$get_url = $proxy."?".$fields_string;

print $get_url;
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$get_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute post
$html = curl_exec($ch);

The file $proxy refers to a PHP proxy which complains it never gets the $_GET['url'] variable despite the $get_url being:
http://www.domainblocked.com/proxy.php?mode=native&cookie_file=%2Ftmp%2FCURLCOOKIEQ1N7ki&full_status=1&remove_cookies=1&url=http%3A%2F%2Fwww.domainblocked.com%2Fblocked_name.php%3F%26room%3D3043542%3B3332215%3B4875165%3B6917670%3B7055833%3B7454057%3B7747396%3B8321764%3B8331103%3B8362498%3B8406246%3B8406305%3B8406671%3B8406728%3B8406965%3B9213754%3B9895515%3B9898865%3B9904319%3B9904558%3B9908327%3B9910403%3B9910760%3B9916830%3B9918045%3B9919351%3B9919603%26avatar69323038%3D%26avatar1%3D6268520%3B6713654%3B7347874%3B7738193%3B7780315%3B8493140%3B8501371%3B8752968%3B9487253%3B9524370%3B9811618%3B10196605%3B10519485%26avatar69527829%3D%26avatar2%3D223055%3B2690693%3B4228334%3B6251471%3B6270797%3B6713654%3B7122151%3B7198849%3B7644202%3B7868916%3B8501371%3B8698810%3B8739013%3B8739767%3B9142768%26avatar38051172%3D%26avatar3%3D4792397%3B6285528%3B7204362%3B7518963%3B7773830%3B7776340%3B8403813%3B8501371%3B9481162%3B9520771%3B9751483%3B9971760%3B9997875%3B10109398%3B10117824%26avatar227598%3D%26avatar4%3D1962690%3B4223019%3B5707484%3B6127072%3B7162053%3B7172244%3B7988191%3B8239420
therefore $_GET['url'] on the proxy file should be  http%3A%2F%2Fwww.domainblocked.com%2Fblocked_name.php%3F%26room%3D3043542%3B3332215%3B4875165%3B6917670%3B7055833%3B7454057%3B7747396%3B8321764%3B8331103%3B8362498%3B8406246%3B8406305%3B8406671%3B8406728%3B8406965%3B9213754%3B9895515%3B9898865%3B9904319%3B9904558%3B9908327%3B9910403%3B9910760%3B9916830%3B9918045%3B9919351%3B9919603%26avatar69323038%3D%26avatar1%3D6268520%3B6713654%3B7347874%3B7738193%3B7780315%3B8493140%3B8501371%3B8752968%3B9487253%3B9524370%3B9811618%3B10196605%3B10519485%26avatar69527829%3D%26avatar2%3D223055%3B2690693%3B4228334%3B6251471%3B6270797%3B6713654%3B7122151%3B7198849%3B7644202%3B7868916%3B8501371%3B8698810%3B8739013%3B8739767%3B9142768%26avatar38051172%3D%26avatar3%3D4792397%3B6285528%3B7204362%3B7518963%3B7773830%3B7776340%3B8403813%3B8501371%3B9481162%3B9520771%3B9751483%3B9971760%3B9997875%3B10109398%3B10117824%26avatar227598%3D%26avatar4%3D1962690%3B4223019%3B5707484%3B6127072%3B7162053%3B7172244%3B7988191%3B8239420
But it never gets it.
If I dont urlencode the $_GET['url'] then it this:
http://www.domainblocked.com/proxy.php?mode=native&cookie_file=%2Ftmp%2FCURLCOOKIEjtmYSU&full_status=1&remove_cookies=1&url=http://www.domainblocked.com/blocked_name.php?&room=3043542;3332215;4875165;6917670;7055833;7454057;7747396;8321764;8331103;8362498;8406246;8406305;8406671;8406728;8406965;9213754;9895515;9898865;9904319;9904558;9908327;9910403;9910760;9916830;9918045;9919351;9919603&avatar69323038=&avatar1=6268520;6713654;7347874;7738193;7780315;8493140;8501371;8752968;9487253;9524370;9811618;10196605;10519485&avatar69527829=&avatar2=223055;2690693;4228334;6251471;6270797;6713654;7122151;7198849;7644202;7868916;8501371;8698810;8739013;8739767;9142768&avatar38051172=&avatar3=4792397;6285528;7204362;7518963;7773830;7776340;8403813;8501371;9481162;9520771;9751483;9971760;9997875;10109398;10117824&avatar227598=&avatar4=1962690;4223019;5707484;6127072;7162053;7172244;7988191;8239420
Which the proxy receieve $_GET['url'] but it's only http://www.domainblocked.com/blocked_name.php?
So I think it has to do with something with the & or urlencode in 5.3
Answer: foreach($_GET as $key => $value) {
    $params .= "&";
    $params .= $key."=".$value;
}

Switch this (and similar code) with http_build_query(). It will handle all the encoding.
Comment: Switching to `http_build_query()` instead of all that other code fixed my problem. Thanks
Comment: On second note, it's not working again despite the changes in the code.


Segmentation bug and Ruby syntax clarification

Question: I got an error with this code:
o = Hash.new do |h,k|
  h[k]
end
o[1] # => [BUG] Segmentation fault at 0x007fff5f3fff80

Trying to understand what this code is doing:
optimal_change = Hash.new do |hash, key|
  hash[key] = if key < coins.min
    []
  elsif coins.include?(key)
    [key]
  ...

o = Hash.new and hash receive a block. What does hash[key] = if key < coins.min mean? Where is key getting it's value from? And what is this = if condition?
Comment: Please ask one question per thread. Your first part includes an import bug discovery, but your second part is gibberish. It is not clear what you are trying to ask.
Comment: Sawa, it's all part of the same question.... I don't know how to ask it because I don't know what the code is.
Comment: Regarding the first point, I just made a bug report on [Ruby trunk](https://bugs.ruby-lang.org/issues/9900).
Comment: Sawa ok that's cool. Do you think you can help me understand the second part?
Answer: In the first case, your IRB crashed due to never ending recursion. You did
o = Hash.new { |h,k| h[k] }
o[1]

Here, you are trying to access the value of key 1 of the hash which has been assigned to o. Now when you will be doing o[1], you block will be called, inside the block you again did h[1], it again calls the same block, the same is being repeated and it falls into never ending recursion, so the error comes out. But the error should be stack level too deep (SystemStackError).
NOTE, Hash::new with the block version, block will be called, only when you would do hash[key] and in the hash, key will not be present.
But in the second case, you are assigning the value to the key of the hash object assgined to o, depending upon the same condition, if the key not already added to O, when you are doing o[:key]. Thus there will not be infinite recursion.
# result of the if-else block will be assigned to the **key** of the **hash**.
hash[key] = if key < coins.min # some condition check is being performed here.
              [] # then an empty is being assigined to the hash[key]
            elsif coins.include?(key) # again a condition test
              [key] # if true this value will be returned.
            else
               # some vale, which you didn't show us. If it is not present, and
               # no condition will be evaluated as true, there is a definite infinte
               # recursion will be happened again.
            end

Read this Hash::new and Hash#[] and Hash#[]= methods.
Example :-
coins = [10, 11, 45, 54]
o = Hash.new do |h,k|
  h[k] = if k < coins.min
            []
         elsif coins.include? k
           [k]
         else
            "k" # I don't know the actual need, this is just to show you
         end
end

o[5]
o # => {5=>[]}
o[11] # => [11]
o # => {5=>[], 11=>[11]}
o[88]
o  # => {5=>[], 11=>[11], 88=>"k"}

Comment: @ArupRakshit You are right that there is an infinite recursion (hence there is a Ruby level error), but that should raise a stackoverflow error. The kind of error that was raised is Ruby's bug. Whenever you see a segmenation fault, it is either Ruby or some C-level library's bug.
Comment: Oh right, and now that the key exists in the hash, the block won't be called again for that hash.
Comment: @sawa Yes.. I mentioned it now, and forgot to write it there. But what you said about the *system level error*, I was not aware of. Thanks for letting me know the same.
Comment: Hey Arup, I appreciate your answer, but I'm still having some issue comprehending this. Perhaps you know of some relevent specific links with solid examples I can review? Thanks.
Comment: Very interesting. But from the `Hash::new` doc's example. `h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }` Why does this code not get into recursion?
Comment: I guess there hash[key] is rvalue. And even though that value is then returned, it's not returned by looking up the hash, again...?
Comment: Arup I will investigate further +1 please consider editing with an example of the execution flow. That would help me better understand the code. You can see the full code on the link in the question above.
Comment: @Spundun Remove *= "Go Fish: #{key}"* and see the magic... :-) Doc example is correct, as When you would do `hash[key]`, at that time, 2 things can be happened ( if you defined the hash with `:new` and *block*)- **a.** key exist in the hash. If so, that value will be returned, block will not be called. **b** key not exist, then block will be called, and the assign the vale to the key, by evaluating the *right side* expression.


How can I add a button under my mobile logo?

Question: This is the website HERE
I am wondering how I can go about adding text or a button directly under my logo specifically on mobile devices?
I would really appreciate some help!
Comment: Welcome to StackOverflow! In order for us to help you better, can you please update your question so that it shows your **existing code** and details any failed [**attempts made so far**](http://meta.stackoverflow.com/questions/261592) in a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve), along with clearly stating what your desired **result** is. For further information, please refer to the help article regarding [**how to ask good questions**](http://stackoverflow.com/help/how-to-ask), and take the [**tour of the site**](http://stackoverflow.com/tour) :)
Answer: Look into your theme's header.php file, you'd have to add media query to make it display on mobile devices only.
Search for "header_top_bottom_holder" class in header.php to get the correct block.
Also, make sure you've your child theme set up first.
Cheers,


Chinese Remainder Theorem when the moduli is not pairwise coprime.

Question: On my textbook, after the proof of the Chinese Remainder Theorem when the moduli is pairwise relatively prime, one modification is left as exercise.
Prove that the system of linear congruences $x\equiv a_i\pmod{m_i}$ is solvable if and only if $gcd(m_i,m_j) \vert (a_i - a_j)$ for all $i\neq j$, and $i,j \in \{ 1,2,\dots r \} .$ (or $a_i\equiv a_j\mod{gcd(m_i,m_j)}$ which is the same). If a solution exists, it is unique $\mod{lcm(m_1,m_2,...,m_r)}$
I managed to find a proof for the case $r=2$, and from there tried to do induction, but I am stuck when I have to use the inductive hypothesis.
$[ \longrightarrow ]$
Suppose that $a_i\equiv a_j\mod{(m_i,m_j)}$ for all $i\neq j$, and $i,j \in \{ 1,2,\dots,r, r+1 \}$.
Then, the system
$$ x\equiv a_1 \mod{m_1} \\
x\equiv a_2 \mod{m_2}\\
.\\.\\.\\
x\equiv a_r \mod{m_r}\\
$$
has a solutions, lets say $b$ (by inductive hypohesis).
I will next like to consider the system
$$
x\equiv b \mod{lcm(m_1,m_2,...,m_3)}\\ x\equiv a_{r+1} \mod{m_{r+1}}
$$
and find that it has a solution using the case $r=2$, but I don't know how to use my hyphotesis here because I need $b \equiv m_{r+1}\mod{gcd(lcm(m_1,m_2,...,m_r),m_{r+1}))}$
$[\longleftarrow]$: As for the converse I don't know how to begin.
Answer: Since $x\equiv b$ is a solution to the first system, $b\equiv a_i \ mod \ m_i$.
Note that $a_i \equiv a_{r+1} \ mod \ gcd(m_i,m_{r+1})$ and $gcd(m_i,m_{r+1})$ divides $m_i$, we get: $$b\equiv a_i \equiv a_{r+1} \ mod \ gcd(m_i,m_{r+1})$$
for all $1 \leq i \leq r$.
Then, $$b \equiv a_{r+1}\mod \ lcm(gcd(m_1,m_{r+1}),...,gcd(m_r,m_{r+1}))=A $$
Now it remains to show that $A$ is divisible by $B=gcd(lcm(m_1,...,m_r),m_{r+1})$
Let $p$ be any prime number, we'll show that $v_p(A) \geq v_p(B)$, where $v_p(x)$ is the multiplicity of $p$ in the prime factorization of $x$.
We can check that $v_p(A)$ is the largest number in $min(v_p(m_i),v_p(m_{r+1}))$ where $1 \leq i \leq r$
and $v_p(B)$ is the smaller number between $max(v_p(m_1),...,v_p(m_r))$ and $v_p(m_{r+1})$
There're only two cases:
$\textbf{Case 1}$: $v_p(m_{r+1}) \gt v_p(m_i)$ for all $1 \leq i \leq r$
Then $v_p(A)$ the largest number in $v_p(m_1),...,v_p(m_r)$ i.e $v_p(A)=max(v_p(m_1),...,v_p(m_r))$
$v_p(m_{r+1}) \gt max(v_p(m_1),...,v_p(m_r)) $ so $v_p(B)=max(v_p(m_1),...,v_p(m_r)) $
$\textbf{Case 2}$: $\exists \ 1 \leq k \leq r: v_p(m_{r+1}) \leq v_p(m_k)$
Then $v_p(A) \geq v_p(m_{r+1}) $ because $min(v_p(m_k),v_p(m_{r+1}))=v_p(m_{r+1})$
$v_p(B)=v_p(m_{r+1})$ because $v_p(m_{r+1}) \leq v_p(m_k) \leq max(v_p(m_1),...,v_p(m_r)) $
In both cases, $v_p(A) \geq v_p(B)$ so $B$ divides $A$ and we're done.
The converse is actually much easier, assume that $x \equiv b \ mod \ lcm(m_1,...,m_r)$ is a solution.
Then $b \equiv a_i \ mod \ m_i$, $  b \equiv a_j \ mod \ m_j$ for all $1 \leq i \lt j \leq r$
But $gcd(m_i,m_j)$ divides both $m_i$ and $m_j$ so $gcd(m_i,m_j)$ divides $(a_i-b)+(b-a_j)=a_i-a_j$
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).


Config Entity list_builder controller path throws Route Does Not Exist error

Question: I have created a custom config entity, which declares a list_builder controller to return a list of the created entities. Before creating a config entity, it renders as expected. Once I create a config entity via its add form, which redirects back to the list_builder controller, the error is thrown. The config entity is saved, but the redirect fails.
Here's the redirect in the config entity form class's ::save() method.
$form_state->setRedirect('my_module.entity.list');

Also, navigating directly to the list_builder controller path throws the same error.

Symfony\Component\Routing\Exception\RouteNotFoundException: Route
  "entity.config_entity_id.edit_form" does not exist. in
  Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of
  /home/vagrant/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php)

I have no idea where the route entity.config_entity_id.edit_form is coming from. How to resolve the thrown error?
Comment: Add the annotation of the entity class and your routing.yml file.
Answer: You have somewhere in your code the wrong route.
Probably your route in *.routing.yml is:
entity.my_new_entity.edit_form

But now you are redirecting to
entity.config_entity_id.edit_form

where there is still the placeholder from some example code.
Comment: I added my form redirect in the question above. I'm redirecting to the list_builder route, which is why I can't determine how the route that does not exist is being passed on to Symfony's router. Additionally, if I navigate directly to the list_builder path, I get the same error.
Comment: grep for the string `config_entity_id`, if you find it replace it with the correct id of your new config entity
Comment: I think the route, entity.config_entity_id.edit_form, was generated dynamically from the schema definition. Changing the schema fixed the issue.
Comment: Please put this in an answer, and accept it, so also others can see the end result!


Model selection for linear regression with categorical variables

Question: I regressed the dependent variable Rating (numeric) on Judge which is categorical. The output of the first model is given at the end of the question. Only Judge John Foy and Linda Murphy came out to be significant. In the next step of modeling, should I consider only 3 factors which are John, Linda and rest judges, and run the regression again?
Please guide me to take the next step to create the final model. Ultimately I want to know that should we combine all the factors which are not significant and run the regression again with new set of factors of a categorical variable.
<code>> levels(wine_data$Judge)
[1] "Danièle Meulders"   "Francis Schott"      "Jamal Rayyis"
[4] "Jean-Marie Cardebat" "John Foy"            "Linda Murphy"
[7] "Olivier Gergaud"     "Robert Hodgson"      "Tyler Colman"

>wine_lm <- lm(Rating ~ Judge, data = wine_data)

>summary(wine_lm)

# Call:
# lm(formula = Rating ~ Judge)
#
# Residuals:
#    Min     1Q Median     3Q    Max
# -7.850 -1.625  0.325  1.400  4.825
#
# Coefficients:
#                          Estimate Std. Error t value Pr(>|t|)
# (Intercept)               13.6000     0.5164  26.337  < 2e-16 ***
# JudgeFrancis Schott        1.2500     0.7303   1.712  0.08877 .
# JudgeJamal Rayyis          1.0750     0.7303   1.472  0.14285
# JudgeJean-Marie Cardebat  -1.0500     0.7303  -1.438  0.15232
# JudgeJohn Foy              3.0250     0.7303   4.142  5.4e-05 ***
# JudgeLinda Murphy          2.0500     0.7303   2.807  0.00558 **
# JudgeOlivier Gergaud       1.0000     0.7303   1.369  0.17269
# JudgeRobert Hodgson       -1.4000     0.7303  -1.917  0.05690 .
# JudgeTyler Colman         -0.4500     0.7303  -0.616  0.53858
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Residual standard error: 2.309 on 171 degrees of freedom
# Multiple R-squared:  0.2713,  Adjusted R-squared:  0.2372
# F-statistic: 7.957 on 8 and 171 DF,  p-value: 4.345e-09
</code>
Answer: In general, you should not just include some levels of a categorical dependent variable.
First, that changes the question you are asking from "Are judges different?" to "Are these three judges different from the others?"
Second, it is "fishing".  If you really wanted to do this (and I don't think you do) then you should separate the data into training and test sets, find the three judges in the training set and then look for those three in the test set.
Comment: Lets say If I want to write down the regression equation and want to predict the rating. Shall the equation be:
Rating = b0 + b1*Judge_John + b2*Judge_Linda
Comment: You would want a b for each judge, including the nonsignificant ones.


How to pass Id of a div that is clicked to a function that handles the click in jQuery

Question: I want to my div ids to correspond to items in a database. Based on an id my app will pull appropriate content from a database.
Hence when I use .click() to handle a click I need to pass the Id of the div being clicked to the function that handles it. How do I do this?
Answer: Inside your click event handler function, the context (the this keyword) refers to the DOM element that triggered the event, you can get the id from it, for example:
$('div[id]').click(function () { // all divs that have an id attribute
  var id = this.id; // or $(this).attr('id');

  someOtherFunction(id);
});

Answer: In the context of a click handler this corresponds to the DOM element which was clicked. You can use it to extract the id:
$('div').click(function() {
    // Get the id of the clicked div
    var id = this.id;
    // Do something with it ...
});


Finding change in spending habits

Question: I have a numpy array full of customer spending data:
x = np.array([5000,5500,6250,4800,3950,5800,5500,800,1200,900,500,400,300,200,3100])

Above, you can see that before index 7 the customer spends much more money than he does after index 7. I am looking to find an abnormality such as index 7 by looking sequentially at the data and want to identify if the split data set has a significant change (i.e. spending habits have changed or remained the same after the first abnormality).
So, 800 would be detected and there would be two lists:
l1 = [5000,5500,6250,4800,3950,5800,5500]
l2 = [1200,900,500,400,300,200,3100]

Here, a similarity measure needs to be upon comparison such to see the similarity or difference of l1 and l2.
Are there any useful sklearn functions for this? I know I can look at means, rolling std's etc, and set thresholds for this but was looking for a more statistical approach possibly something in a more statistical/machine learning python library.
Comment: Research a bit about "clustering" in general and KMeans especially, I think it's what you need to intelligently devide the user behaviour into discrete clusters
Comment: I know about Means and Affinity propagation, but this relies on a sequential aspect. I don't want to just set k = 2 or k = 3 as there can be an out of order arrangement of elements across these clusters. I.e. p_1,p_2,...,p_k all need to be together then p_k+1, p_k+2,...,p_n need to be together
Comment: A possible approach is to find inflection point by finding the concavity changes (look at the second derivative).
Answer: Regarding the list you passed, I don't really understand why 3100is in l2 and not in l1.
However, you find a way to split you list by comparing new numbers. For example, you can use the gradient, when there is a gradient jump is where you have to split. Or you can compare each number of the list to mean of the previous numbers. Without a clustering method, I would begin with something like this :
l1 = l2 = []
x = np.array([5000,5500,6250,4800,3950,5800,5500,800,
1200,900,500,400,300,200,3100])
for i, k in enumerate(x):
    if len(l1) > 2:
        m1 = np.mean(l1)
        if np.abs(m1 -k)/m1 > 0.5:
            index = i
            break
    l1.append(k)
l2 = x[index:]
In [11]: l1, l2
Out[11]:
([5000, 5500, 6250, 4800, 3950, 5800, 5500],
 array([ 800, 1200,  900,  500,  400,  300,  200, 3100]))

Finding change in spending habits


How to create software raid on working ubuntu server with gpt?

Question: i have this structure of hdd on my server:
fdisk -l
Disk /dev/sda: 2.7 TiB, 3000592982016 bytes, 5860533168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: EA206948-7BBC-4AD9-8835-40746D07F575

Device     Start       End   Sectors    Size Type
/dev/sda1     40      2048      2009 1004.5K BIOS boot
/dev/sda2   4096 409602047 409597952  195.3G Linux RAID

Disk /dev/sdb: 2.7 TiB, 3000592982016 bytes, 5860533168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: D2514683-E466-41C0-82AD-44635CA12AE8

Device     Start       End   Sectors    Size Type
/dev/sdb1     40      2048      2009 1004.5K BIOS boot
/dev/sdb2   4096 409602047 409597952  195.3G Linux RAID

Disk /dev/md2: 195.3 GiB, 209714085888 bytes, 409597824 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

How you can see total size of my hdd-s - 2,7T. Also, i have program raid for /. This is /dev/sda2 and /dev/sdb2. How i can create other partition with /dev/sda3 and /dev/sdb3 with size 500GB on both disks and make Linux RAID 1, like i am using on /dev/sda2 and /dev/sdb2 ?
I tried with using of fdisk. I made two partitions with 500GB for each. I made mdadm:
mdadm --create /dev/md3 --metadata=0.90 --level=mirror --raid-devices=2 /dev/sda3 /dev/sdb3
and i added ARRAY /dev/md3 UUID=3a5d7bb4:7f8f4e1f:a4d2adc2:26fd5302 to /etc/mdadm/mdadm.conf. also i added my /dev/md3 to fstab, but after reboot, my system was not loaded. Where i have error ? How can i do this operation ? How can i do to have for /dev/sda3 and /dev/sdb3 Linux Raid and not Linux filesystem
Comment: `but after reboot, my system was not loaded.` what exactly was the error?  What do you mean by 'not loaded'? Did the system not boot at all, or what?  What Linux distro?  For some, you might need to regenerated your initrd, when updating your mdadm.conf.
Answer: It seems /dev/sda3 is missing a filesystem (fs).
Use mkfs to create the fs of your choice and edit /etc/fstab accordingly.


Impossible clean PictureBox

Question: I want clean the PictureBox image, so I make this code:  TransparentPictureBox.Image = Nothing, the image don't disappear and I obtain all new image overlapping to the previous. How can I fix this?

I stay using a custom control, this is the class:
Public Class TransparentPictureBox
Inherits PictureBox

Public Sub New()
    Me.SetStyle(ControlStyles.Opaque, True)
    Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, False)
End Sub

Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
    Get
        Dim cp As CreateParams = MyBase.CreateParams
        cp.ExStyle = cp.ExStyle Or &H20  ' Turn on WS_EX_TRANSPARENT
        Return cp
    End Get
End Property
End Class

Comment: if the PB doesnt also have an image assigned to BackgroundImage, you may not showing all the relevant code.
Comment: The PictureBox.Image = Nothing works for me.  As Plutonix stated, update the post with the additional code you're using to clear/load the image, I suspect something else is causing this issue.
Comment: I'm using a custom control. I've pasted the class of the control
Answer: The control is working exactly as you designed it.
With the ControlStyles.Opaque option set to True, it does not draw its background:

If true, the control is drawn opaque and the background is not painted.

When you set the Image property to Nothing, you're expecting it to be emptied.
How does a PictureBox draw itself though? It first draws the background color, then it draws the image on top of that. Since you've disabled background painting, though, the background doesn't get drawn and the previous image doesn't get erased.
Why do you have that option set? Remove it if that is not the behavior you're looking for.
Comment: Because I want a trasparent PictureBox control, this PictureBox is situated on another PictureBox with the green field. If I remove Me.SetStyle(ControlStyles.Opaque, True) I obtain the PictureBox with the shield with a quadratic blank.
Comment: I'll give it to you straight: WinForms transparency support sucks.  End of story.  Move to WPF if you want that kind of flexibility.  One option is to draw a composite image at run-time with the transparency you want and put that into a single PictureBox.
Answer: Just write this although this not optimal solution but it will work
    picturebox1.imagelocation = ""
Comment: You might try this    PictureBox1.CreateGraphics.Clear(Me.BackColor)
Comment: The only problem is that a white background appears behind the image.
Comment: well instead of using' me.backcolor' you can use any color you want like color.black, color.wheat or same as the background colour you are using
Comment: if I use color.trasparent appear a black background and not the green field of the image that I've uploaded
Comment: PictureBox1.Height = 0

Impossible clean PictureBox


How to prove that $||M\vec{x}|| \leq c||\vec{x}||$?

Question: What are some hints for how I could go about showing that for any $m$ x $n$ matrix M, there exists a constant $c \in \mathbb{R}$ such that for all $x \in \mathbb{R}^n$, the following holds: $||M\vec{x}|| \leq c||\vec{x}||$? I know that I am supposed to use the Cauchy-Schwarz inequality, specifically that for $\vec{x}$ and $\vec{y}$ in $\mathbb{R}^k$, for a dimension $k$, then $|| \vec{x} \cdot \vec{y} || \leq ||x||$ $||x||$. I know that multiplying $M$ and $\vec{x}$ will result in a $m$ dimensional vector, but wouldn't I need a $n$ dimensional vector in order to use the theorem?
Comment: Hint: $|ax+by|\le \max\{|a|,|b|\}\sqrt{x^2+y^2}$.
Answer: Let $c' := \max_{i=1,\dotsc,n} \|M e_i\|$. Then for every $x \in \mathbb{R}^n$
$$
 \|M x\|
 = \left\| \sum_{i=1}^n x_i M e_i \right\|
 \leq \sum_{i=1}^n |x_i| \|M e_i\|
 \leq c' \sum_{i=1}^n \underbrace{|x_i|}_{\leq \|x\|}
 \leq n c' \|x\|,
$$
so we can take $c := nc' = n\max_{i=1,\dotsc,n} \|M e_i\|$.
Answer: Let $v=Mx$. Then
$$
v_i=\sum_{j=1}^nM_{ij}x_j\implies||v||^2=\sum_i\left(\sum_jM_{ij}x_j\right)^2.
$$
By C-S, we have
$$
\left(\sum_jM_{ij}x_j\right)^2\leq\left(\sum_jM_{ij}^2\right)\left(\sum_jx_j^2\right)=\left(\sum_jM_{ij}^2\right)||x||^2.
$$
It follows that
$$
||v||^2\leq\left[\sum_{i=1}^m\left(\sum_{j=1}^nM_{ij}^2\right)\right]||x||^2.
$$
It remains to label the expression in the square brackets above as $c^2$.
If $M=\begin{pmatrix}\alpha_1x' \\ \cdots \\ \alpha_mx'\end{pmatrix}$ for scalars $\alpha_1,\ldots,\alpha_m$, then the inequality above becomes an equality.


Interpreting interaction between a categorical and centered continuous variable (binary response)

Question: In my model, in which I'm attempting to infer which covariates affect whether a fish has an empty stomach or not (1=empty, 0=not empty), I decided to grand-mean center the variable "SL" (standard length) so that the intercept would make more sense (instead of when SL=0). However, I'm not sure how to interpret the interaction in the summary output when one of the covariates is centered. My categorical variable is "fZone" (factor Zone, my location variable).
center_sl = grand-mean centered standard length of each fish caught
fZone = location of catch (3 levels)

> table(c_neb5$fZone)

 Rankin    West Whipray
    201     436      42

c_neb5$center_sl <- scale(c_neb5$SL, scale=FALSE)

mod2 <- bam(empty ~
             center_sl +
             fZone +
             center_sl:fZone +
             ...,
         data = c_neb5,
         method = 'fREML',
         discrete = TRUE,
         family = binomial(link = "logit"),
         select = FALSE)

EDIT: Full model summary
> summary(mod2)

Family: binomial
Link function: logit

Formula:
empty ~ center_sl + fZone + center_sl:fZone + s(sal) + s(temp) +
    s(ToD) + s(fStation, bs = "re") + s(fCYR, bs = "re") + s(fStation,
    fCYR, bs = "re") + s(fStation, CYR.std, bs = "re")

Parametric coefficients:
                        Estimate Std. Error z value Pr(>|z|)
(Intercept)            -1.298719   0.291203  -4.460  8.2e-06 ***
center_sl              -0.038851   0.011985  -3.242  0.00119 **
fZoneWest               0.122594   0.311480   0.394  0.69389
fZoneWhipray           -0.327579   0.639371  -0.512  0.60841
center_sl:fZoneWest    -0.002926   0.014650  -0.200  0.84169
center_sl:fZoneWhipray  0.061163   0.025891   2.362  0.01816 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
                          edf  Ref.df Chi.sq  p-value
s(sal)              1.783e+00   2.231  1.590 0.558432
s(temp)             1.128e+00   1.236  2.972 0.134198
s(ToD)              2.112e+00   2.637 16.235 0.000755 ***
s(fStation)         1.096e-04  82.000  0.000 0.619807
s(fCYR)             4.740e+00  12.000 14.165 0.009002 **
s(fCYR,fStation)    9.693e+00 237.000 11.111 0.205201
s(CYR.std,fStation) 1.258e+01  80.000 23.798 0.008646 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =   0.16   Deviance explained = 18.1%
fREML =  990.1  Scale est. = 1         n = 679

My interpretation is that...(Intercept)=-1.298719 means the average size fish has a exp(-1.298719)= 0.272 odds of an empty stomach; fZoneWest=0.122594 the odds of empty stomach in West compared to my ref. level (Rankin) increase by exp(0.122594)=1.130425; and center_sl:fZoneWest=-0.002926 means for every 1 unit above average in size, the odds of an empty stomach decrease by exp(-0.002926)=0.9970783, compared to my ref. level. Am I on the right track? Any advice or corrections are greatly appreciated! The data is 679 rows in size, so the best I could do was post a subset of it down below.
Subset of my data:
example_data <- c_neb5[sample(nrow(c_neb5), 10), ]

> dput(example_data)
structure(list(CYR_Keyfield = c("C-2018-10-6-255", "C-2017-6-26-278",
"C-2018-9-16-291", "C-2017-10-9-265", "C-2010-11-10-167", "C-2019-10-30-169",
"C-2018-10-6-279", "C-2022-7-10-241", "C-2017-9-4-70", "C-2022-6-23-241"
), Species = c("Cynoscion nebulosus", "Cynoscion nebulosus",
"Cynoscion nebulosus", "Cynoscion nebulosus", "Cynoscion nebulosus",
"Cynoscion nebulosus", "Cynoscion nebulosus", "Cynoscion nebulosus",
"Cynoscion nebulosus", "Cynoscion nebulosus"), ID = c("201810255_86",
"20176278_52", "20189291_39", "201710265_100", "201011167_61",
"201910169_54", "201810279_75", "20227241_46", "2017970_91",
"20226241_34"), SL = c(33.58, 20.12, 50.25, 23.18, 68.72, 14.85,
73.49, 61.84, 13.26, 25.79), empty = c(0, 0, 0, 0, 0, 1, 0, 0,
1, 0), DateTime = structure(c(1538842500, 1498499220, 1537107120,
1507558920, 1289399700, 1572449400, 1538837160, 1657460040, 1504530660,
1656001620), class = c("POSIXct", "POSIXt"), tzone = ""), CYR = c(2018L,
2017L, 2018L, 2017L, 2010L, 2019L, 2018L, 2022L, 2017L, 2022L
), Month = c(10L, 6L, 9L, 10L, 11L, 10L, 10L, 7L, 9L, 6L), DoY = c(279,
177, 259, 282, 314, 303, 279, 191, 247, 174), ToD = c(12.25,
13.7833333333333, 10.2, 10.3666666666667, 9.58333333333333, 11.5,
10.7666666666667, 9.56666666666667, 9.18333333333333, 12.45),
    JDay = c(5129, 4662, 5109, 4767, 2242, 5518, 5129, 6502,
    4732, 6485), Zone = c("Rankin", "Rankin", "Whipray", "Rankin",
    "West", "West", "Rankin", "Rankin", "West", "Rankin"), Station = c(255,
    278, 291, 265, 167, 169, 279, 241, 70, 241), Standard_collection_station = c(0,
    0, 0, 0, 0, 0, 0, 1, 1, 1), Latitude = c(25.085, 25.145,
    25.118, 25.135, 25.106, 25.081, 25.133, 25.0750000309199,
    25.132, 25.0750000309199), Longitude = c(-80.802, -80.809,
    -80.76, -80.823, -80.917, -80.893, -80.797, -80.8159999921917,
    -80.941, -80.8159999921917), sal = c(38.27, 41.01, 33.61,
    26.75, 32, 36.18, 36.42, 40.08, 38.1, 39.07), temp = c(27.856,
    32.2, 31.791, 29.512, 19.3, 28.398, 27.6679999999999, 30.243,
    29.71, 29.262), fCYR = structure(c(9L, 8L, 9L, 8L, 2L, 10L,
    9L, 12L, 8L, 12L), levels = c("2009", "2010", "2011", "2012",
    "2013", "2015", "2016", "2017", "2018", "2019", "2021", "2022"
    ), class = "factor"), fMonth = structure(c(8L, 4L, 7L, 8L,
    9L, 8L, 8L, 5L, 7L, 4L), levels = c("1", "3", "5", "6", "7",
    "8", "9", "10", "11", "12"), class = "factor"), fStation = structure(c(60L,
    69L, 76L, 63L, 40L, 42L, 70L, 57L, 11L, 57L), levels = c("20",
    "21", "22", "23", "24", "40", "54", "65", "67", "68", "70",
    "71", "73", "101", "105", "106", "107", "111", "112", "117",
    "118", "119", "122", "123", "124", "130", "133", "134", "135",
    "137", "143", "144", "145", "146", "147", "156", "157", "158",
    "159", "167", "168", "169", "171", "172", "173", "174", "175",
    "176", "224", "225", "226", "227", "229", "237", "239", "240",
    "241", "253", "254", "255", "256", "257", "265", "266", "267",
    "268", "269", "270", "278", "279", "280", "281", "282", "284",
    "290", "291", "292", "294", "301", "302", "312", "609"), class = "factor"),
    fZone = structure(c(1L, 1L, 3L, 1L, 2L, 2L, 1L, 1L, 2L, 1L
    ), levels = c("Rankin", "West", "Whipray"), class = "factor"),
    CYR.std = c(9L, 8L, 9L, 8L, 1L, 10L, 9L, 13L, 8L, 13L), center_sl = structure(c(-6.70160530191458,
    -20.1616053019146, 9.96839469808542, -17.1016053019146, 28.4383946980854,
    -25.4316053019146, 33.2083946980854, 21.5583946980854, -27.0216053019146,
    -14.4916053019146), dim = c(10L, 1L)), center_sal = structure(c(1.43373534609722,
    4.17373534609722, -3.22626465390278, -10.0862646539028, -4.83626465390278,
    -0.656264653902781, -0.416264653902779, 3.24373534609722,
    1.26373534609722, 2.23373534609722), dim = c(10L, 1L)), center_temp = structure(c(-1.51357879234165,
    2.83042120765835, 2.42142120765835, 0.142421207658348, -10.0695787923417,
    -0.971578792341653, -1.70157879234175, 0.873421207658346,
    0.340421207658348, -0.107578792341652), dim = c(10L, 1L))), row.names = c(495L,
364L, 303L, 652L, 404L, 375L, 469L, 676L, 508L, 675L), class = "data.frame")

Comment: Look at [this question](https://stats.stackexchange.com/q/41129/28500) among others on this site for how to interpret coefficients in models with interactions. With an interaction in default R coding, individual coefficients are for the case when the _interacting_ predictor is at its reference level or at 0, as presented to the model. Interaction coefficients are for the _extra_ association with outcome, _beyond what's predicted from the individual coefficients_, when both predictors are away from reference/0.
Comment: @ShawnHemelstrand; full model summary now included. I thought I'd save space by just including the part my question related to.
Comment: I'm confused...why are you using a generalized additive model (GAM) with terms that are all linear? Wouldn't this be better suited to functions like `lmer` or `glmer` which are suited for linear models?
Comment: @ShawnHemelstrand, the formula after the summary() function shows the whole model.
Comment: I can see that, but where are all your non-parametric coefficients that are supposed to accompany your splines?
Comment: @EdM, would a centered covariate merely adjust your description by saying something akin to that extra association with the outcome is now associated with changes above and below the mean of the covariate, rather than every 1 unit away from 0 (of the covariate)?
Answer:
(Intercept)=-1.298719 means the average size fish has a exp(-1.298719)= 0.272 odds of an empty stomach

Only when fZone=Rankin, the reference level. Interpretation holds because you have presented "standard length" to the model as centered to 0 at the average size fish.

fZoneWest=0.122594 the odds of empty stomach in West compared to my ref. level (Rankin) increase by exp(0.122594)=1.130425

Only for the average fish size, at center_s1=0. I find it confusing, particularly in more complicated models, to work in the odds scale. I prefer to work in the coefficient scale, where coefficients add, and only exponentiate to odds (or convert to probability) at the end of the calculations.

center_sl:fZoneWest=-0.002926 means for every 1 unit above average in size, the odds of an empty stomach decrease by exp(-0.002926)=0.9970783, compared to my ref. level

That's incorrect. The interaction is the extra change beyond what you would predict based on the reference-level coefficients. You have, at the fZone reference level Rankin, a center_sl coefficient of -0.038851 for the log-odds difference per unit of center_sl. The center_sl:fZoneWest=-0.002926 is what you add to that coefficient when fZone=West.  exp(-0.038851-0.002926)=0.959, for the change in odds per unit change in center_sl whenfZone=West.
In this type of model, centering a continuous predictor doesn't affect its own coefficients, only the coefficients of predictors with which it interacts. In your model if you didn't center s1, the sl coefficient would still be-0.038851 for the slope at the fZone reference level Rankin, but the Intercept and the coefficients for other levels would be those corresponding to an (extrapolated) s1 value of 0.
Shawn Hemelstrand has a helpful recent answer that might help you think this through. In that answer, think of $X$ as your original continuous s1 and the $Z$ and $W$ covariates as the two dummy variables that represent your fZone. Then work through what happens to the interpretation of regression coefficients when you replace $X$ with $X-\bar X$ in those equations (equivalent to your converting s1 to center_s1).


Dividing an area into redundant parts

Question: Is it possible to divide a square into $n>2$ parts, such that any $m$ of these $n$ parts can be used to reconstruct the original square, wherein $1<m<n$? The parts may overlap, but cannot rotate.
For the simple case of $n=3$ and $m=2$, I found a solution: dividing the square into four quadrants and then defining the three pieces to be:

top left, bottom left, bottom right quadrants,
top left, top right, bottom left quadrants,
top left, top right, bottom right quadrants.

Is it possible to answer this question for arbitrary $n$, $m$?
Comment: Given $n$, let $A_1,A_2,\dotsc,A_n$ be any $n$ disjoint subsets of the square, and then define the $n$ pieces to be what you get by removing one of the $A_i$ from the square (that is, for the 1st piece, remove just $A_1$, for the 2nd piece, remove just $A_2$, etc. Then for any $m>1$, any subset of $m$ pieces can be used to reconstruct the square.
Comment: @GerryMyerson OK wow, that's a really elegant solution, thank you!
Answer: Given $n$, let $A_1,A_2,\dotsc,A_n$ be any $n$ disjoint subsets of the square, and then define the $n$ pieces to be what you get by removing one of the $A_i$ from the square (that is, for the 1st piece, remove just $A_1$, for the 2nd piece, remove just $A_2$, etc. Then for any $m>1$, any subset of $m$ pieces can be used to reconstruct the square.

Dividing an area into redundant parts


Get the HTML content from the database

Question: I have a copy of a Drupal 9 database from which I need to download all the pages.
I loaded the database in MySQL Workbench CE and connected to it via Python. There are many tables, but no views or stored procedures. I guess that some of those tables house the content, but I have no idea on how to pull them together to extract webpages.
block_content_body looks promising, but then what?
I assume it is a standard Drupal database. Is there a standard schema?
This what I have tried.
<code>#connect to drupal db - done...
#copy to directory assigned.
#othercode config....

try:
    # Define the tables and columns to extract HTML content from
    tables_columns = [
        ('node_field_data', 'body_value'),
        ('block_content_field_data', 'body_value'),
        ('field_data_body', 'body_value'),
        ('field_data_[custom_field_name]', '[custom_field_column]'),
        ('paragraph__field_[custom_field_name]', '[custom_field_column]'),
        ('views_view', 'display_options')
        # Add additional tables and columns as needed

    # Iterate over the tables and columns and export HTML content to separate files
    for table, column in tables_columns:
        output_file = os.path.join(output_dir, f'{table}_{column}.html')
        query = f"SELECT {column} FROM {table}"
        cursor.execute(query)
        rows = cursor.fetchall()

        with open(output_file, 'w', encoding='utf-8') as file:
            for row in rows:
                html_content = row[0]
                file.write(html_content + '\n')

        print(f"HTML content from {table}.{column} exported to: {output_file}")

except mysql.connector.Error as error:
    print(f"Error retrieving data from MySQL: {error}")

finally:
    # Close the database connection
    if connection.is_connected():
        cursor.close()
        connection.close()

I still have to correct the field names but guess these are the html files some how joined together here?

Do you have suggestions, or is this just crazy talk?
</code>
Comment: There are no stored procedures or table views used by Drupal core. Multiple tables store text content of every field, with other tables holding entities that relate to those fields. You will either need to HTML scrape the site, or construct a migration to a new platform using that platforms migration tools.
Comment: Pages are not built that way in Drupal. You'll need to scrape the output to get a copy of all the pages.
Answer: Drupal pages are generated in a complex way.  Even the content stored in the database is often parsed by an input filter prior to processing.  So you will need to use Drupal to generate each page you want a copy of and save that.
But... that's a pain, so there are some automated ways to do it.  The downside is that it takes some work to set them up.
If you want to do this repeatedly, you can try the Tome module.  This allows you to generate a static site from Drupal 8+ on demand.
Alternately, you could look into setting up Gatsby with Drupal.
Answer: The appropriate and documented way to do this is to run the Drupal website on a web server and then create a static archive of the website.
Answer: You can use Tome for that.

Tome is a static site generator, and a static storage system for
content.
When Tome is enabled, any changes to config, content, or files will be
automatically synced to your local filesystem. These exports can be
used to fully rebuild the site from scratch, which removes the need
for a persistent SQL database or filesystem. When you're ready to push
to production, you can use Tome to generate a static HTML version of
your site.
Long story short, you can use Drupal in the same way you would use
other static site generators like Jekyll or Hugo - everything lives in
one repository, and Drupal only runs on your local machine.

Get the HTML content from the database


Regex for 8 to 10 digits

Question: I'm looking for a simple regex exp that will validate a phone number. The number can be between 8 an 10 digits and there can be no other characters. Can someone help out?
Answer: It looks like ^[0-9]{8,10}$ does the trick.
Thanks for all the suggestions.
Answer: You could try this regex:
<code>^[2-9]{2}\d{6,8}$
</code>
Comment: Phone numbers in many countries start with 0, not 2-9... Why so many upvotes?
Answer: <code>\d{8,10}</code>: would be the simplest way
Answer: Haven't checked it but i guess this will work [2-9][0-9]{7,9}
Answer: Something like that ?
<code>^[^01]\d{2}\d{6,8}$
</code>
Comment: No, first part (`[^01]`) matches any characters, for example letters

Regex for 8 to 10 digits


which eigenvalue is the stable one

Question: I'm reading a textbook that says something along the lines of, given a function $f:\mathbb{R}^2\rightarrow\mathbb{R}^2$. The Jacobian evaluated at $x_0$ has one eigenvalue smaller than one one eigenvalue greater than one. Then it says $[1 v]$ be  the eigenvector that corresponds to the stable eignvalue. I'm confused now as to shich one is the stable one. Apparently the textbook assumes this is clear, but I'm not too familiar with dynamic systems so I'm not sure.
Comment: Your question is missing context. There are plenty of Jacobians that have eigenvalues both less that $1$, or both greater than $1$, or both complex etc. You'll need to clarify _what_ Jacobian you are talking about. Also, stability is determined by the real part of the eigenvalue.
Comment: I think that providing exact reference is better than just saying *I'm reading a textbook*. (There is a chance that some readers of your post have access to that book and this information can help them getting more context.) I imagine something like: "I am reading Introduction to Perturbation Methods by Holmes. On [page 360](https://books.google.com/books?id=EX5iNglbqB4C&pg=PA360) relation between Jacobian and stability is discussed. The author says in Corollary 6.1 that..." (This is just an example. Although some relevant keywords appear there, the quote is not exactly about your problem.)
Answer: In general, the unstable manifold $E^u$ of a linear operator corresponds to all eigenvalues of modulus greater than 1, while the stable manifold $E^s$ corresponds to all eigenvalues smaller than 1 in modulus. Perturbations in the $E^s$ direction will decrease (as the eigenvalues are smaller than 1), while perturbations in the $E^u$ direction will increase--hence the names "stable" and "unstable."

which eigenvalue is the stable one


Looking for a way to analyse transporter traffic on shopfloor (Density Map) in AnyLogic

Question: I built up a shopfloor where material flow is realized by Transporters (AGV / AMR) with free space navigation. I am looking for a possibility to observe traffic at certain spots (e.g. work stations, storage areas) or even on the whole shopfloor so I can compare different scenarios of the material flow and supply strategy of the working station with a view on the traffic. I tried out the Density Map but since it observes the whole layout which is quite big the values get too low for the scale quite fast so it isn't performing the way I want it to. Is there a way so set up like a "area density map" so I can just observe a defined rectangle or another functionality which could help me here?
Happy about all ideas! :-)
Answer: You can use normal Rectangular Node elements and trigger "on enter" code to count drive-throughs or similar, as below.
Just make sure to set the capacity to infinity so normal traffic flow is not interrupted :)
Comment: Note that the infinite capacity bit is needed just because access restrictions are needed to have the "On enter" action available. You could also restrict access by condition, with a condition of `false` (i.e., never restrict) which is a bit cleaner than a capacity of 'infinity'.
Comment: Agreed, didn't even check the other options :)


Obtain post param from success url in Paumoney integration

Question: I have integrated payumoney payment gateway in angular 2 but when payumoney redirect to success url that time how can I get the params like transaction id and all other param?
what shall i right in the success url to get the response param by payumoney? I'm not able to see param in url like get url.
<form #f method="post" id="payu-payment-form" action="https://test.payu.in/_payment">
      <input type="hidden" name="hash" value="{{hash}}"/>
      <input type="hidden" name="key" value="{{marchentKey}}"/>
      <input type="hidden" name="txnid" value="{{txnid}}"/>
      <input type="hidden" name="amount" value="{{amount}}" />
      <input type="hidden" name="productinfo" value="{{productinfo}}"/>
      <input type="hidden" name="firstname" value="{{firstname}}" />
      <input type="hidden" name="email" value="{{email}}" />
      <input type="hidden" name="phone" value="{{phone}}" />
      <input type="hidden" name="surl" value="http://example.net/payment"/>
      <input type="hidden" name="furl" value="http://example.com/payment"/>
      <input type="hidden" name="service_provider" value="" />
      <button class="" type="submit" (click)="f.submit()" value="submit" formtarget="_blank" >Buy</button>
      </form>

Obtain post param from url in angular 2?
Comment: *i have no idea how to obtain post param from url?* By reading the manual?
Comment: How on earth did this get 4 upvotes?
Answer: When payment success. PayU money redirects to success url with POST method. You cannot handle POST method using javascript. you need a backend. So please set success url to a backend server, from there handle the post request and redirect your correct front end url
Answer: You can get the params in the response page as follow:

Import ActivatedRoute import { ActivatedRoute } from '@angular/router
Add it to the constructor constructor(private r: ActivatedRoute) {}
Subscribe to the route queryParams and capture the params in the response if available
ngOnInit() {
    this.r.queryParams.subscribe(params => {
       var transactionState =  params['transactionState'] || 'None';
        ...
    });
};

For reference check Angular's ActivatedRoute
Answer: Since Angular is a javascript framework, you can not handle POST requests on Angular side. Payment Gateway POST response needs to be handled at the server side API. I came across a nice article on this. It might help you,
https://www.devglan.com/angular/payumoney-integration-angular


Style KendoUI controls to look like standard controls

Question: We're doing an in-place migration of a fairly large web app (~150 pages, ~150 user controls) from WebForms to MVC.  We've selected KendoUI (MVC Complete) for the MVC control library.
In order to keep the look and feel the same as the existing WebForms pages and controls, we will only be using KendoUI for the Grid, Tree, and Upload controls until such time as we have fully migrated all pages over to MVC.  Note that I recognize the Kendo Grid, Tree, & Upload will be a change in the L&F - that's as much of a change as I could get the biz to agree to :)
Is there a way to style the KendoUI controls to look like standard controls (e.g. standard <select>) until such time that we can flip the switch and drop the last reference to the WebForms stuff?
I'd still like to be able to use KendoUI for all controls if possible, but just have them styled "old school" for now.  This way, I can use cascading updates, Kendo Validation, etc.
The controls I'm specifically thinking of are the DropDownList (<select>), IntegerTextBox (filtered text input), & ListView (<select>).
Answer: There is no out-of-the-box theme which mimics the "default" browser theme. The available themes can be seen in our online demos: http://demos.kendoui.com/web/grid
You can also use the Theme Builder to create a custom theme.
Answer: We've just created our own CSS to override the standard kendo stuff and it's looking pretty good, but would still love to find something OOTB from Telerik.