Read Excel Rows Using Pandas like Xlrd module

Question: In this example, I'm showing 2 ways how I read the excel file and print data.
Instead of using both ways, I want to use pandas module to output data as I did with xlrd module.
I want to loop through the column/rows and append it to the arrays (Col_B3, Col_C3, Col_D3)
How can I do this?
import xlrd
import pandas as pd
import io

path = r'C:\Temp Files\My_Excel_File.xlsx'

''' USING XLRD '''
#open workbook
inputWorkbook = xlrd.open_workbook(path)
#open first sheet
Sheet = inputWorkbook.sheet_by_index(0)

Col_B3 = []
Col_C3 = []
Col_D3 = []

for row in range(2 ,Sheet.nrows):
    Col_B3.append(Sheet.cell_value(row, 1))
    Col_C3.append(Sheet.cell_value(row, 2))
    Col_D3.append(Sheet.cell_value(row, 3))

print(Col_B3)
print(Col_C3)
print(Col_D3)

''' USING PANDAS '''
df = pd.read_excel(path)

print(df)

XLRD OUTPUT

['Col_B3', 1.0, 2.0, 3.0, 4.0]
['Col_C3', 'Jack', 'Jill', 'Peter', 'Jade']
['Col_D3', 1200.0, 875.0, 120.0, 4230.0]

PANDAS OUTPUT

   Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3
0         NaN        NaN        NaN        NaN
1         NaN     Col_B3     Col_C3     Col_D3
2         NaN          1       Jack       1200
3         NaN          2       Jill        875
4         NaN          3      Peter        120
5         NaN          4       Jade       4230

Answer: Try this, i have recreated your data in a spreadsheet.
import pandas as pd
import numpy as np

df = pd.read_excel(r"C:\Temp Files\My_Excel_File.xlsx")
#drop column name
df=df.drop(["Unnamed: 0"],axis=1)
#drop na
df=df.dropna(axis=0)

# remove all non-integer values
df = df[df.applymap(np.isreal).any(1)]

#Map column names

df.columns = ["Col_B3","Col_C3","Col_D3"]

#print results
print(df)

Col_B3 Col_C3 Col_D3
2      1   Jack   1200
3      2   Jill    875
4      3  Peter    120
5      4   Jade   4320

Answer: With XLRD, you had more control on how to wrangle the data as you read it in. Pandas reads your data as is; your first column is empty, same as first row. Your data is also in column format, so Pandas read it in column wise.
You can reshape it into list form with Pandas:
res = (df.dropna(how='all') #remove completely empty rows
      .dropna(how='all',axis=1) #remove completely empty columns
      .T #flip columns into row position
      #convert to list
      .to_numpy()
      .tolist()
      )

print(res)

[['Col_B3', '1', '2', '3', '4'],
 ['Col_C3', 'Jack', 'Jill', 'Peter', 'Jade'],
 ['Col_D3', '1200', '875', '120', '4230']]


When to move a virtualized server to physical?

Question: Virtualization has some great benefits, but there are times when a virtualized server needs more performance and should be moved to physical.
My question is, how do you tell when these times are? I'm looking for measurable data and metrics that show moving a server to its own physical box would make a significant difference to performance. Personally I'm interested in Windows but presumably the essentials are the same across all platforms.
Answer: I disagree that a virtual server would need to be moved to physical because of performance. Hypervisors are now so close to the metal that there is virtually (pun intended) no performance hit. Especially now that many board makers are including hypervisors on the chipset. If you took two servers with identical hardware, one running a single guest and one running an exact copy of that guest on the physical hardware, you would be hard pressed to notice a difference in performance I think.
There are other reasons, though, you may need a physical server rather than virtual. One of them is hardware compatibility. If your application requires non-standard hardware with its own unique bus, you may not be able to run that in a virtual machine.
I'm anxious to hear what others have to say. Great question.
NOTE: We have servers that were virtualized and then put back on the same hardware just to have the snapshot/vmotion capabilities we love.
Answer: I'm not an expert on this subject, but generally speaking: Very hungry I/O applications (especially those who write little and fast) are the ones who gets their own physical server.
It's not very hard to find them either, you just run performance monitor and look for high i/o wait times.
Also, high-end databases usually get its own dedicated server, because of several reasons:

They want to cache everything they can, RAM usage is enormous
They perform better with threading across several cores (8-way is normal), and you generally do not want to assign more than 1 virtual cpu to any server because of blocking
They are very I/O hungry when loading data to cache, low latency on I/O is key.
Comment: I'll disagree with the "usually" comment.  There are papers all over the VMWare site about setting up database servers on VMWare and I don't belive this to be any sort of an issue.  But you make great points about what what needs to be evaluated when considering the move to a Virturalized server.
Comment: We will soon be virtualizing our four database servers because of the benefits we will see with snapshots/vmotion/etc. I agree with LEAT that database servers have and will be virtualized in the future.
Comment: Hungry I/O apps are probably going to be hitting a SAN, though, which means that you're back to fibrechannel or infiniband speed, and not a raw disk under the VM - I've not seen (personally) an app that needs to be on physical hardware, outside of timing-critical systems, or where it's officially unsupported from the vendor
Comment: I get the feeling that people are arguing me for the sake of arguing. I did *not* say that it *needs* a physical host. I said that extremely resource hungry applications/usages *usually* gets it own dedicated server to not block other VM's.
Comment: I think you misunderstood me. I dint say that database servers should not be virtualized (all my dbs are). I said that high-end servers usually stays on separate physical servers, because of the limitations this brings (like only having 4 virtual CPU's aviable).
Answer: The one case where I had to carry out a V2P was for an MS SQL box that had been running on dual 3.2Ghz dual core CPU's (total CPU 14.4Ghz) that we migrated to an ESX 2.5 cluster where the underlying hardware was newer with more slower (2.4Ghz IIRC) cores. Adding in the ~10% overhead even with 4 vCPU's this VM could only ever get an effective 8-8.5Ghz aggregate CPU. 60% peak CPU before migration became 90-100% post migration, customer wanted headroom so we reverted to physical. To answer your question specifically we saw that the box was running at 100% CPU across the board in Perfmon and in the VI client. A better solution (in my view) would have been to upgrade to faster CPU's but there are edge cases like this where thats not economical especially with the trend to slower cpu's with more cores that we saw with the introduction of the Opterons\Core CPU's.
With ESX 4 we could bump a box like this up to 8 vCPU's but that wasn't an option at the time.
As far as looking for performance ceilings that might indicate you need to abandon your VM then with a Windows Guest on VMWare environment then the combination of Perfmon and the VI Client should be more than up to the task of finding any VM's that are performance limited themselves. Add in getting some SAN analytics to that if you can but if the SAN shows an issue then you will almost certainly be just as well off reworking the storage in order to isolate and\or enhance the volumes that the VM's virtual disks are stored on. Same applies to any other OS\Hypervisor combination - get whatever internal stats you can but correlate them to the Hypervisor's view of what's going on because 100% CPU being reported within a VM (for example) does not necessarily mean that the Hypervisor could never deliver more performance, just that it didn't at that point.
Answer: This very much depends on the service this is performing.
I typically look at the resources that are being used, and determining if they are indeed bottelnecks for this guest and the services it provides.
This of it this way:
If you have a Dual Core (2vSMP), 4GB RAM guest running a web server (IIS) and you're not maxing out CPU and RAM requests, then maybe the guest doesn't need more hardware.
We have run into cases where running an Oracle Database on a virtualization platform comes close to the same amount of performance as a similarly sized hardware server.
Obviously, if you wanted to have a 16-core server as a VM, you may have some trouble seeing it perform as well as dedicated hardware.
Answer: When the VM is starved for resources (or perhaps starving other VMs for resources) e.g.:

When the VM's IO can't be satisfied through the host
When the VM needs more network bandwidth than is possible sharing the trunk
When the VM's processes want more CPU than it can get, e.g. if there is a single process that is maxing out a virtual cpu
If its linux and it needs very precise time (if its running on a VMware host linux hosts under VMware drift time. This can be alleviated by using ntp, however for apps which require very precise time, e.g. kerberos, you might consider real hardware)
When its linux and needs very reliable disk (if its running on a VMware host - VMware has had and I believe still has SCSI problems under VMWare under certain conditions. A fix was put out but it still occurs, although much less often)
Answer: I'd say its when the server is at the point where it is consuming enough of the server resources that it cannot share the hardware.
ESX, ESXi & Window Hyper V should all give you near real performance.  So as long as one of the machines is not using 90% of the resources on its own you shouldn't need to move to real hardware.
Exceptions being you wouldn't want things like your 2 domain controllers on the same box should the hardware fail.
Comment: I'd disagree here too.  While the cost for running a single VM on a single host is high considering licensing costs, etc.  There are distinct advantages to it in terms of disaster recovery and hardware failover.  I think even in this case it is worth virtualizing.
Comment: You are quite correct.  With EXSi being free now one could virtualize a single server, your Exchange server for instance and have that on a machine by itself.  When its time to upgrade the hardware just copy the VM to the new machine.
Answer: I doubt there's a generic answer for this, but if you're worried about perfomance, then that's what you have to look at.  The obvious would be to check whether you are maxing out CPU, I/O, ...
But also, performance testing and benchmarks would also help you decide whether there is any penalty for being virtual and whether having a single VM on the host is sensible or not.
Answer: You first need to identify which resource is the bottleneck.
Windows performance monitor ( perfmon ) provides lots of counters for various aspects such as Disk queue, virtual Memory stats etc.
If you are disk bound, giving the virtual machine direct access to a disk instead of something like a vmx file with VMWare could help a lot.
Answer: I think it all depends on two factors:
 Ressource sharing: does the guest consume so much ressources that the other's performance is affected
 Security :if it's a very critical service you should probably not use virtualization as the more you add layers between the software and the hardware the less you might be secure.
just my 2cts.


How to extract frames from video faster?

Question: Currently, I am retrieving video frames based on the following code:
# Retrieve Images from Videos
for video in list_videos:
    vidcap = cv2.VideoCapture(video)
    success, image = vidcap.read()
    count = 0
    print("Successfully retrieving videos from ", video)
    while success:
        cv2.imwrite('.'+video.split('.')[-2]+'/'+'frame%d.png' %count, image)
        success, image = vidcap.read()
        count += 1
    vidcap.release()

This code is taking a lot of time to extract the frames from videos. Is there a faster way to implement this code?
Answer: The line of code that takes the most time is:
cv2.imwrite('.'+video.split('.')[-2]+'/'+'frame%d.png' %count, image)

One way to make that line faster is to resize the image (make it smaller) before writing it to the hard drive:
cv2.resize(image, (640,480))

Another way to process the video more quickly would be to write the images to the memory instead of the hard drive. This method will work only if you have enough RAM to hold the images. It could lead to a catastrophic computer crash:
images = []
while success:
    images.append(image)
    success, image = video.read()

Comment: Thanks for the inputs. I will try the first option. It's a huge data so I am leaving the second option. Is there a way to cv2.imwrite() step


Show a list of all forms

Question:
Possible Duplicate:
How to list all the form IDs

I have been searching for a way of listing all forms that are hooked to a Drupal site. I have read this post How to list all the form IDs, saying that it is impossible.
Now impossible is a big word in my vocabulary;-) If need be I can scan every single module file for the hook_form () function. Yet I am seriously hoping there will be a less hack like solution no matter what the resource cost might be. Any suggestions?
Comment: Out of curiosity, why do you need this list?
Comment: I have a assignment at work that requires me to list all forms through the Servises REST server so they can be used as content in steps for a BPM engine. Since my boss here is not easily convinced that we should deviated from the plan...well I'm stuck with this.
Answer: Well I ended up using Hook_form_alter () to add every form that was being called (and was not on my form list yet) to a form list.
Then I wrote an admin interface that enables the administrator to select what forms are still active/should be listed. Next to this I implemented a REST service for the Services module to GET the list of forms.
The fact that the hook_form_alter () has to preform a DB request to see if the form is on the list everytime a form is viewed is some what performance heavy, but since there is no help, this is the best I can think of. If anyone has interest in the code, drop me a line, ofcourse better ideas are welcome;-)

