how to create asp.net membership tables in postgresql

Question: I'm using MVC 2, Visual Studio 2008, ADO.NET Entity Framework, and previously my database was SQL Server 2008, now i changed it to PostgreSQL.
For implementing asp.net membership in sql server database, we will use
<code> aspnet_regsql
</code>
from visual studio command prompt to generate membership tables, view and stored procedures.
Now is there any tool or script to generate membership tables, views and stored procedures in PostgreSQL database.
Comment: possible duplicate of http://stackoverflow.com/questions/4759195/asp-net-membership-role-providers-for-postgres
Answer: I tried Custom membership, i guess its the only option.


Taxonomy Menu & Hierarchy Trees

Question: So I tried this tutorial on Taxonomy Menu and Menu Block. Now I set up the block to go in the header showing only 1 level deep.
My goal is to click on that 1 level deep link and generate a second menu showing the hierarchy. Instead I get a generic template that displays all posts of the parent taxonomy.
So, ideally:

[Header Menu Item] > Goes to hierarchy tree

Sub category 1 > Goes to hierarchy tree

Nodes of sub category 1
Answer: Have a look at Taxonomy Split, Drupal 6 only at the moment.

if you have a vocabulary in the form of a tree, eg it has terms within terms with nodes attached to them.
It will place all the first level terms in a block and when a term is clicked displays the tree below that term in another block.
Answer: I have successfully used DHTML menu for a similar need. The module allows several behaviors - I used the javascript-based tree browsing. The tree also auto-expands to show reveal the active term, but as far as I recall you'll need Taxonomy Menu Trails for that to work.

Taxonomy Menu & Hierarchy Trees


what's the difference between list '+' list and list .extend in python?

Question: ex. if input "-1 1 3 -2 2", answer should be "-1 -2 1 3 2"
def specialsort(numbers):

    list1 = []
    list2 = []
    list = numbers.split(" ")

    for number in list:
        if int(number)<0:
            list1.append(number)
        else:
            list2.append(number)
    result = list1 + list2
    return " ".join(result)

My question is : In this source code above, when I first used extend list function like result = list1.extend(list2), it turned out to be an error saying TypeError: can only join an iterable. And when I edited it into "result = list1 + list2", it finally worked well. But I still don't understand why the one with extend function doesn't work while the other works well without problem because list1.extend(list2) returns same result with 'list1 + list2'.
If anyone knows about this problem, can you please explain about it?
I would really appreciate your answer. Thanks :)
Answer: Your code:
result = list1 + list2

makes a new list labelled result, whereas your previous:
result = list1.extend(list2)

extends list1 with the contents of list2, so changing list1, but, I suspect the result label will end up with None.
Comment: omg. you are absolutely right Thank you so much!


Python - How do I do conditional counting of rows based on various columns?

Question: I want to create a Python dataframe that counts the number of times that the types C or P occur for each date in each sample. C and P are subsets of F meaning that whenever Type is equal to F, I can count the number of rows with the same Sample value and the same Date value.
I cannot hardcode the conditions as the actual data set is much larger than the sample. This means that I need to base my conditions on the values in the data set where Type is equal to F.
Here is a sample of my data set, df_Data (the actual one being much larger):

Sample | Type | Date | Strike
      A      | F | 1 Jun 2020 |
      A | C | 1 Jun 2020 | 5
      A | P | 1 Jun 2020 | 2.5
      A | F | 1 Dec 2020 |
      A | P | 1 Dec 2020 | 3
      A | P | 1 Dec 2020 | 3.5
      A | P | 1 Dec 2020 | 4
      B | F | 1 Jun 2020 |
      B | C | 1 Jun 2020 | 2.5
      B | C | 1 Jun 2020 | 3
      B | C | 1 Jun 2020 | 4
      B | F | 1 Dec 2020 |
      B | C | 1 Dec 2020 | 2
      B | C | 1 Dec 2020 | 4
      B | P | 1 Dec 2020 | 2
      B | P | 1 Dec 2020 | 4

The corresponding output is a new dataframe like this one:
Sample | Type | Date | Count
=======================
A | F | 1 Jun 2020 |2
A | F | 1 Dec 2020 |3
B | F | 1 Jun 2020 |3
B | F | 1 Dec 2020 |4

In Excel I would have used the CountIfs-function:
IF Type = "F" then countifs(Sample-column, Sample-value, Date-column, Date-value, Type-column, "<> F")
Please help (apologies for the poor table formatting).
Comment: How do you want to implement this?  In a relational database (like mySQL)?  What (if any) programming language are you using?  Please update your tags.
Comment: I made some edits based on FoggyDay's questions.
Answer: I suggest to following code:
import pandas as pd
df = pd.read_csv('sample.csv')
df['Type']=df['Type'].apply(lambda x: 'F' if x == 'P' or 'C' else '')
adf = df.groupby(['Sample', 'Type', 'Dat`enter code here`e'],as_index=False).agg({'Strike':['count']})

This code reads sample.csv into a dataframe. Then, you perform a lambda-query on the column Type.  The final result is in adf.
Comment: Welcome to SO! Code-only answers are likely to be downvoted or deleted altogether. I edit your post a bit, feel free to expand more. For more guidance, please refer to https://stackoverflow.com/help/how-to-answer
Answer: I was able to get the required output based on the logic provided by @Umesh Sharma.
From the original dataframe, df, I created a dataframe without any of the F rows.
df_no_F = df[df['Type'] != "F"]

I then use groupby and count to determine the number of rows for each
Sample and Date combination.
df_count = df_no_F.groupby(['Sample' , 'Date'], as_index=False).count()

Answer: Here's how I would do this. Use df.loc to filter down to the desired Types and then groupby and count :)
import pandas as pd
from io import StringIO

# Getting a df in the right form
s = """Sample | Type | Date | Strike
A | F | 1 Jun 2020 |
A | C | 1 Jun 2020 | 5
A | P | 1 Jun 2020 | 2.5
A | F | 1 Dec 2020 |
A | P | 1 Dec 2020 | 3
A | P | 1 Dec 2020 | 3.5
A | P | 1 Dec 2020 | 4
B | F | 1 Jun 2020 |
B | C | 1 Jun 2020 | 2.5
B | C | 1 Jun 2020 | 3
B | C | 1 Jun 2020 | 4
B | F | 1 Dec 2020 |
B | C | 1 Dec 2020 | 2
B | C | 1 Dec 2020 | 4
B | P | 1 Dec 2020 | 2
B | P | 1 Dec 2020 | 4"""
df = pd.DataFrame(pd.read_csv(StringIO(s), sep='|'))
df.columns = [i.strip() for i in df.columns]
for col in ['Sample', 'Type', 'Date']:
    df[col] = df[col].str.strip()

# Meat and bones of this operation
new_df = df.loc[(df['Type'] == 'C') | (df['Type'] == 'P')].groupby(['Sample', 'Date'])['Strike'].count().reset_index()

# Reformat to desired output
new_df['Type'] = 'F'
new_df = new_df[df.columns].rename(columns={'Strike': 'Count'}).sort_values(by=['Sample', 'Date'], ascending=[True, False])
print(new_df)

Output:
  Sample Type        Date  Count
1      A    F  1 Jun 2020      2
0      A    F  1 Dec 2020      3
3      B    F  1 Jun 2020      3
2      B    F  1 Dec 2020      4


Serve deflected to the left hand court in a doubles match, is it a let?

Question: In a doubles match, is it a let if a serve goes to the left hand court after touching the net?
What if the ball was heading for the right hand court and there was enough spinning to deflect it to the left hand court after hitting the net?
The ITTF Handbook doesn't clarify this edge case:

2.9.1 The rally shall be a let:
126.96.36.199 if in service the ball touches the net assembly, provided the service is otherwise correct or the ball is obstructed by the receiver
  or his or her partner;

Question 5 in this link says it's not a let, but I couldn't find anything more concrete, like an actual occurrence in an official match or a more specific official rule.
Answer: The rules you linked to do address this case, albeit not directly. The rule you cited says (emphasis mine):

2.9.1 The rally shall be a let: 126.96.36.199 if in service the ball touches the net assembly, provided the service is otherwise correct or the ball is obstructed by the receiver or his or her partner.

According to the ITTF rules, in a legal service (again, emphasis mine):

2.6.3 As the ball is falling the server shall strike it so that it touches first his or her court and then touches directly the receiver's court; in doubles, the ball shall touch successively the right half court of server and receiver.

Since the ball, in your scenario, has not touched "successively the right half court of server and receiver" it is not otherwise a legal serve, so the server forfeits the point.
You won't find a more specific rule, since the combination of these two rules is clear.
Comment: This exactly.  Think of "let" from the opposite perspective.  An otherwise valid serve that happens to touch the net on its way in is considered a "let".  Any other serve (a serve that hits any other part of the table or misses it), is simply an invalid serve.


Is there a specific finger for playing a specific key on piano?

Question: I'm new to piano, I can play some stuff following the sheet music, but i'm always wondering if my fingers are on the right position, so, I'd like to know if there's like a map or a way to determine this? or people play however they feel comfortable with?
Answer: There are no hard and fast rules for this. See, everybody's got different sized fingers.
There are plenty of ways to play the same thing. All you've got are just some general rules.
For the "piano lesson" book songs and SOME sheet music, there are little numbers next to the notes from 1 to 5.
They tell you which fingers to use on the note.

thumb
index
middle
4th finger, ring finger, whatever
pinky

But this is (unfortunately) pretty rare.  (Although extremely helpful) and sometimes given fingering won't work for YOUR fingers.
So you're going to have to work it out on your own most of the time. This is what you do in your first several "play through"s of a song:
Write it down (in pencil) on the sheet music !!
(or in the midi sequencer - it lets you do that, right? :)
Use pencil, because you'll likely find a better way to finger it when you
reach the next section or after thinkin' on it a bit (especially after a good night's sleep)
Watch the min and max range of notes for the section you're on, and figure out how you can make your fingers cover them best, with minimal hand position changes.
For chord after chord after chord type sections, you'll probably be moving hand positions.
Otherwise, try to keep your hands somewhat stationary so you'll know what notes you have under your fingers easier.
If possible, try to keep your thumb or your pinky "anchoring" your hand.

Here's some more general tips from "Kreisler" of pianoworld.com's forums:

always figure fingering ONE hand at a time - or you'll drive yourself nuts.
determine fingering -BEFORE- practicing. You want your brain and fingers to remember ONE fingering, not a couple of variations swapped in and out randomly !!
know what notes are under your fingers so you don't have to look down. That's why we have black keys so the hand can always FEEL where it is.
for chords, scales and arpeggios try to use standard fingering
if possible, anchor your hand via the thumb or pinky and keep your fingers on successive keys of the scale to match the sheet music so you can "feel intervals" (or whatever:)
when extending to reach a "way out there" note, use either the fingers or else the thumb.  then move it back so you always know what it's covering. Try to move either the thumb OR the fingers as a group. You don't want to have to readjust gaps between the 4 fingers.
move your whole hand to a new position rather than really stretching your fingers, but also try to minimize hand hops.
try to use your strongest fingers for important notes - first thumb, then index, then middle.
try to minimize thumbs and pinkies on black notes since they're short, they'll squish the rest of your fingers up too far.
practice thumb under (and 2nd or 3rd over the thumb) for smooth legato melodies.
for very very fast melodies, you'll need to use what's CALLED thumb over, but really just means "scoot your whole hand".
pay special attention to smooth transitions between passages of the music.
DON'T bother with fingering the "easy" spots.  Clearer is better.
if the finger doesn't move, DON'T mark it on the 2nd note. just look back across the line.
sometimes awkward fingering in an earlier passage "sets up" the start of the next passage
ask your piano teacher how to do it !!   ;)

I have more info on my site at http://pianocheetah.com/practice/fingering.html
Comment: Edited for readability


How to add page "Contact us"/"Terms of usage" using a link in the footer but page's content to be in the main content(middle region)?

Question: This seems to be a very newbie question. This is what I want to do:
I 'd like to have a link of type "Terms of usage"/"contact us" in the footer, and when the user clicks on it, a page to be appeared in the main region.
How that could be done? Is it possible? Because from what I 've already seen, the page appears in the same theme region with its parent menu.
Comment: What version of Drupal are you using? What other modules or customizations may be affecting the menu system or the rendering of content on pages? When clicking on a menu link, the page's content should always be displaying in the Content region in D6 and in whatever region you have placed the "System Main" block in D7. There should be no relationship between where the menu is placed and where the page's content is rendered unless you have added some configuration to create that functionality.
Answer: Do not know the version your using., search for 'overlay' in modules there are many.
In Drupal 7. Grab the following for direction
http://drupal.org/project/admin_path
http://drupal.org/project/context_overlay
Answer: I can't comment yet so I'm posting this as an answer. Seems like what you are asking for is default Drupal behaviour. If you create a new 'Basic page' called Terms of Usage, and link to that page, it will appear in the main region.
Can you clarify what you meant by 'the page appears in the same theme region with its parent menu'? Providing a link would also be helpful.
Comment: Thank you. Unfortunately I don't have a link because I have it only local. Ok if i create a new Basic page and link the page with a menu, that page will appeared in the same region where the menu is. But I want for example(!) the link "Terms of Usage" to be in the footer, and when I click it, the text/content of the terms to be appeared not in the footer but in the header (for example)
Answer: You could try using Ajax/jQuery to make your T&C/Contact form.
Here is a good tutorial


ScriptDb and Google Visualization API

Question: I have a web app that data is submitted from a Ui embedded in a Google Site and saved in a spreadsheet. I am thinking about switching to scriptDB instead, but I am unsure about querying and displaying data dynamically. The last time I checked it was not possible to refresh a sites page from within a script, so as a work around I wrote a .html page with javascript that accesses the spreadsheet via the key and uses the Visualization DataTables to produce a quick and nicely formatted query. I would like to retain this functionality if possible. Could anyone make some possible suggestions?
Regards,
Shawn
Comment: Have you got more details. I am not clear on what functionality you want to retain. ...that said .... I think this should let you do the refresh. https://developers.google.com/apps-script/html_service
Comment: Thanks for the response. The query is pretty much an html form with drop downs and text fields users can choose criteria that is then put into a query string and submitted when a button is clicked. Once the query is sent using the Google Visualization API the results are returned and then put into a datatable that is displayed on the page.
Comment: The purpose being that users can view submissions pertaining to certain criteria.
Answer: To auto refresh:
You can use CheckBox.setValue(value, fireEvents) - but you may hit quota issues (there is an example somewhere around). If you hit quota issues, then I suspect HTML service is your best option. It also gives you better control.
Comment: I will check out the HTML service. I have had some problems in the past due to Caja stripping out code.
Answer: This is doable today via UiApp (see the Charts api, and note that you can add a Chart to a UiApp).
Comment: Ah ok. That may be what I am looking for.
Answer: Here is an open item requesting expanded Charts service integration with Gviz.
Although, there is limited integration at present, it needs to be expanded to group variables in tables to facilitate basic count and sum operations.
I suggest you "star" the issue to vote for it and to be notified of new developments.

ScriptDb and Google Visualization API


Deriving expression for expected offspring in branching process

Question: I am looking at branching processes in Dobrow 2016 (p. 160), where the author states that the "mean of the offspring distribution" is $\mu =\sum_{k=0}^{\infty} k a_k$.  I want to know why the following equation holds:
$$\sum_{k=0}^{\infty} \mathbb{E} \Big( \sum_{i=1}^k X_i \Big) = \sum_{k=0}^{\infty} k \Big( \sum_{k=0}^{\infty} k a_k \Big).$$
How is this result obtained?
Answer: The paper specifies that $X_1,X_2,X_3,... \sim \text{IID Offspring}$ are values from the offspring distribution.  It also gives the mean of the offspring distribution as:
$$\mathbb{E}(X_i) = \mu = \sum_{k=0}^\infty k a_k.$$
Hence, using the linearity of the expectation operator, you have:
$$\begin{equation} \begin{aligned}
\sum_{k=0}^\infty \mathbb{E} \Big( \sum_{i=1}^k  X_i \Big)
&= \sum_{k=0}^\infty \sum_{i=1}^k \mathbb{E}(X_i) \\[6pt]
&= \sum_{k=0}^\infty \sum_{i=1}^k \mu \\[6pt]
&= \sum_{k=0}^\infty k \mu \\[6pt]
&= \sum_{k=0}^\infty k \Big( \sum_{k=0}^\infty k a_k \Big). \\[6pt]
\end{aligned} \end{equation}$$


What stat test to choose

Question: If I need to asses whether there is a change in activity( for example increase in push ups) of users after some event, which stat test should I use?
Data consists of users who has 2 weeks of activity (for example push ups) before event and 2 weeks of data after events.
As I understand I cannot use t test because there are not independent variables and also non normal distributions if I split data to 2 populations : before and after.
Or maybe I shouldn't use stat testing..
Comment: Do you have a control group?
Comment: If you have before and after data for each individual, then you can take the difference for each individual and test that change.  Each individual may be independent of the others, and the change may be more normally distributed than the before figures and the after figures.
Comment: @henry in that case I can test to what? I do not have control group to compare difference, so I would end up having just difference for each user and nothing to compare.
Comment: @arya-mccarthy no I do not have control group. This data wasn't data from a/b test, so I need to make one from existing data
Comment: Could you please say more about the "two weeks" aspect of this? If you have time series data, the analysis could be more complicated.
Answer: You may use a paired t-test. If your sample size is large enough, you can invoke the central limit theorem in order to not worry about the normality of the distribution of differences. If your sample is small, non-parametric testing using a sign test or better yet, a Wilcoxon signed rank test are options.
Comment: should I care about that for t test I need to have same variance?
My way was to get mean for each user before and do t test to mean after
Comment: For a paired t-test, you are doing the test on the differences, so you just end up with one set of data and thus only one variance to deal with. The assumptions for your null hypothesis are made on the distribution of those differences, not on the distribution of the separate groups.
Answer: How do you know that your data is non-normal? There are several ways to test for normality including doing a shapiro test for a quantitative and objective measurement of normality. However, you should supplement a shaprio test with visual aids such as Quartile-Quartile plots, or even Boxplots to see if there is profound skewness. Please be aware that no matter the size of your data-set, you should always test for normality as that is a basic assumption for parametric statistics. If your data is large enough, parametric analyses can tolerate small deviations from a normal distribution, but if the data is profoundly non-normal, then use non-parametric tests.
If your data is not normally distributed, then try making your data fit a normal distribution by doing a logarithmic transformation. Try taking the natural log or log2 of your data, test for normality using the above methods, and if your transformed data is normally distributed, then you can do a paired parametric t-test using the log-transformed data.
If your data cannot be normally distributed no matter what method that you use, then an alternative is to do a paired Wilcoxon test. A Wilcoxon test will order your data numerically, and will apply a rank for each unique value. However, it is important to make sure that your data doesn't have too many ties, which means that you have multiple entries with the same values. For example, if your data has 10 entries, and 7 entries have a value of 8, then you will have 7 ties which will greatly affect the rank-based analyses.
You didn't ask for this specifically, but another crucial test of assumption when doing parametric analyses is homogeneity of variance. In articles, you typically see researchers only discuss normality of their data, but they don't discuss homogeneity of variance between groups. However, this is very important since parametric analyses considers the variance between groups, so if the groups variances are inherently significantly different, then you will get misleading results. I suggest using the LeveneTest to measure homogeneity of variance.
If you use R, then consider reading these packages
https://www.rdocumentation.org/packages/car/versions/3.0-11/topics/Boxplot
https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/qqnorm
https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/wilcox.test
https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/t.test
https://www.rdocumentation.org/packages/car/versions/3.0-11/topics/leveneTest
Best of luck.

What stat test to choose


asp mvc best way to return a json string from a controller

Question: I have a simple Action that iterates around a dbset does a bit of manipulation on each record then returns the chosen records via json, a bit like this:
List<JsonResult> dataout = new List<JsonResult>();
foreach(var r in db.People.OrderBy("something")) {
    // do stuff to the rec
    string SubmittersName = rec.Submitter.Name;
    dataout.Add(this.Json(new { rec.Created, rec.Name, SubmittersName,
                     OtherStuff }));
}