Show a list of all forms


Parametrizing the intersection of a cylinder and a sphere

Question: I need to parametrize the intersection between the cylinder $
x^2 + y^2= \frac{1}{4}$ and the sphere $(x+ \frac{1}{2})^2 + y^2 +z^2 = 1$.
I tried parametrizing the first equation which gives $r(t) = (\frac{cos(t)}{2}, \frac{sin(t)}{2})$ since the radius is 1/2.
Then, I plugged in the values in the second equation which yields $(\frac{cos(t) +1}{2})^2  + \frac{sin^2(t)}{4} + z^2 = 1$. We isolate $z$ and get that $z = \sqrt{1-\frac{cos(t)}{2}}$. I'm stuck here because the parametrization would be incomplete if we choose the positive or negative root, am I doing something wrong? If so, what would a correct parametrization be?
EDIT: I've just recalled that $\sqrt{\frac{1-cos(t)}{2}} = sin(\frac{x}{2})$ or $cos(\frac{x}{2})$. Is this helpful?
Comment: The possible $z$-values are such that $$(\frac{\cos t +1}{2})^2  + \frac{\sin^2t}{4} + z^2 \le  1\ ,$$so that $z$ (not $z^2$ as in OP, surely a changed intention during typing...) runs in the interval between the two $\pm\sqrt {\dots}$ .
Answer: $x^2+y^2=\frac{1}{4}$
$\left( x+\frac{1}{2} \right)^2 + y^2 + z^2 = 1$
Expand
$x^2 + x + \frac{1}{4} + y^2 + z^2 = 1$
Collect
$\left(x^2+y^2\right)+x+\frac{1}{4}+z^2=1$
Substitute first equation
$\frac{1}{4}+x+\frac{1}{4}+z^2=1$
The key equations now being$\ldots$
$x+z^2=\frac{1}{2}$
$x^2+y^2=\frac{1}{4}$
We pick $z=t$ hoping for a cleaner solution...
$x=\frac{1}{2}-t^2$
$x^2+y^2=\left( \frac{1}{2}-t^2 \right)^2+y^2=t^4-t^2+\frac{1}{4}+y^2=\frac{1}{4}$
$y^2=t^2-t^4$
$y^2=t^2\left(1-t^2\right)$
$y=\pm t\sqrt{1-t^2}$
And we write...
$\left(\frac{1}{2}-t^2,\pm t\sqrt{1-t^2},t\right)$
for $t \in \left[-1,1\right]$
and I expect someone else to point out the algebra mistake if there is one because there's alot of expansion in my approach, but I checked it and I'm pretty sure it's consistent.

Because the cylinder is of lesser radius, the intersection is a single point at the xy plane. The vertical (xy) projection of the curve is a circle. The lateral (xz) cross section of the curve is a parabola.
Comment: Thanks!. I've plotted both your parametrization and mine and they look the same. One last thing though: How did you get the domain  t ∈[−1,1]? Is it because of the root's domain?
Comment: Yeah exactly. $t^2< 1$ from the root
Answer: Your parametrization is OK.
Note that the intersection of the cylinder and the sphere in this case is not just one but two closed curve meeting at the origin, sort of like a figure $8$.
I do not see how we can fit both in one parametric equation.


Using .resemple() in python to go from weekly to monthly time series

Question: Is it possible to use .resample() to take the last observation in a month of a weekly time series to create a monthly time series from the weekly time series?  I don't want to sum or average anything, just take the last observation of each month
Thank you.
Answer: Based on what you want and what the documentation describes, you could try the following :
<code>data[COLUMN].resample('M', convention='end')
</code>
Try it out and update us!
References
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html
Answer: Is the 'week' field as week of year, a date  or other?
If it's a datetime, and you have datetime library imported , use  .dt.to_period('M')   on your current date column to create a new 'month' column, then get  the max date for each month to get the date to sample  ( if you only want the LAST date  in each month ? )
Like max(df['MyDateField'])
Someone else is posting as I type this, so may have a better answer :)


Sharing permissions doesn't apply to sub directories as required

Question: I have few Windows 2008 Enterprise servers with SP2 on a domain environment. Below is a scenario what I was trying to achieve and where I am stuck with.
I have created certain Security - Global groups and have added members accordingly. Afterwards, I have created a folder called "Departmental" and then some sub folders such as IT, Finance, Corporate... etc.
What I have done initially is just shared the Main directory with read permission for Domain Users as I only require the directory to be seen/accessed by domain authenticated users. However, what I have also done is that, each of the sub folders I have manually added the respective groups be removing the inheritance. Now, when I do this all the domain users can see/access the root directory and also the sub directories belonging to their department (e.g. a finance user can only see/view finance folders, the rest are hidden from user view).
However, they are not able write into the directory regardless of the access. And when I move back and give Contribute access to the Domain Users group, then the users are able write into the sub directories.
I know t his will work out as the other folders aren't visible for them but what I require is, if there's a way to over come this by only giving the read access to the root directory and then to sub directories as required? is this possible or am I doing this wrong?
Answer: You've granted everyone the READ permission on the Share. That's all they'll be able to do regardless of your NTFS permissions. Share and NTFS permissions work in tandem to determine the access level of a user when accessing the resource over the network, and the most restrictive combination wins.
You should probably set the Share permissions to Full Control and control access using the NTFS permissions. That's how it's done most of the time.
Comment: Thank for the explanation. Giving out full control on to the root of share will also have write access to it which I don't want, instead allow them to write into the sub directories. I remember a similar set-up that was done on a 2012 by one of my colleague had worked like a charm.. Couldn't figure out where else I would need to alter. :/
Answer: If you access a share via the network, the share permissions have priority.
If you access the files on the server itself, the NTFS permissions have priority.
For example, if you give Everyone read access to the share, and you give the IT group Modify to the IT subfolder, everyone in the IT group will only be able to read "\\share\IT" because the share's privileges are more restrictive (read only).
If someone in the IT group logs onto the server and accesses that folder, they will be able to modify it.
However, if you give the "Everyone" group Full Control on the share you can now restrict access at the NTFS level.
For example, if you give the IT group Full Control of the IT subfolder then they will have Full Control. Other users will not have Full Control unless you give them that access at the NTFS level.
The share permissions are for the share.
This is why it's common practice to give "Everyone" full control at the share level then only apply the users and groups who need access at the NTFS level.


SQL Server Buffer cache content