return new JsonResult() {
    Data = dataout.Select(r=>r),
    ContentEncoding = Encoding.UTF8,
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

To me it seems a bit clumsy, but its easy to follow whats going on.
(Also in the returned json I get ContentEncoding:null which seems a bit strange given that I specified it)
How could this be improved on?
General sugesstions/comments appreciated.
TIA.
Answer: You're misusing JsonResult.
JsonResult isn't a way to store JSON data; it's simply a way to return JSON data from a view.
You shouldn't create a list of them.
By returning JSON from a collection of JsonResults, you're actually converting the JsonResults to JSON, including their ContentEncoding properties (which you never set).
Instead, you can directly return a collection of anonymous types:
return Json(
    db.People.OrderBy(something).Select(rec => new { rec.Created, ... }),
    JsonRequestBehavior.AllowGet
);

Comment: You can put that in the `Select` call, or add them to a `List`.  (Since you cannot easily declare a list of anonymous types)
Comment: exactly the problem not easliy anyway. ArrayList works which is the way i think i'll go to get rid of the problem. I have tried to put the tranform function into the select but it proved difficult, I kept getting lots of compiler errors about not be able to parse the anon function into an expression tree.
Comment: Oh; you're using LINQ to SQL.  You can fix those errors by calling `AsEnumerable()` before `Select()`.


how can I detect if a button was pressed on a simple webpage using embeddedwb

Question: Am using embeddedwb on my application and I have a simple webpage with a button
<input name=mpi type=submit value=" Continue ">

I was trying with but it was no good
if E.outerHTML = '<input name=mpi type=submit value=" Continue ">' then
begin
  if rLoginGate.IsConnectedToLoginGate then
  begin
    ToggleChatBtn;
  end;
end;

now what I want to do is when I press the button I need my application to pick it up and run a simple command like a messagebox anyone got any ideas??
thanks
Comment: It might help you get a better answer than my one if you add to your q what versions of Delphi and TEmbeddedWB you're using.
Answer: A way to do this is using the HTML DOM Object model interfaces in MSHTML.PAS.
My earlier answer, here: Detect when the active element in a TWebBrowser document changes shows how to access this via that Document object of a TWebBrowser.  TEmbeddedWB provides access it via its Document object, too.
That answer and the comments to it shows how to catch events related to a specific node in the document, and also specific event(s).
Of course, if the HTML is under your control, you can make things easier for yourself by giving the HTML node(s) you're interested in an ID or attribute that's easy to find via the DOM model.
The following shows how to modify the code example in my linked answer
to attach an OnClick handler to a specific element node:
procedure TForm1.btnLoadClick(Sender: TObject);
var
  V : OleVariant;
  Doc1 : IHtmlDocument;
  Doc2 : IHtmlDocument2;
  E : IHtmlElement;
begin
  //  First, navigate to About:Blank to ensure that the WebBrowser's document is not null
  WebBrowser1.Navigate('about:blank');

  //  Pick up the Document's IHTMLDocument2 interface, which we need for writing to the Document
  Doc2 := WebBrowser1.Document as IHTMLDocument2;

  //  Pick up the Document's IHTMLDocument3 interface, which we need for finding e DOM
  // Element by ID
  Doc2.QueryInterface(IHTMLDocument3, Doc);
  Assert(Doc <> Nil);

  //  Load the WebBrowser with the HTML contents of a TMemo
  V := VarArrayCreate([0, 0], varVariant);
  V[0] := Memo1.Lines.Text;
  try
    Doc2.Write(PSafeArray(TVarData(v).VArray));
  finally
    Doc2.Close;
  end;

  //  Find the ElementNode whose OnClick we want to handle
  V := Doc.getElementById('input1');
  E := IDispatch(V) as IHtmlElement;
  Assert(E <> Nil);

  //  Create an EventObject as per the linked answer
  DocEvent := TEventObject.Create(Self.AnEvent, False) as IDispatch;

  //  Finally, assign the input1 Node's OnClick handler
  E.onclick := DocEvent;
end;

PS: It's a while since I used TEmbeddedWB and it may turn out that there's a more direct way of doing this stuff, because it was subject to a lot of changes after I stopped using it (in the D5 era).  Even so, you won't be wasting your time studying this stuff, because COM events are applicable to all sorts of things, not just the HTML DOM model.
Comment: I've expanded this answer to make it a bit more self-contained by adding a code example showing how to add an OnClick handler to a specific HTML element node.


WebRtc Bandwidth / resolution / frame rate control

Question: I want to know why I normally transmit a 320240 resolution video and default my uplink traffic is at 1.5MB;
when I modify the SDP bandwidth limit, for example at 500kbps/s my video width and height are still 320240 and the frame rate is not reduced;
So what exactly is this reduced upside traffic?
= =
Comment: It's hard to answer without knowing what sort of app you use for your client. Is it a browser app? A native app? At any rate the camera resolution and frame rate are set at the camera.  500kbps should be more than enough bandwidth for a talking-heads 320x240x15fps. video / audio signal.
Comment: Excuse me, please allow me to describe my question again:
Comment: In the Web end, webRtc is used to connect two peers. In the normal process, CreateOffer, CreateAnswer, SetSDP... Later, for a 320*240 video I observed in WebTC-internals, the outbound bytesSent_in_bits/s should reach 1.5M by default, but after I use bandwidth constraint and other means, the video is still 320*240 and the frame rate is not changed after the bandwidth is limited to 500KB.
I want to know what is the cost of this reduced bandwidth?
Answer: WebRTC uses so-called "lossy perceptual video compression." That is, the video is capable of being compressed into bit streams of various bandwidths... in your case 1.5mbps and 0.5mbps.  It's like JPEG's quality parameter: in JPEG, adjusting that parameter changes the size of the image file.  In video compression, instead of a quality parameter you request a bitrate.
When a lower-bitrate video stream is decompressed, it's a less faithful representation of the original. If you know what to look for you can see various compression artifacts in the decompressed imagery" blockiness, "mosquitoes" around objects, and so forth.
Streaming video and DVD video programs (cinema) use high bandwidth to minimize these effects below the threshold of perception at 1080p or 4K resolution.
In your SIF (320x240) resolution case, your decoded 0.5mbps video has more artifacts in it than your 1.5mbps video. But, because the resolution is relatively low, it will take some looking to find those artifacts.  If they don't annoy you or your users, you can conclude that 0.5mbps is fine for your application. Long experience suggests that you should succeed just fine with that bitrate and resolution. You can even try 250kbps.
Reducing the frame rate doesn't proportionally save bandwidth; most compressed video frames represent differences from the previous frame.
Lower bitrates are better for mobile devices; they save power and your users' data plans.
If you want to see exaggerated compression artifacts and what they look like, set the bitrate down to 125kbps or lower.


Interpretation of an interface driven implementation of the observer pattern in Java

Question: I am studying the observer pattern implemented in Java and I have some doubts about how the tutorial implementation exactly works.
I know that this pattern is used in all the situation that expect the user interaction with a GUI (for example the user click on a button) or all the situation in which an event happen at an unpredictable time (like a timer, when the timer snap an event have to be handled).
I know that in the observer pattern are involved 2 different type of objects:

The subject object: that is the object on which something happen at an unpredictable time (for example a button that could be clicked in any time by the user)
The observer object (or listener): it seems to me that it contains the code that is performed when something change into the subject object (for example it handle the click of my button). Is it true or am I missing something? I am absolutely not true about this statement...I have the doubt that maybe the observer object have only to listen the change on the subject and perform an operation on the subject when this change happens. For example: the button (the subject) is clicked, the observer listen to it and discover this change and it performs a specific operation on the subject (perform a specific method on the subject object).

What is the correct interpretation? The observer listen the subject change and perform an operation defined into the observer or perform an operation defined into the subject?
I know that to do it I can pass a reference of the subject to the observer (I think that the operation performed is defined into the subject.) but this is a bad practice because it involve a form of tight coupling between subject and observer. I know that an interface driven solution exists but I have some difficulties figuring it out.
The tutorial make this example that represent a view that use Swing to render 2 buttons:
package com.caveofprogramming.designpatterns.demo1.view;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

import com.caveofprogramming.designpatterns.demo1.model.Model;

public class View extends JFrame implements ActionListener {

    private Model model;

    private JButton helloButton;        // SUBJECT OBJECT: l'oggetto su cui avviene l'evento
    private JButton goodbyeButton;      // SUBJECT OBJECT: l'oggetto su cui avviene l'evento

    public View(Model model) {
        super("MVC Demo");

        this.model = model;

        // Crea i 2 bottoni definiti sopra:
        helloButton = new JButton("Hello!");
        goodbyeButton = new JButton("Goodbye!");

        // Setta il layout manager da usare che stabilisce come sono posizionati gli elementi:
        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();
        gc.anchor = GridBagConstraints.CENTER;
        gc.gridx=1;
        gc.gridy=1;
        gc.weightx=1;
        gc.weighty=1;
        gc.fill=GridBagConstraints.NONE;

        add(helloButton, gc);   // Aggiunge helloButton dentro il layout

        gc.anchor = GridBagConstraints.CENTER;
        gc.gridx=1;
        gc.gridy=2;
        gc.weightx=1;
        gc.weighty=1;
        gc.fill=GridBagConstraints.NONE;

        add(goodbyeButton, gc); // Aggiunge goodbyeButton dentro il layout

        helloButton.addActionListener(this);
        goodbyeButton.addActionListener(this);

        goodbyeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Sorry to see you go.");
            }

        });

        setSize(600, 500);                          // Setta le dimensioni della finestra
        setDefaultCloseOperation(EXIT_ON_CLOSE);    // Setta il comportamento di cosa succede premendo il tasto X
        setVisible(true);                           // Setta la finestra come visibile
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        JButton source = (JButton)e.getSource();

        if(source == helloButton) {
            System.out.println("Hello there!");
        }
        else {
            System.out.println("Some other button.");
        }

    }

}

In this example I have 2 buttons that represent my subject objects, these:
private JButton helloButton;
private JButton goodbyeButton;

The View class implements an ActionListener interface (That it is the interface mentioned earlier?)
Looking inside the ActionListener.class I found:
// Method descriptor #8 (Ljava/awt/event/ActionEvent;)V
public abstract void actionPerformed(java.awt.event.ActionEvent arg0);

This is a method that has to be implemented and this is the method that is invoked when an action occurs and I have to implement it, this:
@Override
public void actionPerformed(ActionEvent e) {

    JButton source = (JButton)e.getSource();

    if(source == helloButton) {
        System.out.println("Hello there!");
    }
    else {
        System.out.println("Some other button.");
    }

}

The actionPerformed() method is implemented into the View class because it extend the ActionListener interface and it handle the click of the buttons.
Is the ActionListener interface implementation my observer object? And it means that the View* class contains the **subject objects (my buttons) but it is also a observer/listener implementation?
To add the listerner (the observer object) to a button I do:
helloButton.addActionListener(this);

and I pass this because the class that contains the observer is the same of the one where the subject objects are defined. Is it correct?
It is a best practice because I bundle together the subject with the observer into a single class and I have not tight coupling derived by a reference of the subject inside the observer?
Is it my reasoning correct or am I missing something?
Comment: Checking, which button was clicked inside the listener is a bad idea. After all you could write different listeners for both buttons to avoid the `if`. And that's not much work: Anonymus classes, lambda expressions and method references are your friend in this case.
Comment: I've seen this pattern being used many times and it almost always ended in tears. :)
Answer: Let's start with the "theoretical" background. First of all, one has to understand that the observer pattern; and also how "Java" is typically providing it "to you" has been around for "quite some time". There were subtle changes later on, but I think it is fair to say that we are talking about concepts from the late nineties.
My suggestion there: do not only read about the initial form of this pattern (as outlined in the famous Gang-of-four "design principles" book); but also check out what Reactive Programming has to say about it.
So, what I am saying is: in the 2015 you can still sit down and do your Java Swing applications like one did 10 or 15 years ago. But try to not get too focused on this way of doing things; there are alternatives by now; and depending on the requirements of your application, the "old school Java GUI thing" might not be the right answer.
Then: the kind of "bundling" that you suggest in the final paragraphs is more of an "anti-pattern" than a best practice. Sure, it works nice for "very small write-once never-update"-like components.
So, yes, when you start learning about the observer pattern; it is the natural thing to start like that. But it is not an answer to avoid "close coupling" - using your approach, coupling can get so tight (aren't we talking about things that are in the same class?!) that it is almost impossible to "de-couple" them later on.
As soon as you are talking about "realistic" applications, you should avoid such bundling. It starts with the fact ... that you might want the same "action" to happen for a button click ... or when the user turns to some menu. Or other parts of your UI turn more complex; and all of a sudden, "different" actions need to happen for the same button; or the state of "this thingy here" becomes now dependent on the state of "some other thingy over there".
In other words: if your application is complex, changes are very high that the suggested approach leads towards huge, monolithic, un-maintainable spaghetti code bowls.
In other words: anything beyond "simple exercise code that doesn't need maintenance in the future" should not be built following the pattern you outlined here.
Yes, I admit that this doesn't answer the implicit question: "how can it be done better" ... as that is a tough one. One potential tip could be the JavaFx "best practices" from Oracle
Comment: Your answer is more than I expect. Now imy doubt are solved because also to me seemed very strange the fact that in the tutorial speack about no tight coupling and then put the observer in the same class that contains the subjects...
By the way, this is only a tutorial and I am studying patterns from 0 and I think that it is a good starting point but I will follow your suggestion and in the futere I will study also other better implementation of the basic pattern form


Executing Subst command in PowerShell

Question: Would anybody help in executing Subst command in PowerShell; so that it reflects the virtual drive in Windows Explorer!
Thanks in anticipation.
Comment: Do you have any updates on this? I'm also not being able to use `subst` in my script.
Answer: This should work:
<code>Invoke-Expression "subst Z: C:\some\folder"
</code>
Comment: Thanks for your attention. Unfortunately, it does not show the virtual drive in Windows Explorer. It works within PowerShell console or PSIE.
Please suggest a way of creating the drive; which shows up in Explorer.
Comment: @RaabiAnony Press F5 to refresh the view in Explorer. Also check if Explorer is configured to hide empty drives (that's the default).
Comment: Yes, I have done it. Just to confirm, I created the same drive, Z for example; again in the Explorer; and it created as well as displayed it.
Actually, I am trying it for a few days, using different ways; but without success.
Comment: @RaabiAnony All I can say is that it works just fine on my testbox. Directly as well as with `Invoke-Expression`, in the shell as well as in a script.
Comment: I am using Windows 8. Let me explore this aspect.

Executing Subst command in PowerShell


Pesquisa por similaridade PostgreSql

Question: Gostaria de saber se consigo fazer uma pesquisa por similaridade em um campo do tipo  character varying no PostgreSql.
Por exemplo: O nome que tenho gravado na tabela no campo nome é Tauros e estou procurando Taurros. Queria algo que me retornasse o grau de similaridade entre o que foi digitado e o que eu encontrei.
Lembrando que estou utilizando a versão 8.4 do postgresql e também não tenho como fazer instalações no servidor, pois é de uma empresa que divido o banco. Ou seja, não posso utilizar o módulo fuzzystrmatch, com as funções soundex() e difference()
Comment: Conforme comentei, não seria possível utilizar as novas funções, pois essas funções depende de bibliotecas que tem que ser instalada e eu não tenho acesso. Mas obrigado.
Answer: Não creio que algum banco de dados tenha nativamente alguma função que retorne resultados por similaridade. Mas pelas pesquisas que fiz há vários algoritmos que podem solucionar seu problema.
Leia os posts deste fórum, mais abaixo você verá que um usuário postou um script com algumas funções para PostgreSQL que provavelmente vão te ajudar.

Pesquisa por similaridade PostgreSql


Key event modal

Question: Da para chamar uma modal do vue bootstrap usando um keyevent no VUEJS??
Eu não quero nenhuma especie de botão na tela ou inputs, quero saber se eu consigo chamar a modal apenas ao apertar uma tecla especifica. Como por exemplo o ALT.
Answer: Você pode usar os Keyboard Events. Para saber o código de tecla use como referência: https://keycode.info/
Exemplo

$(document).keypress(function(event) {
  if (event.keyCode  == 13){
    $("#myModal").modal("show");
  }

});

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

Esperando abrir o modal quando teclar enter

Modal Heading

        <button type="button" class="close" data-dismiss="modal">×</button>

        Modal body..

        <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

Answer: Você pode usar um input do tipo hidden para ser o acionador do evento.
Dessa forma, basta capturar a tecla que foi pressionada e disparar o evento trigger('click') para abrir o modal.
Aqui contém uma tabela com a numeração de disparo das teclas via javascript.

$(document).keyup(function(ev){
  if(ev.which == 18) { //numero da tecla ALT
     $('#botaomodal').trigger('click')
  }
});
 Pressione "Alt" para exibir o modal

<input type="hidden" id="botaomodal"  data-toggle="modal" data-target="#exampleModal">

Modal Exemplo

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        Exemplo de modal

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Answer: Cara sua pergunta ficou um tanto quanto confusa, não sei se a solução que quer é com jQuery ou com Vue. "Lembrando que: Não é recomendado utilizar os dois por n motivos, tanto é que existe o próprio bootstrap do vue para não utilizar o bootstrap normal que usa jQuery." O meu exemplo é utilizando Vue, mas segue algumas considerações:

1 - O Vue por padrão necessita de um evento manipulador interno dele para que seja disparado juntamente com outro, ou seja, você não conseguirá abrir o modal apenas apertando a tecla alt ele precisa de um evento de click atrelado ao alt por exemplo.
2 - Como o usuário saberá que para abrir o modal é necessário apertar a tecla alt? Botões servem exatamente como um sinal de ação tratando-se de usabilidade!

Vue.component('modal', {
  template: `

Clique aqui e aperte alt para abrir o modal

Modal aberto!!

`,
  methods: {
    abrirModal() {
      this.$refs.meuModal.show()
    }
  }
})

new Vue({
  el: '#app'
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/>

  <modal></modal>

Comment: Obrigado, era sim com vue. Ando sofrendo com isso tem uns 3 dias, porquê neu preciso chamar esse modal sem que exista algo na tela. Apenas uma instrução indicando a tecla. Porém, obrigado
Comment: Você pode usar Bootstrap sem necessariamente ter que usar o Jquery ou Bootstrap-vue. basta remover as chamadas que utilizam Jquery e criar as ações que vão controlar o bootstrap dentro do Vue, com a sintaxe Vue ou com JavasCript puro.

Key event modal


How to return the result of FileReader. in clojurescript

Question: I have a function that reads a file using js/FileReader.:
(defn read-file [file]
  (let [js-file-reader (js/FileReader.)]
    (set! (.-onload js-file-reader)
      (fn [evt]
        (let [result (-> evt .-target .-result)
              array (js/Uint8Array. result)]
          {:content array}))) ; <- This is the value that 'read-file' should return
    (.readAsArrayBuffer js-file-reader file)))

The problem is that I would like it to return the value of the .-onload method of the FileReader, but I only get (of course) the value of (.readAsArrayBuffer js-file-reader file) which, naturally, is undefined.
Thank you very much!
Edit
After trying with Martin Půda's answer, I think that the problem has to do with an asyncrhonous thing. I tested this code:
(defn read-file [file]
  (let [js-file-reader (js/FileReader.)
        reading-result (atom)
        done? (atom false)]
    (set! (.-onload js-file-reader)
      (fn [evt]
        (let [result (-> evt .-target .-result)
              array (js/Uint8Array. result)]
          (reset! reading-result {:content array})
          (reset! done? true)
          (js/console.log "in: " (:content @reading-result)))))
    (.readAsArrayBuffer js-file-reader file)
;;     (while (not @done?) (js/console.log (.-readyState js-file-reader)))
    (js/console.log "out: " @reading-result)
    @reading-result))

I get first the log of out: undefined , and then the log of in: (with the desired result).
When I uncomment the line (while...), I get an infinite loop of 1's... So I think that the function never notices that the FileReader was done... I don't know how to solve this...
Answer: After much reading, I solved it using a callback function:
(ns lopezsolerluis.fits)

(defn read-file [file callback]
  (let [js-file-reader (js/FileReader.)]
    (set! (.-onload js-file-reader)
      (fn [evt]
        (let [result (-> evt .-target .-result)
              array (js/Uint8Array. result)]
          (callback array))))
    (.readAsArrayBuffer js-file-reader file)))

Then read-file is called from this:
(ns lopezsolerluis.annie-web)

(defn procesar-archivo [result]
  (js/console.log "Bloques: " result))

(defn input-file []
  [:input {:type "file" :id "fits" :name "imagenFits" :accept "image/fits"
           :on-change (fn [this]
                        (if (not (= "" (-> this .-target .-value)))
                          (let [^js/File file (-> this .-target .-files (aget 0))]
                            (fits/read-file file procesar-archivo)))
                          (set! (-> this .-target .-value) ""))}])

I added the namespaces because it surprised me that the callback machinery worked even across namespaces. Well, maybe it shouldn't surprise me; but I am learning and was a new concept for me. :)
I answer my question in case it's useful for others (it costed me a lot! :))
Answer: Try this:
(defn read-file [file]
  (let [js-file-reader (js/FileReader.)
        reading-result (atom)]
    (set! (.-onload js-file-reader)
      (fn [evt]
        (let [result (-> evt .-target .-result)
              array (js/Uint8Array. result)]
          (reset! reading-result {:content array}))))
    (.readAsArrayBuffer js-file-reader file)
    @reading-result))

See docs for atom and reset!.
EDIT: See HTML5 FileReader how to return result?- yes, it's asynchronous. I see two possibilities:

You will write all function calls, which work with returned value, inside event listeners.
You will follow this CLJS guide for Promises and use JS Promises or clojure.core.async.
Comment: Thank you very much, but I'm still getting `undefined`. The weird thing is that if I use `(atom 2)` (for example) in line 3, I get `2` as a result, as if the line `(reset! ...)` never happened...
Comment: I wonder if the function `read-file` returns _before_ the `onload` method has a chance of `reset!` the atom...


How to test a directional hypothesis using ANOVA?

Question: Everything I have read has indicated that when performing ANOVA, the null and alternative hypothesis are always the following:

$H_0$: There is no difference in the means,
$H_a$: There is a difference in the means.

But if I have a treatment and I expect, based on past experience or literature, that this treatment would perform better than the other, can the hypothesis with ANOVA ever be:

$H_0$: A would equal or worse than B,
$H_a$: A would be better than B?

I realize the above can be tested with a one-tailed $t$-test, but is the same hypothesis correct/possible for ANOVA, or is it a statistical no no?
Answer: It's correct and reasonable, but ANOVA looks at square of the effect, so you have to go back to the one-sided t-test.  But with two treatments, the t-test and ANOVA are the same thing; the ANOVA F statistic is just $t^2$.
Comment: ANOVA's F test is a generalization of the two sample t-test to cases with more than 2 treatments.
Comment: @suncoolsu - yes, but I thought it was clear that he was thinking anova in the case of 2 treatments.
Comment: Dr. Broman, I was just adding to your statement (nothing else)
Comment: @suncoolsu - Ah yes; no worries; and please just "Karl"


How to randomize an array of a String so it is different every time though the loop

Question: So I am making a description generator and am splitting a text file at a ":". So if the text file had "dog:fish:cat:bird", my code splits it at the ":" and randomly picks one. However, when I print out my ending results, the output is all the same. It will randomly pick the words in the array but then if I said generate it 4 times, it would be the same thing 4 times. So where is my logic wrong on how to approach this? I want it to print 4 random different things. My code is below:
public class Generator
{
public static void main(String[] args)
{
    Scanner scanner = new Scanner(System.in);
    Random r = new Random();

    System.out.print("Enter a file name: ");
    String fName = scanner.nextLine();
    File infle = new File(fName);
    Scanner read = new Scanner(infle);

    System.out.print("Enter number to make: ");
    int things = scanner.nextInt();
    System.out.println();
    System.out.println("Here are " + things + " things: ");
    System.out.println();

    //gets random animal
    String animal = read.nextLine();
    String[]anm1 = animal.split(":");
    int rnd_Animal = r.nextInt(anm1.length);
    String rndAnimal = (anm1[rnd_Animal]);

    //gets random adjective
    String adj = read.next();
    String []adj1 = adj.split(":");
    int rndAdj = r.nextInt(adj1.length);
    String randomAdj = (adj1[rndAdj]);

    for(int i=0; i <things; i++)
    {
        System.out.println(randomAdj + " " + rndAnimal);}

So, my output would print like: "sweaty fish" as many times as I entered for it to be generated. How can I get it to say "sweaty fish","smelly dog","slow fish" if I entered 3 descriptions to be generated? Thank you for any help.
Comment: I think you need to put the "gets random animal" and "gets random adjective" code block inside the for loop.
Answer: The problem is that you get the value for rndAnimal and randomAdj outside the for loop. So it gets the value randomly ONLY ONCE and displays it four times. To solve the problem, assign the value to the two Strings inside the loop.
for(int i=0; i<things; i++){

    //gets random animal
    String animal = read.nextLine();
    String[]anm1 = animal.split(":");
    int rnd_Animal =r.nextInt(anm1.length);
    String rndAnimal =(anm1[rnd_Animal]);

    //gets random adjective
    String adj = read.next();
    String []adj1 = adj.split(":");
    int rndAdj = r.nextInt(adj1.length);
    String randomAdj = (adj1[rndAdj]);

    System.out.println(randomAdj + " " + rndAnimal);
}

Comment: that is definitely it. However, I have a couple other random objects in there and I get a "no line found error". the order of my random objects go, nextLine, next,nextLine,nextLine,nextLine,nextLine. I have the one next in there because it takes from that array twice and I keep fliiping the nexLine and next around but can not seem to get it. Any idea even though that sounds confusing?
Comment: To solve that, I'd suggest you to take care of the scope of objects first, and then check the text file. You might have a problem with file I/O, and you could look for a solution to that, but the problem you ask help for in the question is already solved. See if it helps.
Comment: After further examining your code, If I put everything in the for loop, it will take words from other lines which is not what I need it to do. It has to take the random words in text file from just that line only and that is why I am getting a line not found error.
Comment: Or you can also do one thing, take the input from whichever line you want and store it in a string var. Now forget the file. Use the string as your source. This would make it simple. Generate the random strings inside the loop using the main string outside the loop.
Comment: all I had to do was put my final random string inside the loop and leave everything else on the outside and it works perfectly. Thank you so much for all of your help.


Group views in ConstraintLayout to treat them as a single view

Question: I need to apply some constraints to a group of views in ConstraintLayout. I want to group these views and continue editing while the layout designer in Android studio treats them as a single view. Is there a way to do so without actually wrapping the views with a ViewGroup (another layout)? If such a wrapper is necessary, maybe there is a wrapper layout that comes with ConstraintLayout and allows to group objects without creating heavy layouts like RelativeLayout?
Answer: ConstraintLayout  Chains
Android developers recently released a new version of ConstraintLayout (1.0.2 as of today). This version contains a new major feature - Chains, which allows us to group views in ConstraintLayout.

Chains provide group-like behavior in a single axis (horizontally or vertically).
A set of widgets are considered a chain if they a linked together via a bi-directional connection
Once a chain is created, there are two possibilities:

Spread the elements in the available space
A chain can also be "packed", in that case the elements are grouped together

Currently, you need to use the following gradle dependency to use this feature (since it is an alpha):
 compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'

Here you may find the newest version of ConstraintLayout to use in your projects.
Until Android Studio 2.3, Android Studio user interface designer did not support creating chains since you couldn't add bi-directional constraints in it. The solution was to create these constraints in manually XML, as mentioned by TranslucentCloud. From Android Studio 2.3 (currently only on canary channel), chains are supported in a UI editor as well (as GoRoS mentioned in comments).

Example
Following is an example of how to position two views together in the middle of a screen using ConstraintLayout and chains:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintVertical_chainPacked="true"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"/>
</android.support.constraint.ConstraintLayout>

Update (Jan, 2018) by @Mateus Gondim
In the recent versions, you should use app:layout_constraintVertical_chainStyle="packed" instead of app:layout_constraintVertical_chainPacked="true"
Comment: Necessary to add, in Android Studio 2.2.2 there is no possibility to make bi-directional connections via User Interface Designer, thus they need to be specified directly in the XML resources.
Comment: Nowadays you should use `app:layout_constraintVertical_chainStyle="packed"` instead of `app:layout_constraintVertical_chainPacked="true"`. I'm on `constraint-layout:1.0.2'` version and the latter doesn't work anymore.
Comment: However the new Android Studio 2.3 currently in canary channel does support chains in layout editor view http://tools.android.com/recent/androidstudio23canaryavailable
Comment: Not what he asked.
Comment: Note the key phrase "bi-directional connection". Only having a 1 way connection to the view above tripped me up for a minute.
Comment: Also I had to add the chainStyle attribute to both elements in my chain, not just one. EDIT: looks like nvm as long as you add it to the "first" element in the chain left to right (for horizontal) it works.
Answer: You can use
android.support.constraint.Guideline

to group elements together.
Add a Guideline (vertical or horizontal) and then use that as an anchor for the other views. Here is a simple example of horizontally centering two grouped textviews: (showing design view in AS)

<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@android:color/white"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <TextView
        android:id="@+id/top_text"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:background="@android:color/holo_red_light"
        android:textSize="16sp"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        android:text="Above"
        tools:text="Above" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <TextView
        android:id="@+id/bottom_text"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_bright"
        android:textSize="16sp"
        app:layout_constraintTop_toBottomOf="@+id/guideline"
        android:text="Below"
        tools:text="Below" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="Right vertically centered"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Right vertically centered"/>
</ConstraintLayout>

Comment: what if there are three textViews to be align vertically
Answer: I just want to add some graphics to the great accepted answer.  It is very straightforward:
In layout design view > select all the views that you want to group > right-click them > Chains > Create Horizontal Chain:

It is also straightforward to center them:
Select the head view of the group > Organize > Pack Horizontally > set the start constraint of the first view and the end constraint of the last view to their parent:
Answer: You can use height 0dp and organize views vertically.
in relative layout we can use layout below and above like
<FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav"
        android:layout_below="@+id/toolbar"
        />

In constraint layout giving height is compulsory so you can give 0 height.
and then you can set your view below other views like this
<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tablayout" />

you can use constraintTop_toBottomOf and constraintBottom_toTopOf  properties to adjust your view to above or below of other.
thanks
Comment: Although thats good information, i dont think its what the OP is asking.


Survival analysis and multilevel logistic regression

Question: I want to do a survival analysis using a discrete time multilevel model in Stata, because the data I have is subject to heaping at certain ages (which explains the discrete time) and because the data I have is hierarchal (children are nested in households, the variable hh_number).
Specifically, I want to look at whether the variable polygamy has an effect on survival. I created the following variables:

death_indicator_1: that takes 1 if the child died 0 and 11 months,
death_indicator_2: that takes 1 if the child died between 12 and 23 months, and
death_indicator_3 that takes 1 if the child died between 24 and 60 months.

I also created the variables

survival_time_1 for survival time between 0 and 11 months,
survival_time_2 for survival time between 12 and 23 months, and
survival_time_3 for children between 24 and 60 months.

The variable polygamy takes 1 if the child was born into a polygamous household. In the papers I read that use a similar model, the survival analysis in discrete time is always in reference to one time-interval.
I tried this command to declare interval-timed survival model:
stset survival_time_1 survival_time_2 survival_time_3, failure(death_indicator_1 == 1 | death_indicator_2 == 1 | death_indicator_3 == 1)

But Stata says: too many variables specified
And this command to run the multilevel fixed effect logistic regression:
clogit death_indicator_1 death_indicator_2 death_indicator_3 i.polygam, base(0), group(hh_number)

But I get: invalid 'group'
How can I do this correctly?
Comment: "do not work" is not helpful as a problem report. The code is illegal? Or otherwise unsatisfactory?  Quite how?
Comment: Thank you. For the first command, Stata says : ```too many variables specified````. And for the second command, I get ```invalid 'group' ```
Comment: `help stset` explains that you need one time variable; no more are allowed. The second command has too many commas. Sorry, I don't specialise in survival analysis and never used `clogit`.  But it's puzzling to be asked are these the right commands when Stata is indicating syntax errors in each case.
Answer: The first step to do this correctly is to prepare and organize your data. An amazing reference on how to undertake survival analysis using Stata is Cleves et al.'s 2010 book (refs below). It is very clear and helpful, plus it includes worked examples and commands.
I agree with Nick in the comments about the syntax error. Since the goal is to investigate the same relationship over time, there is no need to define three sets of variables. You could just re-estimate the same model for each sub-period or consider a different one, such as a piecewise model.
On the logistic regression point, the use of logit (or similar) models for discrete-time survival analysis requires a specifically structured dataset. Stephen Jenkins explains it well at p.95 of his unpublished manuscript (2005, still available); the procedure is also described in the Stata help. Honestly, I am not sure how well this kind of discrete-time survival models deals with fixed effects and multilevel interactions. However, the literature you refer to may provide further details in this regard.
References

Cleves, M., Gould, W. W., Gutierrez, R. G., & Marchenko, Y. U. (2010). An introduction to survival analysis using Stata, Third Edition. College Station. TX: Stata Press, StataCorp.
Jenkins, S. P. (2005). Survival analysis. Unpublished manuscript, Institute for Social and Economic Research, University of Essex, Colchester, UK.


Understanding Partial Correlation

Question: I'm having some trouble fully understanding partial correlation and I was wondering if some of you can shred some light on my confusion.
Let's consider the following scenario: It is a known fact that heart disease is related to social and economic status. However, I want to understand if Anger is also a factor. So the obvious next step is to find the correlation between Anger and heart disease while controlling for social and economic status.
There are a couple ways I can do this. The one popular way that I found online was to use partial correlation (ppcor in R). However, when I looked into how they did partial correlation, it didn't make a lot of sense to me mathematically. The way they do it is: let's say they have 3 variables ($X, Y , Z$) and we want to correlate $X$ and $Y$ while taking into consideration $Z$, they take the residuals from correlating $X$ and $Y$, then $X$ and $Z$, then they correlated the two residuals to get the result.
This doesn't make a lot of sense to me, if residuals are variance that are not explained through correlation, then wouldn't it make more sense to only take the residuals from $X$ and $Z$, then correlate that residual with $Y$, that way we can see if $Y$ can explain the variance that is not explained by $X$ and $Z$, therefore "controlling" for $Z$?
Comment: `residuals from correlating X and Y` Correlation cannot produce residuals. It is regression - directed correlation - that can. X is regressed by Z and residuals saved (i.e. Z is washed out from X). Y is regressed by Z and residuals saved  (i.e. Z is washed out from Y). All three variables must be standardized initially. [Then](http://stats.stackexchange.com/a/76819/3277) the two residuals correlate with each other.
Comment: Regarding the statement "So the obvious next step is to find the correlation between Anger and heart disease while controlling for social and economic status" :  https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation
Comment: how is anger measured
Answer: You say that, with $X = \alpha_1 + \beta_1Z + \epsilon_1$ and  $X = \alpha_2 + \beta_2Z + \epsilon_2$, you would prefer to consider $\text{Corr}(\epsilon_1,Y)$ rather than $\text{Corr}(\epsilon_1,\epsilon_2)$. However, please notice that, given $\epsilon_1$ is independent from $Z$, you would not change the covariance ($\text{Cov}(\epsilon_1,Y) = \text{Cov}(\epsilon_1,\epsilon_2)$), so you would only replace the standard error of $\epsilon_2$ with the one of $Y$. You would thus lead your correlation toward zero for no reason.
In your case (let's call Anger $A$, SocioEconomic Status $SES$ and Heart Disease $HD$), you would try to see how much "residual" anger (after controlling for $SES$) affects $HD$. The problem is that, after regressing $A$ on $SES$, what is left (the residuals) cannot explain the part of $HD$ that has already been explained by $SES$. So, by using $HD$ instead of its residuals, you would basically calculate a correlation that would be bounded (both from below and above) by the explanatory power of $SES$ on $HD$. In practice, after controlling for $SES$, in this way you'd have that the partial correlation between $HD$ and any other variable would not range between $-1$ and $+1$, but between $-k$ and $+k$ (with $k<1$, and the higher the explanatory power of $SES$ on $HD$, the lower $k$).

Understanding Partial Correlation


Multiple file upload field option not uploading all the files

Question: I am working with the input type="file" multiple="multiple" and a PHP upload loop.
<input name="data[]" id="file" type="file" multiple="multiple" class="txtinput2" />

Above is my HTML, below is my PHP:
if(isset($_POST['action'])=='uploadfiles'){
$count_data=count($_FILES['data']) ;   ######### count the data #####

for($x=0;$x<$count_data;$x++)

When I echo count_data it gives me an output of 5, but when I select 28 files it says 28 files chosen in the input field. Does the multiple="multiple" only support 5 uploads?
I checked the PHP info and it says max file uploads 20, max post size 8m and max file size 128m and the total size of all the files I am trying to upload is of 1.94 megs.
Array ( [name] => Array ( [0] => DSCF0960.jpg [1] => DSCF0961.jpg [2] => DSCF0963.jpg [3] => DSCF0964.jpg [4] => DSCF0966.jpg [5] => DSCF0967.jpg [6] => DSCF0968.jpg [7] => DSCF0969.jpg [8] => DSCF0970.jpg [9] => DSCF0971.jpg [10] => DSCF0972.jpg [11] => DSCF0973.jpg [12] => DSCF0974.jpg [13] => DSCF0975.jpg [14] => DSCF0976.jpg [15] => DSCF0977.jpg [16] => DSCF0978.jpg [17] => DSCF0979.jpg [18] => DSCF0980.jpg [19] => DSCF0981.jpg ) [type] => Array ( [0] => image/jpeg [1] => image/jpeg [2] => image/jpeg [3] => image/jpeg [4] => image/jpeg [5] => image/jpeg [6] => image/jpeg [7] => image/jpeg [8] => image/jpeg [9] => image/jpeg [10] => image/jpeg [11] => image/jpeg [12] => image/jpeg [13] => image/jpeg [14] => image/jpeg [15] => image/jpeg [16] => image/jpeg [17] => image/jpeg [18] => image/jpeg [19] => image/jpeg ) [tmp_name] => Array ( [0] => /tmp/php4uI9g8 [1] => /tmp/phpVx5WrZ [2] => /tmp/php2DbRCQ [3] => /tmp/phpT2gSNH [4] => /tmp/phpPDlZYy [5] => /tmp/phpMzCcaq [6] => /tmp/phpRxkwlh [7] => /tmp/phpgoRWw8 [8] => /tmp/phpYlGsIZ [9] => /tmp/phpYBG1TQ [10] => /tmp/phpTQBD5H [11] => /tmp/phpQesphz [12] => /tmp/php5U4dtq [13] => /tmp/phpp2G5Eh [14] => /tmp/phpwaZZQ8 [15] => /tmp/php4W0W2Z [16] => /tmp/php7g3WeR [17] => /tmp/phpeZj0qI [18] => /tmp/phpAGo6Cz [19] => /tmp/phpbXlfPq ) [error] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 [14] => 0 [15] => 0 [16] => 0 [17] => 0 [18] => 0 [19] => 0 ) [size] => Array ( [0] => 79605 [1] => 75839 [2] => 71245 [3] => 63228 [4] => 64201 [5] => 74440 [6] => 75350 [7] => 73367 [8] => 72491 [9] => 69725 [10] => 75508 [11] => 72755 [12] => 76076 [13] => 72140 [14] => 68745 [15] => 77859 [16] => 74281 [17] => 74613 [18] => 71702 [19] => 75916 ) )

Comment: What's the result of `print_r($_FILES['data'])`?
Comment: check you POST limit on the server side.
Comment: Comment too long, posted Edit in original question
Answer: You have a total of 20 files in your array divided into 5 sub-array which according to what you've said in your question is your limit of upload.

I checked the PHP info and it says max file uploads 20

The first array is the old file name of each file in order.
The second array is the file type of each file in order.
The third array is where the file was saved and its temporary name.
The fourth array is if any file failed to upload or not, I assume it will be either 0 or 1 being 0 no errors.
The last array is the file size of each file in order.
You count all the files using:
$count_data=count($_FILES['data']['name']) -1;

And read it like this:
for($i=0; $i < $count_data; $i++)
{
    if ($_FILES['data']['error'][$i] == 0)
    {
        $name = $_FILES['data']['name'][$i];
        $temp = $_FILES['data']['tmp_name'][$i];
        $type = $_FILES['data']['type'][$i];
        $size = $_FILES['data']['size'][$i];
    }
}

Comment: Can't believe I missed that, thanks sir

for people looking, changed count($_FILES['data']['name'])


Why arctan equal to -90 degrees?

Question: Can somebody show me why
$$-\arctan\left(\frac{2\pi}{1-\cos(2\pi)}\right)$$
equals to $-90^\circ$ degrees? Thanks.
Comment: $\cos (2\pi) = 1$, so you have an infinity as the argument of $\tan^{-1}$.
Comment: Plus, the $\arctan$ of anything lies strictly between $-90$ and $+90$ degrees. It looks very much like this was originally a statement about limits that got "simplified", so to say. Is that so?
Answer: Since $\;1-\cos 2\pi=0\;$ the argument isn't defined, but I guess the intention here is
$$\lim_{x\to 2\pi}-\arctan\frac{2\pi}{1-\cos x}=-\frac\pi2$$
since we know $\;\tan x\xrightarrow[x\to\frac\pi2\,^-]{}\infty\;$
Comment: Sorry for bothering you with these wrong trivialities, I visualized it completly wrong.You're right, of course.
Comment: I see it this way @GitGud: $$\frac{2\pi}{1-\cos x}\xrightarrow[x\to 2\pi]{}+\infty\implies\,-\arctan\left(\frac{2\pi}{1-\cos x}\right)\xrightarrow[x\to 2\pi]{}-\frac\pi2 $$ precisely because of what you say...
Comment: Close to, and to the left of $\;\pi/2\;$, both $\;\sin\,,\,\cos\;$ are positive, so tangent *must* be non-negative there...!
Comment: Welcome to the " Rats, I read something yet I understood something else!" club, @GitGud: I'm honorary president.
Comment: $\ddot \smile{}$

Why arctan equal to -90 degrees?


Android threading, background process

Question: I want to add the ipaddress on my Arraylist to update my listview which has its own adapter but i receive an error and it stops my app when it detects a server socket. this codes run on background which is scanning the ipaddress of a subnet and saving the address to PostList class.
public class MainActivity extends Activity {

ListView lv;
ArrayList<PostList> list;
ArrayAdapter<PostList> adapter;
int port = 50000;
String ipadd = "192.168.254.";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lv = (ListView)findViewById(R.id.iplist);

        scanIP(ipadd,port);

}

private void scanIP(final String ipadd, final int port){
   final Handler mHandler = new Handler();

   new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 95; i < 105; i++){
            final String ipaddress = ipadd + i;
        try {
            Socket socket = new Socket(ipaddress,port);
            if (socket.isConnected()){
                  try {
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new   OutputStreamWriter(socket
                                    .getOutputStream())), true);
                            out.println("Hey Server im " + ipaddress);
                            Log.d("ClientActivity", "C: Sent.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }

                  runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        insertValue(ipaddress);
                    }

                });

            }
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 }
}).start();

}
private void insertValue(String ipaddress) {
    // TODO Auto-generated method stub
    list.add(new PostList(ipaddress));
    adapter = new PostAdapter(MainActivity.this, list);
    lv.setAdapter(adapter);
}

}

Logcat error, this error shows up when its get my server ip address
12-28 20:15:17.579: I/System.out(15675): [CDS]connect[/192.168.254.100:50000] tm:90
12-28 20:15:17.580: D/Posix(15675): [Posix_connect Debug]Process com.example.practice_socket :50000
12-28 20:15:17.586: D/ClientActivity(15675): C: Sending command.
12-28 20:15:17.587: D/ClientActivity(15675): C: Sent.
12-28 20:15:17.588: D/AndroidRuntime(15675): Shutting down VM
12-28 20:15:17.588: W/dalvikvm(15675): threadid=1: thread exiting with uncaught exception (group=0x411da9a8)
12-28 20:15:17.589: E/test(15675): Exception
12-28 20:15:17.590: E/AndroidRuntime(15675): FATAL EXCEPTION: main
12-28 20:15:17.590: E/AndroidRuntime(15675): java.lang.NullPointerException
12-28 20:15:17.590: E/AndroidRuntime(15675):    at com.example.practice_socket.MainActivity.insertValue(MainActivity.java:95)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at com.example.practice_socket.MainActivity.access$0(MainActivity.java:93)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at com.example.practice_socket.MainActivity$1$1.run(MainActivity.java:74)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at android.os.Handler.handleCallback(Handler.java:725)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at android.os.Looper.loop(Looper.java:153)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at android.app.ActivityThread.main(ActivityThread.java:5299)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at java.lang.reflect.Method.invokeNative(Native Method)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at java.lang.reflect.Method.invoke(Method.java:511)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-28 20:15:17.590: E/AndroidRuntime(15675):    at dalvik.system.NativeStart.main(Native Method)

Answer: Make sure you have instantiated your list object before you call list.add():
list = new ArrayList<PostList>();

Comment: wow, thanks bro, i forgot to instantiate it, i thought i got a problem with the because i just learn it on the internet tutorials only.
Comment: another question bro, how can i make my scanning more faster?
Comment: That question is for Google :)

Android threading, background process


Download a backup of the files directory

Question: I've researched this a little bit, but I'm wondering if anyone else has an idea on how to do this. The request is to be able to create a weekly archive of the files uploaded through a document content type, basically downloading all files. The client is a team of non-technical, financial advisors - so the simpler, the better.
Obviously Backup & Migrate doesn't fit the bill since that's database only. The only thing I can really think of is writing a bash script to gzip their document folder, and then have a continually updating URL based on a date that links to that zipped folder.
Comment: This question appears to be off-topic because it is about server management, not Drupal itself.
Comment: I disagree. The client wants to be able to download all documents uploaded through a document content type. They are financial advisors, not developers. They have no idea what rsync is, nor do they care. They want a button to click in Drupal that will download all files uploaded in a week. That's definitely Drupal, not server management.
Comment: I'm probably making a big assumption actually - are you in a position to install a script and set up a scheduled job on your client's machines (preferably servers) for them? If not then ignore me ;)
Comment: `rsync` is usually the best tool for a job like this
Comment: Right, we were just looking for something that would be more client friendly and wasn't going to cost them a fortune for us to custom build.
Comment: It depends on their local setup of course, but a one line rsync on a cron job to sync the files folder locally should be straightforward to set up on windows/mac (and linux obviously, but clients never seem to be on linux). Might be more straightforward then testing other modules or script based solutions is all I mean
Comment: Why would your client need to know what rsync is? Can't you write the script for them? It's literally one line
Comment: Could you give an example as an answer? I feel like I'm thinking about your solution differently.
Comment: Disagree that this is off-topic.
Answer: There is actually Backup and Migrate Files too.
Comment: I'd prefer something that isn't in dev for a client site, but I'll check it out.
Comment: After multiple conversations, this seems to be the best way to go so far in terms of requirements for our client. Thanks!
Answer: Weate using cdn, having the files folder, nor really in the server but linked to it from the server. You could use this idea to have the files in drop box or any similar service, and mounted in your server.
As it is Dropbox, it will be sync directly with any other folder, like your customerfor example.
Comment: I am sure you can find a similar service in which the client has no access to shared folders, just read. Have a look at this: http://superuser.com/questions/371530/is-there-a-way-to-make-dropbox-public-folders-read-only
Comment: That is actually a pretty creative idea, but I think that puts too much power into the client's hands. I know it's their site, but let's face it - they delete something in Dropbox and then a file doesn't load on their site, I know who they're calling to fix it. I will keep this in my back pocket though, thanks for sharing.