Question: I'm having an issue on my instance page life expectancy would drop to a few seconds.
I know this is due bad code, and I'm trying to find out which object pages are in the buffer cache. That would lead me to what causes the problem. Kind of v$bh equivalent in Oracle.
Edit
I came across this great article which talk about the issue I got with pagelife expectancy. And how to find the buffer content.
Thanks,
Answer: This link should provide you with the queries to use for this: http://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/
Note: You didnt' say which version of SQL Server you are using, but this will only work on 2005 and up boxes
Comment: Thanks a lot! works like a charm. I've added an sp_foreachdb, and got all of what I needed. Oh, and by the way, 2008r2 is my version.
Answer: sys.dm_os_buffer_descriptors has the data about buffer pool content. You will also be interested in sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats. Between these you will be able to identify hot objects. sys.dm_exec_query_stats will show you queries that are touching a lot of pages (high logical_reads).
Comment: Thanks, sys.dm_os_buffer_descriptors is what I was after. I guess my next step is to find how I can me an object not to pin in the buffer pool. I have 64GB of RAM, and most of it's content doesn't need to be.
Comment: IS the 64GB available to SQL? What does [`DBCC MEMORYSTATUS`](http://support.microsoft.com/kb/271624) return?
Comment: Yes it is. Server has 96G total, and 64G allocated to MSSQL (Only cause the 64G limit in standard). I just have objects in cache that don't need to be, along with badly coded app.

SQL Server Buffer cache content


If I want to use chef to install software,what shoud I do on the server machine

Question: I learn chef recently, and I find the tutorial on the Internet,they install the ruby environment and chef before they install software on the server machine.
apt-get -y update
apt-get -y install build-essential zlib1g-dev libssl-dev libreadline5-dev libyaml-dev
cd /tmp
wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p125.tar.gz
tar -xvzf ruby-1.9.3-p125.tar.gz
cd ruby-1.9.3-p125/
./configure --prefix=/usr/local
make
make install
gem install chef ruby-shadow --no-ri --no-rdoc

my question is the ruby environment and gem chef is a requirement if I want to install software on the server machine?
Comment: Which tutorial is this?
Comment: http://railscasts.com/episodes/339-chef-solo-basics
Answer: Since Chef 11, Chef is shipped with Omnibus Installer. This brings (almost) everything that Chef needs, including a ruby environment. So you don't have to install any ruby and you are not supposed to install the Chef gem.
Instead download chef-client and follow the install instructions. Alternatively, you can use this command:
curl -L https://www.opscode.com/chef/install.sh | sudo bash

Comment: Actually Chef client versions back to 10.12 are available through omnibus. But if you are just getting started, you should start with the latest 11+.


is there error on Moldau (=Vltava) arranged for piano by Lechner on measure 59 ? What is the fix?

Question: In this score of Moldau (called also Vltava), by Smetana, arranged for piano by Lothar Lechner (edition Schott),
is the last note of left hand of measure 59 correct ?
Should it be a C instead of a B ?
Comment: Isn't this from Ma vlast by Smetana?
Comment: @JimM : thank you. I made the fix on the author.
Answer: The note is, correctly, a D. It comes from the second violin and is part of a G major harmony.

(Image source: IMSLP, Boosey & Hawkes edition, PDF page 11)


Colocar valor padrão na coluna

Question: Preciso deixar um valor default nessa coluna da tabela, estou fazendo o mapeamento das persistências com o Hibernate (resumindo o banco é criado de acordo com o HQL/JPA que eu defino nos domains.
Como faço para setar um valor padrão para a coluna ?
<code>@NotEmpty(message="O campo foto não pode ficar em branco !")
@Column(name = "foto_usuario", length = 50, nullable = false)
private String foto;
</code>
Answer: Como o colega Wagner postou, um ex:
<code>@NotEmpty(message="O campo foto não pode ficar em branco !")
@Column(name = "foto_usuario", nullable = false, columnDefinition="varchar(50) default 'same one value'")
private String foto;
</code>
ou, aqueles callback methods do Hibernate, ex:
<code>@PrePersist
void defaultValue() {
   foto = "sua imagem aqui";
}
</code>
Agora sendo sincero, se é um valor default por que não atribuir direto no bean?
<code>@NotEmpty(message="O campo foto não pode ficar em branco !")
@Column(name = "foto_usuario", length = 50, nullable = false)
private String foto = "sua foto default aqui";
</code>
Comment: Mas se eu colocar ele direto no bean igual teu último exemplo, quando o cara não colocar nada, ele vai pegar aquele ali ? e quando ele setar uma foto vai a que ele mandou, é a mesma coisa ? funciona como default ?
Comment: Toda vez que você instânciar um objeto ele irá ficar com aquela propriedade preenchida, caso esteja buscando do banco ele terá o valor que foi atribuído anteriormente.
Comment: Acho que serei mais claro agora, eu preciso que o usuário coloque uma foto de url no campo de cadastro, se ele não colocar eu quero uma padrão da nossa empresa, qual você acha que é a maneira mais adequada para fazer isso ?
Comment: as três forma da certo, eu deixaria configurado direto no objeto porque essa imagem default não vai mudar, é uma daquelas imagens fantasmas de cadastro que serve para todo mundo, mas se você tem uma imagem desta para usuário masculino e outra default para usuário feminino ai você não escapa de ter que usar o @PrePersiste
Answer: Tenta assim:
<code>@Column(name="suacoluna", columnDefinition="float default 0")
</code>

Colocar valor padrão na coluna


Solve the recurrence $T(n) = 2T(n-1)+n^2$

Question: Solve the recurrence
$$T(1) = 1, T(2) = 1, T(3) = 1,T(n) = 2T(n-1)+n^2, n > 3$$
I have now,
$$T(n) = 2T(n-1)+^2 $$
$$= 2(2T(n-2)+(n-1)^2+n^2$$
$$=4T(n-2)+2(n-1)^2+n^2$$
$$....$$
$$2^iT(n-i)+\sum_{k=0}^{i-1}=2^{k}(n-k)^2$$
$$2^{n-1}T(1)+\sum_{k=0}^{n-2}=2^{k}(n-k)^2=2^{n-1}+\sum_{k=0}^{n-2}2^k(n-k)^2$$
Can anyone help.
The @all
Comment: I don't think a closed form exists because the recurrence is dependent _only_ on the current term and the previous term and $T(2),T(3)$ doesn't satisfy the recurrence. I may be wrong though.
Comment: @PrasunBiswas : notice that the recurrence relation is only for n > 3, so there is no problem
Comment: Yes, but the recurrence depends on only one previous term, that was the reason for my previous comment. @Tryss
Answer: Less words, more facts. Let
$$ f(z) = \sum_{n\geq 1} T(n)\,z^n.\tag{1}$$
The recurrence relation hence gives:
$$\begin{eqnarray*} f(z) &=& 2\sum_{n\geq 4} T(n-1)\,z^{n} + (z+z^2+z^3)+\sum_{n\geq 4}n^2 z^n\\&=&2z\sum_{n\geq 3}T(n)\,z^n+(z+z^2+z^3)+\frac{z^4 (16 - 23 z + 9 z^2)}{(1-z)^3}\\&=&2z\left(f(z)-z-z^2\right)+(z+z^2+z^3)+\frac{z^4 (16 - 23 z + 9 z^2)}{(1-z)^3}\tag{2}\end{eqnarray*}$$
and it follows that:
$$ f(z) = \frac{z \left(1-4 z+5 z^2+15 z^3-25 z^4+10 z^5\right)}{(1-z)^3 (1-2z)}\tag{3}$$
so, by partial fraction decomposition, we have:

$$ \forall n>2,\qquad  T(n) = 7\cdot 2^{n-1}-(n+2)^2-2. \tag{4}$$
Comment: You have inspired me.  I think I'll begin all of my future proofs with *less words, more facts*.
Comment: Can you elaborate on how you obtained $T(n)$ from the partial fraction decomposition? I guess adding coefficients for the series expansions of each summand?
Comment: @Christoph: exactly. There are two singularities giving different contributes: the simple pole in $z=\frac{1}{2}$ gives the $2^n$ term and the triple pole in $z=1$ gives the polynomial terms. They are just routine computations, not really interesting in themselves.
Answer: This is a non-homogeneous linear recurrence relation.  There is a standard procedure for solving these when the non-homogeneous term has a particular form, namely a polynomial, an exponential, or the product of a polynomial and an exponential.
In your equation, the non-homogeneous term is $F(n)=n^2$.
The first step is to find the general solution to the associated homogeneous equation, obtained by replacing the non-homogeneous term with 0.
In your equation, the associated homogeneous equation is $T(n)=2T(n-1)$.  Suppose the general solution is $u_c(n)$ (also called the complementary function).
The second step is to propose a solution based on the homogeneous term.
Since your non-homogeneous term is a polynomial of degree 2, you propose a general polynomial of degree 2.  So your proposed solution in this case is $u_p(n)=an^2+bn+c$.
The third step is to substitute the proposed solution into the non-homogeneous equation and use the resulting equation to find $a,b,$ and $c$.
The fourth step is to construct the general solution to your equation equation from $u_c(n)$ and $u_p(n).$ This is $T(n)=u_p(n)+u_c(n)$.
As I mentioned, this is a fairly standard method, and can probably be found in most textbooks that cover linear recurrence relations.
Answer: A linear recurrence of first order, which can always be "solved" (as long as finding closed forms of some ugly sums is possible).
The general form is:
$$
a_{n + 1} = f(n) a_n + g(n)
$$
where $a_0$ is given.
Divide by the summing factor:
$$
S_n = \prod_{0 \le k \le n} f(k)
$$
Note this is valid as long as $f(k) \ne 0$ over the relevant range.
Thus:
$\begin{align}
\frac{a_{n + 1}}{S_n} - \frac{a_n}{S_{n - 1}}
  &= \frac{g(n)}{S_n} \\
\sum_{0 \le k \le n - 1}
  \left(
    \frac{a_{k + 1}}{S_k} - \frac{a_k}{S_{k - 1}}
  \right)
  &= \sum_{0 \le k \le n - 1} \frac{g(k)}{S_k} \\
\frac{a_n}{S_{n - 1}} - a_0
  &= \sum_{0 \le k \le n - 1} \frac{g(k)}{S_k} \\
a_n
  &= a_0 S_{n - 1} + s_{n - 1} \sum_{0 \le k \le n - 1} \frac{g(k)}{S_k}
\end{align}$
In your particular case $f(n) = 2$ and $g(n) = (n + 1)^2$, $S_n = 2^n$,
so that:
$\begin{align}
T(n)
  &= 2^{n - 1} T(0)
       + 2^{n - 1} \sum_{0 \le k \le n - 1} \frac{(k + 1)^2}{2^k} \\
  &= 2^{n - 1} T(0)
       + 2^n \sum_{0 \le k \le n - 1} \frac{(k + 1)^2}{2^{k + 1}} \\
  &= 2^{n - 1} T(0)
       + 2^{n - 1} \sum_{0 \le k \le n} \frac{k^2}{2^{k - 1}}
\end{align}$
The resulting sum is somewhat tricky. We know that:
$\begin{align}
\sum_{0 \le k \le n} z^k
  &= \frac{1 - z^{n + 1}}{1 - z} \\
\frac{\mathrm{d}}{\mathrm{d} z}
  \left(
    z \frac{\mathrm{d}}{\mathrm{d} z}
      \sum_{0 \le k \le n} z^k
  \right)
  &= \sum_{0 \le k \le n} k^2 z^{k - 1} \\
  &= \frac{1 + (n z - n - 1) z^n}{(1 - z)^2}
\end{align}$
Evaluate this at $z = 1/2$ to get your sum:
$$
2^{-n + 1} (2^{n + 1} - n - 2)
$$
so the final result is:
$$
T(n) = 2^{n - 1} T(0) + 2^{n + 1} - n - 2
$$


Incorrect Drupal 8 Breadcrumbs

Question: I'm trying to add the page title to the breadcrumbs for each page, unfortunately my breadcrumbs are not updating with current page title. All sibling pages in the menu show the same breadcrumbs.
For example, all these pages will show the same breadcrumbs:
Home > About Us > Our Team
Home > About Us > Our Mission
Home > About Us > Another Page

Whatever page you visit first, you will get the breadcrumbs for that page on all of the above pages. So if you visit the "Our Team" page first, you will get the "Our Team" breadcrumbs on the "Our Mission" and "Another Page" pages as well. The same happens for 2nd level pages.
So if you visit
Home > About Us

You will get the About Us breadcrumbs on
Home > Services

However, you will not get the Home > About Us> Our Team breadcrumbs on
Home > Services > Service A

I have this code in my .theme file:
function themename_preprocess_breadcrumb(&$variables){
   if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
       $variables['breadcrumb'][] = array(
                 'text' => $node->getTitle(),
                     'url' => $node->URL()
                   );
   }
}

And this for my breadcrumbs template:
{% if breadcrumb %}

{{ 'Breadcrumb'|t }}

    {% for item in breadcrumb %}

        {% if item.url %}
          {{ item.text }}
        {% else %}
          {{ item.text }}
        {% endif %}

    {% endfor %}

{% endif %}

I'm guessing it's some sort of caching issue, as it seems to happen per-session (different users will get stuck with different breadcrumbs depending on which pages they visit first).
Anyone know why this may be happening?
Answer: I ran into the same issue
https://www.drupal.org/node/2723061
function my_theme_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    /** @var \Drupal\node\NodeInterface $node */
    $variables['breadcrumb'][] = [
      'text' => $node->getTitle(),
      'url' => $node->toUrl(),
    ];
    $variables['#cache']['contexts'][] = 'url';
    $variables['#cache']['contexts'][] = 'session';
    $variables['#cache']['contexts'][] = 'user';
  }
}