Exportar função utilizando package de terceiro

Question: Possuo um trecho de código que utilizo para consumir uma API e uso este mesmo trecho em diversos arquivos. Sendo assim criei um módulo para exportar tal configuração:
'use strict'

// Module to access woocommerce API endpoints
var woocommerceAPI = require('woocommerce-api')

// Load the environment configuration
require('dotenv').config()

module.exports = () => {
  return new woocommerceAPI({
    url: process.env.URL,
    consumerKey: process.env.CONSUMERKEY,
    consumerSecret: process.env.CONSUMERSECRET,
    version: process.env.VERSION
  })

}
Quando retorno a instancia do package woocommerceAPI o mesmo deveria conter a função get, ficando da seguinte maneira.
const wc = require('./wc-config')

wc.get('products', (err, data, res) => {
  console.log(res)
})

Porém só recebo a mensagem de que wc.get não é uma função.
Answer: Repara que o teu ficheiro/modulo está a exportar uma função e não uma instância de woocommerceAPI.
Quando tens module.exports = () => {...} isso exporta () => {...}, o que queres ter é module.exports = new woocommerceAPI(...); ao estilo Singleton.
Assim o código deveria ser:
'use strict'

// Module to access woocommerce API endpoints
const woocommerceAPI = require('woocommerce-api')