So:
$variables['#cache']['contexts'][] = 'session';
$variables['#cache']['contexts'][] = 'user';
$variables['#cache']['contexts'][] = 'url';

did the trick for me.

Incorrect Drupal 8 Breadcrumbs


How to add JavaScript or CSS library to Composer project?

Question: For some cases, there is the need to add a JavaScript or CSS package to a project. One of those cases was the DropzoneJS package for the drupal/entity_browser. All recommendations I could read online read like

Download manually
Install manually

or like

Use Drush

This is not really satisfying as there should be a way without user interaction or working around interaction in setup scripts.
Answer: The library can be installed into a custom path by utilizing extra : installer-paths to for e.g.:
web/sites/libraries/{$name}

Additional to that, we define the required package repository with the needed type of drupal-library. Example composer.json for a project:
{
    "name"              : "example-composer/example-project",
    "description"       : "Project template for Drupal 8 projects with composer",
    "type"              : "project",
    "minimum-stability" : "dev",
    "prefer-stable"     : true,
    "scripts"           : {
        "post-install-cmd" : "sh ./scripts/composer/post-install.sh"
    },
    "require"           : {
        "composer/installers"       : "^1.0.20",
        "drupal/entity_browser"     : "8.1.0-alpha1",
        "cweagans/composer-patches" : "~1.0",
        "drupal/core"               : "8.0.*",
        "drush/drush"               : "~8.0",
        "drupal/console"            : "~0.9",
        "drupal/devel"              : "dev-8.x-1.x",
        "drupal/entity_browser"     : "8.1.0-alpha1",
        "drupal/inline_entity_form" : "8.1.0-alpha2",
        "drupal/dropzonejs"         : "8.1.*@dev",
        "enyo/dropzone"             : "dev-master"
    },
    "repositories"      : [
        {
            "type" : "composer",
            "url"  : "https://packagist.drupal-composer.org"
        },
        {
            "type"    : "package",
            "package" : {
                "name"    : "enyo/dropzone",
                "version" : "dev-master",
                "type"    : "drupal-library",
                "dist"    : {
                    "url"  : "https://github.com/enyo/dropzone.git",
                    "type" : "drupal-library"
                },
                "source"  : {
                    "url"       : "https://github.com/enyo/dropzone.git",
                    "type"      : "git",
                    "reference" : "origin/master"
                }
            }
        }
    ],
    "extra"             : {
        "installer-paths" : {
            "web/core"                    : [
                "type:drupal-core"
            ],
            ...
            "web/sites/libraries/{$name}" : [
                "type:drupal-library"
            ]
        }
    }
}

The dist part can be left off and is only needed for --prefer-dist cases when installing via php composer.phar update --prefer-dist (opposite: --prefer-source). To install a version and not the latest from the master branch, you need to set the version directly at the package to require then from there. Example:
"require" : {
    "enyo/dropzone" : "v4.2.*@dev"
},
"repositories" : [
    {
        "type"    : "package",
        "package" : {
            "name"    : "enyo/dropzone",
            "version" : "v4.2.0",
            "type"    : "drupal-library",
            "source"  : {
                "url"       : "https://github.com/enyo/dropzone.git",
                "type"      : "git",
                "reference" : "origin/master"
            }
        }
    }
]

Comment: An interesting discussion, but the only practical among you is @kaiser who came with an answer. The others are apparently not convinced enough to come with an actual example how to do the same with Bower. People like me, looking for a answer, will go with an answer, not with some unpractical opinionated discussion.
Comment: For this type of libraries I prefer bower.
Comment: @IvanJaros Because it does _not_ solve conflicts (multiple packages installing the same dependencies multiple times). Also you need packages that have a `bower.json` to not install stuff that the original dev only needed to develop the package or build the distributable files. Upside: It serves _very small_ packages if well configured.
Comment: @Ivan Jaros, I agree with you. Composer is for **PHP** libraries.
Comment: What Kaiser said @Ivan. Great for small, insular projects; doesn't necessarily scale well to larger projects with more entry points, unless you're careful/lucky in my experience
Comment: Package Managers are for _packages_ and are not restricted by language. Also, what would you do if you have **no Nodejs** available in your install location?
Comment: @kaiser In this case no...Composer is, literally, billed as: Dependency Manager **for PHP**. Emphasis mine. Front end packages should be handled by a front end package manner, Bower is a good example though it has its problems. You can shoehorn a CSS dependency into Composer, just like you could do the same to an NPM package, doesn't mean you _should_. If nodejs isn't available, and it's required to do a proper job, it should be installed. Not being able to find a hammer is not an excuse to use a screwdriver to do a hammer's job, in my opinion
Comment: @Clive You are taking that Composer quote quite literally. You wouldn't take Bowers quote of "A package manager for the web" to justify that you are fetching PHP packages with it, right? Aside from that, I would not want two different package managers - who know nothing of each other - to install into the same directory.
Comment: @kaiser Sorry, never going to agree with you here. This is from Bower's front page: _Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn't concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies._. If you can find a similar quote anywhere on the web that says Composer is supposed to be used for the same thing, let's see it :)
Comment: @Clive Please take your time and rephrase this into an answer (and please clean up our last comments that are just opinionated). The more possibilities for later readers, the better. Thanks in advance :)
Comment: @kaiser Just heading to the dentist (groan) will do it a bit later tonight :)
Comment: @Clive "Bower is a good example though it has its problems" - anything in particular?
Answer: An alternative answer, "don't use composer".
We've had pretty good success using a root npm package called "copy-files-from-to"
https://www.npmjs.com/package/copy-files-from-to
Example package.json
{
  "license": "MIT",
  "scripts": {
    "postinstall": "copy-files-from-to"
  },
  "dependencies": {
    "blazy": "^1.8.2",
    "copy-files-from-to": "^2.3.0",
    "select2": "github:select2/select2"
  },
  "copyFiles": [
    {
      "from": "node_modules/blazy/*.js",
      "to": "public/libraries/blazy/"
    },
    {
      "from": "node_modules/select2/dist/**",
      "to": "public/libraries/select2/dist/"
    }
  ]
}


Alternating Series sum

Question: Given $\sum_{n=1}^{\infty} \frac{(-1)^n}{2^n}$ determine ig the series converge or diverge. If convergent calculate the sum.
Using the convergence test I've found out that the series converges. However, I don't know how to go about finding the sum. Any ideas?
Comment: It's geometric.
Comment: Note that $\frac{(-1)^n}{2^n} = \left(-\frac{1}{2}\right)^n$.
Comment: Welcome here! Which convergence test did you use?
Comment: @Taladris the alternant series test
Answer: Recall: the geometric series $\sum_{n=0}^\infty x^n$ is absolutely convergent with value
$$\sum_{n=0}^\infty x^n = \frac{1}{1-x}$$
whenever $|x| < 1$. To find the value for your series, notice that you can "pull out" the general series' first term like this:
$$\sum_{n=0}^\infty x^n = 1 + \sum_{n=1}^\infty x^n$$
Then notice your series has $x = -1/2$, apply the formula for the series, and solve for yours to obtain its value.
More explicitly,

 $$\sum_{n=1}^\infty x^n = \frac{1}{1-x} - 1\;\;\;\;\; \overset{x=-1/2}{\implies} \;\;\;\;\; \sum_{n=1}^\infty \left( - \frac 1 2 \right)^n = - \frac 1 3$$
Comment: I think it's supposed to be $-\dfrac13$.
Comment: Yeah I made a sign error. My bad; thanks
Comment: Oooh, I knew $\sum_{n=1}^{\infty}ar^{n-1} = \frac{a}{1-r}$. But the original had $ar^{n}$, when I encounter a problem like that should I just work with $\sum_{n=0}^{\infty}r^{n} = \frac{1}{1-r}$? I just wasted time playing around with the argument to adapt it to $ar^{n-1}$ haha.
Comment: I feel like I was told a similar formula for stuff like that in middle school. I feel like

$$\sum_{n=0}^\infty r^n = \frac{1}{1-r}$$

is easier to remember, though, and its manipulations are more intuitive as well. Especially considering it amounts to