// Load the environment configuration
require('dotenv').config()

const WooAPI = new woocommerceAPI({
    url: process.env.URL,
    consumerKey: process.env.CONSUMERKEY,
    consumerSecret: process.env.CONSUMERSECRET,
    version: process.env.VERSION
})
module.exports = WooAPI


How to show a message box before star an activity?

Question: In my activity i throw a new one with this code:
    intent = new Intent(this, NewActivity.class);
    startActivity(intent);

How to show a message before launching new activity? I would like to show a warning to users before going to new activity, in which just press OK button to go on...
Comment: see this http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Answer: Simply create a dialog.
Dialog dialog = new AlertDialog.Builder(getActivity())
               .setMessage(R.string.dialog_fire_missiles)
               .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       Intent intent = new Intent(MainActivity.this, NewActivity.class);
                       startActivity(intent);
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               }).create();

dialog.show();

Comment: I get this error: The constructor Intent(new DialogInterface.OnClickListener(){}, Class) is undefined
Comment: It works if i use `Intent intent2` instead of `intent`. Otherwise i get this error: Multiple markers at this line
 - Cannot refer to a non-final variable intent inside an inner class defined in a different
  method
 - The final local variable intent cannot be assigned, since it is defined in an enclosing type
Any idea?
Comment: You just need to create a new Intent. I edited the code again.
Answer: Just Copy this code:-  It will show only ok Button
 AlertDialog.Builder builder = new AlertDialog.Builder(NewActivity.class);
 builder.setMessage("Your Message");
 builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int id) {
  // User clicked OK button
 intent = new Intent(this, NewActivity.class);
 startActivity(intent);
       }
   });

 AlertDialog dialog = builder.create();