$$1+r+r^2 + r^3 + \cdots$$

when expanded. Your first formula is almost equivalent to my simpler series: just re-index it (let $m=n-1$ and rewrite your series) and divide both sides by $a$. Yours basically accounts for series whose first term is not $1$ (but that can be accounted for by factoring anyways).
Answer: Let $a_n = \frac{(-1)^n}{2^n}=\left(-\frac{1}{2}\right)^n$
Then $|a_n| = \frac{1}{2^n}$ and series $$\sum_{n=1}^\infty |a_n| $$
converge because it is geometric series.
So $\sum a_n$ is absolutly converge and this make $\sum a_n$ also converge.

And now we use  $$\sum_{n=1}^\infty x^n = \frac{x}{1-x}$$
put $x=-\frac{1}{2}$ and we get
$$\sum_{n=1}^\infty a_n = \sum_{n=1}^\infty\left(-\frac{1}{2}\right)^n = \frac{-\frac{1}{2}}{1+\frac{1}{2}}=\boxed{-\frac{1}{3}}$$

Alternating Series sum


Resources for solving integration problems analytically

Question: I've started dealing with a lot of (many times nasty) integrals in my research.  When there an integral that I can't readily solve using usual methods (like substitution and integration by parts), I try the following sources, in this order:

Gradshtein & Ryzhik 7th ed.
Wofram Functions page
Handbook of Mathematical Functions
Google (which is how I found this website)

I am wondering what sources of help do others employ when faced with difficult integration problems that require analytical solution (other than posting here.)
Thank you!
Comment: [DLMF](http://dlmf.nist.gov/) would be the updated Abramowitz and Stegun...
Comment: The *Integrals and Series* books by Prudnikov, Brychkov, and Marichev would also be a nice compendium.
Comment: @joriki: I haven't checked my copy in a while to see if it has stuff that the others don't, but it's good to add that to Bullmoose's list anyway. :) Well, that and Jahnke-Emde...
Comment: In the good old days before the internet, I used to use the [Handbook of Mathematics](http://www.amazon.com/Handbook-Mathematics-I-N-Bronshtein/dp/3540721215/ref=sr_1_1?ie=UTF8&qid=1315805981&sr=8-1) by Bronshtein (whose name is spelled "Bronstein" in the German version). It contains quite a number of integrals, but I don't know whether any of them go beyond the other resources listed; I haven't used it for a while now.
Comment: Thanks everyone for helpful suggestions!  And J.M., thanks for the pointer to the DLMF!
Answer: Computer algebra systems could be of great help here. For example, Mathematica boasts to be able to solve most of indefinite and definite integrals from books like Gradshtein & Ryzhik.
There is also Wolfram alpha, which uses the Mathematica kernel. But the time spent on a problem is strictly limited, so it doesn't work for more or less complicated expressions.
Comment: But note that a. it remains useful to be skeptical of the results a computing environment spits out, and b. computing environments won't necessarily return the most convenient closed form for a given integral.
Comment: J. M. ain't a mathematician:  I've worked with *Mathematica* for decades almost never had problem with b).  One uses `Simplify` or `FullSimplify` or computationally make a substitution.  As for a), we should be even *more* skeptical about hand calculation for very difficult problems!


How to call AWS Lambda concurrently without having thousand of connections?

Question: I am trying to call AWS Lambda concurrently to scrape some urls. When doing so I use ThreadPoolExecutor to invoke the lambda. I split the urls into batches of size of 50 to limit the number of concurrently running lambdas. I then wait for them to end, and expect the number of connections to be limited by 50. But, instead I see boto3 creating > 1000 connections.
Here is the code:
def scrape(data):
    with ThreadPoolExecutor(max_workers=10) as executor:
        result = []
        for source_url, info in data.items():
            urls = info['urls']
            source = info['source']
            for batch in batches(urls, 50):
                futures = []
                for url in batch:
                    payload = {
                        'url': url,
                        'country': source['country'],
                        'language': source['language'],
                        'topic': source['topic']
                    }

                    futures.append(
                        executor.submit(client.invoke,
                                        FunctionName='scrape_page',
                                        InvocationType='RequestResponse',
                                        Payload=bytes(json.dumps(payload), 'utf-8')))

                result.extend([future.result() for future in futures])

    return [json.loads(r['Payload'].read().decode('utf-8')) for r in result]

Is this a correct approach to call AWS Lambda concurrently, or there is a better way?
Comment: "Connections" to what?
Comment: Please tell us EXACTLY where & how you measured the number of connections & which connections are you referring to? The Lambda function's connection to the URL?
Comment: I run the script given above, as I understand the boto3 client creates new connection to lambda each time it is being called. I try to limit total number of connections to 50 total, but when running `netstat | grep ec2` I see that the number of connections grows to hundreds, instead of being ~50.
Comment: I haven't tried this, so not an answer. It looks like the default number of pooled connections is 10, which I think means that Boto will create 40 new one-time-use connections for each batch of 50 requests that you make. You can change this, by [passing a config object](https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html) when creating the client.
Comment: That said, your architecture doesn't really leverage Lambda. Rather than invoke Lambdas from your client program, I would instead write the URLs to an SQS queue and let Lambda handle the invocations itself. The resutls can either be written to a different SQS queue and read by your application, or better, to a DynamoDB database or S3 bucket, where they can be read multiple times.
Answer: Your question needs to provide more details like others mentioned,however would like to point out few things.

Instead of using threads inside the lambda you can make your task
idempotent and distribute them to multiple lambda.
Number of cores(1 core=2 threads) available to a lambda is
proportional to Function memory and only when you choose memory size
more than 1.8G you will get more than 1 core.And afaik you will not
get more than 2 cores with max memory setting.
You can cap the concurrent execution by configuring the Reserved
Concurrency ,which will guarantee that at any point the number of concurrent
lambda will not exceed the configured number.


Area of a Hexagon in the Complex Plane given by the solutions of $x^6+x-1=0$

Question: I have this problem I friend gave me a little while ago and I don't even know where to begin.
This was the problem he gave me:
Let $z_0, z_1, z_2, z_3, z_4, z_5$ be the solutions to the equation $x^6+x-1=0$. Find the area of the hexagon given by $z_0z_1z_2z_3z_4z_5$ in the complex plane.
Also I have no clue how to even tag this problem, so feel free to edit them :)
Comment: You know that given three points $z_1, z_2, z_3$ on the complex plane the area of the triangle defined by these three points is $\frac{1}{2} \mathrm{Im}[(z_2-z_1)(z_3-z_1)]$.
Comment: Yet another approach is well described in this video: https://www.youtube.com/watch?v=dtzGm0J-gSc
Comment: @TedBlack I think you have a typo in that formula. With $z_1=0$, $z_2 = 1+i$, $z_3=1-i$ (say) your formula gives an area of $0$, since $\left(z_2-z_1\right)\left(z_3-z_1\right)$ is real.
Comment: $\frac{1}{2}\mathrm{Im}[(z_2-z_1)^*(z_3-z_1)]$ its just the sine rule for the area of a triangle
Comment: @TedBlack No, it's not. (Also, I don't think you mean "sine rule" - I assume you mean $\frac12 ab \sin C$) I think you're possibly looking for an analogy with vector cross products that isn't there. Did you check the counterexample I gave? (The triangle has area $1$, but your formula gives $0$.) The simplest form for the area of a triangle given in the complex plane I've seen is in terms of a determinant involving the points and their conjugates.
Comment: The last formula gives an answer equal to -1 not zero! You don't need a determinant to calculate the area of a triangle!!
Comment: @TedBlack I'm not sure what we're missing here. With $z_1=0$, $z_2=1+i$, $z_3=1-i$, your formula is $\frac12 \text{Im} \left(z_2-z_1\right)\left(z_3-z_1\right)=\frac12 \text{Im} (1+i)(1-i)=\frac12 \text{Im} (2+0i)$. The imaginary part of the number $2+0i$ is zero, so the result of your formula is zero. Could you show how you get $-1$?
Comment: @Chris Lewis the updated formula (see comments) was $\frac{1}{2}\mathrm{Im}[(z_2-z_1)^*(z_3-z_1)]$. Since $z_2-z_1=1+i$ and $z_3-z_1=1-i$ we have $(z_2-z_1)^*(z_3-z_1)=(1-i)(1-i)=-2i$ so $\frac{1}{2}\mathrm{Im}[(z_2-z_1)^*(z_3-z_1)]=\frac{1}{2}(-2)=-1$. See geometric proof of formula here: https://www.geogebra.org/geometry/qf6ytgvb
Answer: As $p(x):=x^6+x-1$ is a polynomial with real coefficients, its roots are

either real :  $\approx -1.1347$ and $\approx 0.7781,$
or pairs of complex conjugate numbers :  $\approx -0.4511 \pm 1.0024i$ and $\approx 0.6294 \pm 0.7358i.$

Therefore, their representative points are either on the real axis or symmetrical with respect to it. See (red) hexagon on this figure :

As a consequence, an approximate answer can be obtained by just computing the upper part of the area (above the real axis) as a sum of trapezoidal areas, then double it.
If you look at the similar question, the opinion expressed there is that no general method exists giving an exact answer. You will find there the following formula for the numerical computation of the area :
$$A=\frac12 \Im\left(\sum_{k=1}^{n}r_k\overline{r_{k+1}}\right)$$
($\Im$ meaning "imaginary part" ; please note that indices are to be understood "modulo n" in order that  $r_{n+1}=r_1$). This formula isn't especialy interesting here.
Edit 1 :
Let us consider the derivative $p'(x)=6x^5+1$ of polynomial $p(x)$. Its $5$ roots $-\frac{1}{\sqrt[5]{6}} e^{i2k\pi/5}, \ k=0,1,2,3,4$ form a pentagon included into the hexagon by the celebrated Gauss-Lucas theorem ; therefore, the area of the hexagon is larger than the area of the pentagon which can be computed exactly (it is an exception !) as $\frac{5}{2}\frac{1}{6^{2/5}}\sin \frac{2 \pi}{5}$). I wonder whether the real question of your friend is indeed to minorate the area of the hexagon..., unless he just wanted a numerical approximation of the area $A \approx 2.67261847$...
Edit 2 :
Some thoughts about the peculiarity of polynomial $p$. The fact that this polynomial has many zero coefficients invites to attempt a factorization :
$$p(x)=(x^2+ax+p)\left(x^4-ax^3+bx^2+cx-\frac{1}{p}\right)\tag{*}$$
where the quadratic factor yields the real roots.
There are 3 constraints on $b$ and $c$ :
$$b=a^2-p, \ c=a(2p-a^2), \ c+a(b-p)=0$$
from which we deduce the following condition linking $a$ and $p$
$$a^4p-3a^2p^2+(p^3+1)=0$$
which can be considered as a quadratic equation in $A:=a^2$.
Therefore, one can express $a$ as a function of $p$. As a consequence, all the coefficients in (*) can be expressed as functions of $p$.
Open question : Can this be used for reaching an exact expression of the area ?
Remark : numerical values of the coefficients of the fourth degree polynomial in (*) can be obtained at once with the very handy function "deconv" of Matlab:
$$    deconv([1,0,0,0,0,1,-1],[1,\underbrace{0.35663453}_a,\underbrace{-0.8829170}_p])$$
Matlab program for the construction of the hexagon above :

<code>L=[1,0,0,0,0,1,-1], % list of coefficients
r=roots(L);
[K,A]=convhull(real(r),imag(r)), % convex hull
r=r(K), % trigonometric ordering of the roots
plot(r,'-or');
Implementation of formula (1) :
s=0;
for k=1:6
   s=s+r(k)*conj(r(k+1));
end;
imag(s)/2, % area (same value as A, up to the sign)
</code>
Comment: Strange not to have any comment from the asker...


Usuário sem acesso a recursos mapeados no Security-role do web.xml

Question: Qual é o comportamento da security-role do web.xml quando o usuário não tem permissão de acesso aos recursos do projeto?
É default o weblogic retornar um 404?
Esse status é configurável?
Existe a possibilidade de quando a security identificar que o usuário não tem permissão de acesso ao recurso, realizar um redirect para outra página?
Answer: Os servidores de aplicação retornam 401 (Not Authenticated) quando o usuário não está autenticado e redirecionam para a página de autenticação, se estiver configurado no web.xml.
Quando o usuário não possui o papel necessário para o recurso, é devolvido código de retorno 403 (Proibido - Forbidden).
Caso queira personalizar o código de retorno, ou a página a ser exibida, você terá de tratar isso programáticamente.
boolean HttpServletRequest.isUserInRole(String role)

O objeto HttpServletRequest pode ser consultado. À partir da resposta você poderá decidir que código de retorno ou página será exibida.


Angularjs ng-bind-html not working with string start with '<'

Question: I want to bind an expression using ng-bind-html , This expression can  contains string having html tag ("google") or simple string (name) , as I created here ,
http://jsfiddle.net/U3pVM/8940/
here , value of location can be any string, when location is location2 i.e  a string started with '<' , code is not working.
please help.
thanks.
Answer: That is because it's trying to parse it into an html element, but there's no closing tag so nothing is shown. If you add a > to the end it will parse an element <mumbai></mumbai>
To actually show the character, use the encoded version < so it won't try to parse it as an element.
http://jsfiddle.net/U3pVM/8941/
Comment: Hi , Nice solution , but I really don't know , whether I get "delhi" or "<abdsc" , How can I identify when to convert "<" in <


Java Finalizers, what tasks are really necessary

Question: ArrayList<Object> foo;
Object[] bar;

typical finalizers will do
foo = null;
bar = null;

My question, will ArrayList call a finalizer wich sets any pointers it holds to null, or do I have to step through the list an do
for(i=1; i<foo.size(); i++) foo.set(i,null); ???

And the other question: for an array, do I need to set any of its contents to null, like
for(i=1; i<bar.length; i++) bar[i] = null;

or is it enough that the whole memory block is discarded and any pointer in it out of scope afterwards?
Sorry, if the question is stupid.
After reading through the answers I figured out, that there is nothing to implement there on your own.
Some sources suggest that if something like this (memory eating apps) happens, that this is by bad design.
My core question is: Doing often
struct = new LargeStructure();

does this exaust memory?
Or does this only need the memory of one of this structures?
BTW: The problem occours in a webapp running tomcat, and there is only one session active wich holds the described pointer as a session variable.
Answer: All objects will be eligible for GC by Garbage collector automatically when they are no longer referenced. You don't have to worry about it. If you are setting the array reference to null , then the array object itself is eligible for GC if there are no other live reference to the array object, the elements of the array will be eligible for GC if there are no live references to them anymore.
As per the documentation:
protected void finalize() throws Throwable

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The finalize() method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object. If the object never becomes unreachable, or the GC doesn't run then finalize() may never be called.
You can try to force the JVM to call finalize() by calling System.runFinalization():

Runs the finalization methods of any objects pending finalization.
Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.
Comment: if I set foo = null; willl any sub-structures it references be automatically deleted or will they persist in memory
Comment: I understood finalizers as a routine, wich sets all sub-structures to null to make them elegible for garbage collection
Comment: I really hoped I could solve a problem with large data structures wich are not freed.
Comment: I often do TreePointer = new Tree() making large Sets of data npo longer referenced. But they seem to be not freed and memory is exausted after an hour or so
Comment: can you make it very clear so I can tell my boss who thinks that it is my fault (we all know better c++)
Comment: If you set the `TreePointer` to `null` , the `Tree` object will be eligible for GC if there is no other reference to that `Tree` object anywhere else.
Comment: If I understnd you correctly: A binary tree consisting of tree objects referencing each other will be freed by GC only if there is no more refrerence to the root node
Comment: if the objects aren't reachable from a root node then they will be reclaimed.
Comment: would it be a good Idea to call System.runGC() after discarding very large cascaded structures
Comment: It is same as `System.runFinalization()` , best effort by JVM but not guaranteed results.
Comment: I don't know if that matters, but I overwrite the pointer with a reference to a new Object created by new. Then the old object is no longer referenced. But I don't set it to null.
Comment: Finalizers are almost never necessary in Java.  The GC is almost always smarter than you.
Answer: Theoretically finalizers let you perform last minute tasks on object before they are reclaimed by garbage collection. In practice however there is no guarantee that they will be called, so they are not very useful.
Answer: You don't have to set your object's references to null in finalizer block. Finalizer's are tipically used for last chance resource closing, it isn't a good practice, but finalizers can provide you a safety net for resource management.
Answer:
My question, will ArrayList call a finalizer wich sets any pointers it holds to null, or do I have to step through the list an do

ArrayList will not call a finalizer, a finalizer thread will do that, but you don't have to worry about that. Also, you do not have to go over a list and finalize your elements your self. Java Garbage Collector will figure that one out for you and pick those objects up as long as they are not referenced anywhere else in the code.

And the other question: for an array, do I need to set any of its contents to null, like

No, same as above. Important thing to remember is that you have no reference to any value in the array, or to the array itself if you want it to be picked up by garbage collector.


Identity Element of a Group of Sections of a Sheaf

Question: Serres gives the following definition of a sheaf in the paper FAC:

Let $X$ be a topological space. A sheaf of abelian groups on $X$ (or
simply a sheaf ) consists of:
(a) A function $x \to \mathscr{F}_x$, giving for all $x \in X$ an
abelian group $\mathscr{F}_x$,
(b) A topology on the set $\mathscr{F}$, the sum of the sets
$\mathscr{F}_x$.
If $f$ is an element of $\mathscr{F}_x$, we put $\pi(f) = x$; we call
the mapping of $\pi$ the projection of $\mathscr{F}$ onto $X$; the
family in $\mathscr{F} \times \mathscr{F}$ consisting of pairs
$(f,g)$ such that $\pi(f) = \pi(g)$ is denoted by
$\mathscr{F}+\mathscr{F}$.
(I) For all $f \in \mathscr{F}$ there exist open neighborhoods $V$ of
$f$ and $U$ of $\pi(f)$ such that the restriction of $\pi$ to $V$ is
a homeomorphism of $V$ and $U$.(In other words,  is a local
homeomorphism).
(II) The mapping $f \mapsto -f$ is a continuous mapping from
$\mathscr{F}$ to $\mathscr{F}$, and the mapping $(f, g) \mapsto f + g$
is a continuous mapping from $\mathscr{F}+\mathscr{F}$ to
$\mathscr{F}$.
If $U$ is an open subset of $X$ then a map $s: U \to \mathscr{F}$ is called a section over $U$ if $s$ is continuous and $\pi \circ s =$ id$_U$.