Comment: I get this error: The constructor Intent(new DialogInterface.OnClickListener(){}, Class) is undefined
Answer: Just use a dialog fragment and when the user clicks "Ok" , launch the activity then.
http://developer.android.com/guide/topics/ui/dialogs.html
Answer: you do it by using toast see this
Toast.makeText(getApplicationContext(), "Message", Toast.LENGTH_LONG).show();

for alert dialogue you can do this
hope it helps.


Calculation without calculator

Question:
Find the value of $\sqrt{5}$ without using calculator.

I've tried using iteration, but it doesn't converge easily.
Pls help me out.
Comment: $\sqrt 5$ has a non periodic decimal expansion. What do you mean by *find the value*?
Comment: Which iteration did you try?
Comment: Newton-raphson Iteration
Answer: For an approximation
$$\sqrt 5=\sqrt{4+1}=2\sqrt{1+\frac14}$$ Now, using the binomial expansion or Taylor series
$$\sqrt{1+x}=1+\frac{x}{2}-\frac{x^2}{8}+\frac{x^3}{16}-\frac{5 x^4}{128}+O\left(x^5\right)$$ Replace $x$ by $\frac14$ to get
$$\sqrt 5\approx \frac{36635}{16384}\approx 2.23602$$ while the "exact" value would be $\approx 2.23607$.
Even simpler, consider the $[2,2]$ Padé approximant
$$\sqrt{1+x}=\frac{1+\frac{5 }{4}x+\frac{5 }{16}x^2}{1+\frac{3 }{4}x+\frac{1}{16}x^2}$$ which gives
$$\sqrt 5\approx \frac{682}{305}\approx 2.23607$$
Edit
Some other answers used Newton method. Using Halley method, the very first iterate would be $\frac {38}{17}\approx 2.23529$ which is not too bad. The second one would be $\frac{219602}{98209}\approx 2.23607$.
What could also be interesting is to consider
$$\sqrt[n]{k^n+a}=k\sqrt[n]{1+\frac a{k^n}}$$ and using the $[2,2]$ Padé approximant, we should get, as an approximation
$$\sqrt[n]{k^n+a}=\frac{1+\left(1+\frac{1}{2 n}\right) \epsilon +\frac{\left(2 n^2+3 n+1\right) }{12 n^2}\epsilon
   ^2 } {1+\left(1-\frac{1}{2 n}\right) \epsilon +\frac{\left(2 n^2-3 n+1\right) }{12 n^2} \epsilon
   ^2}\qquad \text{using}\qquad \epsilon=\frac a {k^n}$$