It is asserted that the set of all sections over a fixed subset $U$ form an abelian group with the operation of pointwise addition. I would like to like to verify this. I see that if there is at least one section $s$ on $U$, the abelian group structure will follow from (2). But how do I know there is at least one section, say $s$, for each $U$?
I tried to prove that for a given $U$, the map that takes $x \in U$ to the identity element of the corresponding stalk, $(x,e)$  is continuous, by invoking 1, but was unsuccessful.
Comment: I think something is missing from your definition. What are (1) and (2)?
Comment: @TobiasKildetoft : if you have a functor $\mathcal{F}$, that is a sheaf according to the "usual definition", then taking $\mathcal{F}_x = \varinjlim_{U\ni x}\mathcal{F}(U)$ yields a sheaf as defined here (you have to topologise it well enough). Conversely, given a sheaf as defined here, the  (functor) sheaf of sections will be a sheaf as you know them
Comment: @TobiasKildetoft: In modern terms, this is defining the "étale space" of a sheaf. There is an equivalence of categories between the category of sheaves on a space $X$ and the slice category $LH/X$, where $LH$ is the subcategory of **Top** consisting of all spaces, but with local homeomorphisms as the maps.
Comment: Rats. You are correct. Sorry, this is the first time trying to ask from my phone. I'll edit
Comment: Ok, it should be all there now. Sorry for the low quality typesetting, I just walked off an airplane and really want to get this figured out.
Comment: You did not define "sections on $U$" - just asking because you define scheaves somewhat unusually (without using functors, restrictions, exactness, ...)
Comment: Where is this definition from? I find it very hard to turn it into the usual definition, which assigns a group to each open set and which does not force a topology on the sum of the groups. It seems like this definition starts with the stalks?
Comment: This is the definition from Serre's original paper FAC. It is 'equivalent' to the functional definition but not immediately obvious. With some work the equivalence is clear. But, for a section 's' over an open subset U, I mean a continuous map s from U to F such that the projection composed with s is the identity on U. Then the set of all sections forms on abelian group by pointwise addition
Comment: @TobiasKildetoft yes it starts with stalks.
Answer: Consider the mapping you gave, that is $x\mapsto (x,e_x)$ where $e_x$ is the identity element of $\mathscr{F}_x$.
You want to show that it is continuous, but continuity is a local property so you can look locally; and then invoke (I) :
Let $x\in X$ and let $V$ be a neighbourhood of $(x,e_x)\in \mathscr{F}$ and $U$ a neighbourhood of $x$ such that $\pi: V\to U$ is a homeomorphism. Let $s:U\to V$ be its converse.
Denote $V\times_X V = \{(z,y) \in V, \pi(z) = \pi(y)\}$ (this is the more common notation for $V+V$). By (II), $m:V\times_X V \to V$ defined by $m(z,y) = z-y$ is continuous.
Consider now $\varphi: V\to V\times_X V$, $y\mapsto (y,y)$ which is also continuous.
Finally, let $d: U\to V$ be defined as $m\circ \varphi \circ s$. $d$ is continuous, $\pi\circ d = id_U$ is also clear from the definitions.
Moreover, unravelling the definition yields that $d:U\to V$ is precisely $d(y)= (y,e_y)$: hence $x\mapsto (x,e_x)$ is locally continuous, hence continuous.
So this gives us a global section $X\to \mathscr{F}$ which is a neutral element in the set of sections of $X$, and clearly its restriction to any open set has the same property.
Passing remark: In the functorial definition, a sheaf of groups is a functor $O(X)^{op}\to \mathbf{Grp}$ satisfying certain "gluing conditions". But it's actually easy to see that it's the same thing as a group object in the category $\mathbf{Sh}(X)$, the category of sheaves of sets on $X$. So with this definition, the continuity of the aforementioned map is automatic, because in the definition of a group object you have a map from the terminal object to the group $G$, but this essentially means a map $X\to G$ "over $X$" (seeing $\mathbf{Sh}(X)$ as $Etale(X)$)
Comment: The idea of using $(x,y)\mapsto x-y$ is indeed a very classical one whenever topology and groups are involved : for instance it's what allows you to prove that a $T_1$ topological group is $T_2$ ! You're welcome !
Comment: Yes, that's exactly it ! Well a constant sheaf from the functorial point of view would be $\mathcal{F}(U) = A$ (for a fixed $A$) hence the restriction maps would be the identity, hence indeed from the etale space point of view this implies that the stalks are all the same (and in fact they're $A$) . So you get that the constant sheaf would be $\displaystyle\bigsqcup_{x\in X} A$ suitably topologised
Comment: Yes I seem to have made a mistake earlier, it's not $\mathcal{F}(U)$ that is constantly $A$, it's really the stalks (hence the etale space point of view makes it easier to see why we say constant sheaf) that are constantly $A$. In particular, you are right, the (functorial) sheaf of sections associated to it takes the value $0$ when evaluated at $\emptyset$.
Comment: And as of course every restriction map sends any map to this map $\emptyset \to \mathscr{F}$, they are indeed homomorphisms. But for the purposes of this technicality, it may be interesting to note that the correct definition of a section should thus be "the corestriction of $\pi\circ s$ onto its image is $id_U$"
Comment: This is excellent, very helpful. I am happy that my approaches at least started similar, but I didn't think to define the maps $\phi$ and $m$ and reroute through $V \times_{X} V$ so I could take advantage of property (2). I was also trying to use the topological definition of pointwise continuity. Local continuity is clearly the better approach here.
Comment: Showing the property for the global section was also helpful. I was trying to work with an arbitrary $U$. Thanks again for your help.
Comment: Can I trouble you for one more question... on this same page in FAC, gives a constant sheaf as an example of a sheaf, but does not define a constant sheaf. There appears to be some controversy on the internet about what a constant sheaf is defined to be. Using the definition of a sheaf above, should I take the definition of a constant sheaf to be a sheaf who's stalks are all the same? It seems using the categorical definition of a constant sheaf is to require certain properties for sections, which leads to equal stalks.
Comment: Also, what is the slick way to justify that $m$ is continuous using axiom (2)? I tried to show that $(f,g) \mapsto (f,-g)$ was continuous, since then I could compose with the map $(f,g) \mapsto f+g$ but I cant seem to get the first map
Comment: Oh wait, I think I see it. Start with $\mathscr{F} \times \mathscr{F}$, the projection map onto each component is continuous. I can compose the second projection with $g \mapsto -g$ continuous by axiom (2). But then I have $(f,g) \mapsto f$ continuous and $(f,g) \mapsto -g$ continuous as maps from $\mathscr{F} \times \mathscr{F} \to \mathscr{F}$ thus I have the map $(f,g) \to (f,-g)$ is continuous in the product topology, but then I can restrict both the domain and codomain to $\mathscr{F}+\mathscr{F}$?
Comment: As you can tell my point set topology is not strong...
Comment: Ok, and a technicality - what is the group associated to the set of sections over the empty set? Or does $\Gamma(U,\mathscr{F})$ being an abelian group only when $U$ is a non empty subset of $X$?
Comment: Er.. wait, for the empty set there would be exactly one function, the empty function, so its automatically the trivial group?
Comment: In the following section, 'Construction of Sheaves', Serre makes some propositions about certain sheaves being isomorphic, but has yet to define a morphism of sheaves. Using the functorial definition, since each sheaf is a functor, the isomorphism would be a natural transformation. But using the definition Serre gives, how should I interpret isomorphism of sheaves? My best guess is homeomorphism that induces isomorphism on stalks?
Comment: Well to define isomorphism you always only need three things : defining morphisms, composition, and identity morphisms. The last one is clear and the second one too (because we sort of know that morphisms will be maps over $X$ - the problem is which maps ?). Now a morphism is simply a map over $X$ that induces a morphism on each stalk. An isomorphism is then, as always, a morphism with an inverse (both left and right). It's a good exercise to see what this means in terms of stalks, yes (and it's probably what you just said - I'm just giving you a recipe for determining what isomorphisms are)
Comment: Should it be a map over $X$ or a map over $\mathscr{F}$, it seems if we had a fixed topological space $X$ and two sheaves $\mathscr{F}$, $\mathscr{G}$ on $X$ would we want the morphism of sheaves to be between $\mathscr{F}$ and $\mathscr{G}$?
Comment: Yes it's between those two but over $X$, i.e. the obvious diagram must commute (my "over" is from french terminology "au-dessus de" I don't know whether that's english terminology as well)
Comment: Ok, so just be sure,  if $g$ is my homeomorphism of sheaves that induces isomorphism on stalks, then the final commutativity requirement would be that $g$ commutes with the projections from the sheaves to $X$?
Comment: Yes, that's it ! I don't know what the correct english translation for "au dessus de $X$" should be, but when you spell it out explicitly that's what it means
Comment: Great, Thanks :)


Using a dictionary to create Caesar Cipher, outputting only one item

Question: For class I am creating a function that converts each letter in the alphabet into its corresponding letter after a given shift, in a way that a caesar cipher would shift each letter. So far I have:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# Problem 1.

def build_cipher(shift):
    '''
    Description: takes in shift (an integer representing the amount the letter key in the dictionary is shifted from its corresponding letter) and returns a dictionary containing all letters and their corresponding letters after the shift. This is achieved through subtracting the shift from the number corresponding to the letter, and using modulo 26.

    >>> build_cipher(3)

    '''

    for i in range(0, 26):
        letter = alphabet[i]
        shiftedletter = alphabet[(i - shift) % 26]

        return {letter : shiftedletter}

This is mostly correct, but it only outputs:
{'a': 'x'}

How can I get it to output for each letter? I want my output to be:
{'a': 'x',
'b': 'y',
'c': 'z',
'd': 'a',
'e': 'b',
'f': 'c',
'g': 'd',
'h': 'e',
'i': 'f',
'j': 'g',
'k': 'h',
'l': 'i',
'm': 'j',
'n': 'k',
'o': 'l',
'p': 'm',
'q': 'n',
'r': 'o',
's': 'p',
't': 'q',
'u': 'r',
'v': 's',
'w': 't',
'x': 'u',
'y': 'v',
'z': 'w'}

I think the problem is that it isn't looping for each letter in the alphabet, but I am not exactly sure how to fix that. Any help is appreciated, thank you!
Comment: Do what @Rocket says but build the dictionary first.
Comment: Move the `return` outside of the `for` loop.
Comment: @RocketHazmat when I do that it only returns {'z': 'w'}
Answer: You want to build the dictionary first. When you're done, return the dictionary you just built.
def build_cipher(shift):
    cipher = dict()
    for i in range(0, 26):
        letter = alphabet[i]
        shiftedletter = alphabet[(i - shift) % 26]
        cipher[letter] = shiftedletter
    return cipher

Or, as a comprehension:
def build_cipher(shift):
    return {alphabet[i]: alphabet[(i - shift) % 26] for i in range(0, 26)}

Comment: Thank you so much!
Answer: As an alternative, you can use str.maketrans() to make a translation table t with any shift value:
def make_table(alpha, shift):
    k = shift % len(alpha)
    return str.maketrans(alpha, alpha[k:] + alpha[:k])

Then use s.translate(t) to translate any string s:
In [1]: s = "hello world"

In [2]: alpha = "abcdefghijklmnopqrstuvwxyz"

In [3]: t = make_table(alpha, 13)

In [4]: s.translate(t)
Out[4]: 'uryyb jbeyq'

In [5]: t = make_table(alpha, -42)

In [8]: s.translate(t)
Out[8]: 'rovvy gybvn'