Comment: I'd use an expansion of $\sqrt{4+x}$
Comment: Pade approximation looks much simpler and very accurate. +1 for mentioning it here.
Comment: @ParamanandSingh. One of my passions ! You could not believe the number of things I have been able to do with it. Cheers.
Answer: In order to approximate $\sqrt{a}$ for $a>0$ by using an iterative method, consider, for $x>0$, the function
$$f(x)=\frac{1}{2}\left(x+\frac{a}{x}\right)$$
that is the average of $x$ and $a/x$. Note that if $x<\sqrt{a}$ then $a/x>\sqrt{a}$ and vice versa.
For $a=5$ and starting from $2$ we obtain after 3 iteration
$$9/4,\quad 161/72,\quad 51841/23184\approx 2.236067978$$
which is a quite good approximation of $\sqrt{5}$.
Comment: A variation on this for $\sqrt A\;$  is $g(x)=x-\frac {2x(x^2-A)}{3x^2+A}.$  If $x^2-A=F$ then $(g(x)-A)^2=\frac {F^3}{(3x^2+A)^2}.$
Answer: $$y = f(x) = \sqrt x$$
$$\Delta y = f(x+\Delta x) - f(x)$$
$$x = 2.2^2=4.84, \Delta x = 0.16$$
$$\implies \Delta y = \sqrt 5 - 2.2$$
$$\Delta y=\frac{\Delta y}{\Delta x}\Delta x \approx \frac{dy}{dx}\Delta x=\frac{1}{2}x^{-1/2}\Delta x=\frac {1}{2} \times \frac{1}{2.2}\times 0.16\approx0.036$$
$$\implies \sqrt 5 \approx 2.236$$
Answer: $9^2-5\times4^2= 81-80=1$ is a solution of the Brahmagupta equation $ x^2-5y^2=1$. So the first approximate solution is $9/4$. To get the next approximation from the first (a/b)  for $x^2-db^2=1$ use the substitution $$(a/b)\longrightarrow (1+2db^2)/2ab= (1+10b^2)/2ab,$$ which yields $161/72$. You can iterate getting more accuracy. Note that we are already very close:  $(161/72)^2=5.000192901234568$. Actually Newton-Raphson for this equation yields the same value as Brahmagupta's formula. (algebraic methods giving numerical approximation!)
Answer: With pen and paper only, one can compute digits of square roots of small integers one by one using algorithm below.
I have done that for $\sqrt{3}$ and get $1.73205080756887\ldots$ while I'm in high school.

$p \leftarrow \verb/input/ \in \{1, \ldots, 99\}\\
    n \leftarrow \verb/input/ \in \mathbb{Z}_{+},\\
    q \leftarrow 0.$
$r \leftarrow \max\big\{ t \in \{ 0, \ldots, 9 \} : 20qt +t^2 \le p \big\},\\
    s \leftarrow (20q + r)r,\\
    q \leftarrow 10q + r,\\
    p \leftarrow 100(p-s),\\
    n \leftarrow n-1.$
$\verb/if/(( p \ne 0 ) \land (n > 0)) \verb/ goto / \text{step} 2.$
$q \rightarrow \verb/output/$.

The basic idea of above algorithm goes like this. In an expression like
$$\sqrt{p} = q\quad\text{ where }\quad q = (q_0.q_1q_2q_3\cdots)_{10}$$
If we know the decimal representation of $q$ up to $k$-digits $(q_0.q_1,\ldots,q_{k})_{10}$, the next digit $q_{k+1}$ will be the largest $r$ which satisfy:
$$p \ge (q_0.q_1\ldots,q_{k} r)_{10}^2$$
In above algorithm, we have keep the partial differences
$p - (q_0.q_1\ldots,q_{k})_{10}^2$ to simplify comparison and multiply everything by suitable powers of $10$ to allow us work within integers.
As an example, I write a program to implement above algorithm for $q = 5, n = 10$.
Following is the output:
<code>[ 0] p <- 5
     q <- 0
     n <- 10
[ 1] r: 2 p: 100          = 100*(5-4)
          q:  2           = 10*0 + 2
[ 2] r: 2 p: 1600         = 100*(100-84)
          q:  22          = 10*2 + 2
[ 3] r: 3 p: 27100        = 100*(1600-1329)
          q:  223         = 10*22 + 3
[ 4] r: 6 p: 30400        = 100*(27100-26796)
          q:  2236        = 10*223 + 6
[ 5] r: 0 p: 3040000      = 100*(30400-0)
          q:  22360       = 10*2236 + 0
[ 6] r: 6 p: 35676400     = 100*(3040000-2683236)
          q:  223606      = 10*22360 + 6
[ 7] r: 7 p: 437151100    = 100*(35676400-31304889)
          q:  2236067     = 10*223606 + 7
[ 8] r: 9 p: 3465895900   = 100*(437151100-402492141)
          q:  22360679    = 10*2236067 + 9
[ 9] r: 7 p: 33540079100  = 100*(3465895900-3130495109)
          q:  223606797   = 10*22360679 + 7
[10] r: 7 p: 223512747100 = 100*(33540079100-31304951629)
          q:  2236067977  = 10*223606797 + 7
result: 2236067977
</code>
The last line means up to $9$ decimal places, the decimal representation of $\sqrt{5}$ is $2.236067977\ldots$.
Comment: This is really nice ! Thanks for providing such an answer. Cheers.
Answer: Everyone is adding their favourite approximation method for quadratic irrationals, so continued fractions, why not?
$$
\begin{align}
x &= \sqrt5\\
x^2 &= 5\\
x^2-1 &= (x-1)(x+1)=4\\
x-1 &=\frac{4}{1+x}\\
x &= 1 + \frac{4}{1+x}\\
x &= 1 + \frac{4}{1+1+\frac{4}{1+x}}=1 + \frac{4}{2+\frac{4}{1+x}}\\
x &=1+{\cfrac {4}{2+{\cfrac {4}{2+{\cfrac {4}{2+{\cfrac {4}{2+\ddots }}}}}}}}
\end{align}
$$
Answer: By Newton's Method, since $\sqrt5$ is the root of $f(x)=x^2-5=0$, we perform the process
$$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}=x_n-\frac{x_n^2-5}{2x_n}=\frac{x_n}{2}+\frac5{2x_n}$$
where $x_n$ is the $n^{th}$ approaxiamtion.
Taking a reasonable approximation of $x_0=2$, we have
$$x_1=1+\frac54=\frac94$$
$$x_2=\frac98+\frac{10}9=\frac{161}{72}$$
$$x_3=\frac{161}{144}+\frac{180}{161}=\frac{51841}{23184}\approx2.23$$
which is a fair approximation since  $2.23^2=4.9729$
Comment: Come on! $51841/23184$ without calculator???
Comment: @Raffaele I originally want to show how close (of my limited knowledge on) this method can be, so just give the numerical value to $x_3$. I admit it may be an inefficient method, but even if $\frac{51841}{23184}\approx 2.23$, which only needs 3 division, it gives the close value $2.23^2=4.9729$. I fixed my answer with reference to your comments. Thank you.
Answer: Iteration without a calculator is a nightmare! How many decimals do you want? $$\sqrt{x+4}=2+\frac{x}{4}-\frac{x^2}{64}++\frac{x^3}{512}+O(x^4)$$ for $x=1$ gives $\sqrt{5}\approx \dfrac{1145}{512}$ with three exact decimals
$1145/512$ by hand is not amusing but one can work it out
<code>1145    512
        2.236
1024
 1210
 1024
  1860
  1536
   3240
   3072
    168
</code>
Answer: Suppose you want to calculate the root of a positive number $M$.
Assume $x=\sqrt M$,then
$f(x)=x^2-M=0$.
Now use the Newton-Raphson Method.Newton-Raphson method  For this equation is given by
\begin{equation}
x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}
\end{equation}

Calculation without calculator