Comment: Interesting function, but the solution asked requires a variable shift
Comment: @DavideMadrisan ...did you not notice that mine includes a `shift` variable?
Comment: Ah, sorry. The last line has misled me because I thought the entire algorithm was working with a shift eq 13 only. Can you edit your answer to make this more explicit?
Comment: @DavideMadrisan is my edit sufficient?
Comment: Yep, stackoverflow just needed an edit for allowing me to remove the downgrade.
Answer: A simple solution that just fixes your code.
def build_cipher(shift):
    '''
    Description: takes in shift (an integer representing the amount the letter
    key in the dictionary is shifted from its corresponding letter) and returns
    a dictionary containing all letters and their corresponding letters after
    the shift. This is achieved through subtracting the shift from the number
    corresponding to the letter, and using modulo 26.

    >>> build_cipher(3)
    '''

    alphabet = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ]

    cipher = {}
    for i in range(0, 26):
        cipher[alphabet[i]] = alphabet[(i - shift) % 26]

    return cipher

cipher = build_cipher(3)
for k,v in cipher.items():
    print("{}: {}".format(k, v))

Output:
a: x
b: y
c: z
d: a
e: b
f: c
g: d
h: e
i: f
j: g
k: h
l: i
m: j
n: k
o: l
p: m
q: n
r: o
s: p
t: q
u: r
v: s
w: t
x: u
y: v
z: w

Answer: This is one way to solve it.
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# Problem 1.

def build_cipher(shift):
result = {}
for i in range(0, 26):
    letter = alphabet[i]
    shiftedletter = alphabet[(i - shift) % 26]

    result.update({letter : shiftedletter})
return result

Answer: The moment you first call return it will jump out of the function.
You could either change the return statement into a print-statement, or you could have a return string, that you partially put together in the loop. Something like this:
ret = ""
for i in range(0, 26):
    letter = alphabet[i]
    shiftedletter = alphabet[(i - shift) % 26]
    ret += "{" + letter +  " : " + shiftedletter + "}\n"
return ret

Comment: You're being downvoted because OP doesn't want a string that looks like a dictionary, they want a dictionary.


Regarding two different definitions of Covering spaces and their equivalence

Question: I got two different definitions of 'Covering spaces' from two different books while reading. I would like to know if they are equivalent, or is it the case that the authors are simply following different conventions. Here they are:

All spaces are assumed to be path-connected and locally path-connected.
Definition 1 (following Hatcher's book) : $(\tilde  X, p : \tilde  X \rightarrow X)$ is called a covering space of $X$ if for each $x \in X$, there exists an open neighbourhood $U$ of $x \in X$ such that $p^{-1}(U) = \bigcup\limits_{\alpha \in \cal(A)} U_{\alpha}$, where $U_{\alpha}$ are disjoint, open subsets of $\tilde  X$ and $ p: U_{\alpha} \rightarrow U$ is a homeomorphism.
Definition 2 (following Massey): $(\tilde  X, p : \tilde  X \rightarrow X)$ is called a covering space of $X$ if for each $x \in X$, there exists an open path-connected neighbourhood $U$ such that each path-component of $p^{-1}(U)$ is homeomorphic to $U$ under the map $p$.

My attempt at showing equivalence:
First, $(2) \implies (1)$ : Recall that if $X$ is locally path-connected space, any open subset of $X$ is also locally path-connected, and path components of $X$ are open. Now, let $V$ be the open connected nbd. obtained from (2). $p^{-1}(U)$ is open in $\tilde X$, hence locally path-connected. So, path components of $p^{-1}(U)$ are open. Also, $p^{-1}(U)$ is union of disjoint path components of $p^{-1}(U)$, hence we get (1).
Now, $(1) \implies (2)$ : Suppose (1) holds with $U$ as the obtained nbd. Since, $X$ is locally path-connected, there exists $U'$ open, path-connected in $X$ such that $ x \in U' \subset U$. Now, $p^{-1}(U') = \bigcup\limits_{\alpha \in \cal(A)} U'_{\alpha}$, where $U'_{\alpha} = U_{\alpha} \cap p^{-1}(U)$. It can be shown that $p : U'_{\alpha} \rightarrow U'$ is a homeomorphism. I don't understand how to show that path components are homeomorphic to some open connected nbd. of $X$ after this.
Answer: You simply have to check that the $U'_\alpha$ are the path components of $p^{-1}(U')$.
First of all, they are disjoint and open by (1) and the choices made. Moreover, $U'$ is path-connected and $U'_\alpha$ is homeomorphic to it under $p$, so $U_\alpha'$ is also path-connected.
The rest follows simply.
Comment: Thank you, I somehow overlooked this.


Como modificar a largura para a adaptação em tablets de um menu sem media queries?

Question: Menu: http://responsivemultimenu.com/lib/responsive-multi-menu/
Eu nunca vi um menu responsivo como esse, não tem nada de media queries, eu acredito que a parte responsiva é criada pelo javascript. De qualquer forma este não é o meu problema, eu quero que o menu fique responsivo antes do que ele está.
 Por exemplo, eu testei ele no resposinator  e mas ou menos em 570px o menu se modifica para se adaptar em celulares, e eu queria aumentar este numero par mais ou menos 760px.
Mas eu olhei todo o css e depois o javascript nenhum número aproximado ou parecido com esse aparece lá.
Tem alguma tag especifica que eu deveria modificar ?
Answer: Realmente ele utiliza javascript para fazer a troca. Calculando o espaço necessário para o menu e faz a quebra quando este valor é ultrapassado, uma maneira que encontrei de modificar isso é adicionando padding em
, assim você diminui o espaço e a troca acontece antes.
Espero ter ajudado.
Comment: eu não entendi muito bem, é pra colocar apenas `padding: (qualquernumero)px`  nesta parte no css: `.rmm.style` . tentei isso e nada mudou.
Answer: Caso queira alternar o estilo de um menu sem utilizar media queries você pode utilizar a junção de css e javascript.
No css você cria uma classe para o respectivo menu relacionado a medida aproximada de 760px.
No arquivo javascript você verifica o tamanho da tela para mudar o estilo da seguinte forma:
if ($(window).width() <= 760 ) {

  $('.rmm').addClass('classe do css que faz o estilo para essa medida');
}


Recurrence or transience of the 1-3 tree

Question: The 1-3 tree is a rooted tree with only the root at level n=1, and from thereafter, $2^n$ vertices at each tier of distance from the root.  However, they are not connected as in the binary tree.  Put the root at the bottom, and as you go up in $n$, at each level draw the $2^n$ vertices from left to right. bAt each level $k$ the connections are drawn towards level $k+1$ so that there are $3$ edges coming out of each of the right half and $1$ edge coming out of each of the left half of the $2^k$ vertices.  The endpoint of these edges within the level $k+1$ is determined so that there are no crossings.
Why is simple random walk on this graph transient? (Or is it actually recurrent, and why?)
This question arises here: http://pages.iu.edu/~rdlyons/prbtree/book.pdf
It does not arise explicitly, but it is my hopeful answer to exercise 3.4 and 3.5 on p.89.
I have tried to calculate the effective resistance, and I have tried to demonstrate that the flow that starts at the top equally distributed and ends up doing whatever it has to to get to the bottom (root) has energy bounded in $n$.  No success here.  The tree in question can be found drawn on p.5.
Comment: Two bits of minor nitpickery: (1) should the root be at level 1 or level 0? (2) what is the degree of the root? My presumption is that the root is at level 0 and of degree 2, respectively, but it's not clear in the Q.  Also, this is a fascinating tree; do you have more references to it?
Comment: @Steven Stadnicki Your presumption is right.  Unfortunately, I don't have any references.
Answer: I realized that I can use the same technique as was used to show that the branching number is $1$ in order to show that the tree walk is actually recurrent.  Thus it does not provide an answer to either exercise 3.4 or 3.5.  Namely, any flow with finite energy, which we assume exists for a contradiction, would have to send nonzero flow down the right most branch or nonzero flow somewhere else.  Either case is a contradiction.


Tailwind - Keep dimensions in sync across elements in a grid so they grow vertically in equal dimensions when contant changes

Question: Tailwind Playground
https://play.tailwindcss.com/Q7z8BXMRKK
I have a 3 block card, the header (title and subtitle) , the body content and the footer.

title and subtitle

        I'm title and subtitle content container and I should grow or shrink to match the dimensions of the other grid element title and subtitle, so they stay vertically aligned with the same dimensions.

      I'm an input field content container , the fields container on the right should grow to matchthe dimensions of the other grid element field container , so they stay vertically aligned with the same dimensions.
      <slot />

      I'm a footer content container and same as the other 2 sections above, I should have the same dimensions as the other grid footer sections in the grid iteration of this component.

When this is used in a grid, I need to keep the dimensions in sync, so the 3 blocks are always equal in height using flex box.
I got seriously stuck here.
I'm showing what I mean more in detail in the playground.
Comment: do you mean in `grid-cols-2` layout the two header should have same heights, the two content should have same height and so on ?
Comment: exaclty, I need to figure out a way to keep the dimensions in sync in the 3 different parts, the header, the body and footter, while using the grid.
Comment: instead of `h-full` give same height for each headers like  `h-[480px]` and so on
Comment: that wouldnt work, I don't know how large the content of each part would be. I need flex to dynamically manage that.
Answer: Let me know if this works for you

        Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1 Header1

        Header2 Header2 Header2 Header2 Header2 Header2 Header2 Header2

        Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1 Body1

        Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2 Body2

        Footer1 Footer1 Footer1 Footer1 Footer1 Footer1 Footer1 Footer1

        Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2 Footer2

Here is the link to it :
https://play.tailwindcss.com/8Uw3qEM4sM


Converting Char to ASCII

Question: Character field in a table is having number values from 1 to 100. What would be the query to display it in order?
Comment: which database ??? what you tried ??? can you elaborate ....
Comment: Your question is not really clear. Can you add more detail to what it is you are trying to achieve?
Comment: What do you mean character field has value 1 to 100? like a varchar column with "100" (three characters)?
Answer: ORDER BY CAST(field_name AS INT)

Answer: ASCII (Transact-SQL)
ASCII ( Char_expression)

Converting Char to ASCII